PageSourceSearch

https://conectawhats.com/assets/Integrations-DbIbRnPu.js

js conectawhats.com collected 2026-10-09 22:01:40 UTC 108,353 bytes, 11 lines download raw bytes

1import{j as e}from"./ui-vendor-DugvyhkM.js";import{r as u,j as vs}from"./react-vendor-CnbS1iJ1.js";import{P as bs}from"./page-header-BWeTeqcF.js";import{c as xe,u as V,b as K}from"./query-vendor-VfPrV_BW.js";import{c as ns,e as De,B as j,u as $,a as Q,s as E,R as ce,L as B,h as Le,i as Re,j as Ke,S as Ns,f as Oe,T as ys}from"./index-Bg0TxxV_.js";import{B as I}from"./badge-CzHqQw3k.js";import{S as ze}from"./switch-DjutE4mV.js";import{C as de}from"./circle-alert-C6anXDVL.js";import{C as re}from"./clock-CpxfZcn9.js";import{C as Y}from"./circle-check-CpUwUsmM.js";import{a as X,A as Ae}from"./motion-vendor-BotnA3l1.js";import{S as ws}from"./settings-2-DifWWjAz.js";import{A as Ee}from"./arrow-right-CC-3bzc2.js";import{I as D}from"./input-7TDv-tmI.js";import{T as We,a as qe,b as M,c as U}from"./tabs-DXQLPVlN.js";import{S as Fe}from"./search-C6gqMBpF.js";import{M as ks,C as ve}from"./mouse-pointer-click-jzxNs6z0.js";import{Z as we}from"./zap-xLc8T9VS.js";import{D as ne,b as ie,c as ee,d as se,e as ae,f as fe,a as is}from"./dialog-Dubnefxk.js";import{L as O}from"./label-kuCvhSP_.js";import{F as os}from"./filter-BTZcxNGP.js";import{C as me}from"./copy-CfZj5p-r.js";import{E as Ne}from"./external-link-CM1uLvZn.js";import{a as he,f as He}from"./date-vendor-Bmuhnpy5.js";import{p as te}from"./pt-BR-DFQWD3yV.js";import{C as T,b as H,c as G,d as le,a as z}from"./card-Cae1mpFA.js";import{P as Cs}from"./progress-3EjR_Gss.js";import{W as _s}from"./wifi-8diP91nL.js";import{C as ue}from"./circle-x-BEDxBoPB.js";import{S as ke,a as Ce,b as _e,c as Se,d as R,C as Ss}from"./select-CBOQZhf-.js";import{C as As,b as Ps,a as Es}from"./collapsible-BMOqVHBZ.js";import{A as ge}from"./activity-C2DpfC_b.js";import{C as Is}from"./chevron-down-B8zXvv0T.js";import{W as pe}from"./webhook-DphB-iDT.js";import{G as cs}from"./globe-CDKcbllv.js";import{L as es}from"./link-CfWcYDc3.js";import{T as ss}from"./test-tube-BYpeCO7I.js";import{P as je}from"./plus-Bwcelgub.js";import{T as Pe}from"./trash-2-mhkoyopA.js";import{S as ls}from"./scroll-area-CYvSnwu3.js";import{C as Ge}from"./checkbox-XQi0-p3B.js";import{T as ds,a as ms,b as Ie,e as J,c as us,d as Z}from"./table-BSabRjfe.js";import{P as Qe,W as Ts}from"./wand-sparkles-CqvQ1O5f.js";import{L as Ve}from"./link-2-BJ6IkEvg.js";import{M as oe}from"./mophy-card-DrCidkCl.js";import{C as Je}from"./circle-check-big-Cq3GO93E.js";import{S as zs}from"./separator-BR_2C1oT.js";import{S as Ze}from"./shield-1rQ6mNn7.js";import{A as Ws}from"./arrow-left-Da74-hSe.js";import{F as Te}from"./facebook-Cwx8eX90.js";import{I as qs}from"./info-BuM_SXo8.js";import{B as xs}from"./building-2-DwC9Ar9P.js";import{P as hs}from"./phone-DQkQS0s7.js";import{S as Fs}from"./send-C4pcxhht.js";import{S as Ms}from"./smartphone-C3IDloT3.js";import{F as Ds}from"./file-text-BY-TZAlQ.js";import{l as as}from"./activityLogger-Bs2uaUcR.js";import{K as ps}from"./key-BZzYPS5y.js";import{T as Ls}from"./trending-up-DtML7QPG.js";import{C as gs}from"./chart-column-CvY_nWg4.js";import{H as Rs}from"./history-Cp4EVpMb.js";import{R as Ks}from"./rotate-ccw-CCPfHniH.js";import"./supabase-vendor-DOL-USaH.js";import"./chevron-right-BPOfCJ9Z.js";import"./charts-vendor-BthknRg3.js";import"./check-CLse9FI2.js";import"./index-5DquiPsd.js";import"./trending-down-DIsld41e.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const fs=ns("ArrowDownUp",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"m21 8-4-4-4 4",key:"1c9v7m"}],["path",{d:"M17 4v16",key:"7dpous"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const Os=ns("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),Bs={connected:{label:"Conectado",variant:"success",icon:Y,dotClass:"bg-success animate-pulse"},disconnected:{label:"Desconectado",variant:"secondary",icon:de,dotClass:"bg-muted-foreground"},pending:{label:"Pendente",variant:"warning",icon:re,dotClass:"bg-warning animate-pulse"},error:{label:"Erro",variant:"destructive",icon:de,dotClass:"bg-destructive"}};function Us({id:t,name:m,description:g,icon:x,color:b,status:N,isActive:o=!1,lastSync:l,eventsCount:p,onConfigure:w,onToggle:r,onConnect:d}){const C=Bs[N],S=C.icon,c=N==="connected";return e.jsxs(X.div,{initial:{opacity:0,y:20}
11,animate:{opacity:1,y:0},whileHover:{y:-4},transition:{duration:.2},className:De("group relative rounded-2xl border bg-card p-6 transition-all duration-300","hover:shadow-lg hover:border-primary/30",!o&&c&&"opacity-70"),children:[e.jsx("div",{className:De("absolute top-4 right-4 h-2.5 w-2.5 rounded-full",C.dotClass)}),e.jsxs("div",{className:"flex items-start gap-4 mb-4",children:[e.jsx("div",{className:De("h-14 w-14 rounded-xl flex items-center justify-center text-2xl border transition-transform group-hover:scale-110",b),children:x}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-lg truncate",children:m}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:g})]})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsxs(I,{variant:C.variant,className:"gap-1.5",children:[e.jsx(S,{className:"h-3 w-3"}),C.label]}),p!==void 0&&p>0&&e.jsxs(I,{variant:"outline",className:"text-muted-foreground",children:[p.toLocaleString()," eventos"]})]}),l&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-4",children:["Última sincronização: ",l]}),e.jsx("div",{className:"flex items-center justify-between pt-4 border-t",children:c?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{checked:o,onCheckedChange:r,className:"data-[state=checked]:bg-success"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o?"Ativo":"Pausado"})]}),e.jsxs(j,{variant:"ghost",size:"sm",className:"gap-2 group-hover:bg-primary/10 group-hover:text-primary",onClick:w,children:[e.jsx(ws,{className:"h-4 w-4"}),"Configurar"]})]}):e.jsxs(j,{className:"w-full gap-2",onClick:d,children:["Conectar",e.jsx(Ee,{className:"h-4 w-4"})]})}),c&&w&&e.jsx(X.div,{initial:{opacity:0}
11,whileHover:{opacity:1},className:"absolute inset-0 rounded-2xl bg-gradient-to-t from-primary/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none"})]})}const Be=[{id:"hotmart",name:"Hotmart",description:"Sincronize compradores e assinantes automaticamente",icon:"🔥",color:"bg-orange-500/10 text-orange-500 border-orange-500/30"},{id:"kiwify",name:"Kiwify",description:"Importe leads e clientes em tempo real",icon:"🥝",color:"bg-purple-500/10 text-purple-500 border-purple-500/30"},{id:"eduzz",name:"Eduzz",description:"Conecte sua conta Eduzz para automações",icon:"📘",color:"bg-blue-500/10 text-blue-500 border-blue-500/30"},{id:"monetizze",name:"Monetizze",description:"Gerencie afiliados e vendas integradas",icon:"💰",color:"bg-green-500/10 text-green-500 border-green-500/30"},{id:"perfectpay",name:"PerfectPay",description:"Checkout e pagamentos integrados",icon:"💎",color:"bg-pink-500/10 text-pink-500 border-pink-500/30"},{id:"ticto",name:"Ticto",description:"Integração completa com Ticto",icon:"🎫",color:"bg-cyan-500/10 text-cyan-500 border-cyan-500/30"},{id:"braip",name:"Braip",description:"Vendas e afiliados sincronizados",icon:"🚀",color:"bg-amber-500/10 text-amber-500 border-amber-500/30"},{id:"zapier",name:"Zapier",description:"Conecte com mais de 5.000 apps",icon:"⚡",color:"bg-orange-500/10 text-orange-600 border-orange-500/30"},{id:"make",name:"Make (Integromat)",description:"Automações visuais poderosas",icon:"🔧",color:"bg-violet-500/10 text-violet-500 border-violet-500/30"},{id:"n8n",name:"n8n",description:"Automação open-source flexível",icon:"🌐",color:"bg-red-500/10 text-red-500 border-red-500/30"},{id:"pabbly",name:"Pabbly Connect",description:"Integrações sem limites mensais",icon:"🔗",color:"bg-indigo-500/10 text-indigo-500 border-indigo-500/30"},{id:"custom",name:"Webhook Customizado",description:"Configure sua própria integração",icon:"⚙️",color:"bg-muted text-muted-foreground border-border"},{id:"mautic",name:"Mautic",description:"Automação de marketing open-source",icon:"🟣",color:"bg-purple-500/10 text-purple-600 border-purple-500/30"},{id:"elementor",name:"Elementor",description:"Formulários e landing pages WordPress",icon:"🎨",color:"bg-pink-500/10 text-pink-600 border-pink-500/30"},{id:"rdstation",name:"RD Station",description:"CRM e automação de marketing",icon:"🟢",color:"bg-emerald-500/10 text-emerald-600 border-emerald-500/30"},{id:"asana",name:"Asana",description:"Gestão de projetos e tarefas",icon:"🔴",color:"bg-rose-500/10 text-rose-500 border-rose-500/30"}],$s={asana:[{id:"create_project",label:"Criar Projeto",description:"Cria um novo projeto no Asana",type:"action"},{id:"create_task",label:"Criar Tarefa",description:"Cria uma nova tarefa em um projeto",type:"action"},{id:"duplicate_task",label:"Duplicar Tarefa",description:"Duplica uma tarefa existente",type:"action"},{id:"update_task",label:"Atualizar Tarefa",description:"Atualiza campos de uma tarefa",type:"action"},{id:"add_comment",label:"Adicionar Comentário",description:"Comenta em uma tarefa",type:"action"},{id:"assign_task",label:"Atribuir Tarefa",description:"Define responsável da tarefa",type:"action"},{id:"task_completed",label:"Tarefa Concluída",description:"Quando uma tarefa é concluída",type:"trigger"},{id:"task_created",label:"Nova Tarefa",description:"Quando uma nova tarefa é criada",type:"trigger"}],mautic:[{id:"create_contact",label:"Criar Contato",description:"Cria um contato no Mautic",type:"action"},{id:"add_to_segment",label:"Adicionar ao Segmento",description:"Adiciona contato a um segmento",type:"action"},{id:"send_email",label:"Enviar E-mail",description:"Envia um e-mail via Mautic",type:"action"},{id:"update_contact",label:"Atualizar Contato",description:"Atualiza dados do contato",type:"action"},{id:"add_to_campaign",label:"Adicionar à Campanha",description:"Insere contato em uma campanha",type:"action"},{id:"form_submitted",label:"Formulário Enviado",description:"Quando um formulário é preenchido",type:"trigger"},{id:"email_opened",label:"E-mail Aberto",description:"Quando um e-mail é aberto",type:"trigger"}],elementor:[{id:"form_submission",label:"Formulário Enviado",description:"Quando um formulário do Elementor é enviado",type:"trigger"},{id:"popup_viewed",label:"Popup Visualizado",description:"Quando um popup é exibido",type:"trigger"},{id:"create_lead",label:"Criar Lead",description:"Cria um lead a partir do formulário",type:"action"},{id:"redirect_user",label:"Redirecionar Usuário",description:"Redireciona após ação",type:"action"}],rdstation:[{id:"create_contact",label:"Criar Contato",description:"Cria um contato no RD Station",type:"action"},{id:"create_deal",label:"Criar Oportunidade",description:"Cria uma oportunidade no CRM",type:"action"},{id:"update_deal",label:"Atualizar Oportunidade",description:"Atualiza uma oportunidade",type:"action"},{id:"add_tag",label:"Adicionar Tag",description:"Adiciona tag ao contato",type:"action"},{id:"move_stage",label:"Mover Estágio",description:"Move oportunidade de estágio",type:"action"},{id:"conversion",label:"Conversão",description:"Quando uma conversão ocorre",type:"trigger"},{id:"deal_won",label:"Oportunidade Ganha",description:"Quando uma oportunidade é ganha",type:"trigger"}],hotmart:[{id:"purchase",label:"Compra Aprovada",description:"Quando uma compra é aprovada",type:"trigger"},{id:"refund",label:"Reembolso",description:"Quando um reembolso é solicitado",type:"trigger"},{id:"subscription_cancel",label:"Assinatura Cancelada",description:"Quando assinatura é cancelada",type:"trigger"},{id:"chargeback",label:"Chargeback",description:"Quando ocorre um chargeback",type:"trigger"}],kiwify:[{id:"purchase",label:"Compra Aprovada",description:"Quando uma compra é aprovada",type:"trigger"},{id:"refund",label:"Reembolso",description:"Quando um reembolso é solicitado",type:"trigger"},{id:"subscription_cancel",label:"Assinatura Cancelada",description:"Quando assinatura é cancelada",type:"trigger"}]};function Qs({providerId:t,providerName:m,providerIcon:g}){const[x,b]=u.useState(""),[N,o]=u.useState("all"),l=$s[t]||[],p=l.filter(d=>!(N!=="all"&&d.type!==N||x&&!d.label.toLowerCase().includes(x.toLowerCase()))),w=l.filter(d=>d.type==="action").length,r=l.filter(d=>d.type==="trigger").length;return l.length===0?null:e.jsxs("div",{className:"space-y-4 pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-sm font-semibold",children:"Ações disponíveis"}),e.jsxs(I,{variant:"outline",className:"text-xs",children:[l.length," ações"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fe,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(D,{placeholder:"Buscar ações...",value:x,onChange:d=>b(d.target.value),className:"pl-9 h-8 text-xs"})]}),e.jsx(We,{value:N,onValueChange:d=>o(d),children:e.jsxs(qe,{className:"h-8",children:[e.jsx(M,{value:"all",className:"text-xs h-6 px-2",children:"Todas"}),e.jsxs(M,{value:"action",className:"text-xs h-6 px-2 gap-1",children:[e.jsx(ks,{className:"h-3 w-3"}),"Ações (",w,")"]}),e.jsxs(M,{value:"trigger",className:"text-xs h-6 px-2 gap-1",children:[e.jsx(we,{className:"h-3 w-3"}),"Gatilhos (",r,")"]})]})})]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:e.jsx(Ae,{mode:"popLayout",children:p.map((d,C)=>e.jsxs(X.div,{layout:!0,initial:{opacity:0,y:8}
11,animate:{opacity:1,y:0},exit:{opacity:0,scale:.95},transition:{delay:C*.03},className:"flex items-start gap-3 p-3 rounded-lg border bg-card hover:bg-accent/50 hover:border-primary/30 transition-all cursor-pointer group",children:[e.jsx("div",{className:"h-8 w-8 rounded-md flex items-center justify-center text-sm bg-muted shrink-0 group-hover:scale-110 transition-transform",children:g}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:d.label}),e.jsx(I,{variant:d.type==="trigger"?"default":"secondary",className:"text-[9px] px-1.5 py-0 shrink-0",children:d.type==="trigger"?"Gatilho":"Ação"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5 line-clamp-1",children:d.description})]})]},d.id))})}),p.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"Nenhuma ação encontrada"})]})}function Vs(){const{currentWorkspace:t}=$(),{toast:m}=Q(),g=xe(),[x,b]=u.useState(""),[N,o]=u.useState("all"),[l,p]=u.useState(!1),[w,r]=u.useState(!1),[d,C]=u.useState(null),[S,c]=u.useState(null),[_,h]=u.useState(""),{data:s=[],isLoading:i}=V({queryKey:["integration-webhooks-grid",t?.id],queryFn:async()=>{if(!t?.id)return[];const{data:f,error:W}=await E.from("integration_webhooks").select("*").eq("workspace_id",t.id).order("created_at",{ascending:!1});if(W)throw W;return f},enabled:!!t?.id}),v=u.useMemo(()=>{const f={};return s.forEach(W=>{f[W.provider]||(f[W.provider]=W)}),f},[s]),k=K({mutationFn:async()=>{if(!t?.id||!d)throw new Error("Missing data");const f=crypto.randomUUID().replace(/-/g,""),{data:W,error:F}=await E.from("integration_webhooks").insert({workspace_id:t.id,name:_||`Webhook ${d.name}`,provider:d.id,webhook_secret:f,is_active:!0,events_config:{on_purchase:!0,on_refund:!0,on_subscription_cancel:!0,on_subscription_renewal:!0,on_chargeback:!0}}).select().single();if(F)throw F;return W},onSuccess:f=>{m({title:"✅ Integração configurada com sucesso!"}),g.invalidateQueries({queryKey:["integration-webhooks-grid"]}),p(!1),h(""),c(f),r(!0)},onError:f=>{m({title:"Erro ao criar integração",description:f.message,variant:"destructive"})}}),A=K({mutationFn:async({id:f,is_active:W})=>{const{error:F}=await E.from("integration_webhooks").update({is_active:W}).eq("id",f);if(F)throw F},onSuccess:()=>{g.invalidateQueries({queryKey:["integration-webhooks-grid"]}),m({title:"Status atualizado!"})}}),P=K({mutationFn:async f=>{const W=crypto.randomUUID().replace(/-/g,""),{data:F,error:Ye}=await E.from("integration_webhooks").update({webhook_secret:W}).eq("id",f).select().single();if(Ye)throw Ye;return F},onSuccess:f=>{m({title:"🔑 Chave regenerada!"}),g.invalidateQueries({queryKey:["integration-webhooks-grid"]}),c(f)}}),a=f=>`https://vcuzkzswgqzwfbmiuvhp.supabase.co/functions/v1/integration-webhook?id=${f.id}&secret=${f.webhook_secret}`,n=f=>{navigator.clipboard.writeText(a(f)),m({title:"📋 URL copiada!"})},y=u.useMemo(()=>{let f=Be.map(W=>{const F=v[W.id];return{...W,webhook:F,status:F?"connected":"disconnected",isActive:F?.is_active??!1,eventsCount:F?.total_events??0,lastSync:F?.last_event_at?he(new Date(F.last_event_at),{addSuffix:!0,locale:te}):void 0}});if(N==="connected"?f=f.filter(W=>W.status==="connected"):N==="available"&&(f=f.filter(W=>W.status==="disconnected")),x){const W=x.toLowerCase();f=f.filter(F=>F.name.toLowerCase().includes(W)||F.description.toLowerCase().includes(W))}return f},[v,N,x]),q=Object.keys(v).length,L=Be.length-q,Xe=f=>{C(f),h(`Webhook ${f.name}`),p(!0)},Me=f=>{const W=v[f.id];W&&(c(W),C(f),r(!0))},js=(f,W)=>{const F=v[f.id];F&&A.mutate({id:F.id,is_active:W})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between",children:[e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Fe,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(D,{placeholder:"Buscar integrações...",value:x,onChange:f=>b(f.target.value),className:"pl-10"})]}),e.jsx(We,{value:N,onValueChange:f=>o(f),children:e.jsxs(qe,{children:[e.jsxs(M,{value:"all",className:"gap-2",children:["Todas",e.jsx(I,{variant:"secondary",className:"ml-1",children:Be.length})]}),e.jsxs(M,{value:"connected",className:"gap-2",children:["Conectadas",e.jsx(I,{variant:"secondary",className:"ml-1 bg-success/20 text-success",children:q})]}),e.jsxs(M,{value:"available",className:"gap-2",children:["Disponíveis",e.jsx(I,{variant:"secondary",className:"ml-1",children:L})]})]})})]}),e.jsx("div",{className:"grid gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:e.jsx(Ae,{mode:"popLayout",children:y.map((f,W)=>e.jsx(X.div,{layout:!0,initial:{opacity:0,scale:.9}
11,animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{delay:W*.05},children:e.jsx(Us,{id:f.id,name:f.name,description:f.description,icon:f.icon,color:f.color,status:f.status,isActive:f.isActive,eventsCount:f.eventsCount,lastSync:f.lastSync,onConnect:()=>Xe(f),onConfigure:()=>Me(f),onToggle:F=>js(f,F)})},f.id))})}),y.length===0&&e.jsxs(X.div,{initial:{opacity:0},animate:{opacity:1},className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"h-16 w-16 rounded-2xl bg-muted flex items-center justify-center mb-4",children:e.jsx(os,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Nenhuma integração encontrada"}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:x?`Nenhum resultado para "${x}"`:"Tente ajustar os filtros"})]}),e.jsx(ne,{open:l,onOpenChange:p,children:e.jsxs(ie,{children:[e.jsxs(ee,{children:[e.jsxs(se,{className:"flex items-center gap-3",children:[d&&e.jsx("span",{className:"text-2xl",children:d.icon}),"Conectar ",d?.name]}),e.jsx(ae,{children:"Configure o webhook para receber eventos desta plataforma automaticamente."})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{htmlFor:"webhook-name",children:"Nome do Webhook"}),e.jsx(D,{id:"webhook-name",value:_,onChange:f=>h(f.target.value),placeholder:"Ex: Hotmart Principal"})]}),e.jsx(j,{className:"w-full",onClick:()=>k.mutate(),disabled:k.isPending,children:k.isPending?"Criando...":"Criar Webhook"})]})]})}),e.jsx(ne,{open:w,onOpenChange:r,children:e.jsxs(ie,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(ee,{children:[e.jsxs(se,{className:"flex items-center gap-3",children:[d&&e.jsx("span",{className:"text-2xl",children:d.icon}),"Configurar ",d?.name]}),e.jsx(ae,{children:"Copie a URL abaixo e configure no painel da plataforma."})]}),S&&e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{children:"URL do Webhook"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(D,{readOnly:!0,value:a(S),className:"font-mono text-xs"}),e.jsx(j,{variant:"outline",size:"icon",onClick:()=>n(S),children:e.jsx(me,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Chave Secreta"}),e.jsxs("p",{className:"text-sm text-muted-foreground font-mono",children:[S.webhook_secret?.slice(0,8),"..."]})]}),e.jsxs(j,{variant:"outline",size:"sm",onClick:()=>P.mutate(S.id),disabled:P.isPending,children:[e.jsx(ce,{className:`h-4 w-4 mr-2 ${P.isPending?"animate-spin":""}`}),"Regenerar"]})]}),e.jsxs("div",{className:"pt-4 border-t space-y-4",children:[d&&e.jsx(Qs,{providerId:d.id,providerName:d.name,providerIcon:d.icon}),e.jsxs(j,{variant:"outline",className:"w-full gap-2",onClick:()=>r(!1),children:[e.jsx(Ne,{className:"h-4 w-4"}),"Ver Documentação"]})]})]})]})})]})}async function Ue(t){const m=performance.now();try{const g=await fetch(t,{method:"HEAD",mode:"no-cors",signal:AbortSignal.timeout(1e4)});return{ok:!0,latency:Math.round(performance.now()-m)}}catch{return{ok:!1,latency:Math.round(performance.now()-m)}}}function Hs({webhookUrl:t,onComplete:m}){const{toast:g}=Q(),[x,b]=u.useState(!1),[N,o]=u.useState(0),[l,p]=u.useState([{name:"Conectividade de Rede",status:"pending"},{name:"API Backend",status:"pending"},{name:"Resposta do Webhook",status:"pending"}]),w="https://vcuzkzswgqzwfbmiuvhp.supabase.co",r=async()=>{b(!0),o(0);const s=[{name:"Conectividade de Rede",status:"testing"},{name:"API Backend",status:"pending"},{name:"Resposta do Webhook",status:"pending"}];p([...s]),o(10);const i=await Ue("https://www.google.com");s[0]={name:"Conectividade de Rede",status:i.ok?i.latency>500?"warning":"success":"failed",latency:i.latency,message:i.ok?i.latency>500?`Lento (${i.latency}ms)`:`OK (${i.latency}ms)`:"Sem conexão"},p([...s]),o(33),s[1].status="testing",p([...s]);const v=await Ue(w);
11if(s[1]={name:"API Backend",status:v.ok?v.latency>1e3?"warning":"success":"failed",latency:v.latency,message:v.ok?v.latency>1e3?`Lento (${v.latency}ms)`:`OK (${v.latency}ms)`:"Falha na conexão"},p([...s]),o(66),s[2].status="testing",p([...s]),t){const P=await Ue(t);s[2]={name:"Resposta do Webhook",status:P.ok?P.latency>2e3?"warning":"success":"failed",latency:P.latency,message:P.ok?P.latency>2e3?`Lento (${P.latency}ms)`:`OK (${P.latency}ms)`:"Falha na conexão"}}else s[2]={name:"Resposta do Webhook",status:"warning",message:"Nenhum URL configurado"};p([...s]),o(100),b(!1);const k=s.every(P=>P.status==="success"),A=s.some(P=>P.status==="failed");g(k?{title:"✅ Todos os testes passaram!",description:"A conectividade está funcionando perfeitamente."}:A?{title:"❌ Alguns testes falharam",description:"Verifique sua conexão e configurações.",variant:"destructive"}:{title:"⚠️ Teste concluído com avisos",description:"Alguns testes apresentaram latência alta."}),m?.(s)},d=()=>{p(l.map(s=>({...s,status:"pending",latency:void 0,message:void 0}))),o(0)},C=s=>{switch(s){case"pending":return e.jsx(re,{className:"h-4 w-4 text-muted-foreground"});case"testing":return e.jsx(B,{className:"h-4 w-4 animate-spin text-primary"});case"success":return e.jsx(Y,{className:"h-4 w-4 text-green-500"});case"warning":return e.jsx(de,{className:"h-4 w-4 text-amber-500"});case"failed":return e.jsx(ue,{className:"h-4 w-4 text-destructive"})}},S=s=>{switch(s){case"pending":return"bg-muted";case"testing":return"bg-primary/10 border-primary/20";case"success":return"bg-green-500/10 border-green-500/20";case"warning":return"bg-amber-500/10 border-amber-500/20";case"failed":return"bg-destructive/10 border-destructive/20"}},c=l.filter(s=>s.status==="success").length,_=l.filter(s=>s.status==="failed").length,h=l.filter(s=>s.status==="warning").length;return e.jsxs(T,{children:[e.jsx(H,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(_s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(G,{className:"text-base",children:"Teste de Conectividade"}),e.jsx(le,{children:"Verifique a saúde da sua integração"})]})]}),e.jsx(j,{onClick:x?void 0:l.some(s=>s.status!=="pending")?d:r,disabled:x,variant:l.some(s=>s.status!=="pending")&&!x?"outline":"default",children:x?e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"h-4 w-4 mr-2 animate-spin"}),"Testando..."]}):l.some(s=>s.status!=="pending")?e.jsxs(e.Fragment,{children:[e.jsx(ce,{className:"h-4 w-4 mr-2"}),"Testar Novamente"]}):e.jsxs(e.Fragment,{children:[e.jsx(we,{className:"h-4 w-4 mr-2"}),"Iniciar Teste"]})})]})}),e.jsxs(z,{className:"space-y-4",children:[x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Cs,{value:N,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:["Executando testes... ",Math.round(N),"%"]})]}),!x&&l.some(s=>s.status!=="pending")&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[_===0?e.jsx(Y,{className:"h-5 w-5 text-green-500"}):e.jsx(de,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm font-medium",children:[c," de ",l.length," testes passaram"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h>0&&`${h} avisos • `,_>0&&`${_} falhas`,h===0&&_===0&&"Tudo funcionando!"]})]})]}),e.jsx("div",{className:"space-y-2",children:e.jsx(Ae,{mode:"popLayout",children:l.map((s,i)=>e.jsxs(X.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:i*.05},className:`flex items-center justify-between p-3 rounded-lg border transition-all ${S(s.status)}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[C(s.status),e.jsx("span",{className:"text-sm font-medium",children:s.name})]}),s.message&&e.jsx(I,{variant:"outline",className:s.status==="success"?"bg-green-500/10 text-green-600 border-green-500/20":s.status==="warning"?"bg-amber-500/10 text-amber-600 border-amber-500/20":s.status==="failed"?"bg-destructive/10 text-destructive border-destructive/20":"",children:s.message})]},s.name))})})]})]})}const ts={hotmart:"bg-orange-500/10 text-orange-600 border-orange-500/20",kiwify:"bg-purple-500/10 text-purple-600 border-purple-500/20",eduzz:"bg-blue-500/10 text-blue-600 border-blue-500/20",monetizze:"bg-green-500/10 text-green-600 border-green-500/20",perfectpay:"bg-pink-500/10 text-pink-600 border-pink-500/20",custom:"bg-muted text-muted-foreground"};function Gs(){const{currentWorkspace:t}=$(),{toast:m}=Q(),[g,x]=u.useState(""),[b,N]=u.useState("all"),[o,l]=u.useState("all"),[p,w]=u.useState(null),{data:r=[],isLoading:d,refetch:C}=V({queryKey:["webhook-delivery-logs",t?.id],queryFn:async()=>
11{if(!t?.id)return[];const{data:i,error:v}=await E.from("webhook_delivery_logs").select("*").eq("workspace_id",t.id).order("created_at",{ascending:!1}).limit(100);if(v)throw v;return(i||[]).map(k=>({id:k.id,webhook_id:k.webhook_id||"",webhook_name:k.webhook_url?new URL(k.webhook_url).hostname:"Webhook",provider:k.event_type?.split(".")[0]||"custom",event_type:k.event_type||"unknown",status:k.status_code&&k.status_code>=200&&k.status_code<300?"success":"failed",request_body:k.request_payload||{},response_body:k.response_body||{},response_status:k.status_code,duration_ms:k.duration_ms,created_at:k.created_at}))},enabled:!!t?.id}),S=r.filter(i=>{const v=i.webhook_name.toLowerCase().includes(g.toLowerCase())||i.event_type.toLowerCase().includes(g.toLowerCase()),k=b==="all"||i.status===b,A=o==="all"||i.provider===o;return v&&k&&A}),c=i=>{navigator.clipboard.writeText(JSON.stringify(i,null,2)),m({title:"📋 JSON copiado!"})},_=i=>{switch(i){case"success":return e.jsx(Y,{className:"h-4 w-4 text-green-500"});case"failed":return e.jsx(ue,{className:"h-4 w-4 text-destructive"});default:return e.jsx(re,{className:"h-4 w-4 text-muted-foreground"})}},h=(i,v)=>{switch(i){case"success":return e.jsxs(I,{className:"bg-green-500/10 text-green-600 border-green-500/20",children:[v||200," OK"]});case"failed":return e.jsxs(I,{className:"bg-destructive/10 text-destructive border-destructive/20",children:[v||"Error"," Falhou"]});default:return e.jsx(I,{variant:"secondary",children:"Pendente"})}},s={total:r.length,success:r.filter(i=>i.status==="success").length,failed:r.filter(i=>i.status==="failed").length,avgLatency:r.length>0?Math.round(r.reduce((i,v)=>i+(v.duration_ms||0),0)/r.length):0};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsx(T,{children:e.jsx(z,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Eventos"}),e.jsx("p",{className:"text-2xl font-bold",children:s.total})]}),e.jsx(ge,{className:"h-8 w-8 text-muted-foreground/50"})]})})}),e.jsx(T,{children:e.jsx(z,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sucesso"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:s.success})]}),e.jsx(Y,{className:"h-8 w-8 text-green-500/50"})]})})}),e.jsx(T,{children:e.jsx(z,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Falhas"}),e.jsx("p",{className:"text-2xl font-bold text-destructive",children:s.failed})]}),e.jsx(ue,{className:"h-8 w-8 text-destructive/50"})]})})}),e.jsx(T,{children:e.jsx(z,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Latência Média"}),e.jsxs("p",{className:"text-2xl font-bold",children:[s.avgLatency,"ms"]})]}),e.jsx(re,{className:"h-8 w-8 text-muted-foreground/50"})]})})})]}),e.jsx(T,{children:e.jsx(z,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fe,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(D,{placeholder:"Buscar por webhook ou evento...",value:g,onChange:i=>x(i.target.value),className:"pl-9"})]}),e.jsxs(ke,{value:b,onValueChange:N,children:[e.jsx(Ce,{className:"w-[180px]",children:e.jsx(_e,{placeholder:"Status"})}),e.jsxs(Se,{children:[e.jsx(R,{value:"all",children:"Todos os status"}),e.jsx(R,{value:"success",children:"Sucesso"}),e.jsx(R,{value:"failed",children:"Falhou"})]})]}),e.jsxs(ke,{value:o,onValueChange:l,children:[e.jsx(Ce,{className:"w-[180px]",children:e.jsx(_e,{placeholder:"Plataforma"})}),e.jsxs(Se,{children:[e.jsx(R,{value:"all",children:"Todas as plataformas"}),e.jsx(R,{value:"hotmart",children:"Hotmart"}),e.jsx(R,{value:"kiwify",children:"Kiwify"}),e.jsx(R,{value:"eduzz",children:"Eduzz"}),e.jsx(R,{value:"monetizze",children:"Monetizze"})]})]}),e.jsx(j,{variant:"outline",size:"icon",onClick:()=>C(),children:e.jsx(ce,{className:"h-4 w-4"})})]})})}
11),e.jsxs(T,{children:[e.jsxs(H,{children:[e.jsxs(G,{className:"flex items-center gap-2",children:[e.jsx(ge,{className:"h-5 w-5"}),"Histórico de Eventos"]}),e.jsxs(le,{children:["Últimos ",S.length," eventos recebidos"]})]}),e.jsx(z,{children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(B,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):S.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ge,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Nenhum evento encontrado"}),e.jsx("p",{className:"text-xs mt-1",children:"Eventos aparecerão aqui quando webhooks forem disparados"})]}):e.jsx("div",{className:"space-y-2",children:e.jsx(Ae,{children:S.map((i,v)=>e.jsx(X.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:v*.03},children:e.jsxs(As,{open:p===i.id,onOpenChange:()=>w(p===i.id?null:i.id),children:[e.jsx(Ps,{asChild:!0,children:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border hover:bg-muted/50 transition-colors cursor-pointer",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[_(i.status),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:i.webhook_name}),e.jsx(I,{variant:"outline",className:ts[i.provider]||ts.custom,children:i.provider}),e.jsx(I,{variant:"outline",className:"font-mono text-xs",children:i.event_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[he(new Date(i.created_at),{addSuffix:!0,locale:te}),i.duration_ms&&` • ${i.duration_ms}ms`]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[h(i.status,i.response_status),p===i.id?e.jsx(Ss,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Is,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Es,{children:e.jsxs("div",{className:"mt-2 p-4 rounded-lg bg-muted/30 border border-dashed space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ee,{className:"h-4 w-4"}),"Request Body"]}),e.jsxs(j,{variant:"ghost",size:"sm",onClick:()=>c(i.request_body),children:[e.jsx(me,{className:"h-3 w-3 mr-1"}),"Copiar"]})]}),e.jsx("pre",{className:"text-xs bg-muted p-3 rounded-lg overflow-x-auto",children:JSON.stringify(i.request_body,null,2)})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ee,{className:"h-4 w-4 rotate-180"}),"Response Body"]}),e.jsxs(j,{variant:"ghost",size:"sm",onClick:()=>c(i.response_body),children:[e.jsx(me,{className:"h-3 w-3 mr-1"}),"Copiar"]})]}),e.jsx("pre",{className:"text-xs bg-muted p-3 rounded-lg overflow-x-auto",children:JSON.stringify(i.response_body,null,2)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground pt-2 border-t",children:[e.jsxs("span",{children:["ID: ",i.id]}),e.jsx("span",{children:He(new Date(i.created_at),"dd/MM/yyyy 'às' HH:mm:ss",{locale:te})})]})]})})]})},i.id))})})})]})]})}const ye=[{id:"hubla",name:"Hubla",color:"bg-emerald-500/10 text-emerald-500 border-emerald-500/20",icon:"🟢"},{id:"hotmart",name:"Hotmart",color:"bg-orange-500/10 text-orange-500 border-orange-500/20",icon:"🔥"},{id:"kiwify",name:"Kiwify",color:"bg-purple-500/10 text-purple-500 border-purple-500/20",icon:"🥝"},{id:"eduzz",name:"Eduzz",color:"bg-blue-500/10 text-blue-500 border-blue-500/20",icon:"📘"},{id:"monetizze",name:"Monetizze",color:"bg-green-500/10 text-green-500 border-green-500/20",icon:"💰"},{id:"perfectpay",name:"PerfectPay",color:"bg-pink-500/10 text-pink-500 border-pink-500/20",icon:"💎"},{id:"ticto",name:"Ticto",color:"bg-cyan-500/10 text-cyan-500 border-cyan-500/20",icon:"🎫"},{id:"braip",name:"Braip",color:"bg-amber-500/10 text-amber-500 border-amber-500/20",icon:"🚀"},{id:"custom",name:"Customizado",color:"bg-muted text-muted-foreground",icon:"⚙️"}],Js=[{id:"zapier",name:"Zapier",description:"Conecte com mais de 5.000 apps",icon:"⚡",color:"bg-orange-500/10 text-orange-500",connected:!1},{id:"make",name:"Make (Integromat)",description:"Automações visuais poderosas",icon:"🔧",color:"bg-violet-500/10 text-violet-500",connected:!1},{id:"n8n",name:"n8n",description:"Automação open-source",icon:"🌐",color:"bg-red-500/10 text-red-500",connected:!1},{id:"pabbly",name:"Pabbly Connect",description:"Integrações sem limites",icon:"🔗",color:"bg-indigo-500/10 text-indigo-500",connected:!1}];function Zs(){const{currentWorkspace:t}=$(),{toast:m}=Q(),g=xe(),[x,b]=u.useState(null),{data:N=[],isLoading:o}=V({queryKey:["integration-webhooks-hub",t?.id],queryFn:async()=>
11{if(!t?.id)return[];const{data:h,error:s}=await E.from("integration_webhooks").select("*").eq("workspace_id",t.id).order("created_at",{ascending:!1});if(s)throw s;return h},enabled:!!t?.id}),l=K({mutationFn:async({name:h,provider:s})=>{if(!t?.id)throw new Error("No workspace");const i=crypto.randomUUID().replace(/-/g,""),{data:v,error:k}=await E.from("integration_webhooks").insert({workspace_id:t.id,name:h||`Webhook ${s}`,provider:s,webhook_secret:i,is_active:!0,events_config:{on_purchase:!0,on_refund:!0,on_subscription_cancel:!0,on_subscription_renewal:!0,on_chargeback:!0}}).select().single();if(k)throw k;return v},onSuccess:()=>{m({title:"✅ Webhook criado com sucesso!"}),g.invalidateQueries({queryKey:["integration-webhooks-hub"]})},onError:h=>{m({title:"Erro ao criar webhook",description:h.message,variant:"destructive"})}}),p=K({mutationFn:async({id:h,is_active:s})=>{const{error:i}=await E.from("integration_webhooks").update({is_active:s}).eq("id",h);if(i)throw i},onSuccess:()=>{g.invalidateQueries({queryKey:["integration-webhooks-hub"]})}}),w=K({mutationFn:async h=>{const{error:s}=await E.from("integration_webhooks").delete().eq("id",h);if(s)throw s},onSuccess:()=>{m({title:"Webhook excluído"}),g.invalidateQueries({queryKey:["integration-webhooks-hub"]})}}),r=K({mutationFn:async h=>{const s=crypto.randomUUID().replace(/-/g,""),{error:i}=await E.from("integration_webhooks").update({webhook_secret:s}).eq("id",h);if(i)throw i},onSuccess:()=>{m({title:"🔑 Chave regenerada com sucesso!"}),g.invalidateQueries({queryKey:["integration-webhooks-hub"]})}}),d=async h=>{b(h.id);try{await new Promise(s=>setTimeout(s,1500)),m({title:"✅ Teste enviado!",description:"O webhook está configurado corretamente."})}catch{m({title:"❌ Falha no teste",description:"Verifique a configuração do webhook.",variant:"destructive"})}finally{b(null)}},C=h=>`https://vcuzkzswgqzwfbmiuvhp.supabase.co/functions/v1/integration-webhook?id=${h.id}&secret=${h.webhook_secret}`,S=h=>{navigator.clipboard.writeText(C(h)),m({title:"📋 URL copiada!"})},c=h=>ye.find(s=>s.id===h)||ye[ye.length-1],_={total:N.length,active:N.filter(h=>h.is_active).length,totalEvents:N.reduce((h,s)=>h+(s.total_events||0),0),providers:new Set(N.map(h=>h.provider)).size};return{webhooks:N,isLoading:o,stats:_,testingWebhook:x,createMutation:l,toggleMutation:p,deleteMutation:w,regenerateSecret:r,testWebhook:d,getWebhookUrl:C,copyWebhookUrl:S,getProviderInfo:c}}function Xs(){const t=Zs(),[m,g]=u.useState("webhooks"),[x,b]=u.useState(!1),[N,o]=u.useState(""),[l,p]=u.useState(""),w=()=>{t.createMutation.mutate({name:l,provider:N}),b(!1),p(""),o("")};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[{label:"Webhooks",value:t.stats.total,icon:pe,color:"primary"},{label:"Ativos",value:t.stats.active,icon:ge,color:"green-500"},{label:"Eventos",value:t.stats.totalEvents,icon:we,color:"blue-500"},{label:"Plataformas",value:t.stats.providers,icon:cs,color:"purple-500"}].map((r,d)=>e.jsx(X.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:d*.1},children:e.jsx(T,{className:`bg-gradient-to-br from-${r.color}/5 to-${r.color}/10 border-${r.color}/20`,children:e.jsx(z,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:r.label}),e.jsx("p",{className:"text-3xl font-bold",children:r.value})]}),e.jsx("div",{className:`h-12 w-12 rounded-xl bg-${r.color}/20 flex items-center justify-center`,children:e.jsx(r.icon,{className:`h-6 w-6 text-${r.color}`})})]})})})},r.label))}),e.jsxs(We,{value:m,onValueChange:g,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qe,{children:[e.jsxs(M,{value:"webhooks",className:"gap-2",children:[e.jsx(pe,{className:"h-4 w-4"}),"Webhooks"]}),e.jsxs(M,{value:"integrations",className:"gap-2",children:[e.jsx(es,{className:"h-4 w-4"}),"Integrações"]}),e.jsxs(M,{value:"logs",className:"gap-2",children:[e.jsx(ge,{className:"h-4 w-4"}),"Logs"]}),e.jsxs(M,{value:"connectivity",className:"gap-2",children:[e.jsx(ss,{className:"h-4 w-4"}),"Teste"]})]}),m==="webhooks"&&e.jsxs(j,{onClick:()=>b(!0),children:[e.jsx(je,{className:"h-4 w-4 mr-2"}),"Novo Webhook"]})]}),e.jsx(U,{value:"webhooks",className:"mt-6",children:t.isLoading?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(B,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):t.webhooks.length===0?e.jsx(T,{className:"border-dashed",children:e.jsxs(z,{className:"flex flex-col items-center py-16",children:[e.jsx("div",{className:"h-16 w-16 rounded-2xl bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(pe,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Nenhum webhook configurado"}),e.jsx("p",{className:"text-muted-foreground text-center mb-6 max-w-md",children:"Configure webhooks para sincronizar automaticamente compradores e assinantes."}),e.jsx("div",{className:"flex flex-wrap gap-2 justify-center mb-6",children:ye.slice(0,6).map(r=>e.jsxs(I,{variant:"outline",className:r.color,children:[r.icon," ",r.name]},r.id))}),e.jsxs(j,{onClick:()=>b(!0),size:"lg",children:[e.jsx(je,{className:"h-5 w-5 mr-2"}),"Configurar Primeiro Webhook"]})]})}):e.jsx("div",{className:"grid gap-4",children:e.jsx(Ae,{children:t.webhooks.map((r,d)=>{const C=t.getProviderInfo(r.provider);return e.jsx(X.div,{initial:{opacity:0,y:20}
11,animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{delay:d*.05},children:e.jsx(T,{className:`transition-all hover:shadow-md ${r.is_active?"":"opacity-60"}`,children:e.jsx(z,{className:"p-6",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 flex-1 min-w-0",children:[e.jsx("div",{className:`h-12 w-12 rounded-xl flex items-center justify-center text-2xl ${C.color} border`,children:C.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold truncate",children:r.name}),e.jsx(I,{variant:"outline",className:C.color,children:C.name}),r.is_active?e.jsxs(I,{className:"bg-green-500/10 text-green-600 border-green-500/20",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-500 mr-1.5 animate-pulse"}),"Ativo"]}):e.jsx(I,{variant:"secondary",children:"Inativo"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Criado em ",He(new Date(r.created_at),"dd/MM/yyyy 'às' HH:mm",{locale:te}),r.last_event_at&&e.jsxs(e.Fragment,{children:[" ","• Último evento: ",he(new Date(r.last_event_at),{addSuffix:!0,locale:te})]})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("code",{className:"flex-1 text-xs bg-muted px-3 py-2 rounded-lg overflow-hidden text-ellipsis whitespace-nowrap",children:t.getWebhookUrl(r)}),e.jsxs(Le,{children:[e.jsx(Re,{asChild:!0,children:e.jsx(j,{variant:"outline",size:"icon",onClick:()=>t.copyWebhookUrl(r),children:e.jsx(me,{className:"h-4 w-4"})})}),e.jsx(Ke,{children:"Copiar URL"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(we,{className:"h-4 w-4"}),r.total_events||0," eventos"]}),r.events_config?.on_purchase&&e.jsx(I,{variant:"outline",className:"text-xs",children:"Compras"}),r.events_config?.on_refund&&e.jsx(I,{variant:"outline",className:"text-xs",children:"Reembolsos"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Le,{children:[e.jsx(Re,{asChild:!0,children:e.jsx(j,{variant:"outline",size:"icon",onClick:()=>t.testWebhook(r),disabled:t.testingWebhook===r.id,children:t.testingWebhook===r.id?e.jsx(B,{className:"h-4 w-4 animate-spin"}):e.jsx(ss,{className:"h-4 w-4"})})}),e.jsx(Ke,{children:"Testar Webhook"})]}),e.jsxs(Le,{children:[e.jsx(Re,{asChild:!0,children:e.jsx(j,{variant:"outline",size:"icon",onClick:()=>t.regenerateSecret.mutate(r.id),disabled:t.regenerateSecret.isPending,children:e.jsx(ce,{className:`h-4 w-4 ${t.regenerateSecret.isPending?"animate-spin":""}`})})}),e.jsx(Ke,{children:"Regenerar Chave"})]}),e.jsx(ze,{checked:r.is_active,onCheckedChange:S=>t.toggleMutation.mutate({id:r.id,is_active:S})}),e.jsx(j,{variant:"ghost",size:"icon",onClick:()=>{confirm("Excluir este webhook?")&&t.deleteMutation.mutate(r.id)},className:"text-destructive hover:text-destructive",children:e.jsx(Pe,{className:"h-4 w-4"})})]})]})})})},r.id)})})})}),e.jsxs(U,{value:"integrations",className:"mt-6",children:[e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:Js.map((r,d)=>e.jsx(X.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:d*.1},children:e.jsx(T,{className:"hover:shadow-md transition-all",children:e.jsx(z,{className:"p-6",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`h-12 w-12 rounded-xl flex items-center justify-center text-2xl ${r.color}`,children:r.icon}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:r.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r.description})]})]}),e.jsxs(j,{variant:"outline",size:"sm",children:[e.jsx(es,{className:"h-4 w-4 mr-2"}),"Conectar"]})]})})})},r.id))}),e.jsx(T,{className:"mt-6 bg-gradient-to-br from-primary/5 to-primary/10 border-primary/20",children:e.jsx(z,{className:"p-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-xl bg-primary/20 flex items-center justify-center",children:e.jsx(Ns,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold",children:"API Pública"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use nossa API REST para integrar com qualquer sistema personalizado"})]}),e.jsxs(j,{children:["Ver Documentação",e.jsx(Ne,{className:"h-4 w-4 ml-2"})]})]})})})]}),e.jsx(U,{value:"logs",className:"mt-6",children:e.jsx(Gs,{})}),e.jsx(U,{value:"connectivity",className:"mt-6",children:e.jsx(Hs,{})})]}),e.jsx(ne,{open:x,onOpenChange:b,children:e.jsxs(ie,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(ee,{className:"pb-4 border-b",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(pe,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(se,{children:"Novo Webhook de Integração"}),e.jsx(ae,{children:"Configure um endpoint para receber eventos de vendas"})]})]})}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Plataforma"}),e.jsx("div",{className:"grid grid-cols-4 gap-2",children:ye.map(r=>e.jsxs("button",{onClick:()=>o(r.id),className:`p-3 rounded-xl border-2 transition-all text-center hover:scale-105 ${N===r.id?"border-primary bg-primary/5":"border-transparent bg-muted/50 hover:border-muted-foreground
11/20"}`,children:[e.jsx("span",{className:"text-2xl block mb-1",children:r.icon}),e.jsx("span",{className:"text-xs font-medium",children:r.name})]},r.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Nome do Webhook"}),e.jsx(D,{value:l,onChange:r=>p(r.target.value),placeholder:"Ex: Curso ABC - Hotmart",className:"h-11"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(j,{variant:"outline",onClick:()=>b(!1),children:"Cancelar"}),e.jsxs(j,{onClick:w,disabled:!N||t.createMutation.isPending,children:[t.createMutation.isPending&&e.jsx(B,{className:"h-4 w-4 mr-2 animate-spin"}),"Criar Webhook"]})]})]})})]})}function Ys(){const{currentWorkspace:t}=$(),m=xe(),[g,x]=u.useState(!1),[b,N]=u.useState(""),[o,l]=u.useState(""),[p,w]=u.useState("hotmart"),[r,d]=u.useState([]),[C,S]=u.useState(""),{data:c=[],isLoading:_}=V({queryKey:["product-mappings",t?.id],queryFn:async()=>{if(!t?.id)return[];const{data:a,error:n}=await E.from("product_group_mappings").select("*").eq("workspace_id",t.id).order("created_at",{ascending:!1});if(n)throw n;return a||[]},enabled:!!t?.id}),{data:h=[]}=V({queryKey:["groups-for-mapping",t?.id],queryFn:async()=>{if(!t?.id)return[];const{data:a,error:n}=await E.from("groups").select("id, name, participant_count, whatsapp_id").eq("workspace_id",t.id).not("instance_id","is",null).order("name");if(n)throw n;return a},enabled:!!t?.id}),s=K({mutationFn:async()=>{if(!t?.id)throw new Error("No workspace");const{error:a}=await E.from("product_group_mappings").insert({workspace_id:t.id,product_id:b,product_name:o,provider:p,group_ids:r,is_active:!0});if(a)throw a},onSuccess:()=>{Oe.success("Mapeamento criado com sucesso!"),m.invalidateQueries({queryKey:["product-mappings"]}),x(!1),v()},onError:a=>{Oe.error("Erro ao criar mapeamento: "+a.message)}}),i=K({mutationFn:async a=>{const{error:n}=await E.from("product_group_mappings").delete().eq("id",a);if(n)throw n},onSuccess:()=>{Oe.success("Mapeamento removido"),m.invalidateQueries({queryKey:["product-mappings"]})}}),v=()=>{N(""),l(""),w("hotmart"),d([])},k=a=>{d(n=>n.includes(a)?n.filter(y=>y!==a):[...n,a])},A=h.filter(a=>a.name.toLowerCase().includes(C.toLowerCase())),P=a=>({hubla:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",hotmart:"bg-orange-500/10 text-orange-600 border-orange-500/20",kiwify:"bg-purple-500/10 text-purple-600 border-purple-500/20",eduzz:"bg-blue-500/10 text-blue-600 border-blue-500/20",monetizze:"bg-green-500/10 text-green-600 border-green-500/20",perfectpay:"bg-pink-500/10 text-pink-600 border-pink-500/20"})[a]||"bg-muted text-muted-foreground";return e.jsxs(T,{children:[e.jsx(H,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(G,{className:"flex items-center gap-2",children:[e.jsx(Qe,{className:"h-5 w-5 text-primary"}),"Mapeamento Produto → Grupos"]}),e.jsx(le,{children:"Configure quais grupos um comprador é adicionado com base no produto"})]}),e.jsxs(j,{onClick:()=>x(!0),children:[e.jsx(je,{className:"h-4 w-4 mr-2"}),"Novo Mapeamento"]})]})}),e.jsx(z,{children:_?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(B,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsxs("div",{className:"flex flex-col items-center py-12 text-center",children:[e.jsx("div",{className:"h-16 w-16 rounded-2xl bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(Ve,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Nenhum mapeamento configurado"}),e.jsx("p",{className:"text-muted-foreground max-w-md mb-4",children:"Crie mapeamentos para adicionar compradores automaticamente aos grupos corretos com base no produto adquirido."}),e.jsxs(j,{onClick:()=>x(!0),children:[e.jsx(je,{className:"h-4 w-4 mr-2"}),"Criar Primeiro Mapeamento"]})]}):e.jsxs(ds,{children:[e.jsx(ms,{children:e.jsxs(Ie,{children:[e.jsx(J,{children:"Produto"}),e.jsx(J,{children:"Plataforma"}),e.jsx(J,{children:"Grupos"}),e.jsx(J,{className:"w-[100px]",children:"Ações"})]})}),e.jsx(us,{children:c.map(a=>e.jsxs(Ie,{children:[e.jsx(Z,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:a.product_name}),e.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:a.product_id})]})}),e.jsx(Z,{children:e.jsx(I,{variant:"outline",className:P(a.provider),children:a.provider})}),e.jsx(Z,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.group_ids.slice(0,3).map(n=>{const y=h.find(q=>q.id===n);return e.jsx(I,{variant:"secondary",className:"text-xs",children:y?.name||"Grupo removido"},n)}),a.group_ids.length>3&&e.jsxs(I,{variant:"secondary",className:"text-xs",children:["+",a.group_ids.length-3]})]})}),e.jsx(Z,{children:e.jsx(j,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Remover este mapeamento?")&&i.mutate(a.id)},children:e.jsx(Pe,{className:"h-4 w-4"})})})]},a.id))})]})}),e.jsx(ne,{open:g,onOpenChange:x,children:e.jsxs(ie,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(ee,{children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Qe,{className:"h-5 w-5 text-primary"}),"Novo Mapeamento de Produto"]}),e.jsx(ae,{children:"Vincule um produto a um ou mais grupos para adicionar compradores automaticamente"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"ID do Produto"}),e.jsx(D,{value:b,onChange:a=>N(a.target.value),placeholder:"Ex: prod_abc123"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Plataforma"}),e.jsxs("select",{value:p,onChange:a=>w(a.target.value),className:"w-full h-10 rounded-md border bg-background px-3 text-sm",children:[e.jsx("option",{value:"hubla",children:"Hubla"}),e.jsx("option",{value:"hotmart",children:"Hotmart"}),e.jsx("option",{value:"kiwify",children:"Kiwify"}),e.jsx("option",{value:"eduzz",children:"Eduzz"}),e.jsx("option",{value:"monetizze",children:"Monetizze"}),e.jsx("option",{value:"perfectpay",children:"PerfectPay"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Nome do Produto"}),e.jsx(D,{value:o,onChange:a=>
11l(a.target.value),placeholder:"Ex: Curso de Marketing Digital"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Grupos de Destino"}),e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Fe,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(D,{value:C,onChange:a=>S(a.target.value),placeholder:"Buscar grupos...",className:"pl-10"})]}),e.jsx(ls,{className:"h-[200px] border rounded-lg p-2",children:A.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsx("p",{className:"text-sm",children:"Nenhum grupo encontrado"})}):e.jsx("div",{className:"space-y-1",children:A.map(a=>e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-all ${r.includes(a.id)?"bg-primary/10 border border-primary/20":"hover:bg-muted"}`,onClick:()=>k(a.id),children:[e.jsx(Ge,{checked:r.includes(a.id),onCheckedChange:()=>k(a.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:a.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.participant_count||0," participantes"]})]})]},a.id))})}),r.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r.length," grupo(s) selecionado(s)"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(j,{variant:"outline",onClick:()=>x(!1),children:"Cancelar"}),e.jsxs(j,{onClick:()=>s.mutate(),disabled:!b||!o||r.length===0||s.isPending,children:[s.isPending&&e.jsx(B,{className:"h-4 w-4 mr-2 animate-spin"}),"Criar Mapeamento"]})]})]})})]})}const $e=[{id:"hotmart",name:"Hotmart",icon:"🔥"},{id:"kiwify",name:"Kiwify",icon:"🥝"},{id:"eduzz",name:"Eduzz",icon:"📚"}],ea={processed:"default",received:"secondary",failed:"destructive",error:"destructive"};function sa(){const{currentWorkspace:t}=$(),{toast:m}=Q(),g=xe(),[x,b]=u.useState("all"),[N,o]=u.useState(!1),[l,p]=u.useState(null),{data:w=[]}=V({queryKey:["platform-configs",t?.id],queryFn:async()=>{if(!t?.id)return[];const{data:s,error:i}=await E.from("platform_webhook_configs").select("*").eq("workspace_id",t.id);if(i)throw i;return s||[]},enabled:!!t?.id}),{data:r=[],isLoading:d,refetch:C}=V({queryKey:["platform-sync-logs",t?.id,x],queryFn:async()=>{if(!t?.id)return[];let s=E.from("platform_sync_logs").select("*").eq("workspace_id",t.id).order("created_at",{ascending:!1}).limit(100);x!=="all"&&(s=s.eq("platform",x));const{data:i,error:v}=await s;if(v)throw v;return i||[]},enabled:!!t?.id}),S=Object.fromEntries(w.map(s=>[s.platform,s])),c=K({mutationFn:async({platform:s,isActive:i})=>{if(!t?.id)throw new Error("No workspace");const v=S[s];if(v){const{error:k}=await E.from("platform_webhook_configs").update({is_active:i}).eq("id",v.id);if(k)throw k}else{const k=crypto.randomUUID().replace(/-/g,""),{error:A}=await E.from("platform_webhook_configs").insert({workspace_id:t.id,platform:s,is_active:!0,webhook_secret:k});if(A)throw A}},onSuccess:()=>{g.invalidateQueries({queryKey:["platform-configs"]}),m({title:"Configuração atualizada"})}}),_=s=>{const i="https://vcuzkzswgqzwfbmiuvhp.supabase.co",k=S[s]?.webhook_secret||"";return`${i}/functions/v1/platform-sync?platform=${s}&workspace_id=${t?.id}&secret=${k}`},h={total:r.length,processed:r.filter(s=>s.status==="processed").length,received:r.filter(s=>s.status==="received").length,failed:r.filter(s=>s.status==="failed"||s.status==="error").length};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsx(oe,{title:"Eventos",value:h.total,icon:e.jsx(fs,{className:"h-5 w-5"}),subtitle:"Total recebidos",gradient:"primary"}),e.jsx(oe,{title:"Processados",value:h.processed,icon:e.jsx(Je,{className:"h-5 w-5"}),subtitle:"Com ação",gradient:"green"}),e.jsx(oe,{title:"Recebidos",value:h.received,icon:e.jsx(re,{className:"h-5 w-5"}),subtitle:"Sem ação",gradient:"blue"}),e.jsx(oe,{title:"Falhas",value:h.failed,icon:e.jsx(ue,{className:"h-5 w-5"}),subtitle:"Com erro",gradient:"orange"})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:$e.map(s=>{const i=S[s.id],v=i?.is_active??!1;return e.jsxs(T,{children:[e.jsx(H,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(G,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-xl",children:s.icon}),s.name]}),e.jsx(ze,{checked:v,onCheckedChange:k=>c.mutate({platform:s.id,isActive:k})})]})}),e.jsxs(z,{children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx(I,{variant:v?"default":"secondary",children:v?"Ativo":"Inativo"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[i?.events_count||0," eventos"]})]}),v&&e.jsx(j,{variant:"outline",size:"sm",className:"w-full mt-3",onClick:()=>{navigator.clipboard.writeText(_(s.id)),m({title:"URL copiada!"})},children:"Copiar URL do Webhook"})]})]},s.id)})}),e.jsxs(T,{children:[e.jsx(H,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(G,{className:"text-base",children:"Logs de Sincronização"}),e.jsx(le,{children:"Eventos recebidos das plataformas"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ke,{value:x,onValueChange:b,children:[e.jsx(Ce,{className:"w-[140px]",children:e.jsx(_e,{})}),e.jsxs(Se,{children:[e.jsx(R,{value:"all",children:"Todas"}),$e.map(s=>e.jsx(R,{value:s.id,children:s.name},s.id))]})]}),e.jsx(j,{variant:"outline",size:"sm",onClick:()=>C(),children:e.jsx(ce,{className:"h-4 w-4"})})]})]})}),e.jsx(z,{children:d?e.jsx("div",{className:"text-center py-6 text-muted-foreground",children:"Carregando..."}):r.length===0?e.jsx("div",{className:"text-center py-6 text-muted-foreground",children:"Nenhum evento recebido ainda"}):e.jsx("div",{className:"space-y-2 max-h-[400px] overflow-y-auto",children:r.map(s=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("span",{className:"text-lg",children:$e.find(i=>i.id===s.platform)?.icon||"📦"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(I,{variant:"outline",className:"text-xs",children:s.event_type}),e.jsx(I,{variant:ea[s.status]||"secondary",className:"text-xs",children:s.status})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[s.customer_name&&e.jsx("span",{children:s.customer_name}),s.product_name&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{children:s.product_name})]}),e.jsx("span",{children:"•"}
11),e.jsx("span",{children:he(new Date(s.created_at),{addSuffix:!0,locale:te})})]})]})]}),s.action_taken&&s.action_taken!=="logged"&&e.jsx(I,{variant:"outline",className:"text-xs shrink-0 ml-2",children:s.action_taken.startsWith("add")?"➕ Grupo":"➖ Grupo"})]},s.id))})})]})]})}const be=[{title:"Criar Facebook App",description:"Crie um aplicativo no Meta for Developers para acessar a API do WhatsApp."},{title:"Configurar WhatsApp",description:"Adicione o produto WhatsApp ao seu app e configure um número de telefone."},{title:"Obter Credenciais",description:"Copie o Phone Number ID, WABA ID e o Token de acesso permanente."},{title:"Validar Conexão",description:"Vamos testar se suas credenciais estão funcionando corretamente."}];function aa({open:t,onOpenChange:m,onSuccess:g}){const{currentWorkspace:x}=$(),{toast:b}=Q(),N=xe(),[o,l]=u.useState(0),[p,w]=u.useState(""),[r,d]=u.useState(""),[C,S]=u.useState(""),[c,_]=u.useState(null),h=()=>{l(0),w(""),d(""),S(""),_(null)},s=K({mutationFn:async()=>{const{data:a,error:n}=await E.functions.invoke("meta-whatsapp",{body:{action:"check_status",workspaceId:x?.id,data:{phoneNumberId:r.trim()}}});if(n)throw n;if(a?.error)throw new Error(a.error);return a},onSuccess:a=>{_({success:!0,data:a})},onError:a=>{_({success:!1,error:a.message})}}),i=K({mutationFn:async()=>{if(!x?.id)throw new Error("Workspace não encontrado");const a=`meta_${r.trim()}`,{data:n,error:y}=await E.from("whatsapp_instances").insert({workspace_id:x.id,name:p.trim()||c?.data?.verifiedName||"WhatsApp Oficial",instance_key:a,provider:"meta_official",meta_phone_number_id:r.trim(),meta_waba_id:C.trim(),status:"connected",phone_number:c?.data?.displayPhoneNumber||null,profile_name:c?.data?.verifiedName||null}).select().single();if(y)throw y;return n},onSuccess:()=>{N.invalidateQueries({queryKey:["meta-instances"]}),N.invalidateQueries({queryKey:["whatsapp_instances"]}),b({title:"Instância criada com sucesso!"}),m(!1),h(),g?.()},onError:a=>{b({title:"Erro",description:a.message,variant:"destructive"})}}),v=a=>{navigator.clipboard.writeText(a),b({title:"Copiado!"})},k=()=>{switch(o){case 0:return!0;case 1:return!0;case 2:return r.trim().length>5&&C.trim().length>5;case 3:return c?.success;default:return!1}},A=()=>{o===2?(l(3),_(null),setTimeout(()=>s.mutate(),300)):o===3&&c?.success?i.mutate():l(a=>Math.min(a+1,be.length-1))},P="https://vcuzkzswgqzwfbmiuvhp.supabase.co/functions/v1/meta-whatsapp-webhook";return e.jsx(ne,{open:t,onOpenChange:a=>{a||h(),m(a)},children:e.jsxs(ie,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ee,{children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-5 w-5 text-emerald-500"}),"Configurar WhatsApp Business API"]}),e.jsx(ae,{children:"Siga o passo a passo para conectar sua conta oficial"})]}),e.jsx("div",{className:"flex items-center gap-1 py-2",children:be.map((a,n)=>e.jsxs("div",{className:"flex items-center gap-1 flex-1",children:[e.jsx("div",{className:`flex items-center justify-center h-7 w-7 rounded-full text-xs font-bold transition-colors shrink-0 ${n<o?"bg-emerald-500 text-white":n===o?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:n<o?e.jsx(Y,{className:"h-4 w-4"}):n+1}),n<be.length-1&&e.jsx("div",{className:`h-0.5 flex-1 transition-colors ${n<o?"bg-emerald-500":"bg-muted"}`})]},n))}),e.jsxs("div",{className:"py-2",children:[e.jsx("h4",{className:"font-semibold text-sm mb-1",children:be[o].title}),e.jsx("p",{className:"text-xs text-muted-foreground mb-4",children:be[o].description}),o===0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(T,{className:"bg-muted/30",children:e.jsxs(z,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ve,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"1. Acesse o Meta for Developers"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Faça login com sua conta do Facebook vinculada ao Business Manager."})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ve,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:'2. Crie um novo App do tipo "Business"'}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Selecione "Outros" → "Business" e dê um nome ao app.'})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ve,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"3. Vincule ao seu Business Manager"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Selecione o portfólio de negócios correto durante a criação."})]})]})]})}),e.jsx(j,{variant:"outline",className:"gap-2 w-full",asChild:!0,children:e.jsxs("a",{href:"https://developers.facebook.com/apps/",target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ne,{className:"h-4 w-4"}),"Abrir Meta for Developers"]})})]}),o===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(T,{className:"bg-muted/30",children:e.jsxs(z,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ve,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:'1. Adicione o produto "WhatsApp"'}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'No dashboard do app, clique em "Adicionar produto" e selecione WhatsApp.'})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ve,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"2. Configure o Webhook"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Cole a URL abaixo no campo "URL de retorno de chamada" e use seu token de verificação.'})]})]})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-xs",children:"URL do Webhook (cole no Meta)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(D,{value:P,readOnly:!0,className:"font-mono text-xs"}),e.jsx(j,{variant:"outline",size:"icon",onClick:()=>v(P),children:e.jsx(me,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Assine os campos: ",e.jsx("strong",{children:"messages"})," e ",e.jsx("strong",{children:"message_template_status_update"})]})]}),e.jsx(j,{variant:"outline",className:"gap-2 w-full",asChild:!0,children:e.jsxs("a",{href:"https://developers.facebook.com/apps/",target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ne,{className:"h-4 w-4"}),"Abrir Dashboard do App"]})})]}),o===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(T,{className:"bg-muted/30",children:e.jsxs(z,{className:"p-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:["Encontre essas informações em ",e.jsx("strong",{children:"WhatsApp → Configuração da API"})," no dashboard do seu app Meta."]}),e.jsx(j,{variant:"outline",size:"sm",className:"gap-2",asChild:!0,children:e.jsxs("a",{href:"https://business.facebook.com/settings/whatsapp-business-accounts/",target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ne,{className:"h-3.5 w-3.5"}),"Abrir Meta Business Suite"]})})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{children:"Nome da Instância"}),e.jsx(D,{value:p,onChange:a=>w(a.target.value),placeholder:"Ex: Atendimento Oficial"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{children:"Phone Number ID *"}),e.jsx(D,{value:r,onChange:a=>d(a.target.value),placeholder:"Ex: 123456789012345",className:"font-mono"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"ID numérico do número de telefone registrado na API"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{children:"WABA ID *"}),e.jsx(D,{value:C,onChange:a=>
11S(a.target.value),placeholder:"Ex: 987654321098765",className:"font-mono"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"ID da sua WhatsApp Business Account (encontrado em Business Settings)"})]})]}),o===3&&e.jsxs("div",{className:"space-y-4",children:[s.isPending&&e.jsx(T,{className:"bg-muted/30",children:e.jsxs(z,{className:"p-6 flex flex-col items-center justify-center gap-3",children:[e.jsx(B,{className:"h-8 w-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Validando suas credenciais..."})]})}),c?.success&&e.jsx(T,{className:"border-emerald-500/30 bg-emerald-500/5",children:e.jsxs(z,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{className:"h-5 w-5 text-emerald-500"}),e.jsx("span",{className:"font-semibold text-sm text-emerald-700 dark:text-emerald-400",children:"Conexão verificada!"})]}),c.data?.verifiedName&&e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Nome verificado:"})," ",e.jsx("strong",{children:c.data.verifiedName})]}),c.data.displayPhoneNumber&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Número:"})," ",e.jsx("strong",{children:c.data.displayPhoneNumber})]}),c.data.qualityRating&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Qualidade:"})," ",e.jsx(I,{variant:"outline",children:c.data.qualityRating})]})]})]})}),c&&!c.success&&e.jsx(T,{className:"border-destructive/30 bg-destructive/5",children:e.jsxs(z,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{className:"h-5 w-5 text-destructive"}),e.jsx("span",{className:"font-semibold text-sm text-destructive",children:"Falha na validação"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c.error}),e.jsxs(j,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>{_(null),s.mutate()},children:[e.jsx(B,{className:"h-3.5 w-3.5"}),"Tentar novamente"]})]})})]})]}),e.jsxs(fe,{className:"flex-row justify-between sm:justify-between",children:[e.jsxs(j,{variant:"ghost",onClick:()=>o===0?m(!1):l(a=>a-1),disabled:i.isPending,children:[e.jsx(Ws,{className:"h-4 w-4 mr-1"}),o===0?"Cancelar":"Voltar"]}),e.jsxs(j,{onClick:A,disabled:!k()||i.isPending||s.isPending,children:[i.isPending&&e.jsx(B,{className:"h-4 w-4 mr-2 animate-spin"}),o===3&&c?.success?"Criar Instância":"Próximo",o<3&&e.jsx(Ee,{className:"h-4 w-4 ml-1"})]})]})]})})}function ta({open:t,onOpenChange:m,onSuccess:g}){const{currentWorkspace:x}=$(),{toast:b}=Q(),N=xe(),[o,l]=u.useState("idle"),[p,w]=u.useState(null),[r,d]=u.useState(""),[C,S]=u.useState(""),{data:c,isLoading:_}=V({queryKey:["platform-meta-config"],queryFn:async()=>{const{data:A,error:P}=await E.from("platform_settings").select("value").eq("key","meta_whatsapp_official").maybeSingle();if(P)throw P;if(A?.value&&typeof A.value=="object"){const a=A.value;return{appId:a.app_id||"",configId:a.config_id||""}}return null},enabled:t});u.useEffect(()=>{t&&!_&&(c?.appId?o==="no_config"&&l("idle"):l("no_config"))},[t,_,c]);const h=()=>{l("idle"),w(null),d(""),S("")},s=u.useCallback(A=>new Promise((P,a)=>{if(!A){a(new Error("Facebook App ID não configurado pelo administrador"));return}if(window.FB){window.FB.init({appId:A,cookie:!0,xfbml:!0,version:"v21.0"}),window.FB.AppEvents.logPageView(),P();return}if(window.fbAsyncInit=function(){window.FB.init({appId:A,cookie:!0,xfbml:!0,version:"v21.0"}),window.FB.AppEvents.logPageView(),P()},!document.getElementById("facebook-jssdk")){const n=document.getElementsByTagName("script")[0],y=document.createElement("script");y.id="facebook-jssdk",y.src="https://connect.facebook.net/en_US/sdk.js",y.onerror=()=>a(new Error("Falha ao carregar Facebook SDK")),n?.parentNode?.insertBefore(y,n)||document.head.appendChild(y)}}),[]),i=async()=>{if(!c?.appId){l("no_config");return}l("loading"),d("");try{await s(c.appId);const A=new Promise(a=>{const n=setTimeout(()=>a({}),12e4),y=q=>{if(!(q.origin!=="https://www.facebook.com"&&q.origin!=="https://web.facebook.com"))try{const L=typeof q.data=="str
11ing"?JSON.parse(q.data):q.data;L.type==="WA_EMBEDDED_SIGNUP"&&(clearTimeout(n),window.removeEventListener("message",y),a(L.data||{}))}catch{}};window.addEventListener("message",y)}),P={scope:"whatsapp_business_management,whatsapp_business_messaging,business_management",extras:{setup:{},featureType:"",sessionInfoVersion:"3"}};c.configId&&(P.config_id=c.configId),window.FB.login(a=>{a.authResponse?.accessToken?A.then(n=>{v(a.authResponse.accessToken,n)}):(l("error"),d("Login cancelado pelo usuário."))},P)}catch(A){l("error"),d(A.message||"Erro ao inicializar Facebook SDK")}},v=async(A,P)=>{try{const{data:a,error:n}=await E.functions.invoke("meta-exchange-token",{body:{action:"exchange_token",accessToken:A,workspaceId:x?.id,embeddedPhoneNumberId:P?.phone_number_id,embeddedWabaId:P?.waba_id}});if(n)throw n;if(a?.error&&!a?.wabaId){l("error"),d(a.error);return}a?.wabaId&&a?.phoneNumberId?(w({wabaId:a.wabaId,wabaName:a.wabaName,phoneNumberId:a.phoneNumberId,verifiedName:a.verifiedName,displayPhone:a.displayPhone,qualityRating:a.qualityRating,businessId:a.businessId,businessName:a.businessName,accessToken:a.accessToken,isClientWaba:a.isClientWaba}),S(a.verifiedName||a.wabaName||"WhatsApp Oficial"),l("detected")):(l("error"),d("Não foi possível detectar sua conta WhatsApp Business automaticamente. Verifique se completou todas as etapas e tente novamente."))}catch(a){l("error"),d(a.message||"Erro ao processar autorização")}},k=K({mutationFn:async()=>{if(!x?.id||!p?.wabaId||!p?.phoneNumberId)throw new Error("Dados incompletos");const{data:A,error:P}=await E.functions.invoke("meta-exchange-token",{body:{action:"provision_waba",workspaceId:x.id,wabaId:p.wabaId,phoneNumberId:p.phoneNumberId,accessToken:p.accessToken,instanceName:C.trim()||"WhatsApp Oficial",displayPhone:p.displayPhone,verifiedName:p.verifiedName}});if(P)throw P;if(A?.error)throw new Error(A.error);return A},onSuccess:()=>{N.invalidateQueries({queryKey:["meta-instances"]}),N.invalidateQueries({queryKey:["whatsapp_instances"]}),b({title:"WhatsApp Business conectado com sucesso! 🎉"}),m(!1),h(),g?.()},onError:A=>{b({title:"Erro",description:A.message,variant:"destructive"})}});return e.jsx(ne,{open:t,onOpenChange:A=>{A||h(),m(A)},children:e.jsxs(ie,{className:"sm:max-w-[520px] max-h-[85vh] overflow-y-auto",children:[e.jsxs(ee,{children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Te,{className:"h-5 w-5 text-primary"}),"Conectar WhatsApp Business"]}),e.jsx(ae,{children:"Conecte seu número WhatsApp Business em poucos cliques"})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[_&&e.jsx(T,{className:"bg-muted/30",children:e.jsxs(z,{className:"p-8 flex flex-col items-center gap-3",children:[e.jsx(B,{className:"h-8 w-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando configurações..."})]})}),o==="no_config"&&!_&&e.jsx(T,{className:"border-amber-500/30 bg-amber-500/5",children:e.jsxs(z,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{className:"h-5 w-5 text-amber-500"}),e.jsx("span",{className:"font-semibold text-sm text-amber-700 dark:text-amber-400",children:"Configuração pendente"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A integração com a API Oficial do WhatsApp ainda não foi configurada pelo administrador da plataforma. Entre em contato com o suporte para habilitar essa funcionalidade."})]})}),o==="idle"&&!_&&c?.appId&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(T,{className:"bg-accent/50 border-border/50",children:e.jsxs(z,{className:"p-4 flex items-start gap-3",children:[e.jsx(qs,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsx("p",{children:"Clique no botão abaixo para iniciar a conexão."}),e.jsxs("p",{children:["Você será redirecionado para o Facebook onde poderá ",e.jsx("strong",{children:"selecionar ou criar"})," sua conta WhatsApp Business e escolher o número."]})]})]})}),e.jsxs(j,{onClick:i,className:"w-full gap-2",size:"lg",children:[e.jsx(Te,{className:"h-4 w-4"}),"Conectar com Facebook"]})]}),o==="loading"&&e.jsx(T,{className:"bg-muted/30",children:e.jsxs(z,{className:"p-8 flex flex-col items-center gap-3",children:[e.jsx(B,{className:"h-8 w-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Processando autorização..."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Complete o fluxo na janela popup da Meta"})]})}),o==="detected"&&p&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(T,{className:"border-emerald-500/30 bg-emerald-500/5",children:e.jsxs(z,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{className:"h-5 w-5 text-emerald-500"}),e.jsx("span",{className:"font-semibold text-sm text-emerald-700 dark:text-emerald-400",children:"WhatsApp Business detectado!"})]}),e.jsxs("div",{className:"grid gap-2 text-sm",children:[p.businessName&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Empresa:"}),e.jsx("strong",{children:p.businessName})]}),p.verifiedName&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Nome verificado:"}),e.jsx("strong",{children:p.verifiedName})]}),p.displayPhone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Número:"}),e.jsx("strong",{children:p.displayPhone})]})]})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{children:"Nome da Instância"}),e.jsx(D,{value:C,onChange:A=>S(A.target.value),placeholder:"WhatsApp Oficial"})]})]}),o==="error"&&e.jsx(T,{className:"border-destructive/30 bg-destructive/5",children:e.jsxs(z,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{className:"h-5 w-5 text-destructive"}),e.jsx("span",{className:"font-semibold text-sm text-destructive",children:"Erro na conexão"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r}),e.jsx(j,{variant:"outline",size:"sm",onClick:()=>l("idle"),children:"Tentar novamente"})]})})]}),e.jsxs(fe,{children:[e.jsx(j,{variant:"outline",onClick:()=>{m(!1),h()},children:"Cancelar"}),o==="detected"&&e.jsxs(j,{onClick:()=>k.mutate(),disabled:k.isPending,className:"gap-2",children:[k.isPending?e.jsx(B,{className:"h-4 w-4 animate-spin"}):e.jsx(we,{className:"h-4 w-4"}),"Ativar WhatsApp"]})]})]})})}function ra({open:t,onOpenChange:m,template:g,instances:x,workspaceId:b}){const{toast:N}=Q(),[o,l]=u.useState(""),p=K({mutationFn:async()=>
11{if(!g||!o.trim())throw new Error("Preencha todos os campos");const w=x.find(C=>C.id===g.instance_id);if(!w)throw new Error("Instância não encontrada");const{data:r,error:d}=await E.functions.invoke("meta-whatsapp",{body:{action:"send_template",workspaceId:b,data:{phoneNumberId:w.meta_phone_number_id,to:o.replace(/\D/g,""),templateName:g.template_name,language:g.language}}});if(d)throw d;if(r?.error)throw new Error(r.error);return r},onSuccess:()=>{N({title:"Template enviado!"}),m(!1),l("")},onError:w=>{N({title:"Erro ao enviar",description:w.message,variant:"destructive"})}});return e.jsx(ne,{open:t,onOpenChange:m,children:e.jsxs(ie,{children:[e.jsxs(ee,{children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4"}),"Enviar Template"]}),e.jsxs(ae,{children:["Template: ",e.jsx("strong",{children:g?.template_name})," (",g?.language,")"]})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{children:"Número do Destinatário *"}),e.jsx(D,{value:o,onChange:w=>l(w.target.value),placeholder:"5511999999999",className:"font-mono"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Número com código do país, sem espaços ou caracteres especiais"})]})}),e.jsxs(fe,{children:[e.jsx(j,{variant:"outline",onClick:()=>m(!1),children:"Cancelar"}),e.jsxs(j,{onClick:()=>p.mutate(),disabled:p.isPending,children:[p.isPending&&e.jsx(B,{className:"h-4 w-4 mr-2 animate-spin"}),"Enviar"]})]})]})})}function na(){const{currentWorkspace:t}=$(),{toast:m}=Q(),g=xe(),[x,b]=u.useState(!1),[N,o]=u.useState(!1),[l,p]=u.useState(!1),[w,r]=u.useState(null),{data:d=[],isLoading:C}=V({queryKey:["meta-instances",t?.id],queryFn:async()=>{if(!t?.id)return[];const{data:s,error:i}=await E.from("whatsapp_instances").select("*").eq("workspace_id",t.id).eq("provider","meta_official").order("created_at",{ascending:!1});if(i)throw i;return s},enabled:!!t?.id}),{data:S=[]}=V({queryKey:["meta-templates",t?.id],queryFn:async()=>{if(!t?.id)return[];const{data:s,error:i}=await E.from("whatsapp_message_templates").select("*").eq("workspace_id",t.id).order("template_name");if(i)throw i;return s},enabled:!!t?.id}),c=K({mutationFn:async s=>{const{data:i,error:v}=await E.functions.invoke("meta-whatsapp",{body:{action:"sync_templates",workspaceId:t?.id,instanceId:s.id,data:{wabaId:s.meta_waba_id}}});if(v)throw v;if(i?.error)throw new Error(i.error);return i},onSuccess:s=>{g.invalidateQueries({queryKey:["meta-templates"]}),m({title:`${s.synced} templates sincronizados!`})},onError:s=>{m({title:"Erro ao sincronizar",description:s.message,variant:"destructive"})}}),_=K({mutationFn:async s=>{const{error:i}=await E.from("whatsapp_instances").delete().eq("id",s);if(i)throw i},onSuccess:()=>{g.invalidateQueries({queryKey:["meta-instances"]}),g.invalidateQueries({queryKey:["whatsapp_instances"]}),m({title:"Instância removida"})},onError:s=>{m({title:"Erro",description:s.message,variant:"destructive"})}}),h=s=>{switch(s){case"APPROVED":return e.jsx(Y,{className:"h-3.5 w-3.5 text-emerald-500"});case"PENDING":return e.jsx(re,{className:"h-3.5 w-3.5 text-amber-500"});case"REJECTED":return e.jsx(ue,{className:"h-3.5 w-3.5 text-destructive"});default:return null}};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center justify-between flex-wrap gap-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-emerald-500/10 flex items-center justify-center",children:e.jsx(Ms,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"WhatsApp Business API"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Conecte seu número via API Oficial da Meta"})]})]})}),d.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:d.map(s=>
11e.jsxs(T,{className:"relative group",children:[e.jsxs(H,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(G,{className:"text-base flex items-center gap-2",children:s.name}),e.jsxs(I,{variant:"success",className:"gap-1",children:[e.jsx(Y,{className:"h-3 w-3"}),"Conectado"]})]}),e.jsxs(le,{className:"space-y-1",children:[s.phone_number&&e.jsxs("span",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(hs,{className:"h-3 w-3"}),s.phone_number]}),s.profile_name&&e.jsxs("span",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(xs,{className:"h-3 w-3"}),s.profile_name]})]})]}),e.jsxs(z,{className:"flex gap-2",children:[e.jsxs(j,{variant:"outline",size:"sm",className:"gap-2",disabled:c.isPending,onClick:()=>c.mutate(s),children:[e.jsx(ce,{className:`h-3.5 w-3.5 ${c.isPending?"animate-spin":""}`}),"Sync Templates"]}),e.jsx(j,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{confirm("Remover esta instância?")&&_.mutate(s.id)},children:e.jsx(Pe,{className:"h-3.5 w-3.5"})})]})]},s.id))}),e.jsxs(j,{variant:"outline",onClick:()=>o(!0),className:"gap-2",children:[e.jsx(Te,{className:"h-4 w-4"}),"Conectar outro número"]})]}):e.jsx(T,{className:"border-dashed",children:e.jsxs(z,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(cs,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h4",{className:"font-medium mb-1",children:"Nenhum WhatsApp conectado"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-6 max-w-md",children:"Conecte seu WhatsApp Business em poucos cliques. Basta fazer login com o Facebook e selecionar seu número."}),e.jsxs("div",{className:"flex gap-3 flex-wrap justify-center",children:[e.jsxs(j,{onClick:()=>o(!0),className:"gap-2",size:"lg",children:[e.jsx(Te,{className:"h-4 w-4"}),"Conectar WhatsApp"]}),e.jsxs(j,{variant:"ghost",size:"sm",onClick:()=>b(!0),className:"gap-2 text-muted-foreground",children:[e.jsx(Ts,{className:"h-4 w-4"}),"Configuração manual"]})]})]})}),S.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(zs,{}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Ds,{className:"h-4 w-4"}),"Templates (",S.length,")"]}),e.jsx(ls,{className:"max-h-[400px]",children:e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:S.map(s=>e.jsx(T,{className:"cursor-pointer hover:border-primary/30 transition-colors",onClick:()=>{r(s),p(!0)},children:e.jsxs(z,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:s.template_name}),h(s.status)]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:"outline",className:"text-xs",children:s.language}),s.category&&e.jsx(I,{variant:"secondary",className:"text-xs",children:s.category})]})]})},s.id))})})]})]}),e.jsx(aa,{open:x,onOpenChange:b}),e.jsx(ta,{open:N,onOpenChange:o}),e.jsx(ra,{open:l,onOpenChange:p,template:w,instances:d,workspaceId:t?.id})]})}const ia=[{id:"read",label:"Leitura",description:"Ler grupos, contatos e métricas"},{id:"write",label:"Escrita",description:"Criar e editar grupos, contatos"},{id:"messages",label:"Mensagens",description:"Enviar mensagens e broadcasts"},{id:"admin",label:"Administração",description:"Acesso total à API"}];function oa(){const{currentWorkspace:t,user:m}=$(),{toast:g}=Q(),[x,b]=u.useState([]),[N,o]=u.useState(!0),[l,p]=u.useState(!1),[w,r]=u.useState(null),[d,C]=u.useState(!1),[S,c]=u.useState(""),[_,h]=u.useState(["read"]);u.useEffect(()=>{t&&s()},[t]);const s=async()=>{if(t)try{const{data:n,error:y}=await E.from("api_keys").select("*").eq("workspace_id",t.id).order("created_at",{ascending:!1});if(y)throw y;b(n||[])}catch(n){console.error("Error fetching API keys:",n)}finally{o(!1)}},i=()=>{const n=new Uint8Array(24);return crypto.getRandomValues(n),`sk_live_${Array.from(n,q=>q.toString(16).padStart(2,"0")).join("")}`},v=async n=>{const q=new TextEncoder().encode(n),L=await crypto.subtle.digest("SHA-256",q);return Array.from(new Uint8Array(L)).map(Me=>Me.toString(16).padStart(2,"0")).join("")},k=async()=>
11{if(!(!t||!S.trim())){p(!0);try{const n=i(),y=await v(n),q=n.substring(0,12),{error:L}=await E.from("api_keys").insert({workspace_id:t.id,name:S.trim(),key_hash:y,key_prefix:q,permissions:_,created_by:m?.id});if(L)throw L;r(n),c(""),h(["read"]),s(),g({title:"API Key criada",description:"Copie a chave agora, ela não será exibida novamente."}),as({action:"create",entityType:"api_key",entityName:S.trim(),workspaceId:t?.id,source:"workspace"})}catch(n){console.error("Error creating API key:",n),g({title:"Erro ao criar chave",description:"Tente novamente.",variant:"destructive"})}finally{p(!1)}}},A=async n=>{try{const{error:y}=await E.from("api_keys").delete().eq("id",n);if(y)throw y;b(q=>q.filter(L=>L.id!==n)),g({title:"API Key removida"}),as({action:"revoke",entityType:"api_key",entityId:n,workspaceId:t?.id,source:"workspace"})}catch(y){console.error("Error deleting API key:",y),g({title:"Erro ao remover chave",variant:"destructive"})}},P=n=>{navigator.clipboard.writeText(n),g({title:"Copiado!"})},a=n=>{h(y=>y.includes(n)?y.filter(q=>q!==n):[...y,n])};return e.jsxs(T,{children:[e.jsx(H,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(G,{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"h-5 w-5"}),"API Keys"]}),e.jsx(le,{children:"Gerencie suas chaves de acesso à API pública"})]}),e.jsxs(ne,{open:d,onOpenChange:C,children:[e.jsx(is,{asChild:!0,children:e.jsxs(j,{children:[e.jsx(je,{className:"mr-2 h-4 w-4"}),"Nova Chave"]})}),e.jsx(ie,{children:w?e.jsxs(e.Fragment,{children:[e.jsxs(ee,{children:[e.jsx(se,{children:"🔑 Sua Nova API Key"}),e.jsx(ae,{children:"Copie esta chave agora. Por segurança, ela não será exibida novamente."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-lg font-mono text-sm",children:[e.jsx("code",{className:"flex-1 break-all",children:w}),e.jsx(j,{variant:"ghost",size:"icon",onClick:()=>P(w),children:e.jsx(me,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-warning/10 rounded-lg",children:[e.jsx(ys,{className:"h-5 w-5 text-warning shrink-0"}),e.jsx("p",{className:"text-sm text-warning",children:"Armazene esta chave em um local seguro. Você não poderá vê-la novamente."})]})]}),e.jsx(fe,{children:e.jsx(j,{onClick:()=>{r(null),C(!1)},children:"Entendi, fechar"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ee,{children:[e.jsx(se,{children:"Criar Nova API Key"}),e.jsx(ae,{children:"Configure as permissões da sua nova chave de API"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{htmlFor:"name",children:"Nome da Chave"}),e.jsx(D,{id:"name",placeholder:"Ex: Integração N8N",value:S,onChange:n=>c(n.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{children:"Permissões"}),e.jsx("div",{className:"space-y-2",children:ia.map(n=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsx(Ge,{checked:_.includes(n.id),onCheckedChange:()=>a(n.id)}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:n.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.description})]})]},n.id))})]})]}),e.jsxs(fe,{children:[e.jsx(j,{variant:"outline",onClick:()=>C(!1),children:"Cancelar"}),e.jsx(j,{onClick:k,disabled:l||!S.trim(),children:l?"Criando...":"Criar Chave"})]})]})})]})]})}),e.jsx(z,{children:N?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Carregando..."}):x.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhuma API key criada ainda"}):e.jsxs(ds,{children:[e.jsx(ms,{children:e.jsxs(Ie,{children:[e.jsx(J,{children:"Nome"}),e.jsx(J,{children:"Chave"}),e.jsx(J,{children:"Permissões"}),e.jsx(J,{children:"Último Uso"}),e.jsx(J,{children:"Status"}),e.jsx(J,{})]})}),e.jsx(us,{children:x.map(n=>e.jsxs(Ie,{children:[e.jsx(Z,{className:"font-medium",children:n.name}),e.jsx(Z,{children:e.jsxs("code",{className:"text-xs bg-muted px-2 py-1 rounded",children:[n.key_prefix,"..."]})}),e.jsx(Z,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.permissions.map(y=>e.jsx(I,{variant:"secondary",className:"text-xs",children:y},y))})}),e.jsx(Z,{className:"text-muted-foreground text-sm",children:n.last_used_at?He(new Date(n.last_used_at),"dd/MM/yy HH:mm",{locale:te}):"Nunca"}),e.jsx(Z,{children:e.jsx(I,{variant:n.is_active?"default":"secondary",children:n.is_active?"Ativa":"Inativa"})}),e.jsx(Z,{children:e.jsx(j,{variant:"ghost",size:"icon",onClick:()=>A(n.id),children:e.jsx(Pe,{className:"h-4 w-4 text-destructive"})})})]},n.id))})]})})]})}function ca(){const{currentWorkspace:t}=$(),{data:m=[],isLoading:g}=V({queryKey:["api-usage",t?.id],queryFn:async()=>
11{if(!t?.id)return[];const{data:o,error:l}=await E.from("api_usage_logs").select("*, api_keys(name, key_prefix)").eq("workspace_id",t.id).order("created_at",{ascending:!1}).limit(100);if(l)throw l;return o||[]},enabled:!!t?.id}),x={total:m.length,success:m.filter(o=>o.status_code>=200&&o.status_code<400).length,errors:m.filter(o=>o.status_code>=400).length,avgTime:m.length>0?Math.round(m.reduce((o,l)=>o+(l.response_time_ms||0),0)/m.length):0},b={};m.forEach(o=>{const l=`${o.method} ${o.endpoint}`;b[l]=(b[l]||0)+1});const N=Object.entries(b).sort((o,l)=>l[1]-o[1]).slice(0,5);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsx(oe,{title:"Requisições",value:x.total,icon:e.jsx(ge,{className:"h-5 w-5"}),subtitle:"Últimas 100",gradient:"primary"}),e.jsx(oe,{title:"Sucesso",value:x.success,icon:e.jsx(Ls,{className:"h-5 w-5"}),subtitle:"2xx/3xx",gradient:"green"}),e.jsx(oe,{title:"Erros",value:x.errors,icon:e.jsx(gs,{className:"h-5 w-5"}),subtitle:"4xx/5xx",gradient:"orange"}),e.jsx(oe,{title:"Tempo médio",value:`${x.avgTime}ms`,icon:e.jsx(re,{className:"h-5 w-5"}),subtitle:"Resposta",gradient:"blue"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(T,{children:[e.jsx(H,{children:e.jsx(G,{className:"text-base",children:"Endpoints Mais Usados"})}),e.jsx(z,{children:N.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum dado ainda"}):e.jsx("div",{className:"space-y-2",children:N.map(([o,l])=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("code",{className:"text-xs bg-muted px-2 py-1 rounded",children:o}),e.jsx(I,{variant:"secondary",children:l})]},o))})})]}),e.jsxs(T,{children:[e.jsx(H,{children:e.jsx(G,{className:"text-base",children:"Atividade Recente"})}),e.jsx(z,{children:g?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando..."}):m.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma requisição ainda"}):e.jsx("div",{className:"space-y-2 max-h-[250px] overflow-y-auto",children:m.slice(0,20).map(o=>e.jsxs("div",{className:"flex items-center justify-between text-xs p-2 border rounded",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{variant:o.status_code<400?"default":"destructive",className:"text-[10px] px-1.5",children:o.status_code}),e.jsxs("code",{className:"text-muted-foreground",children:[o.method," ",o.endpoint]})]}),e.jsx("span",{className:"text-muted-foreground",children:he(new Date(o.created_at),{addSuffix:!0,locale:te})})]},o.id))})})]})]})]})}const rs={success:{icon:Je,label:"Sucesso",variant:"default"},failed:{icon:ue,label:"Falhou",variant:"destructive"},sending:{icon:ce,label:"Enviando",variant:"secondary"},retry_pending:{icon:re,label:"Retry pendente",variant:"outline"},pending:{icon:re,label:"Pendente",variant:"secondary"}};function la({webhookId:t}){const{currentWorkspace:m}=$(),{toast:g}=Q(),[x,b]=u.useState([]),[N,o]=u.useState(!0),[l,p]=u.useState("all"),[w,r]=u.useState("all");u.useEffect(()=>{m&&d()},[m,t,l,w]);const d=async()=>{if(m){o(!0);try{let c=E.from("webhook_delivery_logs").select("*").eq("workspace_id",m.id).order("created_at",{ascending:!1}).limit(100);t&&(c=c.eq("webhook_id",t)),l!=="all"&&(c=c.eq("event_type",l)),w!=="all"&&(c=c.eq("status",w));const{data:_,error:h}=await c;if(h)throw h;b(_||[])}catch(c){console.error("Error fetching delivery logs:",c)}finally{o(!1)}}},C=async c=>{try{const{error:_}=await E.functions.invoke("webhook-dispatcher",{body:{action:"retry",log_id:c}});if(_)throw _;g({title:"Retry iniciado"}),d()}catch(_){console.error("Error retrying:",_),g({title:"Erro ao reenviar",variant:"destructive"})}},S=[...new Set(x.map(c=>c.event_type))];
11return e.jsxs(T,{children:[e.jsxs(H,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(G,{className:"flex items-center gap-2 text-base",children:[e.jsx(Rs,{className:"h-4 w-4"}),"Histórico de Entregas"]}),e.jsx(le,{children:"Logs detalhados de cada disparo de webhook"})]}),e.jsxs(j,{variant:"outline",size:"sm",onClick:d,children:[e.jsx(ce,{className:"h-4 w-4 mr-1"}),"Atualizar"]})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs(ke,{value:l,onValueChange:p,children:[e.jsxs(Ce,{className:"w-[180px]",children:[e.jsx(os,{className:"h-3 w-3 mr-1"}),e.jsx(_e,{placeholder:"Evento"})]}),e.jsxs(Se,{children:[e.jsx(R,{value:"all",children:"Todos os eventos"}),S.map(c=>e.jsx(R,{value:c,children:c},c))]})]}),e.jsxs(ke,{value:w,onValueChange:r,children:[e.jsx(Ce,{className:"w-[160px]",children:e.jsx(_e,{placeholder:"Status"})}),e.jsxs(Se,{children:[e.jsx(R,{value:"all",children:"Todos"}),e.jsx(R,{value:"success",children:"Sucesso"}),e.jsx(R,{value:"failed",children:"Falhou"}),e.jsx(R,{value:"retry_pending",children:"Retry pendente"})]})]})]})]}),e.jsx(z,{children:N?e.jsx("div",{className:"text-center py-6 text-muted-foreground",children:"Carregando..."}):x.length===0?e.jsx("div",{className:"text-center py-6 text-muted-foreground",children:"Nenhum log encontrado"}):e.jsx("div",{className:"space-y-2 max-h-[400px] overflow-y-auto",children:x.map(c=>{const _=rs[c.status]||rs.pending,h=_.icon;return e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(h,{className:"h-4 w-4 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(I,{variant:"outline",className:"text-xs",children:c.event_type}),e.jsx(I,{variant:_.variant,className:"text-xs",children:_.label}),c.response_status&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["HTTP ",c.response_status]}),c.duration_ms!==null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[c.duration_ms,"ms"]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Tentativa ",c.attempt,"/",c.max_attempts]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:he(new Date(c.created_at),{addSuffix:!0,locale:te})}),c.error_message&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-destructive truncate max-w-[200px]",children:c.error_message})]})]})]})]}),(c.status==="failed"||c.status==="retry_pending")&&e.jsxs(j,{variant:"ghost",size:"sm",onClick:()=>C(c.id),className:"shrink-0 ml-2",children:[e.jsx(Ks,{className:"h-3 w-3 mr-1"}),"Retry"]})]},c.id)})})})]})}const da=[{id:"member.joined",label:"Membro entrou",description:"Quando alguém entra em um grupo"},{id:"member.left",label:"Membro saiu",description:"Quando alguém sai de um grupo"},{id:"message.sent",label:"Mensagem enviada",description:"Quando uma mensagem é enviada"},{id:"broadcast.completed",label:"Broadcast concluído",description:"Quando um disparo termina"},{id:"instance.connected",label:"Instância conectada",description:"Quando uma instância conecta"},{id:"instance.disconnected",label:"Instância desconectada",description:"Quando uma instância cai"},{id:"funnel.response",label:"Resposta de funil",description:"Quando um lead responde um funil"}];function ma(){const{currentWorkspace:t}=$(),{toast:m}=Q(),[g,x]=u.useState([]),[b,N]=u.useState(!0),[o,l]=u.useState(!1),[p,w]=u.useState(!1),[r,d]=u.useState(""),[C,S]=u.useState(""),[c,_]=u.useState([]);u.useEffect(()=>{t&&h()},[t]);const h=async()=>{if(t)try{const{data:a,error:n}=await E.from("outbound_webhooks").select("*").eq("workspace_id",t.id).order("created_at",{ascending:!1});if(n)throw n;x(a||[])}catch(a){console.error("Error fetching webhooks:",a)}finally{N(!1)}},s=()=>{const a=new Uint8Array(24);return crypto.getRandomValues(a),`whsec_${Array.from(a,y=>y.toString(16).padStart(2,"0")).join("")}`},i=async()=>
11{if(!t||!r.trim()||!C.trim()||c.length===0){m({title:"Preencha todos os campos",description:"Nome, URL e pelo menos um evento são obrigatórios.",variant:"destructive"});return}l(!0);try{const a=s(),{error:n}=await E.from("outbound_webhooks").insert({workspace_id:t.id,name:r.trim(),url:C.trim(),events:c,secret_key:a});if(n)throw n;d(""),S(""),_([]),w(!1),h(),m({title:"Webhook criado",description:"O webhook foi configurado com sucesso."})}catch(a){console.error("Error creating webhook:",a),m({title:"Erro ao criar webhook",variant:"destructive"})}finally{l(!1)}},v=async(a,n)=>{try{const{error:y}=await E.from("outbound_webhooks").update({is_active:n}).eq("id",a);if(y)throw y;x(q=>q.map(L=>L.id===a?{...L,is_active:n}:L)),m({title:n?"Webhook ativado":"Webhook desativado"})}catch(y){console.error("Error toggling webhook:",y)}},k=async a=>{try{const{error:n}=await E.from("outbound_webhooks").delete().eq("id",a);if(n)throw n;x(y=>y.filter(q=>q.id!==a)),m({title:"Webhook removido"})}catch(n){console.error("Error deleting webhook:",n)}},A=a=>{navigator.clipboard.writeText(a),m({title:"Copiado!"})},P=a=>{_(n=>n.includes(a)?n.filter(y=>y!==a):[...n,a])};return e.jsxs(e.Fragment,{children:[e.jsxs(T,{children:[e.jsx(H,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(G,{className:"flex items-center gap-2",children:[e.jsx(pe,{className:"h-5 w-5"}),"Webhooks de Saída"]}),e.jsx(le,{children:"Receba notificações de eventos em sua aplicação"})]}),e.jsxs(ne,{open:p,onOpenChange:w,children:[e.jsx(is,{asChild:!0,children:e.jsxs(j,{children:[e.jsx(je,{className:"mr-2 h-4 w-4"}),"Novo Webhook"]})}),e.jsxs(ie,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(ee,{children:[e.jsx(se,{children:"Criar Webhook"}),e.jsx(ae,{children:"Configure um endpoint para receber eventos"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{htmlFor:"webhook-name",children:"Nome"}),e.jsx(D,{id:"webhook-name",placeholder:"Ex: Zapier Integration",value:r,onChange:a=>d(a.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{htmlFor:"webhook-url",children:"URL do Endpoint"}),e.jsx(D,{id:"webhook-url",type:"url",placeholder:"https://hooks.zapier.com/...",value:C,onChange:a=>S(a.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{children:"Eventos"}),e.jsx("div",{className:"grid gap-2 max-h-48 overflow-y-auto",children:da.map(a=>e.jsxs("div",{className:"flex items-start gap-3 p-2 rounded border",children:[e.jsx(Ge,{checked:c.includes(a.id),onCheckedChange:()=>P(a.id)}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:a.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})]},a.id))})]})]}),e.jsxs(fe,{children:[e.jsx(j,{variant:"outline",onClick:()=>w(!1),children:"Cancelar"}),e.jsx(j,{onClick:i,disabled:o,children:o?"Criando...":"Criar Webhook"})]})]})]})]})}),e.jsx(z,{children:b?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Carregando..."}):g.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum webhook configurado ainda"}):e.jsx("div",{className:"space-y-4",children:g.map(a=>e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium truncate",children:a.name}),e.jsx(I,{variant:a.is_active?"default":"secondary",children:a.is_active?"Ativo":"Inativo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate mt-1",children:a.url}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Je,{className:"h-3 w-3 text-success"}),a.success_count," sucessos"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ue,{className:"h-3 w-3 text-destructive"}),a.failure_count," falhas"]}),a.last_triggered_at&&e.jsxs("span",{children:["Último disparo:"," ",he(new Date(a.last_triggered_at),{addSuffix:!0,locale:te})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[e.jsx(ze,{checked:a.is_active,onCheckedChange:n=>v(a.id,n)}),a.secret_key&&e.jsx(j,{variant:"ghost",size:"icon",onClick:()=>A(a.secret_key),title:"Copiar secret",children:e.jsx(me,{className:"h-4 w-4"})}),e.jsx(j,{variant:"ghost",size:"icon",onClick:()=>k(a.id),children:e.jsx(Pe,{className:"h-4 w-4 text-destructive"})})]})]},a.id))})})]}),e.jsx(la,{})]})}function _t(){const[t]=vs(),m=t.get("tab")||"connectors";return e.jsxs("div",{className:"space-y-6",children:[e.jsx(bs,{icon:e.jsx(Ve,{}),title:"Central de Integrações",description:"Conecte plataformas de vendas, APIs e webhooks externos",iconColor:"info"}),e.jsxs(We,{defaultValue:m,className:"space-y-4",children:[e.jsxs(qe,{className:"flex-wrap h-auto gap-1 p-1",children:[e.jsxs(M,{value:"connectors",className:"gap-2",children:[e.jsx(Os,{className:"h-4 w-4"}),"Conectores"]}),e.jsxs(M,{value:"hub",className:"gap-2",children:[e.jsx(pe,{className:"h-4 w-4"}),"Webhooks Avançados"]}),e.jsxs(M,{value:"sync",className:"gap-2",children:[e.jsx(fs,{className:"h-4 w-4"}),"Sync Plataformas"]}),e.jsxs(M,{value:"mapping",className:"gap-2",children:[e.jsx(Qe,{className:"h-4 w-4"}),"Mapeamento"]}),e.jsxs(M,{value:"api-keys",className:"gap-2",children:[e.jsx(ps,{className:"h-4 w-4"}),"API Keys"]}),e.jsxs(M,{value:"api-usage",className:"gap-2",children:[e.jsx(gs,{className:"h-4 w-4"}),"API Usage"]}),e.jsxs(M,{value:"outbound",className:"gap-2",children:[e.jsx(Ve,{className:"h-4 w-4"}),"Webhooks de Saída"]}),e.jsxs(M,{value:"meta-whatsapp",className:"gap-2",children:[e.jsx(Ze,{className:"h-4 w-4"}),"API Oficial WhatsApp"]})]}),e.jsx(U,{value:"connectors",children:e.jsx(Vs,{})}),e.jsx(U,{value:"hub",children:e.jsx(Xs,{})}),e.jsx(U,{value:"sync",children:e.jsx(sa,{})}),e.jsx(U,{value:"mapping",children:e.jsx(Ys,{})}),e.jsx(U,{value:"api-keys",children:e.jsx(oa,{})}),e.jsx(U,{value:"api-usage",children:e.jsx(ca,{})}),e.jsx(U,{value:"outbound",children:e.jsx(ma,{})}),e.jsx(U,{value:"meta-whatsapp",children:e.jsx(na,{})})]})]})}export{_t 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.