PageSourceSearch

https://www.richardrasmussen.com.br/assets/Dashboard-ZEAFmOb9.js

js richardrasmussen.com.br collected 2026-09-25 01:51:57 UTC 924,761 bytes, 95 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-exceljs-AsZnDCZx.js","assets/react-vendor-CCSw6ZEf.js","assets/vendor-remix-run-router-D1FRce34.js"])))=>i.map(i=>d[i]);
2import{e as nr,r,j as e,d as Fd,L as lt,R as fn,k as _i,N as Ga,u as Od,f as Mu,h as ot}from"./react-vendor-CCSw6ZEf.js";import{a as $e,m as Zt,n as mt,B as w,o as Ks,Y as qd,T as ls,g as qt,Z as Fu,C as he,c as ge,d as ze,e as je,A as nn,y as Zn,z as on,b as Be,w as Jt,I as Te,_ as Sr,$ as Ir,a0 as Ar,a7 as Vn,a1 as tt,a8 as Gn,u as jn,L as Oe,a9 as Fa,D as at,p as rt,q as nt,t as it,a3 as Ut,W as zd,a6 as vn,v as Ba,S as io,aa as Ou,ab as qu,ac as zu,ad as Uu,ae as Bu,af as Vu,ag as Gu,ah as Hu,ai as Ku,x as Tr,E as Qu,aj as Wu,a5 as Ju}from"./index-BBHF0xNG.js";import{u as $o,f as Yu,i as Ud}from"./scanner-event-access-Cop7jne2.js";import{B as Hn,ah as oo,a3 as Ya,ai as nl,aj as bn,H as Xu,g as Cr,ak as lo,f as Sa,i as gr,y as tn,al as Bd,T as Ea,am as Zu,an as Nn,r as Lo,p as Vd,ao as Gd,ap as Ia,U as Er,aq as em,X as yt,af as Mo,a5 as co,o as Za,t as Vt,k as ra,C as er,d as ei,h as sm,e as At,ar as Hd,F as Ci,as as Oa,at as tm,a8 as wa,au as ln,a4 as Cs,av as Kn,s as Kd,E as sr,aw as Da,ax as il,a0 as et,a6 as si,ay as ta,az as Fo,a2 as Xt,a1 as am,aA as uo,aB as mo,R as rm,a as ti,ab as Qd,I as kr,ad as Pa,aC as Oo,ac as Li,n as pr,aD as nm,aE as Mi,j as im,aF as xo,aG as ai,aH as po,aI as qo,ae as tr,aJ as qa,x as hr,aK as om,aL as lm,aM as ri,z as dm,aN as cm,aO as ol,aP as ni,aQ as um,aR as mm,aS as xm,aT as pm,aU as hm,aV as gm,aW as Yr,Q as fm,aX as jm,N as ii,aY as Wd,aZ as Jd,ag as Yd,a_ as zo,a$ as ll,b0 as dl,b1 as vm,b2 as Xd,q as bm,b3 as Nm,b4 as xr,b5 as ym,b6 as wm,b7 as kn,b8 as oi,b9 as cl,ba as _m,bb as Cm,Z as km,$ as Sm,J as Zd,v as ul,bc as Sn,bd as Im,be as Am,D as Em,bf as Dm,bg as Pm,bh as ml}from"./vendor-lucide-react-CVJ6MdTe.js";import{u as Rt,c as na,d as fa}from"./vendor-tanstack-react-query-6BGTSrdj.js";import{g as Uo,d as xl}from"./cpf-CAGOLQAs.js";import{g as Bt,a as Dr,b as li,f as pl,c as Rm,B as Tm,P as $m}from"./eventSectionMode-DcuYv07J.js";import{S as rs,a as ns,b as is,c as os,d as xe}from"./select-B0m-Cu-o.js";import{s as hl,e as gl,a as fl,b as Lm,c as zt,f as Us,p as Vs,d as Fi,i as ec,g as Bo,h as Ur,j as Mm,k as Fm,l as yr,m as Oi}from"./vendor-date-fns-CYWKq5sg.js";import{b5 as Ca,b6 as Xa,b7 as Ra,b8 as Ta,b9 as $a,ba as Aa,bb as ha,bc as sc,bd as tc,be as ac,bf as Xr,bg as Om,bh as jl,bi as rc,bj as di}from"./recharts-B4dQrgrr.js";import{a1 as nc,a2 as qm,a3 as zm,a4 as Um,a5 as Bm,a6 as ic,a7 as Vm,a8 as Gm,a9 as Hm,aa as oc,ab as Km,ac as Qm,ad as lc,ae as Wm}from"./radix-BokqOchy.js";import{g as dc,p as dn,f as _a,n as Et,a as cn,c as un,b as Va,d as qi,r as vl,e as Zr,h as cc,i as Jm,j as Ym,k as Pr,l as ci}from"./evento-helpers-DF_OI7B5.js";import{S as It,g as Qn,f as aa,a as Xm}from"./index-C9PownV9.js";import{_ as $r,D as Zm,P as ex,a as sx,b as tx}from"./pdf-B-NwQtV1.js";import{T as vt,a as bt,b as $s,c as ue,d as Ct,e as ye}from"./table-D4o8Mwbg.js";import{S as Ls,g as ax,C as bl}from"./complementoIcons-CWNbNI-m.js";import{D as Rr}from"./vendor-flowbite-react-BYjxqowS.js";import{P as se}from"./vendor-prop-types-VhKX4fo3.js";import{C as Ja}from"./checkbox-C0bLD3Ss.js";import{T as yn}from"./textarea-XNmZjWqp.js";import{A as ui,b as mi}from"./alert-Bnb2l_I8.js";import{H as ja}from"./vendor-cmdk-Bu6RHhOa.js";import{T as Lr,a as Mr,b as Gt,c as Ht}from"./tabs-CVgawKax.js";import{b as ho,c as rx,d as nx,e as ix}from"./useInvites-_wRUzYqq.js";import{r as uc}from"./holderFields-BIw3-h7Z.js";import{y as ox}from"./vendor-lottiefiles-dotlottie-react-DApYlsOT.js";import{A as lx,m as Br}from"./framer-motion-BCLZEr8O.js";import{u as dx,a as cx,b as ux,c as mx,d as xx,e as px}from"./useCombos-Bu1P-ueG.js";import{u as hx,i as gx,a as fx,b as jx,E as vx}from"./tiptap-B11i9HCf.js";import{B as bx}from"./vendor-strapi-blocks-react-renderer-CYlUNgqC.js";import{b as mc,d as xc,m as Nx}from"./extratoApi-Dxn61gBI.js";import{a as Yt}from"./vendor-axios-C0aBZUJO.js";import"./nivo-CVisVx5A.js";import{n as yx,f as wx}from"./loteAvailability-mF0euq3H.js";import{u as Nl,c as _x,d as Cx,g as kx}from"./cupomApi-BScRLq8m.js";import"./vendor-remix-run-router-D1FRce34.js";import"./vendor-react-helmet-async-B_XhbgGa.js";import"./vendor-react-fast-compare-CtGQnoZf.js";import"./vendor-invariant-BiDOPSg-.js";import"./vendor-shallowequal-BLtJ1KLn.js";
2import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-B9ugUrge.js";import"./vendor-next-themes-C2ChR3O9.js";import"./vendor-sonner-DkdUxslH.js";import"./vendor-tanstack-query-core-DMBgdga1.js";import"./vendor-vercel-analytics-f2YKXRTp.js";import"./vendor-dotlottie-player-component-5ED_Q4va.js";import"./vendor-embla-carousel-react-CvYxkVB6.js";import"./vendor-embla-carousel-reactive-utils-DkegjUUZ.js";import"./vendor-embla-carousel-C_-5d5m1.js";import"./vendor-make-event-props-BSS3Agxc.js";import"./vendor-make-cancellable-promise-BDT7duwA.js";import"./vendor-tiny-invariant-CopsF_GD.js";import"./vendor-warning-BQfmDc6B.js";import"./vendor-dequal-tFQomdd2.js";import"./vendor-merge-refs-B7wZyJkK.js";import"./vendor-aria-hidden-DQ5UC2Eg.js";import"./vendor-react-remove-scroll-Bkf2ge9v.js";import"./vendor-tslib-CDuPK5Eb.js";import"./vendor-react-remove-scroll-bar-BSRJNvbz.js";import"./vendor-react-style-singleton-CrAFO0Uv.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C5lMNcSF.js";import"./vendor-use-callback-ref-wnUOprTt.js";import"./vendor-floating-ui-react-dom-ChD05eNf.js";import"./vendor-floating-ui-dom-Br9gUqw7.js";import"./vendor-floating-ui-core-BATz1Rcj.js";import"./vendor-floating-ui-utils-ye2j5HVc.js";import"./vendor-babel-runtime-CF3RwP-h.js";import"./vendor-lodash-BfIr-VrS.js";import"./vendor-react-is-DcAOwtUU.js";import"./vendor-react-smooth-U5p00sft.js";import"./vendor-fast-equals-C7yKKq-w.js";import"./vendor-internmap-BkD7Hj8s.js";import"./vendor-recharts-scale-CaaRa_DC.js";import"./vendor-decimal.js-light-ZKFLnszB.js";import"./vendor-eventemitter3-BBNU2OEB.js";import"./vendor-deepmerge-ts-BW_Gihi2.js";import"./vendor-klona-DlDznzHl.js";import"./vendor-tailwind-merge-v3-DmRrY2wj.js";import"./vendor-motion-dom-D5VY27l4.js";import"./vendor-motion-utils-DBsP9okC.js";import"./vendor-use-sync-external-store-odF8qR1x.js";import"./vendor-linkifyjs-YKhy6aow.js";import"./vendor-orderedmap-C4TimWWB.js";import"./vendor-w3c-keyname-DEtA-KhA.js";import"./vendor-rope-sequence-Cxv9J64N.js";import"./vendor-react-spring-web-DBMM81tv.js";import"./vendor-react-spring-core-Hm3FJ_lV.js";import"./vendor-react-spring-shared-KB5DFx1s.js";import"./vendor-react-spring-rafz-CyzLKOK9.js";import"./vendor-react-spring-animated-DqGANZev.js";async function an(s){try{return(await $e.post("/dashboard-alerts/logs",s)).data}catch{return null}}async function xi(s=[]){try{return(await $e.post("/dashboard-alerts/ack",{ids:s})).data}catch{return null}}async function Sx(s=200){try{return(await $e.get(`/dashboard-alerts/history?limit=${encodeURIComponent(s)}`)).data}catch{return{readAlerts:[]}}}function In({icon:s,title:t,message:a,onClick:n,onAck:o,onGo:i}){return e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border px-2 py-2 cursor-pointer hover:bg-muted/40",onClick:n,children:[s,e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:t}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:a})]}),o&&e.jsx("button",{className:"text-[10px] px-2 py-1 rounded border bg-background hover:bg-muted",onClick:u=>{u.stopPropagation(),o()},"aria-label":"Marcar como lido",children:"Ler"}),i&&e.jsx("button",{className:"ml-1 text-[10px] px-2 py-1 rounded border bg-background hover:bg-muted",onClick:u=>{u.stopPropagation(),i()},"aria-label":"Ir para",children:"Ir"})]})}function Ix(){const{user:s}=Zt(),t=(s?.role?.name||s?.role?.type||s?.role?.code||"").toLowerCase(),a=t.includes("superadmin"),n=t.includes("admin")||a,{data:o,refetch:i}=$o({enabled:n||a,refetchInterval:n||a?3e4:!1,refetchOnWindowFocus:!1}),{toast:u}=mt(),l=nr(),c="alerts:ack",m="alerts:lastEventIds",x="alerts:lastTransferIds",h="alerts:collapsed",[p,f]=r.useState(!1),[I,g]=r.useState(!1),[N,b]=r.useState([]),[C,q]=r.useState(!1),L=r.useMemo(()=>{try{return new Set(JSON.parse(localStorage.getItem(c)||"[]"))}catch{return new Set}},[p]),M=(o?.stockAlerts||[]).filter(y=>!L.has(y.id)),z=(o?.comboAlerts||[]).filter(y=>!L.has(y.id)),D=(o?.eventAccomplishments||[]).filter(y=>!L.has(y.id)),E=(o?.transferAlerts||[]).filter(y=>!L.has(y.id)),A=M.length+z.length+D.length+E.length,S=async()=>{q(!0);try{const y=await Sx(200);b(y?.readAlerts||[])}finally{q(!1)}},P=(y,$)=>{const W=y.id;an({action:"ack",meta:{id:W,title:y.title,message:y.message,severity:y.severity,type:$}}).catch(()=>{});const ie=new Set(Array.from(L));ie.add(W),localStorage.setItem(c,JSON.stringify(Array.from(ie))),xi([W]).catch(()=>{}),window.location.reload()},F=y=>{y==="stock"?l("/dashboard/estoque"):y==="combo"?l("/dashboard/combos"):y==="event"?l("/dashboard/eventos"):y==="transfer"&&l("/dashboard/extratos"),f(!1)},[ee,re]=r.useState(()=>{try{return new Set(JSON.parse(localStorage.getItem(h)||"[]"))}catch{return new Set}}),te=y=>{const $=new Set(Array.from(ee));$.has(y)?$.delete(y):$.add(y),re($),localStorage.setItem(h,JSON.stringify(Array.from($)))};r.useEffect(()=>{if(!o?.eventAccomplishments)return;const y=o.eventAccomplishments.map(ke=>ke.id);let $=[];try{$=JSON.parse(localStorage.getItem(m)||"[]")}catch{}const W=o.eventAccomplishments.filter(ke=>!$.includes(ke.id));
2W.filter(ke=>{const Ae=ke?.meta?.reason,be=ke?.meta?.redirect||"";return!(Ae==="pedido_necessidades_pagamento"||be.includes("/dashboard/pedidos"))}).length>0&&u({title:"Novo marco de vendas",description:"Um evento atingiu um novo marco de vendas.",duration:5e3}),W.length>0&&localStorage.setItem(m,JSON.stringify(y))},[o?.eventAccomplishments]),r.useEffect(()=>{if(!E)return;const y=E.map(ie=>ie.id);let $=[];try{$=JSON.parse(localStorage.getItem(x)||"[]")}catch{}const W=E.filter(ie=>!$.includes(ie.id));if(W.length>0){const ie=W[0];u({title:"Nova transferência",description:ie.message||"Transferência registrada.",duration:6e3}),navigator?.serviceWorker?.controller&&navigator.serviceWorker.controller.postMessage({type:"TRANSFER_ALERT",count:E.length}),localStorage.setItem(x,JSON.stringify(y))}},[E]);const G=async()=>{const y=[...M.map(W=>W.id),...z.map(W=>W.id),...D.map(W=>W.id),...E.map(W=>W.id)];an({action:"ack",meta:{items:[...M.map(W=>({id:W.id,title:W.title,message:W.message,severity:W.severity,type:"stock"})),...z.map(W=>({id:W.id,title:W.title,message:W.message,severity:W.severity,type:"combo"})),...D.map(W=>({id:W.id,title:W.title,message:W.message,severity:W.severity,type:"event"})),...E.map(W=>({id:W.id,title:W.title,message:W.message,severity:W.severity,type:"transfer"}))]}}).catch(()=>{});const $=new Set(Array.from(L));y.forEach(W=>$.add(W)),localStorage.setItem(c,JSON.stringify(Array.from($))),an({action:"ack",meta:{count:y.length}}).catch(()=>{}),xi(y).catch(()=>{}),window.location.reload()};return e.jsxs("div",{className:"relative",children:[e.jsxs(w,{variant:"ghost",size:"icon",onClick:()=>f(y=>!y),"aria-label":"Alertas",children:[e.jsx(Hn,{className:"h-10 w-10"}),A>0&&e.jsx("span",{className:"absolute -top-1 -right-1 inline-flex items-center justify-center rounded-full bg-red-600 text-white text-[10px] h-4 min-w-4 px-1",children:A})]}),p&&e.jsxs("div",{className:"absolute right-0 mt-2 w-[22rem] max-w-[90vw] rounded-xl border bg-card text-card-foreground shadow-lg p-3 z-50",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Alertas"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{className:"text-[11px] underline",onClick:async()=>{const y=!I;g(y),y&&N.length===0&&await S()},children:I?"Ocultar lidos":"Mostrar lidos"}),A>0&&e.jsx(w,{size:"xs",variant:"outline",onClick:G,className:"h-7 px-2 text-xs",children:"Marcar como lido"})]})]}),e.jsxs("div",{className:"space-y-3 max-h-80 overflow-auto",children:[M.length>0&&e.jsxs("div",{className:"flex items-center justify-between text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("span",{children:"Estoque"}),e.jsx("button",{className:"text-[11px] underline",onClick:()=>te("stock"),children:ee.has("stock")?"Expandir":"Recolher"})]}),!ee.has("stock")&&M.map(y=>e.jsx(In,{icon:y.severity==="critical"?e.jsx(oo,{className:"h-4 w-4 text-red-600"}):e.jsx(Ya,{className:"h-4 w-4 text-amber-600"}),title:y.title,message:y.message,onClick:()=>F("stock"),onAck:()=>P(y,"stock"),onGo:()=>F("stock")},y.id)),z.length>0&&e.jsxs("div",{className:"flex items-center justify-between text-[11px] uppercase tracking-wide text-muted-foreground pt-1",children:[e.jsx("span",{children:"Combos"}),e.jsx("button",{className:"text-[11px] underline",onClick:()=>te("combo"),children:ee.has("combo")?"Expandir":"Recolher"})]}),!ee.has("combo")&&z.map(y=>e.jsx(In,{icon:e.jsx(Ya,{className:"h-4 w-4 text-amber-600"}),title:y.title,message:y.message,onClick:()=>F("combo"),onAck:()=>P(y,"combo"),onGo:()=>F("combo")},y.id)),D.length>0&&e.jsxs("div",{className:"flex items-center justify-between text-[11px] uppercase tracking-wide text-muted-foreground pt-1",children:[e.jsx("span",{children:"Eventos"}),e.jsx("button",{className:"text-[11px] underline",onClick:()=>te("event"),children:ee.has("event")?"Expandir":"Recolher"})]}),!ee.has("event")&&D.map(y=>e.jsx(In,{icon:e.jsx(nl,{className:"h-4 w-4 text-emerald-600"}),title:y.title,message:y.message,onClick:()=>F("event"),onAck:()=>P(y,"event"),onGo:()=>F("event")},y.id)),E.length>0&&e.jsxs("div",{className:"flex items-center justify-between text-[11px] uppercase tracking-wide text-muted-foreground pt-1",children:[e.jsx("span",{children:"Transferências"}),e.jsx("button",{className:"text-[11px] underline",onClick:()=>te("transfer"),children:ee.has("transfer")?"Expandir":"Recolher"})]}),!ee.has("transfer")&&E.map(y=>e.jsx(In,{icon:e.jsx(bn,{className:"h-4 w-4 text-emerald-600"}),title:y.title,message:y.message,onClick:()=>F("transfer"),onAck:()=>P(y,"transfer"),onGo:()=>F("transfer")},y.id)),A===0&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Sem alertas no momento."}),I&&e.jsxs("div",{className:"pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] uppercase tracking-wide text-muted-foreground pt-1",children:[e.jsx("span",{children:"Já lidos"}),C?e.jsx("span",{className:"text-[11px]",children:"Carregando…"}):e.jsx("button",{className:"text-[11px] underline",onClick:()=>b([]),children:"Limpar"})]}),(!N||N.length===0)&&!C&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Nenhum alerta lido ainda."}),N.length>0&&N.map((y,$)=>e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border px-2 py-2 bg-muted/30",children:[y.type==="event"?e.jsx(nl,{className:"h-4 w-4 text-emerald-600"}):y.severity==="critical"?e.jsx(oo,{className:"h-4 w-4 text-red-600"}):e.jsx(Ya,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:y.title}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:y.message}),y.readAt&&e.jsxs("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:["Lido em ",new Date(y.readAt).toLocaleStr
2ing()]})]})]},`${y.id}-${$}`))]})]})]})]})}const Ax={habilitar_links_convite:!0,habilitar_estatisticas_pedidos:!0,habilitar_bar:!0,habilitar_combos:!0,habilitar_estoque:!0,habilitar_vendas_bar:!0,habilitar_pedidos_filtro_bar:!0,habilitar_extrato:!0,total_reembolsado_taxa_antecipacao_brl:0,exibir_texto_total_reembolsado_taxa_antecipacao:!0,atualizar_convite_pago:!1,observacoes:""};function Fr(s={}){const{data:t,isLoading:a,isError:n,error:o}=Ks(["checkout-config"],"/config",{staleTime:3e4,...s}),{data:i,isLoading:u,isError:l,error:c}=Ks(["dashboard-config-flags"],"/pedido-dashboard-config",{staleTime:30*1e3,...s}),m=t?.data||t||{},x=m.attributes||m||{},h=i?.data||i||{},p=h.attributes||h||{};return{config:{...Ax,...p},checkoutConfig:x,isLoading:a||u,isError:n||l,error:c||o}}const Ex=[{name:"Dashboard",href:"/dashboard",icon:Xu,roles:["admin","supersuporte"]},{name:"Pedidos",href:"/dashboard/pedidos",icon:Cr,roles:["admin","supersuporte"]},{name:"Atividades",href:"/dashboard/atividades",icon:lo,roles:["admin","supersuporte","estoquista","scan"]},{name:"Scanner",href:"/dashboard/scanner",icon:lo,roles:["scan"]},{name:"Eventos",href:"/dashboard/eventos",icon:Sa,roles:["admin","supersuporte"]},{name:"Usuários",href:"/dashboard/usuarios",icon:gr,roles:["admin","supersuporte","vendedor","gerenteVendedores","comissao"]},{name:"Formulários",href:"/dashboard/formularios-palestra",icon:tn,roles:["admin","supersuporte","vendedor","vendedores","gerenteVendedores","comissao","estoquista"]},{name:"IA",href:"/dashboard/ai",icon:Bd,roles:["admin","supersuporte"]},{name:"Extratos",href:"/dashboard/extratos",icon:bn,roles:["admin"]},{name:"Vendedor",href:"/dashboard/link-convites",icon:gr,roles:["admin","supersuporte","estoquista","vendedor","gerenteVendedores","comissao","vendedoresExternos"]},{name:"Convites",href:"/dashboard/convites",icon:Ea,roles:["admin"]},{name:"Chamados",href:"/dashboard/chamados",icon:Zu,roles:["admin","supersuporte","vendedor","gerenteVendedores","comissao"]},{name:"Links de vendas",href:"/dashboard/link-vendas",icon:Cr,roles:["admin","supersuporte"]},{name:"Cupons",href:"/dashboard/cupons",icon:Nn,roles:["admin","supersuporte"]},{name:"Certificados",href:"/dashboard/certificado-templates",icon:Lo,roles:["superadmin","supersuporte"]},{name:"Maquininha",href:"/dashboard/cielo",icon:Vd,roles:["admin","supersuporte","terminal"]},{name:"Bar",href:"/dashboard/bar",icon:Gd,roles:["admin","supersuporte","estoquista"]},{name:"Estoque",href:"/dashboard/estoque",icon:Cr,roles:["admin","supersuporte","estoquista"]},{name:"Combos",href:"/dashboard/combos",icon:Ia,roles:["admin","supersuporte","estoquista"]}];function Dx({children:s,role:t="admin"}){const[a,n]=r.useState(!1),[o,i]=r.useState(!1),u=Fd(),{user:l,profile:c,logout:m}=Zt(),x=(l?.role?.name||l?.role?.type||l?.role?.code||"").toLowerCase(),h=x.includes("superadmin"),p=x.includes("supersuporte")&&!h,f=x.includes("admin")||h||p,I=x.includes("externo"),g=x.includes("vendedor")&&!I,N=x.includes("scan")||x.includes("scanner"),{config:b,checkoutConfig:C}=Fr({refetchOnWindowFocus:!1}),{data:q}=$o({enabled:f||h||p,refetchInterval:f||h||p?3e4:!1,refetchOnWindowFocus:!1}),L=Ex.filter(be=>(be.roles.includes("superadmin")||be.roles.includes("supersuporte"))&&!be.roles.includes("admin")?be.roles.includes("supersuporte")&&p?!0:h:be.roles.includes("scan")&&N?!0:be.roles.includes(t)).filter(be=>be.href==="/dashboard/bar"?b.habilitar_bar!==!1:be.href==="/dashboard/estoque"?b.habilitar_estoque!==!1:be.href==="/dashboard/combos"?b.habilitar_combos!==!1:be.href==="/dashboard/link-vendas"?h||p||f?!0:C?.habilitar_links_vendas===!0:be.href==="/dashboard/formularios-palestra"?h||p||f||g?!0:c?.podeVerFormularios===!0:!0),{mode:M}=qd(),z=M==="light",{data:D}=Ks("dashboard-header","/header"),E=D?.data||D,A=E?.brandName||"TicketTop Admin",S=E?.logo?.url,P=E?.logo_escuro?.url,F=z?P||S:S||S,{primaryLink:ee,secondaryLinks:re,leftLinks:te,rightLinks:G}=r.useMemo(()=>{if(!L||L.length===0)return{primaryLink:null,secondaryLinks:[],leftLinks:[],rightLinks:[]};const be=L.find(K=>K.href==="/dashboard")||L[0],Fe=L.filter(K=>K!==be),ae=Math.ceil(Fe.length/2);return{primaryLink:be,secondaryLinks:Fe,leftLinks:Fe.slice(0,ae),rightLinks:Fe.slice(ae)}},[L]),y=r.useMemo(()=>
2{if(!q)return 0;if(typeof window>"u")return q?.summary?.transfers||0;const be="alerts:ack";let Fe=[];try{Fe=JSON.parse(localStorage.getItem(be)||"[]")}catch{Fe=[]}const ae=new Set(Fe),O=(Array.isArray(q.transferAlerts)?q.transferAlerts:[]).filter(ve=>!ae.has(ve.id)).length,oe=q?.summary?.transfers;return Number.isFinite(oe)&&oe>O?oe:O},[q]),{mobileBottomItems:$,homeItem:W,overlayItems:ie,showMenu:ke}=r.useMemo(()=>{const be=Ze=>L.find(qe=>qe.href===Ze),Fe=["vendedor","gerentevendedores","comissao","vendedoresexternos"].includes(t.toLowerCase());let ae;Fe?ae=be("/dashboard/link-convites")||be("/dashboard")||L[0]:ae=be("/dashboard")||L[0];const K=be("/dashboard/pedidos"),O=be("/dashboard/usuarios"),oe=be("/dashboard/formularios-palestra"),ve=be("/dashboard/link-convites"),me=be("/dashboard/atividades"),fe={name:"Perfil",href:"/perfil",icon:Er,roles:["admin","supersuporte","estoquista","vendedor","gerenteVendedores","comissao","scan","vendedoresExternos"]},le=fe.roles.includes(t)?fe:null,_e=Fe?[K,O,oe,me,le].filter(Boolean):[K,O,ve,me,le].filter(Boolean),U=new Set([ae?.href,K?.href,O?.href,oe?.href,ve?.href,me?.href,fe.href].filter(Boolean)),J=L.filter(Ze=>!U.has(Ze.href)),T=J.length>0||_e.length>4;let Ee;if(_e.length<=4)Ee=_e;else{const Ze={name:"Menu",href:"#menu",icon:em,roles:["admin","estoquista","vendedor","gerenteVendedores","comissao","scan"]};Ee=[..._e.slice(0,3),Ze]}const Se=T?[..._e.slice(3),...J]:[];return{mobileBottomItems:Ee,homeItem:ae,overlayItems:Se,showMenu:T}},[L,t]),Ae=be=>{if(!be)return null;const Fe=be.icon,ae=u.pathname===be.href||u.pathname.startsWith(`${be.href}/`);return be.href==="#menu"?e.jsxs("button",{onClick:()=>{i(K=>!K),n(!1)},className:ls("flex flex-col items-center justify-center gap-1 px-3 py-2 rounded-xl transition-colors text-xs font-medium",o?" text-primary":"text-foreground/70 hover:bg-muted hover:text-foreground"),children:[e.jsx(Fe,{className:"h-5 w-5"}),e.jsx("span",{className:"truncate max-w-[6rem]",children:be.name})]},"menu"):e.jsxs(lt,{to:be.href,onClick:()=>{i(!1),n(!1)},className:ls("flex flex-col w-4 items-center justify-center gap-1 px-3 py-2 rounded-xl transition-colors text-xs font-medium",ae?"text-primary":"text-foreground/70 hover:bg-muted hover:text-foreground"),children:[e.jsx(Fe,{className:"h-5 w-5"}),e.jsx("span",{className:"truncate max-w-[4rem]",children:be.name})]},be.href)};return e.jsxs("div",{className:"flex min-h-[100dvh] bg-background",children:[a&&e.jsx("div",{className:"fixed inset-0 z-40 bg-black/50 lg:hidden",onClick:()=>n(!1)}),e.jsx("div",{className:ls("fixed inset-y-0 left-0 z-50 w-64 bg-card text-card-foreground border-r border-border shadow-lg transform transition-transform duration-300 ease-in-out lg:relative lg:transform-none",a?"translate-x-0":"-translate-x-full lg:translate-x-0"),children:e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between md:justify-center p-4 border-b border-border",children:[e.jsx(lt,{to:"/",className:"flex items-center gap-2 min-h-8",children:F?e.jsx("img",{src:qt(F),alt:A,className:"max-h-20 w-auto rounded"}):e.jsx("span",{className:"text-lg font-bold",children:A})}),e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>n(!1),className:"lg:hidden",children:e.jsx(yt,{className:"h-4 w-4"})})]}),e.jsx("nav",{className:"flex-1 p-4 space-y-2",children:L.map(be=>{const Fe=u.pathname===be.href;return e.jsxs(lt,{to:be.href,className:ls("flex items-center px-3 py-2 text-sm font-medium rounded-md transition-colors",Fe?"bg-primary/15 text-foreground":"text-foreground/80 hover:bg-muted hover:text-foreground"),onClick:()=>n(!1),children:[e.jsx(be.icon,{className:"mr-3 h-5 w-5"}),e.jsx("span",{className:"flex-1",children:be.name}),be.href==="/dashboard/extratos"&&y>0&&e.jsx("span",{className:"ml-2 inline-flex items-center justify-center rounded-full bg-red-600 text-white text-[10px] h-5 px-2",children:y})]},be.name)})})]})}),e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx("header",{className:"bg-card text-card-foreground shadow-sm border-b border-border",children:e.jsxs("div",{className:"flex items-center justify-between px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{to:"/",className:"flex items-center gap-2 min-h-4  md:hidden",children:F?e.jsx("img",{src:qt(F),alt:A,className:"max-h-14 w-auto rounded"}):e.jsx("span",{className:"text-lg font-bold",children:A})}),e.jsx("span",{className:"hidden sm:block text-sm text-muted-foreground",children:new Date().toLocaleDateString("pt-BR",{weekday:"long",year:"numeric",month:"long",day:"numeric"})})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Fu,{}),e.jsx(Ix,{})]})]})}),e.jsx("main",{className:"flex-1 overflow-auto pb-36 lg:pb-0",children:e.jsx("div",{className:"md:p-6 p-2",children:s})})]}),W&&e.jsx("nav",{className:"lg:hidden fixed bottom-0 left-0 right-0 z-40 border-t border-border/40 bg-card/95 backdrop-blur-md pb-safe",children:e.jsx("div",{className:"flex items-center justify-center px-2 pt-2 pb-2",children:e.jsxs("div",{className:"grid grid-cols-5 ga
2p-2 w-full max-w-md mx-auto",children:[$.slice(0,2).map((be,Fe)=>e.jsx("div",{className:"flex justify-center",children:be?Ae(be):e.jsx("div",{})},be?.href||Fe)),e.jsx("div",{className:"flex justify-center ",children:e.jsx(lt,{to:W.href,onClick:()=>{i(!1),n(!1)},className:ls("relative flex flex-col items-center justify-center rounded-full shadow-lg transition-transform duration-200 bg-primary text-primary-foreground","w-16 h-16 -mt-3",u.pathname===W.href||u.pathname.startsWith(`${W.href}/`)?"ring-4 ring-primary/30 scale-[1.05]":"ring-4 ring-primary/10 hover:scale-105"),"aria-label":W.name,children:e.jsx(W.icon,{className:"h-7 w-7"})})}),$.slice(2,4).map((be,Fe)=>e.jsx("div",{className:"flex justify-center",children:be?Ae(be):e.jsx("div",{})},be?.href||Fe+2))]})})}),o&&ie.length>0&&e.jsxs("div",{className:"lg:hidden fixed inset-0 z-30",role:"presentation",onClick:()=>i(!1),children:[e.jsx("div",{className:"absolute inset-0 bg-black/40"}),e.jsx("div",{className:"absolute bottom-24 left-0 right-0 px-4",onClick:be=>be.stopPropagation(),children:e.jsxs("div",{className:"rounded-3xl border border-border/40 bg-card/95 backdrop-blur-md shadow-2xl p-4",children:[e.jsx("h2",{className:"text-sm font-semibold text-muted-foreground mb-3",children:"Ir para"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:ie.map(be=>e.jsxs(lt,{to:be.href,onClick:()=>i(!1),className:ls("flex items-center gap-3 rounded-xl border border-border/40 px-3 py-2 transition-colors",u.pathname===be.href||u.pathname.startsWith(`${be.href}/`)?"bg-primary/10 text-primary":"bg-background/80 hover:bg-muted"),children:[e.jsx(be.icon,{className:"h-5 w-5"}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.name}),be.href==="/dashboard/extratos"&&y>0&&e.jsx("span",{className:"ml-2 inline-flex items-center justify-center rounded-full bg-red-600 text-white text-[10px] h-5 px-2",children:y})]},be.href))})]})})]})]})}const Or=s=>s&&typeof s=="object"&&"attributes"in s,pc=s=>s?s.data?s:{data:{id:s.id,attributes:{...s}}}:{data:null},mn=s=>s?s.data?s:Or(s)?{data:s}:{data:{id:s.id,attributes:{...s}}}:{data:null},hc=s=>Array.isArray(s)?s.length&&Or(s[0])?{data:s}:{data:s.map(t=>({id:t.id,attributes:{...t}}))}:{data:[]},Px=s=>{if(!s||Or(s))return s;const{usuario:t,eventos:a,items:n,link_convite:o,...i}=s;return{id:s.id,attributes:{...i,usuario:mn(t),eventos:hc(a||[]),items:Array.isArray(n)?n:[],link_convite:mn(o)}}},gc=s=>{if(!s||Or(s))return s;const{imagem:t,pedidos:a,...n}=s;return{id:s.id,attributes:{...n,imagem:pc(t),pedidos:hc(a||[])}}},Rx=s=>{if(!s||Or(s))return s;const{avatar:t,user:a,cart:n,...o}=s;return{id:s.id,attributes:{...o,avatar:pc(t),user:a?mn(a):{data:null},cart:Array.isArray(n)?n.map(i=>({...i,evento:i.evento?gc(i.evento):null})):[]}}},Tx=s=>{if(!s||Or(s))return s;const{created_by_usuario:t,evento:a,...n}=s;return{id:s.id,attributes:{...n,created_by_usuario:mn(t),evento:mn(a)}}},za=(s,t)=>{if(!Array.isArray(s))return[];switch(t){case"pedido":return s.map(Px);case"evento":return s.map(gc);case"usuario":return s.map(Rx);case"link-convite":return s.map(Tx);default:return s}},fc=s=>s?.attributes||s||{},$x=s=>{const t=s?.gateway||s?.dados_gateway||s?.dadosGateway;return t&&typeof t=="object"?t:null},jc=s=>{const a=$x(s)?.merged_totals;return a&&typeof a=="object"?a:null},Vo=s=>{const t=s?.resumo_totais||s?.resumoTotais;return t&&typeof t=="object"?t:null},Lx=s=>{const t=jc(s),a=Vo(s),n=[s?.desconto_cupom,t?.desconto_cupom,a?.descontoCupom,a?.desconto_cupom];for(const o of n){if(o==null)continue;const i=Number(o);if(!Number.isNaN(i))return i}return 0},Mx=(s,t)=>Array.isArray(t)?t:Array.isArray(s?.items?.data)?s.items.data.map(a=>a?.attributes||a).filter(Boolean):Array.isArray(s?.items)?s.items.map(a=>a?.attributes||a).filter(Boolean):[],xn=(s,t)=>{const a=fc(s),n=Vo(a);if(n?.subtotalBruto!=null){const c=Number(n.subtotalBruto);if(!Number.isNaN(c))return c}if(n?.subtotal_bruto!=null){const c=Number(n.subtotal_bruto);if(!Number.isNaN(c))return c}const o=jc(a);if(o?.subtotal!=null){const c=Number(o.subtotal);return Number.isNaN(c)?0:c}const i=a.subtotal??a.valor_subtotal??a.total_sem_taxa;if(i!=null){const c=Number(i);if(!Number.isNaN(c))return c}const u=Mx(a,t);
2if(u.length)return u.reduce((c,m)=>{const x=Number(m?.quantidade||m?.qty||0)||0,h=Number(m?.preco_unitario||m?.precoUnitario||m?.price||0)||0;return c+x*h},0);const l=Number(a.total||a.valor_total||a.amount||0);return Number.isNaN(l)?0:l},Ua=(s,t)=>{const a=fc(s),n=Vo(a);if(n?.subtotal!=null){const u=Number(n.subtotal);if(!Number.isNaN(u))return u}const o=xn(s,t),i=Lx(a);return i>0&&o>0?Number(Math.max(0,o-i).toFixed(2)):Number(o.toFixed(2))},go=(s,t,a)=>{const n=Number.isFinite(t)?t:xn(s,a);if(n<=0)return 1;const o=Ua(s,a);return Number.isFinite(o)?o/n:1},pi=250,Fx=4,Ox=s=>{switch(s){case"paid":return"pago";case"pending":return"pendente";case"canceled":case"cancelled":return"cancelado";default:return s}},yl=s=>Array.isArray(s?.data?.data)?s.data.data:Array.isArray(s?.data)?s.data:[],qx=s=>{const t=Number(s?.data?.meta?.pagination?.pageCount||s?.meta?.pagination?.pageCount||1);return Number.isFinite(t)&&t>0?t:1},fo=async({fetchPage:s,pageSize:t=pi,concurrency:a=Fx})=>{const n=await s(1,t),o=qx(n),i=[...yl(n)];if(o<=1)return i;const u=Array.from({length:o-1},(l,c)=>c+2);for(let l=0;l<u.length;l+=a){const c=u.slice(l,l+a);(await Promise.all(c.map(x=>s(x,t)))).forEach(x=>{i.push(...yl(x))})}return i},zx=(s=[])=>{const t=new Set;return s.filter((a,n)=>{const o=a?.id??a?.documentId??a?.attributes?.documentId??a?.attributes?.id;if(o==null)return!0;const i=String(o);return t.has(i)?!1:(t.add(i),!0)})},jo=(s=[])=>zx(za(s,"pedido")).map(t=>{const a=Ox(t.attributes?.status_pedido||t.attributes?.status);return{...t,attributes:{...t.attributes,status:a,status_pedido:a}}}),Ux=()=>{const s="/pedidos?excludeSuperAdmin=true&populate[usuario][fields][0]=nome&populate[usuario][fields][1]=email&populate[eventos][fields][0]=titulo&populate[items][fields][0]=item_tipo&populate[items][fields][1]=quantidade&populate[items][fields][2]=preco_unitario&populate[items][fields][3]=subtotal&populate[link_convite][fields][0]=referral&populate[link_convite][fields][1]=id&populate[link_convite][populate][created_by_usuario][fields][0]=nome&populate[link_convite][populate][created_by_usuario][fields][1]=email&populate[link_convite][populate][created_by_usuario][populate][avatar][fields][0]=url&populate[link_convite][populate][created_by_usuario][populate][user]=true&sort=createdAt:desc",{data:t,isLoading:a,error:n}=Rt({queryKey:["dashboard-pedidos",s],queryFn:async()=>{const N=await fo({pageSize:pi,fetchPage:(b,C)=>$e.get(`${s}&pagination[page]=${b}&pagination[pageSize]=${C}`)});return{data:jo(N)}},staleTime:6e4,gcTime:6e5,refetchOnWindowFocus:!1}),o="/eventos?populate[imagem][fields][0]=url&populate[imagem][fields][1]=name&populate[imagem][fields][2]=formats&populate[datas_passadas][fields][0]=data&populate[datas_passadas][fields][1]=observacao&populate[datas_futuras][fields][0]=data&populate[datas_futuras][fields][1]=observacao&populate[datas_futuras][fields][2]=ingressos_disponiveis&populate[datas_futuras][fields][3]=limite_ingressos&populate[datas_futuras][fields][4]=ativo&sort=data_evento:desc",{data:i,isLoading:u,error:l}=Ks(["dashboard-eventos",o],o),c="/usuarios?fields[0]=createdAt&fields[1]=updatedAt&sort=createdAt:desc",{data:m,isLoading:x,error:h}=Rt({queryKey:["dashboard-usuarios",c],queryFn:async()=>{const N=await fo({pageSize:pi,fetchPage:(b,C)=>$e.get(`${c}&pagination[page]=${b}&pagination[pageSize]=${C}`)});return{data:za(N,"usuario")}},staleTime:60*1e3,gcTime:10*60*1e3,refetchOnWindowFocus:!1}),{data:p,isLoading:f,error:I}=Ks("dashboard-link-convites","/link-convites?populate[created_by_usuario][fields][0]=nome&populate[created_by_usuario][fields][1]=email&populate[created_by_usuario][populate][avatar][fields][0]=url&populate[created_by_usuario][populate][user]=true&sort=used_count:desc&pagination[pageSize]=200");return{...r.useMemo(()=>{const N=Array.isArray(t?.data)?t.data:[],b=za(i?.data||[],"evento"),C=za(m?.data||[],"usuario"),q=za(p?.data||[],"link-conv
2ite"),L=ae=>ae?ae.toString().trim().toUpperCase():"",M=q.reduce((ae,K)=>{const O=L(K?.attributes?.referral);return O&&(ae[O]=K),ae},{}),z=N.length,D=N.filter(ae=>ae?.attributes?.status==="pago").length,E=N.filter(ae=>ae?.attributes?.status==="pendente").length,A=N.filter(ae=>ae?.attributes?.status==="cancelado").length,S=N.filter(ae=>ae?.attributes?.status==="pago").reduce((ae,K)=>ae+Ua(K),0),P=b.length,F=C.length,ee=N.reduce((ae,K)=>{if(!K||!K.attributes)return ae;const O=K.attributes.usuario?.data?.id;return O&&(ae[O]||(ae[O]={totalOrders:0,totalSpent:0,lastOrder:null,paidOrders:0}),ae[O].totalOrders+=1,K.attributes.status==="pago"&&(ae[O].paidOrders+=1,ae[O].totalSpent+=Ua(K)),(!ae[O].lastOrder||new Date(K.attributes.createdAt)>new Date(ae[O].lastOrder))&&(ae[O].lastOrder=K.attributes.createdAt)),ae},{}),re=Object.keys(ee).length,te=Object.values(ee).filter(ae=>ae.lastOrder&&new Date(ae.lastOrder)>new Date(Date.now()-30*24*60*60*1e3)).length,G=new Date,y=b.filter(ae=>{const K=Bt(ae?.attributes||ae);return K&&new Date(K)<G}).length,$=b.filter(ae=>{const K=Bt(ae?.attributes||ae);return K&&new Date(K)>G}).length,W=b.filter(ae=>{const K=Bt(ae?.attributes||ae);return K?new Date(K).toDateString()===G.toDateString():!1}).length,ie=b.filter(ae=>ae&&ae.attributes&&Dr(ae.attributes||ae)===0).length,ke=N.filter(ae=>ae&&ae.attributes&&ae.attributes.createdAt).sort((ae,K)=>new Date(K.attributes.createdAt)-new Date(ae.attributes.createdAt)).slice(0,10),Ae=N.reduce((ae,K)=>{if(!K?.attributes)return ae;const O=K.attributes;if(O.status!=="pago")return ae;const ve=L(O.referral_code),me=L(O.link_convite?.data?.attributes?.referral),fe=ve||me;let le=O.link_convite?.data||null;!le&&fe&&M[fe]&&(le=M[fe]);const _e=le?.attributes?.created_by_usuario?.data;if(!_e)return ae;const U=_e.id;ae[U]||(ae[U]={profile:_e,paidOrders:0,totalRevenue:0,referralCodes:new Set,linkIds:new Set}),ae[U].paidOrders+=1,ae[U].totalRevenue+=Ua(K),fe&&ae[U].referralCodes.add(fe);const J=le?.id||le?.attributes?.id;return J&&ae[U].linkIds.add(J),ae},{}),be=Object.values(Ae).sort((ae,K)=>K.paidOrders!==ae.paidOrders?K.paidOrders-ae.paidOrders:K.totalRevenue-ae.totalRevenue)[0]||null,Fe=be?{seller:be.profile,paidOrders:be.paidOrders,totalRevenue:be.totalRevenue,referralCodes:Array.from(be.referralCodes).sort(),linkCount:be.linkIds.size}:null;return{pedidos:N,eventos:b,usuarios:C,linkConvites:q,totalPedidos:z,pedidosPagos:D,pedidosPendentes:E,pedidosCancelados:A,totalRevenue:S,totalEventos:P,totalUsuarios:F,usersWithOrders:re,activeUsers:te,eventosPassados:y,eventosFuturos:$,eventosHoje:W,eventosEsgotados:ie,userActivity:ee,recentOrders:ke,topSeller:Fe,getUserActivity:ae=>ee[ae]||null,getOrdersByStatus:ae=>N.filter(K=>K?.attributes?.status===ae),getEventsByStatus:ae=>{switch(ae){case"past":return b.filter(K=>{const O=Bt(K?.attributes||K);return O&&new Date(O)<G});case"future":return b.filter(K=>{const O=Bt(K?.attributes||K);return O&&new Date(O)>G});case"today":return b.filter(K=>{const O=Bt(K?.attributes||K);return O?new Date(O).toDateString()===G.toDateString():!1});case"sold-out":return b.filter(K=>K&&K.attributes&&Dr(K.attributes||K)===0);default:return b}}}},[t,i,m,p]),isLoading:a||u||x||f,error:n||l||h||I,hasError:!!(n||l||h||I)}},Bx=(s=1,t=10,a={})=>{const{status:n}=a;let o=`/eventos?populate[imagem][fields][0]=url&populate[imagem][fields][1]=name&populate[imagem][fields][2]=formats&populate[pedidos]=true&populate[datas_futuras][fields][0]=data&populate[datas_futuras][fields][1]=observacao&populate[datas_futuras][fields][2]=ingressos_disponiveis&populate[datas_futuras][fields][3]=limite_ingressos&populate[datas_futuras][fields][4]=ativo&sort=data_evento:desc&pagination[page]=${s}&pagination[pageSize]=${t}`;return Ks(["eventos-paginated",s,t,n],o,{select:i=>({...i,data:za(i?.data||[],"evento")})})},Vx=(s=1,t=10,a={})=>{const{search:n,...o}=a;let i=`/usuarios?populate[avatar][fields][0]=url&populate[avatar][fields][1]=name&populate[user]=true&sort=createdAt:desc&pagination[page]=${s}&pagination[pageSize]=${t}`;if(n){const u=String(n).trim(),l=Array.from(new Set([u,...Uo(u)])),c=[{field:"nome",value:u},{field:"email",value:u},...l.map(m=>
2({field:"cpf",value:m}))];i+=`&${c.map((m,x)=>`filters[$or][${x}][${m.field}][$containsi]=${encodeURIComponent(m.value)}`).join("&")}`}return Ks(["usuarios-paginated",s,t,n||""],i,{select:u=>({...u,data:za(u?.data||[],"usuario")}),...o})};function Gx({pedidos:s=[],eventos:t=[],usuarios:a=[],topSeller:n=null}){const{config:o}=Fr({refetchOnWindowFocus:!1}),i=fn.useMemo(()=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",maximumFractionDigits:2}),[]),u=(P=0)=>i.format(Number(P)||0),l=s.filter(P=>P&&P.attributes&&(P.attributes.status_pedido||P.attributes.status)==="pago");let c=0,m=0,x=0;const h=l.reduce((P,F)=>P+Ua(F),0),p=P=>{const F=P?.attributes||{};return Array.isArray(F.items?.data)?F.items.data.map(ee=>ee?.attributes||ee).filter(Boolean):Array.isArray(F.items)?F.items.map(ee=>ee?.attributes||ee).filter(Boolean):[]};l.forEach(P=>{const F=p(P),ee=xn(P,F),re=go(P,ee,F);if(F.length)F.forEach(te=>{const G=(te.item_tipo||te.type||"").toLowerCase(),y=Number(te.quantidade||te.qty||0)||0,$=Number(te.preco_unitario||te.precoUnitario||0)||0,ie=y*$*re;G==="ingresso"?(x+=y,c+=ie):G==="estoque"||G==="combo"||G==="bar"?m+=ie:(x+=y,c+=ie)});else{const te=Ua(P);c+=te}});const f=c+m,I=Number((h-f).toFixed(2));I!==0&&(c+=I);const g=t.filter(P=>P&&P.attributes&&li(P.attributes||P)>0),N=g.length>0?g.reduce((P,F)=>{const ee=li(F.attributes||F),re=Dr(F.attributes||F),te=ee-re,G=ee>0?te/ee*100:0;return P+G},0)/g.length:0,b=new Set;l.forEach(P=>{const F=P.attributes?.usuario?.data?.id||P.attributes?.usuario?.id;F&&b.add(F)});const C=b.size;let q=[{title:"Receita Total",value:u(h),subtitle:"Vendas de todos os eventos",icon:Mo,color:"bg-green-500"},{title:"Ingressos Vendidos",value:x.toLocaleString("pt-BR"),subtitle:`${u(c)} em ingressos • ${N.toFixed(1)}% dos eventos disponíveis`,icon:Ea,color:"bg-blue-500"},{title:"Vendas no Bar",value:u(m),subtitle:"Total geral do bar em todos os eventos.",icon:Gd,color:"bg-purple-500"},{title:"Usuários Ativos",value:C.toLocaleString("pt-BR"),subtitle:"Compradores únicos em todos os eventos",icon:gr,color:"bg-orange-500"}];(o.habilitar_bar===!1||o.habilitar_vendas_bar===!1)&&(q=q.filter(P=>P.title!=="Vendas no Bar"));const L=n?.seller?.attributes,M=L?.nome||L?.username||"Sem nome",z=L?.email||L?.user?.data?.attributes?.email||"",D=L?.avatar?.data?.attributes?.url?qt(L.avatar.data.attributes.url):L?.avatar?.url?qt(L.avatar.url):null,E=M.split(" ").filter(Boolean).slice(0,2).map(P=>P[0]).join("").toUpperCase()||"TT",A=n?.referralCodes?.length?n.referralCodes.slice(0,3).join(", "):null,S=n&&n.referralCodes.length>3?n.referralCodes.length-3:0;return e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[q.map(P=>e.jsx(he,{className:"border-0 shadow-md",children:e.jsx(ge,{className:"p-6",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:`${P.color} p-3 rounded-lg`,children:e.jsx(P.icon,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{className:"ml-4",children:[e.jsx(ze,{className:"text-sm font-medium text-foreground-600",children:P.title}),e.jsx("div",{className:"text-2xl font-bold text-foreground-900",children:P.value}),e.jsx("p",{className:"text-xs text-foreground-500",children:P.subtitle})]})]})})},P.title)),e.jsx(he,{className:"border-0 shadow-md",children:e.jsx(ge,{className:"p-6",children:e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"bg-amber-500/90 text-white p-3 rounded-lg",children:e.jsx(Lo,{className:"h-6 w-6"})}),e.jsxs("div",{className:"ml-4 flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ze,{className:"text-sm font-medium text-foreground-600",children:"Top vendedor (links)"}),n?e.jsxs(je,{variant:"outline",className:"border-amber-200 text-amber-700",children:[n.paidOrders," pedidos pagos"]}):null]}),n?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(nn,{className:"h-10 w-10",children:[D?e.jsx(Zn,{src:D,alt:M}):null,e.jsx(on,{children:E})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:M}),e.jsx("p",{className:"text-xs text-muted-foreground",children:z||"Sem e-mail cadastrado"})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:A?e.jsxs(e.Fragment,{children:["Códigos: ",A,S>0?` +${S}`:""]}):"Nenhum código registrado"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase text-muted-foreground",children:"Receita via links"}),e.jsx("p",{className:"text-base font-semibold",children:u(n.totalRevenue)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase text-muted-foreground",children:"Links ativos"}),e.jsx("p",{className:"text-base font-semibold",children:n.linkCount||n.referralCodes.length||1})]})]})]}):e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Nenhum pedido pago foi rastreado por links de vendedores ainda. ",e.jsx("br",{}),"Gere e compartilhe convites na aba",e.jsx("span",{className:"font-semibold",children:" Vendedores"})," para acompanhar o desempenho por aqui."]})]})]})})})]})}function Hx(){const{data:s,isLoading:t,error:a}=Rt({queryKey:["dashboard-analytics"],queryFn:async()=>(await $e.get("/dashboard-analytics")).data,refetchInterval:3e4});if(t)return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6",children:[...Array(4)].map((o,i)=>e.jsxs(he,{className:"animate-pulse",children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx("div",{className:"h-4 bg-muted rounded w-20"}),e.jsx("div",{className:"h-4 w-4 bg-muted rounded"})]}),e.jsxs(ge,{children:[e.jsx("div",{className:"h-8 bg-muted rounded w-16 mb-2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-24"})]})]},i))});if(a)return e.jsx(he,{className:"mb-6",children:e.jsx(ge,{className:"pt-6",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx("p",{children:"Erro ao carregar métricas de scanner"}),e.jsx("p",{className:"text-sm",children:a.message})]})})});const n=s?.data||{};return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6",children:[e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ze,{className:"text-sm font-medium",children:"Entradas Confirmadas"}),e.jsx(co,{className:"h-4 w-4 text-green-600"})]}),e.jsxs(ge,{children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:n.confirmedEntries||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"✅ Itens escaneados"})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ze,{className:"text-sm font-medium",children:"Pedidos Pendentes"}),e.jsx(Za,{className:"h-4 w-4 text-amber-600"})]}),e.jsxs(ge,{children:[e.jsx("div",{className:"text-2xl font-bold text-amber-600",children:n.pendingOrders||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"⏳ Status pendente"})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ze,{className:"text-sm font-medium",children:"Horário de Pico"}),e.jsx(Za,{className:"h-4 w-4 text-blue-600"})]}),e.jsxs(ge,{children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:n.peakHour||"--:--"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"🕓 Baseado nas leituras"})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ze,{className:"text-sm font-medium",children:"Top Colaborador"}),e.jsx(Er,{className:"h-4 w-4 text-purple-600"})]}),e.jsxs(ge,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-lg font-bold text-purple-600",children:n.topCollaborator?.name||"N/A"}),n.topCollaborator&&e.jsxs(je,{variant:"secondary",className:"text-xs",children:[n.topCollaborator.scanCount," validações"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"👤 Quem mais validou"})]})]})]})}function Kx({pedidos:s=[]}){const[t,a]=r.useState("week"),n=r.useMemo(()=>
2{if(!s.length)return[];const o=p=>{if(!p)return null;try{if(p instanceof Date)return isNaN(p)?null:p;if(typeof p=="string"){const f=zt(p);return isNaN(f)?null:f}}catch{return null}return null},i=new Date;let u,l,c,m;switch(t){case"week":u=hl(i,{locale:Vs}),l=gl(i,{locale:Vs}),c=p=>Us(p,"EEE",{locale:Vs}),m=p=>Fi(p).getTime();break;case"month":u=Lm(i),l=fl(i),c=p=>Us(p,"dd/MM"),m=p=>Fi(p).getTime();break;case"3months":u=new Date(i.getFullYear(),i.getMonth()-2,1),l=fl(i),c=p=>Us(p,"MMM",{locale:Vs}),m=p=>new Date(p.getFullYear(),p.getMonth(),1).getTime();break;default:u=hl(i,{locale:Vs}),l=gl(i,{locale:Vs}),c=p=>Us(p,"EEE",{locale:Vs}),m=p=>Fi(p).getTime()}const x=s.filter(p=>{if(!p||!p.attributes)return!1;const f=o(p.attributes.data_pedido||p.attributes.createdAt);return f?f>=u&&f<=l:!1}),h={};return x.forEach(p=>{if(!p||!p.attributes)return;const f=o(p.attributes.data_pedido||p.attributes.createdAt);if(!f)return;const I=c(f);h[I]||(h[I]={name:I,t:m(f),total:0,pago:0,pendente:0,cancelado:0}),h[I].total+=1;const g=p.attributes.status_pedido||p.attributes.status||"pendente";h[I][g]!==void 0&&(h[I][g]+=1)}),Object.values(h).sort((p,f)=>p.t-f.t).map(({t:p,...f})=>f)},[s,t]);return e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ze,{className:"text-base font-medium",children:"Pedidos por Período"}),e.jsxs(rs,{value:t,onValueChange:a,children:[e.jsx(ns,{className:"w-[140px]",children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"week",children:"Esta Semana"}),e.jsx(xe,{value:"month",children:"Este Mês"}),e.jsx(xe,{value:"3months",children:"3 Meses"})]})]})]}),e.jsx(ge,{children:e.jsx("div",{className:"h-[300px]",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(Xa,{data:n,children:[e.jsx(Ra,{strokeDasharray:"3 3"}),e.jsx(Ta,{dataKey:"name",tick:{fontSize:12}}),e.jsx($a,{tick:{fontSize:12}}),e.jsx(Aa,{formatter:(o,i)=>[o,i==="total"?"Total":i.charAt(0).toUpperCase()+i.slice(1)],labelStyle:{color:"#374151"}}),e.jsx(ha,{dataKey:"pago",stackId:"a",fill:"#10B981",name:"Pago"}),e.jsx(ha,{dataKey:"pendente",stackId:"a",fill:"#F59E0B",name:"Pendente"}),e.jsx(ha,{dataKey:"cancelado",stackId:"a",fill:"#EF4444",name:"Cancelado"})]})})})})]})}function Qx({eventos:s=[]}){const t=new Date,a=l=>{if(!l)return null;try{if(l instanceof Date)return isNaN(l)?null:l;if(typeof l=="string"){const c=zt(l);return isNaN(c)?null:c}}catch{return null}return null},n=s.reduce((l,c)=>{if(!c||!c.attributes)return l;const m=Bt(c.attributes||c);if(!m)return l;const x=a(m);return x&&(ec(x,t)?l.passados+=1:Bo(x,t)?l.futuros+=1:l.hoje+=1),l},{passados:0,hoje:0,futuros:0}),o=[{name:"Eventos Passados",value:n.passados,color:"#6B7280"},{name:"Eventos Hoje",value:n.hoje,color:"#10B981"},{name:"Eventos Futuros",value:n.futuros,color:"#3B82F6"}].filter(l=>l.value>0),i=s.reduce((l,c)=>{if(!c||!c.attributes)return l;const m=Dr(c.attributes||c);return m>50?l.alta+=1:m>10?l.media+=1:m>0?l.baixa+=1:l.esgotado+=1,l},{alta:0,media:0,baixa:0,esgotado:0}),u=({active:l,payload:c})=>l&&c&&c.length?e.jsxs("div",{className:"bg-card text-card-foreground p-3 border border-border rounded-lg shadow-lg",children:[e.jsx("p",{className:"font-medium",children:c[0].name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[c[0].value," evento",c[0].value!==1?"s":""]})]}):null;return e.jsxs(he,{children:[e.jsx(Be,{children:e.jsx(ze,{className:"text-base font-medium",children:"Distribuição de Eventos"})}),e.jsx(ge,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-3",children:"Por Período"}),e.jsx("div",{className:"h-[200px]",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(sc,{children:[e.jsx(tc,{data:o,cx:"50%",cy:"50%",innerRadius:40,outerRadius:80,paddingAngle:5,dataKey:"value",children:o.map((l,c)=>e.jsx(ac,{fill:l.color},`cell-${c}`))}),e.jsx(Aa,{content:e.jsx(u,{})})]})})}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:o.map((l,c)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:l.color}}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[l.name,": ",l.value]})]},c))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-3",children:"Disponibilidade de Ingressos"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Alta (50+)"}),e.jsx("span",{className:"text-sm font-medium text-green-600",children:i.alta})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Média (11-50)"}),e.jsx("span",{className:"text-sm font-medium text-yellow-600",children:i.media})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Baixa (1-10)"}),e.jsx("span",{className:"text-sm font-medium text-orange-600",children:i.baixa})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Esgotado"}),e.jsx("span",{className:"text-sm font-medium text-red-600",children:i.esgotado})]})]})]})]})})]})}function Wx({pedidos:s=[]}){const t=nr(),a=s.slice(0,10),n=l=>{if(!l)return null;try{if(l instanceof Date)return isNaN(l)?null:l;if(typeof l=="string"){const c=zt(l);return isNaN(c)?null:c}}catch{return null}return null},o=l=>{const c={pago:{variant:"default",className:"bg-green-100 text-green-800 hover:bg-green-100"},pendente:{variant:"secondary",className:"bg-yellow-100 text-yellow-800 hover:bg-yellow-100"},cancelado:{variant:"destructive",className:"bg-red-100 text-red-800 hover:bg-red-100"}};return c[l]||c.pendente},i=l=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(l||0),u=l=>{t(`/dashboard/pedidos?search=${l}`)};return a.length===0?e.jsxs(he,{children:[e.jsx(Be,{children:e.jsx(ze,{className:"text-base font-medium",children:"Pedidos Recentes"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-muted-foreground",children:"Nenhum pedido encontrado"})})})]}):e.jsxs(he,{className:"h-full",children:[e.jsx(Be,{children:e.jsx(ze,{className:"text-base font-medium",children:"Pedidos Recentes"})}),e.jsx(ge,{children:e.jsx("div",{className:"space-y-4",children:a.map(l
2=>{const c=o(l.attributes.status_pedido||l.attributes.status),m=n(l.attributes.data_pedido||l.attributes.createdAt),x=Ua(l);return e.jsxs("div",{className:"flex items-center justify-between p-4 border border-border rounded-lg hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsxs("div",{className:"font-medium text-foreground",children:["Pedido #",l.id]}),e.jsx(je,{variant:c.variant,className:c.className,children:(l.attributes.status_pedido||l.attributes.status).charAt(0).toUpperCase()+(l.attributes.status_pedido||l.attributes.status).slice(1)})]}),e.jsxs("div",{className:"text-sm text-muted-foreground space-y-1",children:[e.jsxs("div",{children:["Data: ",m?Us(m,"dd/MM/yyyy HH:mm",{locale:Vs}):"—"]}),l.attributes.usuario?.data&&e.jsxs("div",{children:["Usuário: ",l.attributes.usuario.data.attributes.nome||l.attributes.usuario.data.attributes.email]}),l.attributes.eventos?.data&&l.attributes.eventos.data.length>0&&e.jsxs("div",{children:["Eventos: ",l.attributes.eventos.data.map(h=>h.attributes.titulo).join(", ")]}),l.attributes.items&&l.attributes.items.length>0&&e.jsxs("div",{children:["Itens: ",l.attributes.items.length," item",l.attributes.items.length!==1?"s":""]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-semibold text-foreground",children:i(x)}),e.jsxs("button",{onClick:()=>u(l.id),className:"text-blue-600 hover:text-blue-800 text-sm flex items-center gap-1 mt-1 transition-colors",children:[e.jsx(Vt,{className:"h-3 w-3"}),"Ver detalhes"]})]})]},l.id)})})})]})}const vc=r.forwardRef(({className:s,value:t,...a},n)=>e.jsx(nc,{ref:n,className:ls("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...a,children:e.jsx(qm,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));vc.displayName=nc.displayName;function Jx({usuarios:s=[],pedidos:t=[]}){const a=s.length,n=new Set(t.filter(m=>m&&m.attributes&&m.attributes.usuario?.data?.id).map(m=>m.attributes.usuario.data.id)).size,o=a>0?n/a*100:0,i=t.filter(m=>m&&m.attributes&&(m.attributes.status_pedido==="pago"||m.attributes.status==="pago")).reduce((m,x)=>{const h=x.attributes.data_pedido||x.attributes.createdAt;if(h){const f=`${new Date(h).getHours().toString().padStart(2,"0")}:00`;m[f]=(m[f]||0)+1}return m},{}),u=Object.entries(i).sort(([,m],[,x])=>x-m).slice(0,3),l=s.reduce((m,x)=>{if(!x||!x.attributes)return m;const h=x.attributes.createdAt||x.attributes.updatedAt;if(h){const p=new Date(h).toLocaleDateString("pt-BR",{year:"numeric",month:"short"});m[p]=(m[p]||0)+1}return m},{}),c=Object.entries(l).sort(([m],[x])=>new Date(m)-new Date(x)).slice(-6);return e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"text-base font-medium flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5"}),"Demografia de Usuários"]})}),e.jsxs(ge,{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Usuários Ativos"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[n,"/",a]})]}),e.jsx(vc,{value:o,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[o.toFixed(1),"% dos usuários fizeram pelo menos um pedido"]})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium text-foreground mb-3 flex items-center gap-2",children:[e.jsx(Za,{className:"h-4 w-4"}),"Horários de Pico - Pedidos Pagos"]}),e.jsx("div",{className:"space-y-2",children:u.length>0?u.map(([m,x],h)=>{const p=Math.max(...u.map(([,I])=>I)),f=x/p*100;return e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground w-4",children:["#",h+1]}),e.jsx("span",{className:"text-sm text-foreground font-medium",children:m})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-foreground",children:[x," pedido",x!==1?"s":""]}),e.jsx("div",{className:"w-16 bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-green-500 h-2 rounded-full",style:{width:`${f}%`}})})]})]},m)}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum pedido pago encontrado"})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-3",children:"Registros por Mês"}),e.jsx("div",{className:"space-y-2",children:c.length>0?c.map(([m,x])=>e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:m}),e.jsxs("span",{className:"text-sm font-medium text-foreground",children:[x," usuário",x!==1?"s":""]})]},m)):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum dado disponível"})})]}),e.jsx("div",{className:"pt-4 border-t border-border",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:a}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total de Usuários"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Compraram"})]})]})})]})]})}const Yx=s=>{const t=s.metadata;if(!t)return null;if(typeof t=="string")try{return JSON.parse(t)?.data_evento||null}catch{return null}return t.data_evento||null};function Xx({eventos:s=[],pedidos:t=[]}){const a=nr(),[n,o]=r.useState(new Set),i=s.filter(g=>g&&(g.attributes||g)).sort((g,N)=>
2{const b=Bt(g.attributes||g)||"",C=Bt(N.attributes||N)||"";return b.localeCompare(C)}).slice(0,8),u=t.filter(g=>{if(!g||!g.attributes)return!1;const N=(g.attributes.status_pedido||g.attributes.status||"").toLowerCase();return N==="pago"||N==="paid"||N==="completed"}),l=g=>{const N=new Set(n);N.has(g)?N.delete(g):N.add(g),o(N)},c=g=>{const N=p(g);let b=0,C=0,q=0,L=0,M=0;u.forEach(E=>{const A=x(E),S=m(E),P=xn(E,S),F=go(E,P,S),ee=A.some($=>h($,N)),re=S.some($=>{const W=$.evento?.data||$.evento||null;return W?h(W,N):!1});if(!ee&&!re)return;const te=A.length<=1;let G=!1,y=!1;if(S.forEach($=>{const W=$.evento?.data||$.evento||null;if(!(W?h(W,N):te))return;y=!0;const ke=($.item_tipo||$.type||"").toLowerCase(),Ae=Number($.quantidade||$.qty||0)||0,be=Number($.preco_unitario||$.precoUnitario||$.price||0)||0,ae=Ae*be*F;ke==="ingresso"?(q+=Ae,b+=ae):ke==="estoque"||ke==="combo"||ke==="bar"?(C+=ae,L+=Ae,G=!0):(q+=Ae,b+=ae)}),!y&&te){const $=f(E,S);$>0&&(b+=$)}G&&(y||te)&&M++});let z=0;const D=g?.attributes||{};if(D){const E=Dr(D);E<=10&&E>0&&z++,E===0&&z++}return{totalRevenue:b+C,ticketRevenue:b,barRevenue:C,ticketsSold:q,alertCount:z,barItemsCount:L,barPedidosCount:M}},m=g=>{const N=g?.attributes||{};return Array.isArray(N.items?.data)?N.items.data.map(b=>
2b?.attributes||b).filter(Boolean):Array.isArray(N.items)?N.items.map(b=>b?.attributes||b).filter(Boolean):[]},x=g=>{const N=g?.attributes||{},b=N.eventos,C=Array.isArray(b?.data)?b.data.slice():Array.isArray(b)?b.slice():[],q=N.evento?.data||N.evento;return q&&C.push(q),C.filter(Boolean)},h=(g,N)=>{if(!g)return!1;const b=Array.isArray(N)?N:[N];return b.length===0?!1:typeof g=="string"||typeof g=="number"?b.includes(String(g)):[g.id,g.documentId,g.attributes?.documentId,g.attributes?.document_id,g.document_id].some(q=>q!=null&&b.includes(String(q)))},p=g=>{if(!g)return[];const N=g.attributes||{};return[g.id,g.documentId,N.documentId,N.document_id,N.slug,N.uid].filter(C=>C!=null&&C!=="").map(String)},f=(g,N)=>Ua(g,N),I=g=>{const N=g?.attributes||{},b=p(g),C=new Map,q=(D,E)=>{!D||C.has(D)||C.set(D,{date:D,note:E||null,ticketsSold:0,ticketRevenue:0})};if((N.datas_futuras||[]).forEach(D=>{D.data&&q(D.data,D.observacao||null)}),C.size<=1)return[];let L=0,M=0;u.forEach(D=>{const E=x(D),A=m(D),S=xn(D,A),P=go(D,S,A),F=E.some(te=>h(te,b)),ee=A.some(te=>{const G=te.evento?.data||te.evento||null;return G?h(G,b):!1});if(!F&&!ee)return;const re=E.length<=1;A.forEach(te=>{const G=te.evento?.data||te.evento||null;if(!(G?h(G,b):re))return;const $=(te.item_tipo||te.type||"").toLowerCase();if(!($==="ingresso"||$!=="estoque"&&$!=="combo"&&$!=="bar"))return;const ie=Number(te.quantidade||te.qty||0)||0,ke=Number(te.preco_unitario||te.precoUnitario||te.price||0)||0,Ae=Yx(te),be=ie*ke*P;if(Ae&&C.has(Ae)){const Fe=C.get(Ae);Fe.ticketsSold+=ie,Fe.ticketRevenue+=be}else L+=ie,M+=be})});const z=[...C.values()].sort((D,E)=>D.date.localeCompare(E.date));return L>0&&z.push({date:null,note:null,ticketsSold:L,ticketRevenue:M}),z};return i.length===0?e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"text-base font-medium flex items-center gap-2",children:[e.jsx(Sa,{className:"h-5 w-5"}),"Performance por Evento"]})}),e.jsx(ge,{children:e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-muted-foreground",children:"Nenhum evento encontrado"})})})]}):e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"text-base font-medium flex items-center gap-2",children:[e.jsx(Sa,{className:"h-5 w-5"}),"Performance por Evento"]})}),e.jsxs(ge,{children:[e.jsx("div",{className:"space-y-3",children:i.map(g=>{if(!g||!g.attributes)return null;const N=g.attributes||g,b=Bt(N),C=dc(b),q=b?dn(b):null,L=n.has(g.id),M=c(g),z=li(N);return e.jsxs("div",{className:"border border-border rounded-lg",children:[e.jsxs("div",{className:"p-4 cursor-pointer hover:bg-muted/50 transition-colors flex items-center justify-between",onClick:()=>l(g.id),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[L?e.jsx(ra,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(er,{className:"h-4 w-4 text-muted-foreground"}),g.attributes.imagem?.data?.attributes?.url&&e.jsx("img",{src:qt(g.attributes.imagem.data.attributes.url),alt:g.attributes.titulo,className:"w-16 h-16 rounded-md object-cover"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-1",children:[e.jsx("h3",{className:"font-semibold text-foreground text-sm",children:g.attributes.titulo}),e.jsx("div",{className:"flextext-xs",children:e.jsx("span",{className:"font-semibold text-green-600 -ml-2 text-sm",children:new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(M.totalRevenue)})})]}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Sa,{className:"h-3 w-3"}),q&&!isNaN(q)?Us(q,"dd/MM/yyyy",{locale:Vs}):b||"—"]}),g.attributes.local&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ei,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate max-w-[200px]",children:g.attributes.local})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(je,{variant:C.variant,className:`${C.className} text-xs`,children:C.label}),M.alertCount>0&&e.jsxs("div",{className:"flex items-center gap-1 text-orange-600",children:[e.jsx(Ya,{className:"h-3 w-3"}),e.jsx("span",{children:M.alertCount})]})]})]}),L&&(()=>{const D=c(g),E=I(g);return e.jsx("div",{className:"px-4 pb-4 border-t border-border bg-muted/20",children:e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mo,{className:"h-4 w-4 text-green-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Receita total"}),e.jsx("p",{className:"font-semibold text-sm",children:new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(D.totalRevenue)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"h-4 w-4 text-blue-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ingressos vendidos"}),e.jsxs("p",{className:"font-semibold text-sm",children:[D.ticketsSold," / ",z]}
2)]})]})]}),E.length>0&&e.jsxs("div",{className:"border rounded-md overflow-hidden",children:[e.jsx("div",{className:"px-3 py-2 bg-muted/50 border-b",children:e.jsx("span",{className:"text-xs font-semibold text-foreground",children:"Ingressos por data"})}),e.jsx("div",{className:"divide-y",children:E.map(A=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-xs",children:[e.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[e.jsx("span",{className:"font-medium text-foreground",children:A.date?(()=>{try{return Us(dn(A.date),"dd/MM/yyyy",{locale:Vs})}catch{return A.date}})():e.jsx("span",{className:"italic text-muted-foreground",children:"Data não especificada"})}),A.note&&e.jsx("span",{className:"text-muted-foreground truncate max-w-[180px]",children:A.note})]}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0 pl-4",children:[e.jsxs("span",{className:"text-muted-foreground",children:[e.jsx(Ea,{className:"inline h-3 w-3 mr-1 text-blue-500"}),A.ticketsSold]}),e.jsx("span",{className:"font-medium text-green-600",children:new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(A.ticketRevenue)})]})]},A.date||"__unassigned__"))})]}),e.jsx("div",{className:"pt-2 border-t border-border",children:e.jsxs(w,{variant:"outline",size:"sm",className:"text-xs",onClick:A=>{A.stopPropagation(),a(`/dashboard/eventos/${encodeURIComponent(g.attributes.documentId||g.id)}`)},children:[e.jsx(sm,{className:"h-3 w-3 mr-1"}),"Ver Detalhes"]})})]})})})()]},g.id)})}),s.length>8&&e.jsx("div",{className:"mt-4 text-center",children:e.jsxs(w,{variant:"link",className:"text-blue-600 hover:text-blue-800 text-sm font-medium",onClick:()=>a("/dashboard/eventos"),children:["Ver todos os ",s.length," eventos"]})})]})]})}const An={pix:"#10b981",credit:"#3b82f6"},Zx=({pedidos:s=[]})=>{const[t,a]=r.useState("30d"),[n,o]=r.useState("numbers"),i=[{value:"7d",label:"Últimos 7 dias"},{value:"30d",label:"Últimos 30 dias"},{value:"90d",label:"Últimos 90 dias"},{value:"1y",label:"Último ano"}],u=r.useMemo(()=>{const p=new Date;let f;switch(t){case"7d":f=Ur(p,7);break;case"30d":f=Ur(p,30);break;case"90d":f=Ur(p,90);break;case"1y":f=Ur(p,365);break;default:f=Ur(p,30)}return s.filter(I=>{if(!I||!I.attributes)return!1;const g=new Date(I.attributes.createdAt||I.attributes.data_pedido);return Mm(g,{start:f,end:p})})},[s,t]),l=r.useMemo(()=>{const p=u.filter(I=>{const g=I.attributes||I;return g.metodo_pagamento==="pix"||g.pagamento==="pix"}).length,f=u.filter(I=>{const g=I.attributes||I;return g.metodo_pagamento==="credit"||g.pagamento==="credit"}).length;if(n==="percentages"&&p+f>0){const I=p+f,g=Math.round(p/I*100),N=Math.round(f/I*100);return[{name:"Pagamentos",pix:g,credit:N,pixCount:p,creditCount:f}]}return[{name:"Pagamentos",pix:p,credit:f,pixCount:p,creditCount:f}]},[u,n]),c=u.length,m=u.filter(p=>{const f=p.attributes||p;return f.metodo_pagamento==="pix"||f.pagamento==="pix"}).length,x=u.filter(p=>{const f=p.attributes||p;return f.metodo_pagamento==="credit"||f.pagamento==="credit"}).length,h=({active:p,payload:f,label:I})=>p&&f&&f.length?e.jsxs("div",{className:"bg-background border border-border rounded-lg p-3 shadow-lg",children:[e.jsx("p",{className:"font-medium",children:I}),f.map((g,N)=>e.jsxs("p",{className:"text-sm",style:{color:g.color},children:[g.name,": ",Math.abs(g.value),n==="percentages"?"%":" pedidos",n==="percentages"?` (${g.payload[`${g.dataKey}Count`]})`:""]},N))]}):null;return e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs("div",{className:"flex flex-col gap-6 md:flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ze,{children:"Métodos de Pagamento"}),e.jsx(Jt,{children:"Comparação entre PIX e Cartão de Crédito"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(rs,{value:t,onValueChange:a,children:[e.jsx(ns,{className:"w-40",children:e.jsx(is,{})}),e.jsx(os,{children:i.map(p=>e.jsx(xe,{value:p.value,children:p.label},p.value))})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1",children:[e.jsx(w,{variant:n==="numbers"?"default":"ghost",size:"sm",onClick:()=>o("numbers"),className:"text-xs",children:"Números"}),e.jsx(w,{variant:n==="percentages"?"default":"ghost",size:"sm",onClick:()=>o("percentages"),className:"text-xs",children:"%"})]})]})]})}),e.jsx(ge,{children:c===0?e.jsx("div",{className:"flex items-center justify-center h-64 text-muted-foreground",children:"Nenhum pedido encontrado no período selecionado"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-foreground",children:c}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-2xl font-bold",style:{color:An.pix},children:[n==="percentages"?Math.abs(l[0]?.pix??0):m,n==="percentages"?"%":""]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"PIX"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-2xl font-bold",style:{color:An.credit},children:[n==="percentages"?Math.abs(l[0]?.credit??0):x,n==="percentages"?"%":""]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Cartão"})]})]}),e.jsx("div",{className:"h-48",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(Xa,{data:l,margin:{top:20,right:30,left:2
20,bottom:5},children:[e.jsx(Ra,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Ta,{dataKey:"name",className:"text-muted-foreground",fontSize:12}),e.jsx($a,{className:"text-muted-foreground",fontSize:12,label:{value:n==="percentages"?"%":"Pedidos",angle:-90,position:"insideLeft",style:{textAnchor:"middle"}}}),e.jsx(Aa,{content:e.jsx(h,{})}),e.jsx(ha,{dataKey:"pix",fill:An.pix,name:"PIX",radius:[4,4,0,0]}),e.jsx(ha,{dataKey:"credit",fill:An.credit,name:"Cartão",radius:[4,4,0,0]})]})})})]})})]})};function ep(){const{pedidos:s,eventos:t,usuarios:a,isLoading:n,hasError:o,error:i,recentOrders:u,topSeller:l}=Ux();return n?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx(It,{size:36,thickness:4}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Carregando dados do dashboard..."})]})}):o?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsxs("div",{className:"text-center text-red-600",children:[e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Erro ao carregar dados"}),e.jsxs("p",{children:[i?.message||"Ocorreu um erro inesperado",i?.response?.status&&` (código ${i.response.status})`]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Verifique a aba Network do navegador para confirmar URL, headers e corpo da resposta."})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Dashboard"}),e.jsx("p",{className:"text-muted-foreground",children:"Visão geral do seu sistema de ingressos"})]}),e.jsx(Gx,{pedidos:s,eventos:t,usuarios:a,topSeller:l}),e.jsx(Xx,{eventos:t,pedidos:s}),e.jsx(Hx,{}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(Kx,{pedidos:s}),e.jsx(Qx,{eventos:t})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-[60%_40%] gap-6",children:[e.jsx("div",{children:e.jsx(Wx,{pedidos:u})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(Jx,{usuarios:a,pedidos:s}),e.jsx(Zx,{pedidos:s})]})]})]})}const fr=zm,jr=Um,ar=r.forwardRef(({className:s,align:t="center",sideOffset:a=4,...n},o)=>e.jsx(Bm,{children:e.jsx(ic,{ref:o,align:t,sideOffset:a,className:ls("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n})}));ar.displayName=ic.displayName;function pa(s){return String(s).padStart(2,"0")}function En(s){if(!s)return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(s);if(!t)return null;const a=Number(t[1]),n=Number(t[2])-1,o=Number(t[3]),i=new Date(a,n,o);return Number.isNaN(i.valueOf())?null:i}function wl(s){return!(s instanceof Date)||Number.isNaN(s.valueOf())?"":`${s.getFullYear()}-${pa(s.getMonth()+1)}-${pa(s.getDate())}`}function zi(s){if(!s)return{dateLabel:"",timeLabel:""};if(s instanceof Date&&!Number.isNaN(s.valueOf()))return{dateLabel:`${pa(s.getDate())}/${pa(s.getMonth()+1)}/${s.getFullYear()}`,timeLabel:`${pa(s.getHours())}:${pa(s.getMinutes())}`};const t=String(s).trim();if(!t)return{dateLabel:"",timeLabel:""};if(/^\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}/.test(t)){const i=new Date(t);if(!Number.isNaN(i.valueOf()))return{dateLabel:`${pa(i.getDate())}/${pa(i.getMonth()+1)}/${i.getFullYear()}`,timeLabel:`${pa(i.getHours())}:${pa(i.getMinutes())}`}}const n=/^(\d{4})-(\d{2})-(\d{2})(?:[T\s](\d{2}):(\d{2}))?/.exec(t);if(n)return{dateLabel:`${n[3]}/${n[2]}/${n[1]}`,timeLabel:n[4]&&n[5]?`${n[4]}:${n[5]}`:""};const o=zt(t);return Number.isNaN(o.valueOf())?{dateLabel:"",timeLabel:""}:{dateLabel:`${pa(o.getDate())}/${pa(o.getMonth()+1)}/${o.getFullYear()}`,timeLabel:`${pa(o.getHours())}:${pa(o.getMinutes())}`}}function wn(s){if(!s?.attributes)return{};const t=s.attributes.gateway||s.attributes.dados_gateway;return t&&typeof t=="object"?t:{}}function Ui(s){const a=wn(s)?.pos_customer;return a&&typeof a=="object"?a:null}function sp(s){const a=wn(s)?.merged_totals;return a&&typeof a=="object"?a:null}function tp(s){const t=wn(s);return Array.isArray(t?.payment_records)?t.payment_records.filter(
2Boolean):[]}function ap(s){const t=s?.attributes||{},n=sp(s)?.total??t.total??t.valor_total??0,o=Number(n);return Number.isNaN(o)?0:o}function vo(s){const t=s?.attributes||{};return((t.referral_code||t.link_convite?.data?.attributes?.referral||"")+"").toUpperCase().trim()}const Bi={totalSold:0,totalOrders:0,totalOrdersAll:0,refunds:0,averageTicket:0,paymentMethods:{pix:0,credito:0,debito:0}},_l={root:{base:"relative !w-full",input:{field:{base:"relative w-full",icon:{svg:"h-5 w-5 !text-muted-foreground"},input:{base:"block w-full border focus:outline-none focus:ring-1 disabled:cursor-not-allowed disabled:opacity-50",colors:{gray:"!border-input !bg-background !text-foreground !placeholder:text-muted-foreground focus:!border-ring focus:!ring-ring"},sizes:{md:"!px-3 !py-2 !text-sm"},withIcon:{on:"!pl-10",off:""},withAddon:{on:"!rounded-r-md",off:"!rounded-md"}}}}},popup:{root:{base:"absolute top-10 !z-50 block pt-2",inline:"relative top-0 z-auto",inner:"inline-block !rounded-xl !bg-popover !p-4 !text-popover-foreground !shadow-md"},header:{title:"!px-2 !py-3 text-center font-semibold !text-popover-foreground",selectors:{base:"!mb-2 flex justify-between",button:{base:"!rounded-lg !bg-background !px-5 !py-2.5 !text-sm font-semibold !text-foreground hover:!bg-accent focus:outline-none focus:!ring-2 focus:!ring-ring"}}},view:{base:"!p-1"},footer:{base:"!mt-2 flex !space-x-2",button:{base:"!w-full !rounded-lg !px-5 !py-2 text-center !text-sm font-medium focus:!ring-2 focus:!ring-ring",today:"!bg-primary !text-primary-foreground hover:!bg-primary/90",clear:"!border !border-input !bg-background !text-foreground hover:!bg-accent"}}},views:{days:{header:{title:"!h-6 text-center !text-sm font-medium leading-6 !text-muted-foreground"},items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}},months:{items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}},years:{items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}},decades:{items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}}}};function rp(s){return s?.attributes?(s.attributes.metodo_pagamento||s.attributes.pagamento||"").toLowerCase()==="pos"?!0:wn(s)?.source==="pos":!1}function Vr(s){return rp(s)?!s.attributes.usuario?.data:!1}function Cl({pedidoId:s,onAssigned:t}){const{toast:a}=mt(),[n,o]=r.useState(!1),[i,u]=r.useState(""),[l,c]=r.useState(!1),[m,x]=r.useState([]),[h,p]=r.useState(!1),f=async()=>{const g=i.trim();if(g){c(!0),p(!1);try{const N=g.replace(/\D/g,""),b=/^\d{9,11}$/.test(N);let C="/usuarios?pagination[pageSize]=5&";b?C+=`filters[$or][0][email][$containsi]=${encodeURIComponent(g)}&filters[$or][1][cpf][$contains]=${encodeURIComponent(N)}`:C+=`filters[$or][0][email][$containsi]=${encodeURIComponent(g)}&filters[$or][1][nome][$containsi]=${encodeURIComponent(g)}`;const L=(await $e.get(C))?.data?.data||[];x(L.map(M=>({id:M.id,nome:M.attributes?.nome||M.nome||"",email:M.attributes?.email||M.email||"",cpf:M.attributes?.cpf||M.cpf||""})))}catch(N){console.error("Usuario search failed",N),x([])}finally{c(!1),p(!0)}}},I=async g=>{try{c(!0),await $e.put(`/pedidos/${s}/assign-usuario`,{data:{usuarioId:g}}),a({title:"Usuário atribuído",description:"Pedido vinculado ao usuário com sucesso."}),o(!1),u(""),x([]),p(!1),t?.()}catch(N){const b=N?.response?.data?.error?.message||N.message||"Erro desconhecido";a({title:"Erro ao atribuir",description:b,variant:"destructive"})}finally{c(!1)}};return e.jsxs(fr,{open:n,onOpenChange:o,children:[e.jsx(jr,{asChild:!0,children:e.jsxs(w,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5",children:[e.jsx(Kn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Atribuir Usuário"})]})}),e.jsx(ar,{className:"w-80 p-3",align:"end",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-sm font-medium",children:"Buscar usuário por e-mail ou CPF"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Te,{placeholder:"E-mail ou CPF...",value:i,onChange:g=>u(g.target.value),onKeyDown:g=>g.key==="Enter"&&f(),className:"h-8 text-sm"}),e.jsx(w,{type:"button",size:"sm",className:"h-8 px-3",onClick:f,disabled:l||!i.trim(),children:l?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):e.jsx(At,{className:"h-4 w-4"})})]}),h&&m.length===0&&e.jsx("div",{className:"text-xs text-muted-foreground text-center py-2",children:"Nenhum usuário encontrado"}),m.length>0&&e.jsx("div",{className:"space-y-1 max-h-48 overflow-y-auto",children:m.map(g=>e.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 rounded-md p-2 text-left text-sm hover:bg-accent transition-colors",onClick:()=>I(g.id),disabled:l,children:[e.jsx(nn,{className:"h-6 w-6",children:e.jsx(on,{className:"text-[10px]",children:(g.nome||"U").split(" ").slice(0,2).map(N=>N[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:g.nome||"Sem nome"}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[g.email,g.cpf?` · ${g.cpf}`:""]})]})]},g.id))})]})})]})}function kl({pedido:s,referralOptions:t,onUpdated:a}){const{toast:n}=mt(),[o,i]=r.useState(!1),[u,l]=r.useState(!1),c=vo(s),[m,x]=r.useState(c||"");r.useEffect(()=>{o&&x(c||"")},[o,c]);const h=r.useMemo(()=>{const I=new Set((t||[]).map(g=>
2(g?.value||"").toString().trim().toUpperCase()).filter(Boolean));return c&&I.add(c),Array.from(I).sort((g,N)=>g.localeCompare(N)).map(g=>({value:g,label:g}))},[t,c]),p=m!==c,f=async()=>{if(!p){i(!1);return}try{l(!0);const I={referral_code:m||null};await $e.put(`/pedidos/${s.id}/referral`,{data:I}),n({title:"Link vendedor atualizado",description:m?`Código ${m} aplicado ao pedido.`:"Código removido do pedido."}),a?.(m||""),i(!1)}catch(I){const g=I?.response?.data?.error?.message||I?.message||"Erro ao atualizar link vendedor.";n({title:"Falha ao atualizar",description:g,variant:"destructive"})}finally{l(!1)}};return e.jsxs(fr,{open:o,onOpenChange:i,children:[e.jsx(jr,{asChild:!0,children:e.jsx(w,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",title:"Editar link vendedor",children:e.jsx(ln,{className:"h-3.5 w-3.5"})})}),e.jsx(ar,{className:"w-72 p-3",align:"end",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-sm font-medium",children:"Editar Link Vendedor"}),e.jsxs(rs,{value:m||"none",onValueChange:I=>x(I==="none"?"":I),children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Selecione um código"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"none",children:"Sem link vendedor"}),h.map(I=>e.jsx(xe,{value:I.value,children:I.label},I.value))]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>i(!1),disabled:u,children:"Cancelar"}),e.jsx(w,{type:"button",size:"sm",onClick:f,disabled:u||!p,children:u?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):"Salvar"})]})]})})]})}function np(){const{toast:s}=mt(),{config:t}=Fr({refetchOnWindowFocus:!1}),{user:a}=Zt(),n=(a?.role?.name||a?.role?.type||a?.role?.code||"").toLowerCase(),o=n.includes("superadmin"),i=n.includes("supersuporte")&&!o,u=n.includes("admin")||o||i,l=u||o||i,c=(()=>{try{const R=new URLSearchParams(typeof window<"u"?window.location.search:"");return{search:R.get("search")||"",status:R.get("status")||"all",from:R.get("from")||"",to:R.get("to")||"",event:R.get("event")||"all",eventDate:R.get("eventDate")||"",itemType:R.get("itemType")||"all",referral:R.get("referral")||"all",source:R.get("source")||"all"}}catch{return{search:"",status:"all",from:"",to:"",event:"all",eventDate:"",itemType:"all",referral:"all",source:"all"}}})(),[m,x]=r.useState(c.search),[h,p]=r.useState(c.search),[f,I]=r.useState(c.status||"all"),[g,N]=r.useState(1),b=100,[C,q]=r.useState({page:1,pageSize:b,pageCount:1,total:0}),[L,M]=r.useState(!1),[z,D]=r.useState(!1),[E,A]=r.useState(c.from||""),[S,P]=r.useState(c.to||""),[F,ee]=r.useState(c.event||"all"),[re,te]=r.useState(c.eventDate||""),[G,y]=r.useState(c.itemType||"all"),[$,W]=r.useState(c.referral||"all"),[ie,ke]=r.useState(c.source||"all"),[Ae,be]=r.useState(!1),[Fe,ae]=r.useState(!1),[K,O]=r.useState(null),[oe,ve]=r.useState([]),[me,fe]=r.useState(Bi),[le,_e]=r.useState(!1),[U,J]=r.useState(null),[T,Ee]=r.useState([]),Se=F!=="all"&&F!==""?F:void 0,{data:Ze}=Ks(["orders-events-options"],"/eventos?fields[0]=titulo&sort=titulo&pagination[pageSize]=200"),{data:qe}=Ks(["orders-referrals-options"],"/link-convites?fields[0]=referral&sort=referral&pagination[pageSize]=200"),Qe=r.useMemo(()=>(Ze?.data||[]).map(Le=>{const as=Le?.id?.toString()||"",ms=Le?.documentId?.toString()||"",Ke=Le?.attributes?.titulo??Le?.titulo;return{value:ms||as,label:Ke||`Evento ${Le?.id??""}`}}).filter(Le=>Le.value),[Ze]);r.useEffect(()=>{if(!F||F==="all")return;const Le=(Ze?.data||[]).find(ms=>{const Ke=ms?.id!=null?ms.id.toString():"",gs=ms?.documentId!=null?ms.documentId.toString():"";return Ke===F||gs===F}),as=Le?.documentId!=null?Le.documentId.toString():"";as&&F!==as&&ee(as)},[Ze,F]),r.useEffect(()=>{!Se&&re&&te("")},[Se,re]),r.useEffect(()=>{N(1)},[f,E,S,F,re,G,$,ie,m,Ae]);const we=E&&S||!E&&!S,Me=r.useMemo(()=>En(E),[E]),ks=r.useMemo(()=>En(S),[S]),xs=r.useMemo(()=>({status:f,fromDate:we?E:"",toDate:we?S:"",eventId:Se,eventDate:re,itemType:G,referral:$,source:ie,search:m,onlyWithNecessidades:Ae}),[f,we,E,S,Se,re,G,$,ie,m,Ae]);r.useEffect(()=>{try{const R=new URL(window.location.href),Le=R.searchParams;m?Le.set("search",m):Le.delete("search"),f&&f!=="all"?Le.set("status",f):Le.delete("status"),we&&E?Le.set("from",E):Le.delete("from"),we&&S?Le.set("to",S):Le.delete("to"),F&&F!=="all"?Le.set("event",F):Le.delete("event"),re?Le.set("eventDate",re):Le.delete("eventDate"),G&&G!=="all"?Le.set("itemType",G):Le.delete("itemType"),$&&$!=="all"?Le.set("referral",$):Le.delete("referral"),ie&&ie!=="all"?Le.set("source",ie):Le.delete("source"),window.history.replaceState({},"",`${R.pathname}?${Le.toString()}`)}catch{}},[m,f,E,S,F,re,G,$,ie,we]),r.useMemo(()=>!we||!E?null:En(E),[E,we]),r.useMemo(()=>
2{if(!we||!S)return null;const R=En(S);return R?(R.setHours(23,59,59,999),R):null},[S,we]);function k(R){if(!R)return null;try{if(R instanceof Date)return Number.isNaN(R.valueOf())?null:R;if(typeof R=="string"){const Le=zt(R);return Number.isNaN(Le.valueOf())?null:Le}}catch{return null}return null}const De=R=>{const Le=R?.attributes||{};return Array.isArray(Le.items?.data)?Le.items.data.map(as=>as?.attributes||as).filter(Boolean):Array.isArray(Le.items)?Le.items.map(as=>as?.attributes||as).filter(Boolean):[]},Ne=r.useMemo(()=>(Array.isArray(T)?T:[]).sort((R,Le)=>R.localeCompare(Le)).map(R=>{const Le=zt(R);return Number.isNaN(Le.valueOf())?{value:R,label:R}:{value:R,label:Us(Le,"dd/MM/yyyy",{locale:Vs})}}),[T]),es=R=>{if(!R||!R.attributes)return!1;const Le=R.attributes;return!!(Le.referral_code&&`${Le.referral_code}`.trim()||Le.link_convite?.data)},ss=oe,We=Math.max(1,Number(C?.pageCount||1));r.useEffect(()=>{g>We&&N(We)},[g,We]);const hs=ss,Is=R=>Ua(R),Y=(R,Le)=>{ve(as=>as.map(ms=>ms?.id!==R?ms:{...ms,attributes:{...ms.attributes||{},referral_code:Le||null}}))},Q=(R,Le,as={},ms={})=>{const{status:Ke,fromDate:gs,toDate:fs,eventId:Ms,eventDate:Fs,itemType:As,referral:ws,source:Rs,search:us,onlyWithNecessidades:Gs}=as,Ss=new URLSearchParams;return Ss.set("pagination[page]",String(R)),Ss.set("pagination[pageSize]",String(Le)),Ke&&Ke!=="all"&&Ss.set("status",Ke),gs&&Ss.set("fromDate",gs),fs&&Ss.set("toDate",fs),Ms&&Ss.set("eventId",Ms),Fs&&Ss.set("eventDate",Fs),As&&As!=="all"&&Ss.set("itemType",As),ws&&ws!=="all"&&Ss.set("referral",ws.toUpperCase()),Rs&&Rs!=="all"&&Ss.set("source",Rs),us&&Ss.set("search",us),Gs&&Ss.set("onlyWithNecessidades","true"),ms.includeSummary===!1&&Ss.set("includeSummary","false"),ms.includeEventDateOptions&&Ss.set("includeEventDateOptions","true"),`/pedidos/dashboard-data?${Ss.toString()}`};r.useEffect(()=>{let R=!1;return(async()=>{try{_e(!0),J(null);const as=await $e.get(Q(g,b,xs,{includeSummary:!0,includeEventDateOptions:!!Se})),ms=as?.data?.data||[],Ke=as?.data?.meta?.pagination||{},gs=as?.data?.meta?.summary||Bi,fs=Array.isArray(as?.data?.meta?.eventDateOptions)?as.data.meta.eventDateOptions:[],Ms=jo(ms);if(R)return;ve(Ms),q({page:Number(Ke.page||g),pageSize:Number(Ke.pageSize||b),pageCount:Number(Ke.pageCount||1),total:Number(Ke.total||Ms.length||0)}),fe({totalSold:Number(gs.totalSold||0),totalOrders:Number(gs.totalOrders||0),totalOrdersAll:Number(gs.totalOrdersAll||0),refunds:Number(gs.refunds||0),averageTicket:Number(gs.averageTicket||0),paymentMethods:{pix:Number(gs?.paymentMethods?.pix||0),credito:Number(gs?.paymentMethods?.credito||0),debito:Number(gs?.paymentMethods?.debito||0)}}),Ee(fs)}catch(as){if(R)return;ve([]),q({page:1,pageSize:b,pageCount:1,total:0}),fe(Bi),Ee([]),J(as)}finally{R||_e(!1)}})(),()=>{R=!0}},[xs,g,b,Se]);const X=r.useMemo(()=>{const R=Array.isArray(qe?.data)?qe.data.map(ms=>(ms?.attributes?.referral||ms?.referral||"").toString().toUpperCase()):[],Le=Array.isArray(oe)?oe.flatMap(ms=>[((ms?.attributes||{}).referral_code||"").toString().toUpperCase()].filter(Boolean)):[],as=new Set([...R,...Le].filter(Boolean));return Array.from(as).sort().map(ms=>({value:ms,label:ms}))},[qe,oe]),V=async()=>{try{if(le){s({title:"Aguarde o carregamento",description:"Os pedidos ainda estao sendo atualizados com os filtros atuais."});return}M(!0);const R=await fo({pageSize:pi,fetchPage:(ys,Ps)=>$e.get(Q(ys,Ps,xs,{includeSummary:!1,includeEventDateOptions:!1}))}),Le=jo(R),as=ys=>{const Bs=(ys?.attributes||{})?.dados_faturamento;if(!Bs)return"";const dt=Bs?.telefone;if(dt!=null&&String(dt).trim())return String(dt).trim();const Ts=Bs?.customer?.phones?.mobile_phone,Mt=Ts?.area_code!=null?String(Ts.area_code).trim():"",Ys=Ts?.number!=null?String(Ts.number).trim():"";return`${Ts?.country_code!=null?String(Ts.country_code).trim():""}${Mt}${Ys}`.trim()},ms=Le.map(ys=>{const Ps=ys.attributes||{},Bs=Ui(ys),dt=[...new Set(tp(ys).map(Tt=>String(Tt?.metodo_pagamento||"").trim()).filter(Boolean))],Ts=Ps.usuario?.data?.attributes||{},Ys=(Array.isArray(Ps.eventos?.data)?Ps.eventos.data:Array.isArray(Ps.eventos)?Ps.eventos:[]).map(Tt=>
2Tt?.attributes?.titulo||Tt?.titulo).filter(Boolean).join(", "),ht=dt.length>0?dt.join(" + "):(Ps.metodo_pagamento||Ps.pagamento||"").toString(),Xs=De(ys).reduce((Tt,Js)=>Tt+Number(Js?.quantidade??1),0),xt=Ps.data_pedido||Ps.createdAt,{dateLabel:ia,timeLabel:oa}=zi(xt),st=(Ps.status_pedido||Ps.status||"").toString(),wt=Is(ys),va=((Ps.referral_code||Ps.link_convite?.data?.attributes?.referral||"")+"").toUpperCase(),la=as(ys),da=(Ps.necessidades||"").toString().trim();return{ID:ys.id,Usuário:Ts.nome||Bs?.name||"","E-mail":Ts.email||Bs?.email||"",Telefone:la,Eventos:Ys,Método:ht,Origem:wn(ys)?.source==="pos"?"POS":"Online",Status:st,"Qtd Itens":Xs,Total:Number(wt)||0,"Necessidades Especiais":da,Cupom:Ps.codigo_cupom||"",Data:ia,Hora:oa,...z?{Referral:va}:{}}}),Ke=await $r(()=>import("./vendor-exceljs-AsZnDCZx.js").then(ys=>ys.e),__vite__mapDeps([0,1,2])),gs=Ke.default||Ke,fs=new gs.Workbook,Ms=fs.addWorksheet("Pedidos"),Fs=[{header:"ID",key:"ID",width:8},{header:"Usuário",key:"Usuário",width:22},{header:"E-mail",key:"E-mail",width:28},{header:"Telefone",key:"Telefone",width:14},{header:"Eventos",key:"Eventos",width:30},{header:"Método",key:"Método",width:14},{header:"Status",key:"Status",width:12},{header:"Qtd Itens",key:"Qtd Itens",width:10},{header:"Total",key:"Total",width:14},{header:"Necessidades Especiais",key:"Necessidades Especiais",width:35},{header:"Cupom",key:"Cupom",width:16},{header:"Data",key:"Data",width:12},{header:"Hora",key:"Hora",width:8}];z&&Fs.push({header:"Referral",key:"Referral",width:14}
2),Ms.columns=Fs,ms.forEach(ys=>Ms.addRow(ys)),Ms.getRow(1).font={bold:!0};for(let ys=2;ys<=ms.length+1;ys++){const Ps=Ms.getCell(`I${ys}`);typeof Ps.value=="number"&&(Ps.numFmt='"R$" #,##0.00')}const ws=`pedidos_${Us(new Date,"yyyy-MM-dd")}.xlsx`,Rs=await fs.xlsx.writeBuffer(),us=new Blob([Rs],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),Gs=URL.createObjectURL(us),Ss=document.createElement("a");Ss.href=Gs,Ss.download=ws,document.body.appendChild(Ss),Ss.click(),Ss.remove(),URL.revokeObjectURL(Gs);try{s({title:"Exportação concluída",description:`${ms.length} pedidos exportados para ${ws}.`})}catch{}}catch(R){console.error("Falha ao exportar pedidos:",R);try{s({title:"Falha ao exportar",description:"Veja o console para detalhes.",variant:"destructive"})}catch{alert("Falha ao exportar pedidos. Veja o console para detalhes.")}}finally{M(!1)}},pe=t.habilitar_links_convite!==!1&&t.atualizar_convite_pago===!1,Ce=async(R,Le,as)=>{try{const ms=Le||R;if(!window.confirm(`Confirmar marcar pedido ${ms?`#${ms}`:""} como pago?`))return;Le?await $e.put(`/pedidos/doc/${Le}`,{data:{status_pedido:"pago"}}):await $e.put(`/pedidos/${R}`,{data:{status_pedido:"pago"}})}catch(ms){throw console.error("Falha ao marcar pedido como pago",ms),ms}},Ue=R=>Qn(R),Xe=R=>aa(R),Ve=(t?.habilitar_estatisticas_pedidos??t?.estatisticas_pedidos??t?.estatiscas_pedidos??!0)!==!1,bs=!!(E||S||Se||re||G!=="all"||$!=="all"||ie!=="all"||f!=="all"||Ae),ts=r.useMemo(()=>{const R=[];return f!=="all"&&R.push(`Status: ${f}`),G!=="all"&&R.push(`Tipo: ${G}`),Se&&R.push("Evento selecionado"),re&&R.push("Data do evento"),$!=="all"&&R.push(`Código: ${$}`),ie!=="all"&&R.push(`Origem: ${ie}`),Ae&&R.push("Com necessidades"),E&&S&&R.push(`${E} → ${S}`),R.join(" · ")||"Sem filtros adicionais"},[f,G,Se,re,$,ie,E,S,Ae]);return U?e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsxs("div",{className:"text-center text-red-600",children:["Erro ao carregar pedidos",U.response?.status&&` (código ${U.response.status})`,": ",U.message,".",e.jsx("br",{}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Verifique a aba Network do navegador para detalhes e tente novamente."})]})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Gerenciar Pedidos"}),e.jsx("p",{className:"text-muted-foreground",children:"Visualize e gerencie todos os pedidos do sistema"})]}),e.jsx(w,{asChild:!0,variant:"outline",size:"sm",children:e.jsx("a",{href:"/scanner",children:"Abrir Scanner"})})]}),Ve?e.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 ${l?"lg:grid-cols-4":"lg:grid-cols-2"} gap-4`,children:[l&&e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"💳 Total Vendido"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:Xe(me.totalSold)})]})})})}),e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"🧾 Total de Pedidos"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:me.totalOrdersAll})]})})})}),e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"🚫 Cancelados"}),e.jsx("p",{className:"text-2xl font-bold text-red-600",children:me.refunds})]})})})}),l&&e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"📊 Ticket Médio"}),e.jsx("p",{className:"text-2xl font-bold text-purple-600",children:Xe(me.averageTicket)})]})})})})]}):e.jsx("div",{className:"grid grid-cols-1 gap-4",children:e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"🧾 Total de Pedidos"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:me.totalOrdersAll})]})})})})}),Ve&&e.jsxs(he,{children:[e.jsx(Be,{children:e.jsx(ze,{className:"text-lg",children:"Métodos de Pagamento"})}),e.jsxs(ge,{children:[e.jsxs("div",{className:"hidden md:grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-green-600",children:me.paymentMethods.pix}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"PIX"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:me.paymentMethods.credito}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Crédito"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-orange-600",children:me.paymentMethods.debito}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Débito"})]})]}),e.jsxs("div",{className:"md:hidden",children:[e.jsx(Ca,{width:"100%",height:200,children:e.jsx(sc,{children:e.jsx(tc,{data:[{name:"PIX",value:me.paymentMethods.pix,color:"#16a34a"},{name:"Crédito",value:me.paymentMethods.credito,color:"#2563eb"},{name:"Débito",value:me.paymentMethods.debito,color:"#ea580c"}].filter(R=>R.value>0),cx:"50%",cy:"50%",innerRadius:40,outerRadius:80,paddingAngle:5,dataKey:"value",children:[{name:"PIX",value:me.paymentMethods.pix,color:"#16a34a"},{name:"Crédito",value:me.paymentMethods.credito,color:"#2563eb"},{name:"Débito",value:me.paymentMethods.debito,color:"#ea580c"}].filter(R=>R.value>0).map((R,Le)=>e.jsx(ac,{fill:R.color},`cell-${Le}`))})})}),e.jsxs("div",{className:"flex justify-center gap-4 mt-2",children:[me.paymentMethods.pix>0&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-3 bg-green-600 rounded-full"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PIX (",me.paymentMethods.pix,")"]})]}),me.paymentMethods.credito>0&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-3 bg-blue-600 rounded-full"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Crédito (",me.paymentMethods.credito,")"]})]}),me.paymentMethods.debito>0&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-3 bg-orange-600 rounded-full"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Débito (",me.paymentMethods.debito,")"]})]})]})]})]})]}),e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-[260px]",children:[e.jsx("div",{className:"block text-xs font-medium text-muted-foreground mb-2",children:"Buscar"}),e.jsxs("div",{className:"relative",children:[e.jsx(At,{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(Te,{placeholder:"Buscar por ID, usuário ou evento... ( Enter para buscar )",value:h,onChange:R=>p(R.target.value),onKeyDown:R=>{R.key==="Enter"&&x(h)},className:"pl-10 w-full max-w-3xl","aria-label":"Buscar por ID, usuário ou evento"})]})]}),e.jsxs("div",{className:"flex md:flex-row sm:flex-col items-end md:gap-8 gap-2 lg:justify-end",children:[e.jsxs(fr,{open:Fe,onOpenChange:ae,children:[e.jsx(jr,{asChild:!0,children:e.jsxs(w,{variant:bs?"outline":"default",size:"sm",className:"gap-2 s",children:[e.jsx(Hd,{className:"h-4 w-4"}),"Filtros",e.jsx("span",{className:"hidden sm:inline text-xs text-muted-foreground truncate max-w-[180px]",children:ts})]})}),e.jsxs(ar,{className:"w-[min(420px,94vw)] space-y-4",align:"end",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Status"}),e.jsxs(rs,{value:f,onValueChange:I,children:[e.jsxs(ns,{className:"w-full",children:[e.jsx(Ci,{className:"mr-2 h-4 w-4"}),e.jsx(is,{placeholder:"Todos status"})]}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos Status"}),e.jsx(xe,{value:"pago",children:"Pago"}),e.jsx(xe,{value:"pendente",children:"Pendente"}),e.jsx(xe,{value:"cancelado",children:"Cancelado"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Tipo"}),e.jsxs(rs,{value:G,onValueChange:y,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Tipo de item"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos itens"}),e.jsx(xe,{value:"ingresso",children:"Ingressos"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Evento"}),e.jsxs(rs,{value:F,onValueChange:ee,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Todos eventos"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos eventos"}),Qe.map(R=>e.jsx(xe,{value:R.value,children:R.label},R.value))]})]})]}),Se&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Data do evento"}),e.jsxs(rs,{value:re||"all",onValueChange:R=>te(R==="all"?"":R),children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Todas as datas"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todas as datas"}),Ne.map(R=>e.jsx(xe,{value:R.value,children:R.label},R.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Código de vendedor"}),e.jsxs(rs,{value:$,onValueChange:W,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Todos os códigos"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos os códigos"}),X.map(R=>e.jsx(xe,{value:R.value,children:R.label},R.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Origem"}),e.jsxs(rs,{value:ie,onValueChange:ke,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Origem"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todas origens"}),e.jsx(xe,{value:"online",children:"Online"}),e.jsx(xe,{value:"fisico",children:"Físico (Maquininha)"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-input px-3 py-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"text-xs font-medium",children:"Necessidades especiais"}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Exibir apenas pedidos com necessidades preenchidas"})]}),e.jsx(Ls,{checked:Ae,onCheckedChange:be})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Período"," ",E&&!S||!E&&S?e.jsx("span",{className:"text-amber-600",children:"(selecione ambos)"}):""]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-lg ${E&&!S||!E&&S?"border-amber-600":"border-input"}`,children:[e.jsx(Rr,{language:"pt-BR",showClearButton:!1,showTodayButton:!1,title:"De",theme:_l,value:Me,onChange:R=>{const Le=R instanceof Date&&!Number.isNaN(R.valueOf())?R:null,as=Le?wl(Le):"";A(as),S&&as&&as>S&&P(as)},className:"flex-1"}),e.jsx("span",{className:"text-muted-foreground font-medium px-1",children:"→"}),e.jsx(Rr,{language:"pt-BR",showClearButton:!1,showTodayButton:!1,title:"Até",theme:_l,value:ks,onChange:R=>{const Le=R instanceof Date&&!Number.isNaN(R.valueOf())?R:null,as=Le?wl(Le):"";P(as),E&&as&&as<E&&A(as)},className:"flex-1"}),(E||S)&&e.jsx("button",{onClick:()=>{A(""),P("")},className:"p-1 text-muted-foreground hover:text-foreground hover:bg-accent rounded text-lg leading-none",type:"button",title:"Limpar período",children:"✕"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>{A(""),P(""),ee("all"),te(""),y("all"),I("all"),W("all"),ke("all"),be(!1)},children:"Limpar filtros"}),e.jsx(w,{size:"sm",onClick:()=>ae(!1),children:"Fechar"})]})]})]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:V,disabled:L||le,className:"min-w-[140px] whitespace-nowrap w-full md:w-auto",children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),L?"Exportando…":"Exportar"]}),(E||S||Se||re||G!=="all"||$!=="all"||ie!=="all"||f!=="all"||m||Ae)&&e.jsx(w,{variant:"ghost",type:"button",size:"sm",className:"whitespace-nowrap",onClick:()=>{p(""),x(""),A(""),P(""),ee("all"),te(""),y("all"),I("all"),W("all"),ke("all"),be(!1)},children:"Limpar filtros"})]})]})})}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{children:["Pedidos (",C.total||me.totalOrdersAll||0,")"]})}),e.jsxs(ge,{className:"relative",children:[le&&e.jsx("div",{className:"absolute inset-0 bg-background/60 backdrop-blur-sm rounded-lg flex items-center justify-center z-50",children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx(It,{size:36,thickness:4}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Carregando pedidos..."})]})}),ss.length===0?e.jsx("div",{className:"text-center py-8",children:e.jsx("p",{className:"text-muted-foreground",children:"Nenhum pedido encontrado"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto hidden md:block",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"ID"}),e.jsx(ue,{children:"Usuário"}),e.jsx(ue,{children:"Eventos"}),e.jsx(ue,{children:"Status"}),l&&e.jsx(ue,{children:"Total"}),e.jsx(ue,{children:"Cupom"}),e.jsx(ue,{children:"Link Vendedor"}),e.jsx(ue,{children:"Data"}),e.jsx(ue,{children:"Ações"})]})}),e.jsx(Ct,{children:hs.map(R=>{if(!R||!R.attributes)return null;const Le=Ue(R.attributes.status_pedido||R.attributes.status);k(R.attributes.data_pedido||R.attributes.createdAt);const as=zi(R.attributes.data_pedido||R.attributes.createdAt),ms=vo(R);return e.jsxs($s,{children:[e.jsxs(ye,{className:"font-medium",children:["#",R.id]}),e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(nn,{className:"h-8 w-8",children:[R.attributes.usuario?.data?.attributes?.avatar?.data?.attributes?.url&&e.jsx(Zn,{src:qt(R.attributes.usuario.data.attributes.avatar.data.attributes.url),alt:R.attributes.usuario?.data?.attributes?.nome||"Usuario"}),e.jsx(on,{children:(R.attributes.usuario?.data?.attributes?.nome||(Vr(R)?"POS":"U")).toString().trim().split(" ").slice(0,2).map(Ke=>Ke[0]).join("").toUpperCase()})]}),e.jsx("div",{children:R.attributes.usuario?.data?.attributes?.nome?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"font-medium",children:R.attributes.usuario.data.attributes.nome}),e.jsx("div",{className:"text-sm text-gray-500",children:R.attributes.usuario.data.attributes.email||"N/A"})]}):Vr(R)?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(je,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-amber-400 text-amber-600",children:"POS"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Sem usuário"})]}),(()=>{const Ke=Ui(R);return Ke?.email||Ke?.name?e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[160px]",children:Ke.name||Ke.email}):null})()]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"font-medium",children:"N/A"}),e.jsx("div",{className:"text-sm text-gray-500",children:"N/A"})]})})]})}),e.jsx(ye,{children:e.jsx("div",{className:"max-w-[200px]",children:(Array.isArray(R.attributes.eventos?.data)?R.attributes.eventos.data.length:Array.isArray(R.attributes.eventos)?R.attributes.eventos.length:0)>
20?e.jsxs("div",{className:"space-y-1",children:[(Array.isArray(R.attributes.eventos?.data)?R.attributes.eventos.data:R.attributes.eventos).slice(0,2).map((Ke,gs)=>e.jsx("div",{className:"text-sm truncate text-foreground",children:Ke?.attributes?.titulo||Ke?.titulo||"Evento sem título"},gs)),(Array.isArray(R.attributes.eventos?.data)?R.attributes.eventos.data.length:(R.attributes.eventos||[]).length)>2&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["+",(Array.isArray(R.attributes.eventos?.data)?R.attributes.eventos.data.length:(R.attributes.eventos||[]).length)-2," mais"]})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Nenhum evento"})})}),e.jsx(ye,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(je,{variant:Le.variant,className:Le.className+" w-fit",children:Le.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(()=>{const Ke=R.attributes.items||[],gs=Ke.filter(Ms=>(Ms.status||"disponivel")==="disponivel").length,fs=Ke.filter(Ms=>Ms.status==="usado").length;return`${gs} disponivel · ${fs} usado`})()}),t.habilitar_links_convite!==!1&&ie&&ie!=="all"&&(()=>{const Ke=((R.attributes.referral_code||R.attributes.link_convite?.data?.attributes?.referral||"")+"").toUpperCase();return Ke?e.jsx("div",{className:"mt-1",children:e.jsxs(je,{variant:"outline",className:"w-fit",children:["Convite: ",Ke]})}):null})()]})}),l&&e.jsx(ye,{className:"font-medium",children:Xe(Is(R))}),e.jsx(ye,{children:R.attributes.codigo_cupom?e.jsx(je,{variant:"outline",className:"gap-1 text-xs font-mono",children:R.attributes.codigo_cupom}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[ms?e.jsx(je,{variant:"secondary",className:"text-xs font-mono",children:ms}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"}),e.jsx(kl,{pedido:R,referralOptions:X,onUpdated:Ke=>Y(R.id,Ke)})]})}),e.jsxs(ye,{children:[e.jsx("div",{className:"text-sm text-foreground",children:as.dateLabel||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:as.timeLabel||""})]}),e.jsx(ye,{children:e.jsxs(Sr,{children:[e.jsx(Ir,{asChild:!0,children:e.jsx(w,{type:"button",variant:"ghost",size:"sm",children:e.jsx(tm,{className:"h-4 w-4"})})}),e.jsxs(Ar,{align:"end",className:"w-64",children:[e.jsx(Vn,{children:"Ações"}),l&&e.jsx(tt,{disabled:!0,className:"opacity-100",children:(()=>{const Ke=!!(R.attributes.referral_code&&`${R.attributes.referral_code}`.trim()||R.attributes.link_convite?.data);return e.jsxs("span",{className:"text-sm",children:["Total: ",e.jsx("span",{className:"font-medium",children:Ke?"—":Xe(ap(R))})]})})()}),R.attributes?.documentId&&e.jsx(tt,{asChild:!0,children:e.jsxs(lt,{to:`/pedido/${R.attributes.documentId}`,className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"h-4 w-4"})," Ver pedido"]})}),R.attributes?.usuario?.data?.id&&e.jsx(tt,{asChild:!0,children:e.jsxs(lt,{to:`/dashboard/usuarios?usuarioId=${R.attributes.usuario.data.id}`,className:"flex items-center gap-2",children:[e.jsx(Er,{className:"h-4 w-4"})," Ver usuário"]})}),u&&Vr(R)&&e.jsx(tt,{onSelect:Ke=>Ke.preventDefault(),className:"p-0",children:e.jsx(Cl,{pedidoId:R.id,onAssigned:()=>window.location.reload()})}),e.jsx(Gn,{}),pe&&es(R)&&(R.attributes?.status_pedido||R.attributes?.status)!=="pago"&&e.jsxs(tt,{onClick:async()=>{try{await Ce(R.id,R.attributes?.documentId,!0),window.location.reload()}catch{}},children:[e.jsx(wa,{className:"h-4 w-4 mr-2"})," Marcar como pago"]}),e.jsx(Gn,{}),e.jsx(Vn,{children:"Itens"}),(R.attributes.items||[]).slice(0,5).map(Ke=>{const gs=Ke.status||"disponivel";return e.jsxs(tt,{className:"text-sm flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(Ea,{className:"h-3 w-3 mr-2"})," #",Ke.id," • ",Ke.evento?.data?.attributes?.titulo||Ke.evento?.attributes?.titulo||Ke.evento?.titulo||"Evento"," x",Ke.quantidade||1]}),e.jsx(je,{variant:gs==="usado"?"destructive":"secondary",className:"capitalize",children:gs})]},Ke.id)}),Array.isArray(R.attributes.items)&&R.attributes.items.length>5&&e.jsxs(tt,{className:"text-xs text-muted-foreground",children:["+",R.attributes.items.length-5," mais…"]}),e.jsx(Gn,{}),e.jsx(Vn,{children:"Alterar status do item"}),(R.attributes.items||[]).slice(0,5).map(Ke=>e.jsxs(tt,{onClick:async()=>{try{await $e.post("/scanner/use",{pedidoId:R.id,itemId:Ke.id}),window.location.reload()}catch(gs){console.error("Falha ao marcar item como usado",gs)}},children:[e.jsx(wa,{className:"h-4 w-4 mr-2"})," Marcar item #",Ke.id," como usado"]},`use-${Ke.id}`)),e.jsxs(tt,{onClick:async()=>{try{const Ke=(R.attributes.items||[]).filter(gs=>(gs.status||"disponivel")==="disponivel");for(const gs of Ke)await $e.post("/scanner/use",{pedidoId:R.id,itemId:gs.id});window.location.reload()}catch(Ke){console.error("Falha ao marcar todos como usados",Ke)}},children:[e.jsx(wa,{className:"h-4 w-4 mr-2"})," Marcar todos disponiveis como usados"]})]})]})})]},R.id)}
2).filter(Boolean)})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:hs.map(R=>{if(!R||!R.attributes)return null;const Le=R.attributes.status_pedido||R.attributes.status,as=Ue(Le),ms=String(Le||"").toLowerCase(),Ke=ms==="pendente"||ms==="cancelado"||ms==="falho"||ms==="falhou";k(R.attributes.data_pedido||R.attributes.createdAt);const gs=zi(R.attributes.data_pedido||R.attributes.createdAt),fs=R.attributes.usuario?.data?.attributes?.email||"",Ms=Is(R),Fs=!!(R.attributes.referral_code&&`${R.attributes.referral_code}`.trim()||R.attributes.link_convite?.data),As=vo(R),Rs=((Array.isArray(R.attributes.eventos?.data)?R.attributes.eventos.data:Array.isArray(R.attributes.eventos)?R.attributes.eventos:[])||[]).map(us=>us?.attributes?.titulo||us?.titulo).filter(Boolean).join(", ");return e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"text-sm font-medium",children:["#",R.id]})}),e.jsx(je,{variant:as.variant,className:as.className,children:as.label})]}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground truncate",children:Rs||"—"}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2 text-xs text-muted-foreground",children:[e.jsx("div",{children:fs||(Vr(R)?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(je,{variant:"outline",className:"text-[10px] px-1 py-0 border-amber-400 text-amber-600",children:"POS"}),Ui(R)?.email||"Sem usuário"]}):"—")}),l&&e.jsx("div",{className:"text-right text-foreground font-medium",children:Fs?"—":Xe(Ms)}),e.jsxs("div",{className:"col-span-2 flex items-center justify-between",children:[e.jsx("span",{children:gs.dateLabel||"—"}),e.jsx(w,{type:"button",variant:"",size:"sm",className:"h-8 px-2",onClick:()=>O(us=>us===R.id?null:R.id),children:K===R.id?"Fechar":"Ver detalhes"})]}),e.jsxs("div",{className:"col-span-2 flex items-center justify-between pt-1 border-t border-border/70",children:[e.jsx("span",{className:"text-muted-foreground",children:"Link vendedor"}),e.jsxs("div",{className:"flex items-center gap-1",children:[As?e.jsx(je,{variant:"secondary",className:"text-xs font-mono",children:As}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"}),e.jsx(kl,{pedido:R,referralOptions:X,onUpdated:us=>Y(R.id,us)})]})]})]}),K===R.id&&e.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between text-foreground font-semibold",children:[e.jsx("span",{children:"Ações"}),l&&e.jsxs("span",{className:"text-muted-foreground",children:["Total: ",Fs?"—":Xe(Ms)]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[pe&&es(R)&&(R.attributes?.status_pedido||R.attributes?.status)!=="pago"&&e.jsxs(w,{type:"button",size:"sm",variant:"outline",className:"h-8 px-2",onClick:async()=>{try{await Ce(R.id,R.attributes?.documentId,!0),window.location.reload()}catch{}},children:[e.jsx(wa,{className:"h-4 w-4 mr-1"})," Pagar"]}),R.attributes?.documentId&&e.jsx(w,{asChild:!0,type:"button",size:"sm",variant:"outline",className:"h-8 px-2",children:e.jsxs(lt,{to:`/pedido/${R.attributes.documentId}`,className:"flex items-center gap-1",children:[e.jsx(Vt,{className:"h-4 w-4"})," Ver pedido"]})}),R.attributes?.usuario?.data?.id&&e.jsx(w,{asChild:!0,type:"button",size:"sm",variant:"outline",className:"h-8 px-2",children:e.jsxs(lt,{to:`/dashboard/usuarios?usuarioId=${R.attributes.usuario.data.id}`,className:"flex items-center gap-1",children:[e.jsx(Er,{className:"h-4 w-4"})," Ver usuário"]})}),u&&Vr(R)&&e.jsx(Cl,{pedidoId:R.id,onAssigned:()=>window.location.reload()})]}),e.jsxs("div",{className:`pt-2 border-t border-border space-y-2 ${Ke?"opacity-50 blur-[1px] pointer-events-none select-none":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between text-foreground font-semibold",children:[e.jsx("span",{children:"Itens"}),Array.isArray(R.attributes.items)&&R.attributes.items.length>5&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["+",R.attributes.items.length-5," mais…"]})]}),e.jsx("div",{className:"space-y-2",children:(R.attributes.items||[]).slice(0,5).map(us=>{const Gs=us.status||"disponivel";return e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[13px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"h-3 w-3"}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium text-foreground",children:["#",us.id," • ",us.evento?.data?.attributes?.titulo||us.evento?.attributes?.titulo||us.evento?.titulo||"Evento"]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["x",us.quantidade||1]})]})]}),e.jsx(je,{variant:Gs==="usado"?"destructive":"secondary",className:"capitalize",children:Gs})]},us.id)})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[(R.attributes.items||[]).slice(0,5).map(us=>e.jsxs(w,{type:"button",size:"sm",variant:"ghost",className:"h-8 px-2",disabled:Ke,onClick:async()=>{try{await $e.post("/scanner/use",{pedidoId:R.id,itemId:us.id}),window.location.reload()}catch(Gs){console.error("Falha ao marcar item como usado",Gs)}},children:[e.jsx(wa,{className:"h-4 w-4 mr-1"})," Usar #",us.id]},`use-${us.id}`)),e.jsxs(w,{type:"button",size:"sm",variant:"secondary",className:"h-8 px-2",disabled:Ke,onClick:async()=>{try{const us=(R.attributes.items||[]).filter(Gs=>(Gs.status||"disponivel")==="disponivel");for(const Gs of us)await $e.post("/scanner/use",{pedidoId:R.id,itemId:Gs.id});window.location.reload()}catch(us){console.error("Falha ao marcar todos como usados",us)}},children:[e.jsx(wa,{className:"h-4 w-4 mr-1"})," Usar todos disp."]})]})]})]})]},R.id)})}),We>1&&e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Página ",g," de ",We,"(",C.total||me.totalOrdersAll||0," total)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{variant:"outline",size:"sm",onClick:()=>N(R=>Math.max(1,R-1)),disabled:g<=1,children:"Anterior"}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>N(R=>R+1),disabled:g>=We,children:"Próxima"})]})]})]})]})]})]})}const ki=Vm,Si=Gm,Ii=Hm,ip=s=>{if(s==="all")return{from:null,to:null};const t=new Date,a=new Date(t);let n=new Date(t);return s==="today"?n.setHours(0,0,0,0):s==="7d"?n=new Date(t.getTime()-7*24*60*60*1e3):s==="15d"?n=new Date(t.getTime()-15*24*60*60*1e3):s==="30d"?n=new Date(t.getTime()-30*24*60*60*1e3):n=new Date(t.getTime()-7*24*60*60*1e3),{from:n.toISOString(),to:a.toISOString()}},bc=(s,{period:t="7d",group:a="day",enabled:n}={})=>{const{from:o,to:i}=ip(t),u=!!s&&n!==!1,l=new URLSearchParams;u&&(l.set("eventId",String(s)),l.set("group",String(a)),o&&l.set("from",o),i&&l.set("to",i));const c=u?`/pedidos/event-analytics?${l.toString()}`:null;return Ks(["event-analytics",s,t],c||"/__noop__",{enabled:u,retry:1,staleTime:60*1e3})};async function Nc(s){return(await $e.get(`/planejamentos?filters[evento][id][$eq]=${encodeURIComponent(s)}&sort=data:asc&pagination[pageSize]=200`)).data}const Dn=s=>{const t=Number(s);return Number.isFinite(t)?t:0},Ai=s=>String(s?.moeda||"BRL").toUpperCase(),Go=s=>Ai(s)==="USD"&&s?.usar_gateway_pagarme_usd===!0,en=s=>{const t=Array.isArray(s?.datas_futuras)?s.datas_futuras.filter(
2Boolean):[],a=t.filter(c=>c?.ativo===!0&&c?.data),n=a.length>0?a:t.filter(c=>c?.data),o=n.length>0?n.reduce((c,m)=>c+Dn(m?.ingressos_disponiveis),0):Dn(s?.ingressos_disponiveis),i=n.length>0?n.reduce((c,m)=>c+Dn(m?.limite_ingressos),0):Dn(s?.limite_ingressos),u=Math.max(0,i-o),l=i>0?Math.round(u/i*100):null;return{available:o,limit:i,sold:u,soldPercent:l,scopedToActiveDates:a.length>0}},Sl=s=>s?s.limit>0&&s.available===0&&s.soldPercent!==null?{primary:`${s.soldPercent}% vendidos`,secondary:s.scopedToActiveDates?"datas ativas combinadas":"capacidade total"}:{primary:_a(s.available),secondary:s.limit>0&&s.soldPercent!==null?`${s.soldPercent}% vendidos`:"disponíveis"}:{primary:"—",secondary:null};function Ho({evento:s,onSaved:t}){const{formatPrice:a,convertFromBRL:n}=jn(),o=s?.attributes||s||{},i=r.useMemo(()=>Array.isArray(o.lotes)?o.lotes:[],[o.lotes]),u=r.useMemo(()=>Array.isArray(o.datas_futuras)?o.datas_futuras:[],[o.datas_futuras]),l=o.documentId||s?.documentId||null,c=Ai(o),m=Go(o),x=D=>{const E=Number(D||0),A=m?n(E,c):E;return a(A,c)},[h,p]=r.useState({}),[f,I]=r.useState(!1),[g,N]=r.useState(new Set),b=(D,E)=>h[`${D}::${E}`],C=(D,E,A)=>p(S=>({...S,[`${D}::${E}`]:A})),q=Object.keys(h).length>0,L=r.useMemo(()=>{const D=new Map;for(const A of u){const S=Et(A?.data)||"__unknown";D.set(S,{label:cn(A.data),limite:A.limite_ingressos??null,disp:A.ingressos_disponiveis??null,lotes:[]})}const E=D.keys().next().value;for(const A of i){const S=Et(A?.data_evento)||E;S&&D.has(S)?D.get(S).lotes.push(A):S&&D.set(S,{label:cn(A.data_evento),limite:null,disp:null,lotes:[A]})}return D},[i,u]),M=async()=>{I(!0);try{const D=i.map(A=>{const S=b(A.id,"quantidade_disponivel"),P=b(A.id,"ativo");return un({...A,...S===void 0?{}:{quantidade_disponivel:Number(S)},...P===void 0?{}:{ativo:P}})}),E=o.documentId||s?.documentId;await $e.put(`/eventos/${E}`,{data:{lotes:D}}),p({}),t?.()}catch(D){console.error("Falha ao salvar lotes do evento",D)}finally{I(!1)}},z=D=>N(E=>{const A=new Set(E);return A.has(D)?A.delete(D):A.add(D),A});return i.length===0?e.jsxs("div",{className:"flex items-center gap-2 py-3 text-xs text-muted-foreground",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"}),"Nenhum lote cadastrado"]}):e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Lotes"]}),q&&e.jsxs(w,{size:"sm",className:"h-7 gap-1.5 text-xs",onClick:M,disabled:f,children:[e.jsx(Da,{className:"h-3 w-3"}),f?"Salvando...":"Salvar lotes"]})]}),Array.from(L.entries()).map(([D,E])=>{const A=g.has(D),S=l&&D!=="__unknown"?`/dashboard/eventos/${encodeURIComponent(l)}/data/${encodeURIComponent(D)}`:null,P=E.limite??0,F=E.disp??0,ee=P>0?Math.min(100,Math.round((P-F)/P*100)):0,re=P>0&&F===0,te=P>0&&F>0&&F<=10,G=re?"bg-rose-500":te?"bg-amber-500":"bg-emerald-500",y=re?"text-rose-600":te?"text-amber-600":"text-muted-foreground";return e.jsxs(ki,{open:A,onOpenChange:()=>z(D),children:[e.jsx(Si,{asChild:!0,children:e.jsxs("button",{type:"button",className:"w-full flex items-center gap-2.5 py-1.5 px-2 rounded-md hover:bg-muted/50 transition-colors text-left group",children:[e.jsx(ra,{className:ls("h-3.5 w-3.5 text-muted-foreground transition-transform duration-150 shrink-0",A&&"rotate-180")}),e.jsx("span",{className:"text-xs font-semibold capitalize flex-1 truncate",children:E.label}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[E.lotes.length===0&&e.jsx(je,{variant:"destructive",className:"text-[9px] px-1 py-0 h-4",children:"Sem lotes"}),P>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"h-1 w-16 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:ls("h-full rounded-full transition-all",G),style:{width:`${ee}%`}})}),e.jsxs("span",{className:ls("text-[10px] tabular-nums font-medium",y),children:[F,"/",P]})]})]})]})}),e.jsxs(Ii,{children:[S?e.jsx("div",{className:"pl-6 pt-1",children:e.jsx(w,{asChild:!0,variant:"outline",size:"sm",className:"h-7 gap-1.5 text-xs",children:e.jsxs(lt,{to:S,children:[e.jsx(sr,{className:"h-3.5 w-3.5"}),"Ver pessoas desta data"]})})}):null,E.lotes.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden sm:block mt-1 rounded-md border overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/40 text-[10px] uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"text-left font-medium px-3 py-1.5",children:"Lote"}),e.jsx("th",{className:"text-left font-medium px-3 py-1.5",children:"Tipo"}),e.jsx("th",{className:"text-right font-medium px-3 py-1.5",children:"Preç
2o"}),e.jsx("th",{className:"text-center font-medium px-3 py-1.5",children:"Estoque"}),e.jsx("th",{className:"text-center font-medium px-3 py-1.5",children:"Ativo"})]})}),e.jsx("tbody",{className:"divide-y divide-border/40",children:E.lotes.map($=>{const W=$.tipo_ingresso||{},ie=W.progressivo===!0,ke=ie?Math.max(1,Number(W.quantidade_itens||1)):null,Ae=b($.id,"quantidade_disponivel")??$.quantidade_disponivel??0,be=b($.id,"ativo")??$.ativo!==!1,Fe=b($.id,"quantidade_disponivel")!==void 0||b($.id,"ativo")!==void 0;return e.jsxs("tr",{className:ls("transition-colors",!be&&"opacity-50",Fe&&"bg-amber-50/40 dark:bg-amber-950/20"),children:[e.jsx("td",{className:"px-3 py-1.5 font-medium",children:e.jsxs("div",{className:"flex items-center gap-1",children:[$.nome||"—",ie&&e.jsxs(je,{variant:"outline",className:"text-[9px] px-1 py-0 h-4 border-violet-300 text-violet-600",children:[ke,"x"]})]})}),e.jsx("td",{className:"px-3 py-1.5 text-muted-foreground",children:W.nome||W.titulo||"—"}),e.jsx("td",{className:"px-3 py-1.5 text-right tabular-nums",children:x($.preco_lote)}),e.jsx("td",{className:"px-3 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Te,{type:"number",min:0,className:ls("w-16 h-6 text-xs text-center tabular-nums p-1",Fe&&"ring-1 ring-amber-400"),value:Ae,onChange:ae=>C($.id,"quantidade_disponivel",ae.target.value)}),ie&&e.jsxs("span",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:["=",Number(Ae)*ke]})]})}),e.jsx("td",{className:"px-3 py-1.5 text-center",children:e.jsx(Ls,{checked:be,onCheckedChange:ae=>C($.id,"ativo",ae),className:"scale-75 origin-center"})})]},$.id)})})]})}),e.jsx("div",{className:"sm:hidden mt-1 space-y-1.5",children:E.lotes.map($=>{const W=$.tipo_ingresso||{},ie=W.progressivo===!0,ke=ie?Math.max(1,Number(W.quantidade_itens||1)):null,Ae=b($.id,"quantidade_disponivel")??$.quantidade_disponivel??0,be=b($.id,"ativo")??$.ativo!==!1,Fe=b($.id,"quantidade_disponivel")!==void 0||b($.id,"ativo")!==void 0;return e.jsxs("div",{className:ls("rounded border px-3 py-2 space-y-2 text-xs",!be&&"opacity-50",Fe&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1 font-medium",children:[$.nome||"—",ie&&e.jsxs(je,{variant:"outline",className:"text-[9px] px-1 py-0 h-4 border-violet-300 text-violet-600",children:[ke,"x"]})]}),e.jsx("span",{className:"tabular-nums text-muted-foreground",children:x($.preco_lote)})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Qtd"}),e.jsx(Te,{type:"number",min:0,className:ls("w-16 h-6 text-xs text-center p-1",Fe&&"ring-1 ring-amber-400"),value:Ae,onChange:ae=>C($.id,"quantidade_disponivel",ae.target.value)}),ie&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["=",Number(Ae)*ke]})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-auto",children:[e.jsx("span",{className:"text-muted-foreground",children:"Ativo"}),e.jsx(Ls,{checked:be,onCheckedChange:ae=>C($.id,"ativo",ae),className:"scale-75 origin-center"})]})]})]},$.id)})})]}):e.jsx("p",{className:"text-[11px] text-muted-foreground pl-6 py-1",children:"Nenhum lote para esta data."})]})]},D)})]})}Ho.propTypes={evento:se.object.isRequired,onSaved:se.func};Ho.defaultProps={onSaved:void 0};function op({evento:s,eventDate:t,eventStatus:a,ordersType:n,ordersPeriod:o,ordersStatus:i}){const{formatPrice:u,convertFromBRL:l}=jn(),c=s.id,{config:m}=Fr({refetchOnWindowFocus:!1}),x=m.habilitar_links_convite===!0||m.habilitar_bar===!1&&m.habilitar_combos===!1&&m.habilitar_estoque===!1,{data:h,isLoading:p}=bc(c,{period:o,enabled:!x}),f=na(),{data:I,isLoading:g}=Rt({queryKey:["planejamentos",c],queryFn:()=>Nc(c),staleTime:30*1e3,enabled:!!c&&!x}),[N,b]=r.useState({titulo:"",tipo:"custo",categoria:"",valor:"",data:"",descricao:"",pago:!1}),[C,q]=r.useState(null),[L,M]=r.useState({titulo:"",tipo:"custo",categoria:"",valor:"",data:"",descricao:"",pago:!1});h?.kpis,h?.charts?.byDay,h?.breakdowns;const z=s.attributes||s||{},D=Ai(z),E=Go(z),A=ee=>{const re=Number(ee||0),te=E?l(re,D):re;return u(te,D)},S=en(z),P=S.limit,F=S.available;return e.jsxs("div",{className:"rounded-md border bg-card/60 p-4 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-semibold",children:"Visão geral"}),s?.attributes?.documentId?e.jsx(w,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(lt,{to:`/dashboard/eventos/${encodeURIComponent(s.attributes.documentId)}`,children:"Painel completo"})}):e.jsx(w,{variant:"outline",size:"sm",disabled:!0,children:"Painel completo"})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-x-4 gap-y-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Data"}),e.jsx("div",{className:"font-medium",children:t?Us(t,"dd/MM/yyyy",{locale:Vs}):"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Disponível / Limite"}),e.jsx("div",{className:"font-medium tabular-nums",children:P>0?`${_a(F??0)} / ${_a(P)}`:_a(F)}),P>0&&e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[S.soldPercent,"% vendidos",S.scopedToActiveDates?" nas datas ativas":""]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Local"}),e.jsx("div",{className:"font-medium truncate",children:s.attributes.local||"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Preç
2o"}),e.jsx("div",{className:"font-medium",children:A(z.preco)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx("div",{className:"font-medium",children:a.label==="Passado"?"Finalizado":"Ativo"})]})]}),e.jsx("div",{className:"border-t"}),e.jsx(Ho,{evento:s,onSaved:()=>f.invalidateQueries({queryKey:["dashboard-events"]})})]})}function lp(){const{formatPrice:s,convertFromBRL:t}=jn(),[a,n]=r.useState(""),[o,i]=r.useState("all"),[u,l]=r.useState(1),[c,m]=r.useState(null),x=10,[h]=r.useState("all"),[p]=r.useState("30d"),[f]=r.useState("paid"),{data:I,isLoading:g}=Bx(u,x,{status:o}),N=I?.data||[],b=I?.meta?.pagination||{page:1,pageCount:1,total:0},C=(D,E={})=>{const A=Ai(E),S=Number(D||0),P=Go(E)?t(S,A):S;return s(P,A)},q=D=>D===0?{className:"text-red-600"}:typeof D=="number"&&D<=10?{className:"text-orange-600"}:{className:"text-green-600"},L=D=>{if(!D)throw new TypeError("Missing date");const E=String(D).slice(0,10),[A,S,P]=E.split("-"),F=Number.parseInt(A,10),ee=Number.parseInt(S,10),re=Number.parseInt(P,10);if(!Number.isInteger(F)||!Number.isInteger(ee)||!Number.isInteger(re))throw new TypeError("Invalid date parts");const te=new Date(F,ee-1,re);if(Number.isNaN(te.getTime())||te.getFullYear()!==F||te.getMonth()!==ee-1||te.getDate()!==re)throw new Error("Invalid date value");return te},M=D=>{try{const E=L(D);return yr(E)?{label:"Hoje",variant:"default",className:"bg-green-100 text-green-800"}:Oi(E)?{label:"Futuro",variant:"secondary",className:"bg-blue-100 text-blue-800"}:{label:"Passado",variant:"outline",className:"bg-muted text-foreground"}}catch{return{label:"—",variant:"outline",className:"bg-muted text-foreground"}}},z=N.filter(D=>{const E=D?.attributes?.titulo||"",A=D?.attributes?.local||"";if(!(!a||E.toLowerCase().includes(a.toLowerCase())||A.toLowerCase().includes(a.toLowerCase())))return!1;const P=Bt(D?.attributes||D),F=en(D?.attributes||D),ee=F.available;let re=!0;try{const te=P?L(P):null;switch(o){case"upcoming":re=te?Oi(te)&&!yr(te):!1;break;case"today":re=te?yr(te):!1;break;case"past":re=te?Fm(te)&&!yr(te):!1;break;case"available":re=typeof ee=="number"?ee>0:!0;break;case"sold-out":re=F.limit>0&&typeof ee=="number"?ee===0:!1;break;default:re=!0}}catch{re=o==="all"}return re});return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex justify-between items-start",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Gerenciar Eventos"}),e.jsx("p",{className:"text-muted-foreground",children:"Visualize e gerencie todos os eventos do sistema"})]})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[{label:"Total de Eventos",value:N.length,icon:Sa,color:"bg-blue-500"},{label:"Eventos Futuros",value:N.filter(D=>{try{const E=L(Bt(D.attributes||D));return E&&Oi(E)&&!yr(E)}catch{return!1}}).length,icon:Sa,color:"bg-green-500"},{label:"Eventos Hoje",value:N.filter(D=>{try{const E=L(Bt(D.attributes||D));return E&&yr(E)}catch{return!1}}).length,icon:Sa,color:"bg-purple-500"},{label:"Eventos Esgotados",value:N.filter(D=>{const E=en(D.attributes||D);return E.limit>0&&E.available===0}).length,icon:Ea,color:"bg-red-500"}].map((D,E)=>e.jsx(he,{children:e.jsx(ge,{className:"p-4",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx("div",{className:`${D.color} p-2 rounded-lg`,children:e.jsx(D.icon,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{className:"ml-3",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:D.label}),e.jsx("p",{className:"text-xl font-bold text-foreground-900",children:D.value})]})]})})},E))}),e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-col items-center justify-center sm:flex-row gap-4",children:[e.jsx("div",{className:"flex-1 w-full",children:e.jsxs("div",{className:"relative",children:[e.jsx(At,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(Te,{placeholder:"Buscar eventos por título ou local...",value:a,onChange:D=>n(D.target.value),className:"pl-10"})]})}),e.jsxs(rs,{value:o,onValueChange:i,children:[e.jsxs(ns,{className:"w-full max-w-lg",children:[e.jsx(Ci,{className:"mr-2 h-4 w-4"}),e.jsx(is,{})]}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),e.jsx(xe,{value:"upcoming",children:"Futuros"}),e.jsx(xe,{value:"today",children:"Hoje"}
2),e.jsx(xe,{value:"past",children:"Passados"}),e.jsx(xe,{value:"available",children:"Disponíveis"}),e.jsx(xe,{value:"sold-out",children:"Esgotados"})]})]})]})})}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{children:["Eventos (",z.length,")"]})}),e.jsx(ge,{children:z.length===0?e.jsx("div",{className:"text-center py-8",children:e.jsx("p",{className:"text-muted-foreground",children:"Nenhum evento encontrado"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto hidden md:block",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Evento"}),e.jsx(ue,{children:"Data"}),e.jsx(ue,{children:"Local"}),e.jsx(ue,{children:"Preço"}),e.jsx(ue,{children:"Ingressos"}),e.jsx(ue,{children:"Status"}),e.jsx(ue,{children:"Ações"})]})}),e.jsx(Ct,{children:z.map(D=>{const E=D.attributes||D,A=Bt(E),S=en(E),P=Sl(S),F=S.available,ee=M(A),re=q(F),te=(()=>{try{return A?L(A):null}catch{return null}})();return e.jsxs(fn.Fragment,{children:[e.jsxs($s,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[D.attributes.imagem?.data&&e.jsx("div",{className:"w-12 h-12 bg-muted rounded-lg overflow-hidden",children:e.jsx("img",{src:qt(D.attributes.imagem.data.attributes.url),alt:D.attributes.titulo,className:"w-full h-full object-cover"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-foreground",children:D.attributes.titulo}),D.attributes.descricao&&e.jsx("div",{className:"text-sm text-muted-foreground max-w-[200px] truncate",children:D.attributes.descricao})]})]})}),e.jsxs(ye,{children:[e.jsx("div",{className:"text-sm",children:te?Us(te,"dd/MM/yyyy",{locale:Vs}):"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:te?Us(te,"EEEE",{locale:Vs}):""})]}),e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(ei,{className:"h-3 w-3 text-muted-foreground"}),D.attributes.local||"N/A"]})}),e.jsx(ye,{className:"font-medium",children:C(D.attributes.preco,D.attributes)}),e.jsx(ye,{children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:`text-sm font-medium ${re.className}`,children:P.primary}),P.secondary?e.jsx("span",{className:"text-xs text-muted-foreground",children:P.secondary}):null]})}),e.jsx(ye,{children:e.jsx(je,{variant:ee.variant,className:ee.className,children:ee.label})}),e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>m(G=>G===D.id?null:D.id),"aria-label":c===D.id?"Esconder visão geral":"Mostrar visão geral",children:c===D.id?e.jsx(Kd,{className:"h-4 w-4"}):e.jsx(Vt,{className:"h-4 w-4"})}),D?.attributes?.documentId?e.jsx(w,{variant:"ghost",size:"sm",asChild:!0,children:e.jsx(lt,{to:`/dashboard/eventos/${encodeURIComponent(D.attributes.documentId)}`,"aria-label":"Abrir detalhes do evento",children:e.jsx(sr,{className:"h-4 w-4"})})}):e.jsx(w,{variant:"ghost",size:"sm",disabled:!0,"aria-label":"Abrir detalhes do evento",children:e.jsx(Vt,{className:"h-4 w-4"})}),D?.attributes?.documentId?e.jsx(w,{variant:"ghost",size:"sm",asChild:!0,children:e.jsx(lt,{to:`/dashboard/pedidos?event=${encodeURIComponent(D.attributes.documentId)}`,"aria-label":"Ver pedidos deste evento",children:e.jsx(At,{className:"h-4 w-4"})})}):e.jsx(w,{variant:"ghost",size:"sm",disabled:!0,"aria-label":"Ver pedidos deste evento",children:e.jsx(At,{className:"h-4 w-4"})})]})})]}),c===D.id&&e.jsx($s,{children:e.jsx(ye,{colSpan:7,children:e.jsx(op,{evento:D,eventDate:te,eventStatus:ee,ordersType:h,ordersPeriod:p,ordersStatus:f})})})]},D.id)})})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:z.map(D=>{const E=D.attributes||D,A=Bt(E),S=en(E),P=Sl(S),F=M(A),ee=(()=>{try{return L(A)}catch{return null}})();return e.jsxs("div",{className:"border rounded-lg p-3 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex gap-3",children:[D.attributes.imagem?.data&&e.jsx("div",{className:"w-16 h-16 bg-muted rounded-md overflow-hidden shrink-0",children:e.jsx("img",{src:qt(D.attributes.imagem.data.attributes.url),alt:D.attributes.titulo,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"font-medium truncate",children:D.attributes.titulo}),e.jsx(je,{variant:F.variant,className:F.className,children:F.label})]}),D.attributes.descricao&&e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:D.attributes.descricao}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Sa,{className:"h-3 w-3"}),ee?Us(ee,"dd/MM",{locale:Vs}):"—"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ei,{className:"h-3 w-3"}),D.attributes.local||"N/A"]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ea,{className:"h-3 w-3"}),P.primary]}),P.secondary?e.jsx("div",{className:"pl-4 text-[10px] text-muted-foreground",children:P.secondary}):null]}),e.jsx("div",{className:"text-foreground font-medium",children:C(D.attributes.preco,D.attributes)})]})]})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[D?.attributes?.documentId?e.jsx(w,{variant:"outline",size:"sm",asChild:!0,className:"flex-1",children:e.jsx(lt,{to:`/dashboard/pedidos?event=${encodeURIComponent(D.attributes.documentId)}`,children:"Ver pedidos"})}):e.jsx(w,{variant:"outline",size:"sm",disabled:!0,className:"flex-1",children:"Ver pedidos"}),D?.attributes?.documentId?e.jsx(w,{variant:"ghost",size:"sm",asChild:!0,className:"shrink-0",children:e.jsx(lt,{to:`/dashboard/eventos/${encodeURIComponent(D.attributes.documentId)}`,"aria-label":"Abrir detalhes do evento",children:e.jsx(Vt,{className:"h-4 w-4"})})}):e.jsx(w,{variant:"ghost",size:"sm",disabled:!0,className:"shrink-0","aria-label":"Abrir detalhes do evento",children:e.jsx(Vt,{className:"h-4 w-4"})}),D?.attributes?.documentId?e.jsx(w,{variant:"ghost",size:"sm",className:"shrink-0",asChild:!0,children:e.jsx(lt,{to:`/dashboard/pedidos?event=${encodeURIComponent(D.attributes.documentId)}`,"aria-label":"Ver pedidos deste evento",children:e.jsx(At,{className:"h-4 w-4"})})}):e.jsx(w,{variant:"ghost",size:"sm",className:"shrink-0",disabled:!0,"aria-label":"Ver pedidos deste evento",children:e.jsx(At,{className:"h-4 w-4"})})]})]},D.id)})}
2),b.pageCount>1&&e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Página ",b.page," de ",b.pageCount,"(",b.total," total)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{variant:"outline",size:"sm",onClick:()=>l(D=>Math.max(1,D-1)),disabled:b.page<=1,children:"Anterior"}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>l(D=>D+1),disabled:b.page>=b.pageCount,children:"Próxima"})]})]})]})})]})]})}function pn(){const[s,t]=r.useState({}),a=r.useCallback((u,l)=>s[`${u}::${l}`],[s]),n=r.useCallback((u,l,c)=>{t(m=>({...m,[`${u}::${l}`]:c}))},[]),o=r.useMemo(()=>Object.keys(s).length>0,[s]),i=r.useCallback(()=>t({}),[]);return{edits:s,getVal:a,setVal:n,hasEdits:o,clearEdits:i}}const bo={promocao_ativa:!1,promocao_tipos:[],promocao_bandas:[]};function Il({value:s,onChange:t,tipoOptions:a,disabled:n}){const o=s||bo,i=Array.isArray(o.promocao_tipos)?o.promocao_tipos:[],u=Array.isArray(o.promocao_bandas)?o.promocao_bandas:[],l=p=>t({...o,...p}),c=p=>{const f=i.map(String).includes(String(p));l({promocao_tipos:f?i.filter(I=>String(I)!==String(p)):[...i,Number(p)]})},m=(p,f)=>l({promocao_bandas:u.map((I,g)=>g===p?{...I,...f}:I)}),x=()=>l({promocao_bandas:[...u,{label:"",idade_min:"",idade_max:"",desconto_percentual:""}]}),h=p=>l({promocao_bandas:u.filter((f,I)=>I!==p)});return e.jsxs("div",{className:"mt-3 rounded-md border border-emerald-500/30 bg-emerald-500/[0.04] p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide flex items-center gap-1.5",children:[e.jsx(am,{className:"h-3 w-3 text-emerald-600 dark:text-emerald-400"}),"Promoção por idade"]}),e.jsx(Ls,{checked:o.promocao_ativa===!0,disabled:n,onCheckedChange:p=>l({promocao_ativa:p})})]}),o.promocao_ativa===!0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground",children:"Aplicar aos tipos de ingresso"}),a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nenhum tipo de ingresso cadastrado."}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(p=>{const f=i.map(String).includes(String(p.id));return e.jsx("button",{type:"button",disabled:n,onClick:()=>c(p.id),className:ls("rounded-full border px-2.5 py-1 text-xs transition-colors",f?"border-emerald-500 bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"border-border text-muted-foreground hover:bg-muted"),children:p.nome},p.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground",children:"Faixas de idade e desconto"}),u.map((p,f)=>e.jsxs("div",{className:"flex items-end gap-1.5",children:[e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx(Oe,{className:"text-[10px] text-muted-foreground",children:"Rótulo"}),e.jsx(Te,{className:"h-7 text-xs",placeholder:"Ex: Criança",value:p.label??"",disabled:n,onChange:I=>m(f,{label:I.target.value})})]}),e.jsxs("div",{className:"w-16 space-y-0.5",children:[e.jsx(Oe,{className:"text-[10px] text-muted-foreground",children:"Idade mín"}),e.jsx(Te,{className:"h-7 text-xs tabular-nums",type:"number",min:0,placeholder:"0",value:p.idade_min??"",disabled:n,onChange:I=>m(f,{idade_min:I.target.value})})]}),e.jsxs("div",{className:"w-16 space-y-0.5",children:[e.jsx(Oe,{className:"text-[10px] text-muted-foreground",children:"Idade máx"}),e.jsx(Te,{className:"h-7 text-xs tabular-nums",type:"number",min:0,placeholder:"—",value:p.idade_max??"",disabled:n,onChange:I=>m(f,{idade_max:I.target.value})})]}),e.jsxs("div",{className:"w-20 space-y-0.5",children:[e.jsx(Oe,{className:"text-[10px] text-muted-foreground",children:"% desc."}),e.jsx(Te,{className:"h-7 text-xs tabular-nums",type:"number",min:0,max:100,placeholder:"0",value:p.desconto_percentual??"",disabled:n,onChange:I=>m(f,{desconto_percentual:I.target.value})})]}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:text-destructive",disabled:n,onClick:()=>h(f),title:"Remover faixa",children:e.jsx(yt,{className:"h-3.5 w-3.5"})})]},f)),e.jsxs(w,{type:"button",variant:"outline",size:"sm",className:"h-7 gap-1 text-xs",disabled:n,onClick:x,children:[e.jsx(et,{className:"h-3 w-3"})," Adicionar faixa"]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Deixe a idade máxima vazia para faixa aberta (ex: 60+). O desconto é aplicado por participante após informarem a data de nascimento. Quando há sobreposição, vale o maior desconto."})]})]})]})}function Al({value:s,onChange:t,catalog:a,disabled:n}){const o=s&&typeof s=="object"?s:{},i=(c,m)=>{const x=o[c]&&typeof o[c]=="object"?o[c]:{};t({...o,[c]:{...x,...m}})},u=(c,m)=>{const x=o[c]&&typeof o[c]=="object"?o[c]:{};i(c,{...x,ativo:m===!0})},l=(c,m)=>{const x=o[c]&&typeof o[c]=="object"?o[c]:{},h=m===""?"":Math.max(0,Number(m)||0),p=x.disponivel!=null&&x.disponivel!=="";i(c,{...x,limite:h,disponivel:p?x.disponivel:h===""?"":h})};return e.jsxs("div",{className:"mt-3 rounded-md border border-indigo-500/30 bg-indigo-500/[0.04] p-3 space-y-3",children:[e.jsxs(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide flex items-center gap-1.5",children:[e.jsx(uo,{className:"h-3 w-3 text-indigo-600 dark:text-indigo-400"}),"Complementos (itens adicionais)"]}),a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cadastre complementos no card Complementos para ativá-los por data."}):e.jsx("div",{className:"space-y-2",children:a.map(c=>{const m=o[c.chave]&&typeof o[c.chave]=="object"?o[c.chave]:{},x=m.ativo===!0;return e.jsxs("div",{className:"rounded border border-border/60 bg-background/40 px-2.5 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-xs font-medium truncate",children:c.nome||c.chave}),e.jsx("div",{className:"text-[10px] text-muted-foreground font-mono truncate",children:c.chave})]}),e.jsx(Ls,{checked:x,disabled:n,onCheckedChange:h=>u(c.chave,h)})]}),x&&e.jsxs("div",{className:"mt-2 flex items-end gap-2",children:[e.jsxs("div",{className:"w-32 space-y-0.5",children:[e.jsx(Oe,{className:"text-[10px] text-muted-foreground",children:"Limite por data"}),e.jsx(Te,{className:"h-7 text-xs tabular-nums",type:"number",min:0,placeholder:"ilimitado",value:m.limite??"",disabled:n,onChange:h=>l(c.chave,h.target.value)})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground pb-1.5",children:"Vazio ou 0 = ilimitado."})]})]},c.chave)})})]})}function dp({evento:s,onSaved:t,analytics:a}){const{toast:n}=mt(),[o,i]=r.useState(!1),[u,l]=r.useState(null),[c,m]=r.useState(null),{getVal:x,setVal:h,hasEdits:p,clearEdits:f,edits:I}=pn(),[g,N]=r.useState(!1),[b,C]=r.useState({data:"",observacao:"",limite_ingressos:0,whatsapp_group_url:"",mensagem_confirmacao:"",complementos_config:{},...bo}),[q,L]=r.useState(new Set),M=s?.attributes||s||{},z=r.useMemo(()=>Array.isArray(M.datas_futuras)?M.datas_futuras:[],[M.datas_futuras]),D=r.useMemo(()=>{const G=Array.isArray(M.tipos_ingresso)?M.tipos_ingresso:[],y=new Map;for(const $ of G){const W=$?.tipo_ingresso?.data??$?.tipo_ingresso??null,ie=W?.id??W?.data?.id??null,ke=W?.nome??W?.attributes?.nome??W?.data?.attributes?.nome??null;ie!=null&&!y.has(Number(ie))&&y.set(Number(ie),ke||`Tipo ${ie}`)}return Array.from(y,([$,W])=>({id:$,nome:W}))},[M.tipos_ingresso]),E=r.useMemo(()=>(Array.isArray(M.complementos)?M.complementos:[]).filter(y=>y&&y.ativo!==!1&&String(y.chave||"").trim()).map(y=>({chave:String(y.chave).trim(),nome:y.nome||y.chave})),[M.complementos]),A=z,S=p||q.size>0,P=async()=>
2{if(a?.dates)return a;if(c?.dates)return c;const G=s?.id;if(!G)return null;const y=new URLSearchParams({eventId:String(G),group:"day"}),W=(await $e.get(`/pedidos/event-analytics?${y.toString()}`))?.data;return W?.dates&&m(W),W},F=async()=>{i(!0);try{const G=z.filter(ie=>!q.has(ie.id)).map(ie=>{const ke=x(ie.id,"ativo"),Ae=x(ie.id,"limite_ingressos"),be=x(ie.id,"observacao"),Fe=x(ie.id,"ingressos_disponiveis"),ae=x(ie.id,"whatsapp_group_url"),K=x(ie.id,"mensagem_confirmacao"),O=x(ie.id,"promocao"),oe=x(ie.id,"complementos_config");return qi({...ie,...oe!==void 0?{complementos_config:oe}:{},...ke!==void 0?{ativo:ke}:{},...Ae!==void 0?{limite_ingressos:Number(Ae)}:{},...be!==void 0?{observacao:be}:{},...Fe!==void 0?{ingressos_disponiveis:Number(Fe)}:{},...ae!==void 0?{whatsapp_group_url:ae?.trim()||null}:{},...K!==void 0?{mensagem_confirmacao:K?.trim()||null}:{},...O!==void 0?{promocao_ativa:O.promocao_ativa===!0,promocao_tipos:O.promocao_tipos||[],promocao_bandas:O.promocao_bandas||[]}:{}})}),y=M.documentId||s?.documentId,W=await Fa(y,{datas_futuras:G});f(),L(new Set),n({title:"Datas atualizadas com sucesso"}),t?.(W)}catch(G){n({title:"Erro ao salvar datas",description:G?.response?.data?.error?.message||"Tente novamente.",variant:"destructive"})}finally{i(!1)}},ee=async()=>{if(!b.data){n({title:"Selecione uma data",variant:"destructive"});return}i(!0);try{const G=[...z.map(qi),qi({data:b.data,observacao:b.observacao||"",limite_ingressos:Number(b.limite_ingressos)||0,ingressos_disponiveis:Number(b.limite_ingressos)||0,whatsapp_group_url:b.whatsapp_group_url?.trim()||null,mensagem_confirmacao:b.mensagem_confirmacao?.trim()||null,ativo:!0,promocao_ativa:b.promocao_ativa===!0,promocao_tipos:b.promocao_tipos||[],promocao_bandas:b.promocao_bandas||[],complementos_config:b.complementos_config||{}})],y=M.documentId||s?.documentId,$=await Fa(y,{datas_futuras:G});C({data:"",observacao:"",limite_ingressos:0,whatsapp_group_url:"",mensagem_confirmacao:"",complementos_config:{},...bo}),N(!1),n({title:"Data adicionada com sucesso",description:"Lotes serao criados automaticamente."}),t?.($)}catch(G){n({title:"Erro ao adicionar data",description:G?.response?.data?.error?.message||"Tente novamente.",variant:"destructive"})}finally{i(!1)}},re=G=>{L(y=>{const $=new Set(y);return $.has(G)?$.delete(G):$.add(G),$})},te=async(G,y)=>{l(G);try{if(!s?.id){n({title:"Erro",description:"ID do evento não encontrado",variant:"destructive"});return}if(!y){n({title:"Erro",description:"Data do evento não encontrada para recontagem",variant:"destructive"});return}const W=String(y).slice(0,10),ie=await P();if(!ie?.dates){n({title:"Erro",description:"Nao foi possivel carregar as metricas do evento.",variant:"destructive"});return}const Ae=[...Array.isArray(ie?.dates?.future)?ie.dates.future:[],...Array.isArray(ie?.dates?.past)?ie.dates.past:[]].find(K=>String(K?.date||"")===W),be=Number(Ae?.ingressos||0)||0,Fe=x(G,"limite_ingressos")??z.find(K=>K.id===G)?.limite_ingressos??0,ae=Math.max(0,Number(Fe)-be);h(G,"ingressos_disponiveis",ae),n({title:"Estoque recontado",description:`${W}: ${ae} disponíveis (${be} vendidos de ${Fe}). Clique em Salvar para confirmar.`})}catch($){console.error("[DatasFuturasManager] recount error:",$),n({title:"Erro ao recontar",description:$?.response?.data?.error?.message||$?.message||"Tente novamente.",variant:"destructive"})}finally{l(null)}};return e.jsxs(he,{className:"overflow-hidden",children:[e.jsx(Be,{className:"pb-3 border-b bg-muted/20",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"flex items-center justify-center w-8 h-8 rounded-lg bg-primary/10 dark:bg-secondary/10",children:e.jsx(il,{className:"h-4 w-4 text-primary dark:text-secondary"})}),e.jsxs("div",{children:[e.jsx(ze,{className:"text-base leading-tight",children:"Datas do Evento"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[A.length," data",A.length!==1&&"s"," cadastrada",A.length!==1&&"s"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[S&&e.jsxs(w,{size:"sm",onClick:F,disabled:o,className:"gap-1.5",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),o?"Salvando...":"Salvar"]}),e.jsx(w,{size:"sm",variant:"outline",onClick:()=>N(!g),className:"gap-1.5",children:g?"Cancelar":e.jsxs(e.Fragment,{children:[e.jsx(et,{className:"h-3.5 w-3.5"})," Adicionar"]})})]})]})}),e.jsxs(ge,{className:"p-0",children:[g&&e.jsxs("div",{className:"px-4 py-4 border-b bg-muted/10 space-y-3",children:[e.jsx("div",{className:"text-sm font-medium",children:"Nova data"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-xs text-muted-foreground",children:"Data"}),e.jsx(Te,{type:"date",value:b.data,onChange:G=>C(y=>({...y,data:G.target.value}))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-xs text-muted-foreground",children:"Limite de ingressos"}),e.jsx(Te,{type:"number",min:0,value:b.limite_ingressos,onChange:G=>C(y=>({...y,limite_ingressos:G.target.value}))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-xs text-muted-foreground",children:"Observacao"}),e.jsx(Te,{value:b.observacao,onChange:G=>C(y=>({...y,observacao:G.target.value})),placeholder:"Ex: Edicao especial"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Oe,{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(si,{className:"h-3 w-3 text-emerald-600 dark:text-emerald-400"}),"Grupo do WhatsApp desta data"]}),e.jsx(Te,{type:"url",value:b.whatsapp_group_url,onChange:G=>C(y=>({...y,whatsapp_group_url:G.target.value})),placeholder:"https://chat.whatsapp.com/..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-xs text-muted-foreground",children:"Mensagem de confirmação desta data"}),e.jsx(Te,{value:b.mensagem_confirmacao,onChange:G=>C(y=>({...y,mensagem_confirmacao:G.target.value})),placeholder:"Ex: Nos vemos no sábado! Leve um agasalho."})]}),e.jsx(Il,{value:{promocao_ativa:b.promocao_ativa,promocao_tipos:b.promocao_tipos,promocao_bandas:b.promocao_bandas},onChange:G=>C(y=>({...y,...G})),tipoOptions:D}),e.jsx(Al,{value:b.complementos_config,onChange:G=>C(y=>({...y,complementos_config:G})),catalog:E}),e.jsxs(w,{size:"sm",onClick:ee,disabled:o,className:"gap-1.5",children:[e.jsx(et,{className:"h-3.5 w-3.5"}),o?"Adicionando...":"Adicionar"]})]}),A.length===0&&!g?e.jsxs("div",{className:"px-4 py-8 text-center",children:[e.jsx(il,{className:"h-8 w-8 text-muted-foreground
2/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma data futura cadastrada."})]}):A.length>0?e.jsx("div",{className:"divide-y divide-border/50",children:A.map(G=>{const y=q.has(G.id),$=x(G.id,"ativo")??G.ativo!==!1,W=x(G.id,"limite_ingressos")??G.limite_ingressos??0,ie=x(G.id,"observacao")??G.observacao??"",ke=x(G.id,"whatsapp_group_url")??G.whatsapp_group_url??"",Ae=x(G.id,"mensagem_confirmacao")??G.mensagem_confirmacao??"",be=x(G.id,"ingressos_disponiveis")??G.ingressos_disponiveis??0,Fe=x(G.id,"promocao")??{promocao_ativa:G.promocao_ativa===!0,promocao_tipos:Array.isArray(G.promocao_tipos)?G.promocao_tipos:[],promocao_bandas:Array.isArray(G.promocao_bandas)?G.promocao_bandas:[]},ae=x(G.id,"complementos_config")??(G.complementos_config&&typeof G.complementos_config=="object"?G.complementos_config:{});return e.jsxs("div",{className:ls("px-4 py-3 transition-opacity",y&&"opacity-30"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsx("span",{className:ls("text-sm font-semibold capitalize ",y&&"line-through"),children:Va(G.data)})}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(w,{variant:"ghost",size:"sm",onClick:()=>te(G.id,G.data),disabled:y||u===G.id,className:"h-7 gap-1 text-xs text-secondary hover:text-secondary",title:"Recontar ingressos disponíveis baseado em vendas",children:[e.jsx(ta,{className:ls("h-3 w-3",u===G.id&&"animate-spin")}),u===G.id?"Recontando...":"Recontar"]}),e.jsx(w,{variant:y?"outline":"ghost",size:"sm",onClick:()=>re(G.id),className:ls("h-7 gap-1 text-xs",!y&&"text-destructive hover:text-destructive"),children:y?e.jsxs(e.Fragment,{children:[e.jsx(Fo,{className:"h-3 w-3"})," Desfazer"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xt,{className:"h-3 w-3"})," Remover"]})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Limite"}),e.jsx(Te,{type:"number",min:0,className:"h-7 text-sm tabular-nums",value:W,disabled:y,onChange:K=>h(G.id,"limite_ingressos",K.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Disponivel"}),e.jsx("div",{className:"h-7 flex items-center",children:e.jsx(je,{variant:"outline",className:"tabular-nums",children:be})})]}),e.jsxs("div",{className:"space-y-1 col-span-2 sm:col-span-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Obs"}),e.jsx(Te,{className:"h-7 text-xs",value:ie,disabled:y,onChange:K=>h(G.id,"observacao",K.target.value),placeholder:"..."})]}),e.jsxs("div",{className:"space-y-1 flex flex-col items-start sm:items-center",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Ativo"}),e.jsx(Ls,{checked:$,disabled:y,onCheckedChange:K=>h(G.id,"ativo",K)})]})]}),e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsxs(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide flex items-center gap-1.5",children:[e.jsx(si,{className:"h-3 w-3 text-emerald-600 dark:text-emerald-400"}),"Grupo do WhatsApp"]}),e.jsx(Te,{type:"url",className:"h-7 text-xs",value:ke,disabled:y,onChange:K=>h(G.id,"whatsapp_group_url",K.target.value),placeholder:"https://chat.whatsapp.com/... (mostrado ao comprador desta data)"})]}),e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Mensagem de confirmação"}),e.jsx(Te,{className:"h-7 text-xs",value:Ae,disabled:y,onChange:K=>h(G.id,"mensagem_confirmacao",K.target.value),placeholder:"Texto mostrado ao comprador desta data (vazio = mensagem padrão)"})]}),e.jsx(Il,{value:Fe,onChange:K=>h(G.id,"promocao",K),tipoOptions:D,disabled:y}),e.jsx(Al,{value:ae,onChange:K=>h(G.id,"complementos_config",K),catalog:E,disabled:y})]},G.id)})}):null]})]})}const yc=r.forwardRef(({className:s,...t},a)=>e.jsx(ja,{ref:a,className:ls("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));yc.displayName=ja.displayName;const wc=r.forwardRef(({className:s,...t},a)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(At,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(ja.Input,{ref:a,className:ls("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",s),...t})]}));wc.displayName=ja.Input.displayName;const _c=r.forwardRef(({className:s,...t},a)=>e.jsx(ja.List,{ref:a,className:ls("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));_c.displayName=ja.List.displayName;const Cc=r.forwardRef((s,t)=>e.jsx(ja.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));Cc.displayName=ja.Empty.displayName;
2const kc=r.forwardRef(({className:s,...t},a)=>e.jsx(ja.Group,{ref:a,className:ls("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",s),...t}));kc.displayName=ja.Group.displayName;const cp=r.forwardRef(({className:s,...t},a)=>e.jsx(ja.Separator,{ref:a,className:ls("-mx-1 h-px bg-border",s),...t}));cp.displayName=ja.Separator.displayName;const Sc=r.forwardRef(({className:s,...t},a)=>e.jsx(ja.Item,{ref:a,className:ls("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",s),...t}));Sc.displayName=ja.Item.displayName;function El({value:s,onChange:t,disabled:a,className:n,placeholder:o="Selecionar ícone"}){const[i,u]=r.useState(!1),l=String(s||"").trim(),c=l?ax(l,null):null,m=bl.find(h=>h.name===l)?.label,x=h=>{t?.(h),u(!1)};return e.jsxs(fr,{open:i,onOpenChange:u,children:[e.jsx(jr,{asChild:!0,children:e.jsxs(w,{type:"button",variant:"outline",size:"sm",disabled:a,"aria-label":"Selecionar ícone",className:ls("h-9 justify-between gap-2 font-normal",n),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[c?e.jsx(c,{className:"h-4 w-4 shrink-0 text-foreground"}):e.jsx("span",{className:"h-4 w-4 shrink-0 rounded-sm border border-dashed border-muted-foreground/50"}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:l?m||l:o})]}),e.jsx(ra,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]})}),e.jsx(ar,{className:"w-64 p-0",align:"start",children:e.jsxs(yc,{filter:(h,p)=>h.toLowerCase().includes(p.toLowerCase())?1:0,children:[e.jsx(wc,{placeholder:"Buscar ícone...",className:"text-sm"}),e.jsxs(_c,{className:"max-h-64",children:[e.jsx(Cc,{className:"py-6 text-center text-xs text-muted-foreground",children:"Nenhum ícone encontrado."}),e.jsx(kc,{className:"p-2",children:e.jsx("div",{className:"grid grid-cols-6 gap-1",children:bl.map(({name:h,label:p,Icon:f})=>e.jsx(Sc,{value:`${h} ${p}`,onSelect:()=>x(h),title:`${p} (${h})`,className:ls("flex h-9 w-9 items-center justify-center rounded-md p-0 data-[selected=true]:bg-accent",l===h&&"bg-primary/10 ring-1 ring-primary"),children:e.jsx(f,{className:"h-4 w-4"})},h))})})]})]})})]})}function Vi(s){return String(s||"").normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function up(s){const t=n=>Array.isArray(n)?n.map(o=>String(o??"").trim()).filter(Boolean):[],a=n=>Array.isArray(n)?n.map(o=>({titulo:String(o?.titulo??"").trim(),subtitulo:String(o?.subtitulo??"").trim(),destaque:String(o?.destaque??"").trim(),icone:String(o?.icone??"").trim(),incluso:t(o?.incluso),nao_incluso:t(o?.nao_incluso)})):[];return{chave:String(s.chave||"").trim(),nome:String(s.nome||"").trim(),descricao:s.descricao?.trim?s.descricao.trim()||null:s.descricao??null,preco:s.preco===""||s.preco==null?0:Number(s.preco)||0,icone:s.icone?.trim?s.icone.trim()||null:s.icone??null,imagem:s.imagem?.id??(typeof s.imagem=="number"?s.imagem:null),incluso:t(s.incluso),nao_incluso:t(s.nao_incluso),roteiro:a(s.roteiro),ativo:s.ativo!==!1}}const mp=()=>({titulo:"",subtitulo:"",destaque:"",icone:"",incluso:[],nao_incluso:[]});function Pn({label:s,items:t,onChange:a,disabled:n,tone:o="emerald",placeholder:i}){const u=Array.isArray(t)?t:[],l=(p,f)=>a(u.map((I,g)=>g===p?f:I)),c=()=>a([...u,""]),m=p=>a(u.filter((f,I)=>I!==p)),x=o==="emerald"?ti:Qd,h=o==="emerald"?"text-emerald-600 dark:text-emerald-400":"text-rose-600 dar
2k:text-rose-400";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(Oe,{className:"text-[11px] text-muted-foreground flex items-center gap-1.5",children:[e.jsx(x,{className:ls("h-3 w-3",h)}),s]}),u.map((p,f)=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Te,{className:"h-7 text-xs",value:p??"",disabled:n,placeholder:i,onChange:I=>l(f,I.target.value)}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:text-destructive",disabled:n,onClick:()=>m(f),title:"Remover item",children:e.jsx(yt,{className:"h-3.5 w-3.5"})})]},f)),e.jsxs(w,{type:"button",variant:"outline",size:"sm",className:"h-7 gap-1 text-xs",disabled:n,onClick:c,children:[e.jsx(et,{className:"h-3 w-3"})," Adicionar item"]})]})}const xp=()=>({_uid:`new-${Math.random().toString(36).slice(2,9)}`,chave:"",nome:"",descricao:"",preco:"",icone:"",imagem:null,incluso:[],nao_incluso:[],roteiro:[],ativo:!0});function pp({evento:s,onSaved:t}){const{toast:a}=mt(),[n,o]=r.useState(!1),i=s?.attributes||s||{},u=r.useMemo(()=>(Array.isArray(i.complementos)?i.complementos:[]).map(($,W)=>({_uid:$.id!=null?`srv-${$.id}`:`srv-idx-${W}`,chave:$.chave??"",nome:$.nome??"",descricao:$.descricao??"",preco:$.preco??"",icone:$.icone??"",imagem:$.imagem??null,incluso:Array.isArray($.incluso)?$.incluso:[],nao_incluso:Array.isArray($.nao_incluso)?$.nao_incluso:[],roteiro:Array.isArray($.roteiro)?$.roteiro.map(ie=>({titulo:ie?.titulo??"",subtitulo:ie?.subtitulo??"",destaque:ie?.destaque??"",icone:ie?.icone??"",incluso:Array.isArray(ie?.incluso)?ie.incluso:[],nao_incluso:Array.isArray(ie?.nao_incluso)?ie.nao_incluso:[]})):[],ativo:$.ativo!==!1})),[i.complementos]),[l,c]=r.useState(u),[m,x]=r.useState(new Set),[h,p]=r.useState(!1),f=r.useMemo(()=>JSON.stringify(u),[u]),[I,g]=r.useState(f);f!==I&&!h&&(c(u),g(f),x(new Set));const N=(y,$)=>{p(!0),c(W=>W.map(ie=>ie._uid===y?{...ie,...$}:ie))},[b,C]=r.useState(null),q=async(y,$)=>{if($){C(y);try{const W=new FormData;W.append("files",$);const ke=(await $e.post("/upload",W,{headers:{"Content-Type":"multipart/form-data"}}))?.data?.[0];if(ke?.id)N(y,{imagem:ke});else throw new Error("Upload sem retorno")}catch(W){a({title:"Erro ao enviar imagem",description:W?.response?.data?.error?.message||W?.message||"Tente novamente.",variant:"destructive"})}finally{C(null)}}},[L,M]=r.useState(new Set),z=y=>{M($=>{const W=new Set($);return W.has(y)?W.delete(y):W.add(y),W})},D=(y,$,W,ie)=>N(y,{roteiro:$.map((ke,Ae)=>Ae===W?{...ke,...ie}:ke)}),E=(y,$)=>N(y,{roteiro:[...$,mp()]}),A=(y,$,W)=>N(y,{roteiro:$.filter((ie,ke)=>ke!==W)}),S=()=>{p(!0),c(y=>[...y,xp()])},P=y=>{p(!0),x($=>{const W=new Set($);return W.has(y)?W.delete(y):W.add(y),W})},F=(y,$)=>{!$.chave&&$.nome&&N(y,{chave:Vi($.nome)})},ee=r.useMemo(()=>{const y=new Map;for(const $ of l){if(m.has($._uid))continue;const W=String($.chave||"").trim();W&&y.set(W,(y.get(W)||0)+1)}return y},[l,m]),re=h&&(l.length>0||m.size>0),te=l.filter(y=>!m.has(y._uid)),G=async()=>{const y=[],$=new Set;for(const W of te){const ie=String(W.chave||"").trim()||Vi(W.nome);if(!W.nome?.trim()){a({title:"Nome obrigatório",description:"Todo complemento precisa de um nome.",variant:"destructive"});return}if(!ie){a({title:"Chave obrigatória",description:`Defina uma chave para "${W.nome}".`,variant:"destructive"});return}if($.has(ie)){a({title:"Chave duplicada",description:`A chave "${ie}" está repetida. Cada complemento precisa de uma chave única.`,variant:"destructive"});return}$.add(ie),y.push(up({...W,chave:ie}))}o(!0);try{const W=i.documentId||s?.documentId,ie=await Fa(W,{complementos:y});p(!1),x(new Set),a({title:"Complementos salvos com sucesso"}),t?.(ie)}catch(W){a({title:"Erro ao salvar complementos",description:W?.response?.data?.error?.message||"Tente novamente.",variant:"destructive"})}finally{o(!1)}};return e.jsxs(he,{className:"overflow-hidden",children:[e.jsx(Be,{className:"pb-3 border-b bg-muted/20",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"flex items-center justify-center w-8 h-8 rounded-lg bg-primary/10 dark:bg-secondary/10",children:e.jsx(uo,{className:"h-4 w-4 text-primary dark:text-secondary"})}),e.jsxs("div",{children:[e.jsx(ze,{className:"text-base leading-tight",children:"Complementos"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[te.length," item",te.length!==1&&"s"," adiciona",te.length!==1?"is":"l"," · ative por data no card Datas do Evento"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[re&&e.jsxs(w,{size:"sm",onClick:G,disabled:n,className:"gap-1.5",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),n?"Salvando...":"Salvar"]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:S,className:"gap-1.5",children:[e.jsx(et,{className:"h-3.5 w-3.5"})," Adicionar complemento"]})]})]})}),e.jsx(ge,{className:"p-0",children:l.length===0?e.jsxs("div",{className:"px-4 py-8 text-center",children:[e.jsx(uo,{className:"h-8 w-8 text-muted-foreground
2/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum complemento cadastrado. Adicione itens adicionais (ex.: transfer, passeio) para oferecer no carrinho."})]}):e.jsx("div",{className:"divide-y divide-border/50",children:l.map(y=>{const $=m.has(y._uid),W=String(y.chave||"").trim(),ie=W&&(ee.get(W)||0)>1;return e.jsxs("div",{className:ls("px-4 py-4 transition-opacity",$&&"opacity-30"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(je,{variant:y.ativo!==!1?"default":"outline",className:ls("text-[10px]",$&&"line-through"),children:y.ativo!==!1?"Ativo":"Inativo"}),e.jsx("span",{className:ls("text-sm font-semibold truncate",$&&"line-through"),children:y.nome?.trim()||"Novo complemento"})]}),e.jsx(w,{variant:$?"outline":"ghost",size:"sm",onClick:()=>P(y._uid),className:ls("h-7 gap-1 text-xs",!$&&"text-destructive hover:text-destructive"),children:$?e.jsxs(e.Fragment,{children:[e.jsx(Fo,{className:"h-3 w-3"})," Desfazer"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xt,{className:"h-3 w-3"})," Remover"]})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Nome"}),e.jsx(Te,{className:"h-7 text-sm",value:y.nome??"",disabled:$,placeholder:"Ex: Transfer aeroporto",onChange:ke=>N(y._uid,{nome:ke.target.value}),onBlur:()=>F(y._uid,y)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Chave"}),e.jsx(Te,{className:ls("h-7 text-xs font-mono",ie&&"border-destructive focus-visible:ring-destructive"),value:y.chave??"",disabled:$,placeholder:"auto pelo nome",onChange:ke=>N(y._uid,{chave:Vi(ke.target.value)})}),ie?e.jsxs("p",{className:"text-[10px] text-destructive flex items-center gap-1",children:[e.jsx(Ya,{className:"h-3 w-3"})," Chave duplicada"]}):e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Estável. Alterar quebra as ativações por data existentes."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Preço (R$/pessoa)"}),e.jsx(Te,{type:"number",min:0,step:"0.01",className:"h-7 text-sm tabular-nums",value:y.preco??"",disabled:$,placeholder:"0,00",onChange:ke=>N(y._uid,{preco:ke.target.value})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Ícone"}),e.jsx(El,{className:"w-full",value:y.icone??"",disabled:$,onChange:ke=>N(y._uid,{icone:ke})})]})]}),(()=>{const ke=qt(y.imagem?.formats?.thumbnail?.url||y.imagem?.url||null),Ae=b===y._uid;return e.jsxs("div",{className:"mt-3 space-y-1.5",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Imagem do banner"}),e.jsx("div",{className:"relative w-full max-w-md overflow-hidden rounded-md border border-border",style:{aspectRatio:"1200 / 360",backgroundColor:"hsl(var(--muted))",backgroundImage:"linear-gradient(45deg,hsl(var(--border)) 25%,transparent 25%,transparent 75%,hsl(var(--border)) 75%),linear-gradient(45deg,hsl(var(--border)) 25%,transparent 25%,transparent 75%,hsl(var(--border)) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0,8px 8px"},children:ke?e.jsx("img",{src:ke,alt:"",className:"h-full w-full object-cover"}):e.jsx("div",{className:"grid h-full w-full place-items-center text-muted-foreground",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx(mo,{className:"h-5 w-5"}),e.jsx("span",{className:"text-[10px]",children:"Sem imagem — usa o ícone"})]})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:ls("inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-md border border-input bg-background px-2.5 text-xs font-medium hover:bg-accent",($||Ae)&&"pointer-events-none opacity-50"),children:[Ae?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(mo,{className:"h-3.5 w-3.5"}),y.imagem?"Trocar imagem":"Enviar imagem",e.jsx("input",{type:"file",accept:"image/jpeg,image/png,image/webp",className:"hidden",disabled:$||Ae,onChange:be=>q(y._uid,be.target.files?.[0]||null)})]}),y.imagem&&!$&&e.jsxs(w,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 px-1.5 text-xs text-destructive hover:text-destructive",onClick:()=>N(y._uid,{imagem:null}),children:[e.jsx(yt,{className:"h-3 w-3"})," Remover"]})]}),e.jsxs("p",{className:"text-[10px] leading-relaxed text-muted-foreground",children:["A imagem preenche o banner do carrinho (recorte central, ",e.jsx("em",{children:"cover"}),"). Recomendado: horizontal ",e.jsx("strong",{children:"~1200×360px (proporção 10:3)"}),", formato ",e.jsx("strong",{children:"JPG"})," ou PNG/WebP ",e.jsx("strong",{children:"opaco"}),". Evite PNG com transparência — as áreas vazias mostram o fundo. Quando há imagem, ela substitui o ícone."]})]})})(),e.jsxs("div",{className:"mt-3 grid grid-cols-1 sm:grid-cols-[1fr_auto] gap-3 items-start",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Descrição"}),e.jsx(yn,{className:"min-h-[56px] text-xs",value:y.descricao??"",disabled:$,placeholder:"Breve descrição mostrada no carrinho",onChange:ke=>N(y._uid,{descricao:ke.target.value})})]}),e.jsxs("div",{className:"space-y-1 flex flex-col items-start sm:items-center",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Ativo"}),e.jsx(Ls,{checked:y.ativo!==!1,disabled:$,onCheckedChange:ke=>N(y._uid,{ativo:ke})})]})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 sm:grid-cols-2 gap-4 roun
2ded-md border border-emerald-500/20 bg-emerald-500/[0.03] p-3",children:[e.jsx(Pn,{label:"Incluso",tone:"emerald",items:y.incluso,disabled:$,placeholder:"Ex: Café da manhã",onChange:ke=>N(y._uid,{incluso:ke})}),e.jsx(Pn,{label:"Não incluso",tone:"rose",items:y.nao_incluso,disabled:$,placeholder:"Ex: Bebidas alcoólicas",onChange:ke=>N(y._uid,{nao_incluso:ke})})]}),(()=>{const ke=Array.isArray(y.roteiro)?y.roteiro:[],Ae=L.has(y._uid),be=Ae?ra:er;return e.jsxs("div",{className:"mt-3 rounded-md border border-indigo-500/20 bg-indigo-500/[0.03] p-3",children:[e.jsxs("button",{type:"button",onClick:()=>z(y._uid),className:"flex w-full items-center justify-between gap-2 text-left",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-indigo-600 dark:text-indigo-400",children:[e.jsx(rm,{className:"h-3.5 w-3.5"}),"Roteiro dia a dia",ke.length>0&&e.jsxs(je,{variant:"outline",className:"text-[10px] font-normal",children:[ke.length," dia",ke.length!==1&&"s"]})]}),e.jsx(be,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),Ae&&e.jsxs("div",{className:"mt-3 space-y-3",children:[ke.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Nenhum dia cadastrado. Adicione dias para montar o roteiro deste complemento."}):ke.map((Fe,ae)=>e.jsxs("div",{className:"rounded-md border border-border/60 bg-background/60 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-[11px] font-medium text-muted-foreground",children:["Dia ",ae+1]}),e.jsxs(w,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs text-destructive hover:text-destructive",disabled:$,onClick:()=>A(y._uid,ke,ae),title:"Remover dia",children:[e.jsx(Xt,{className:"h-3 w-3"})," Remover dia"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Título"}),e.jsx(Te,{className:"h-7 text-sm",value:Fe.titulo??"",disabled:$,placeholder:"Ex: Terça · Chegada",onChange:K=>D(y._uid,ke,ae,{titulo:K.target.value})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Subtítulo"}),e.jsx(Te,{className:"h-7 text-sm",value:Fe.subtitulo??"",disabled:$,placeholder:"Ex: Chegada a Manaus, por conta do participante",onChange:K=>D(y._uid,ke,ae,{subtitulo:K.target.value})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Destaque"}),e.jsx(Te,{className:"h-7 text-sm",value:Fe.destaque??"",disabled:$,placeholder:"Ex: Tudo incluso — deixe vazio se não",onChange:K=>D(y._uid,ke,ae,{destaque:K.target.value})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"Ícone"}),e.jsx(El,{className:"w-full",value:Fe.icone??"",disabled:$,onChange:K=>D(y._uid,ke,ae,{icone:K})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 rounded-md border border-emerald-500/20 bg-emerald-500/[0.03] p-3",children:[e.jsx(Pn,{label:"Incluso",tone:"emerald",items:Fe.incluso,disabled:$,placeholder:"Ex: Café da manhã",onChange:K=>D(y._uid,ke,ae,{incluso:K})}),e.jsx(Pn,{label:"Não incluso",tone:"rose",items:Fe.nao_incluso,disabled:$,placeholder:"Ex: Bebidas alcoólicas",onChange:K=>D(y._uid,ke,ae,{nao_incluso:K})})]})]},ae)),e.jsxs(w,{type:"button",variant:"outline",size:"sm",className:"h-7 gap-1 text-xs",disabled:$,onClick:()=>E(y._uid,ke),children:[e.jsx(et,{className:"h-3 w-3"})," Adicionar dia"]})]})]})})()]},y._uid)})})})]})}function hp({evento:s,onSaved:t,allTipos:a=[],refetchTipos:n}){const o=s?.attributes||s||{},{toast:i}=mt(),u=r.useMemo(()=>Array.isArray(o.tipos_ingresso)?o.tipos_ingresso:[],[o.tipos_ingresso]),l=r.useMemo(()=>new Set(u.map(A=>{const S=A?.tipo_ingresso;return S?.data?.documentId??S?.documentId??null}
2).filter(Boolean)),[u]),c=r.useMemo(()=>a.filter(A=>!l.has(A.documentId)),[a,l]),m=pn(),x=pn(),[h,p]=r.useState(!1),[f,I]=r.useState(!1),[g,N]=r.useState(!1),[b,C]=r.useState({nome:"",desconto_percentual:0,progressivo:!1,quantidade_itens:1,requer_cpf:!0}),q=m.hasEdits||x.hasEdits,L=A=>{const S={...A};if(m.getVal(A.id,"preco_especifico")!==void 0){const P=m.getVal(A.id,"preco_especifico");S.preco_especifico=P===""?null:Number(P)}return m.getVal(A.id,"ativo")!==void 0&&(S.ativo=m.getVal(A.id,"ativo")),S},M=async()=>{p(!0);try{const A=o.documentId||s?.documentId,S=m.hasEdits,P=x.hasEdits;let F;if(S){const ee=u.map(re=>Zr(L(re)));F=await Fa(A,{tipos_ingresso:ee}),m.clearEdits()}if(P){const ee={};for(const[re,te]of Object.entries(x.edits)){const G=re.indexOf("::"),y=re.slice(0,G),$=re.slice(G+2);ee[y]||(ee[y]={}),ee[y][$]=te}await Promise.all(Object.entries(ee).map(([re,te])=>$e.put(`/tipo-ingressos/${re}`,{data:te}))),x.clearEdits(),n?.()}i({title:"Tipos de ingresso atualizados"}),t?.(P?void 0:F)}catch{i({title:"Erro ao salvar tipos",variant:"destructive"})}finally{p(!1)}},z=async A=>{p(!0);try{const S=o.documentId||s?.documentId,P=u.map(ee=>Zr(ee));P.push({tipo_ingresso:A,preco_especifico:null,quantidade_disponivel:0,ativo:!0});const F=await Fa(S,{tipos_ingresso:P});I(!1),i({title:"Tipo vinculado ao evento"}),t?.(F)}catch{i({title:"Erro ao vincular",variant:"destructive"})}finally{p(!1)}},D=async()=>{if(b.nome.trim()){p(!0);try{const A=await $e.post("/tipo-ingressos",{data:{...b,ativo:!0,ordem:a.length}}),P=(A?.data?.data||A?.data)?.documentId;let F;if(P){const ee=o.documentId||s?.documentId,re=u.map(te=>Zr(te));re.push({tipo_ingresso:P,preco_especifico:null,quantidade_disponivel:0,ativo:!0}),F=await Fa(ee,{tipos_ingresso:re})}C({nome:"",desconto_percentual:0,progressivo:!1,quantidade_itens:1,requer_cpf:!0}),N(!1),i({title:`"${b.nome}" criado e vinculado`}),n?.(),t?.(F)}catch{i({title:"Erro ao criar tipo",variant:"destructive"})}finally{p(!1)}}},E=async A=>{p(!0);try{const S=o.documentId||s?.documentId,P=u.filter(ee=>ee.id!==A).map(ee=>Zr(ee)),F=await Fa(S,{tipos_ingresso:P});i({title:"Tipo removido do evento"}),t?.(F)}catch{i({title:"Erro ao remover",variant:"destructive"})}finally{p(!1)}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"rounded-md border border-amber-300/60 bg-amber-50/50 dark:bg-amber-950/20 dark:border-amber-500/30 px-3 py-2",children:e.jsxs("p",{className:"text-xs text-amber-800 dark:text-amber-300 leading-relaxed",children:[e.jsx("strong",{children:"Legado:"})," Os lotes agora possuem tipo_ingresso diretamente. Use a aba ",e.jsx("strong",{children:"Lotes"})," para gerenciar precos e estoque por tipo. Esta aba gerencia apenas vinculos antigos."]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-2",children:q&&e.jsxs(w,{size:"sm",className:"h-8 gap-1.5 text-xs bg-teal-600 hover:bg-teal-700 text-white shadow-sm",onClick:M,disabled:h,children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),h?"Salvando...":"Salvar"]})}),e.jsxs("div",{className:"relative",children:[e.jsxs(w,{variant:"outline",size:"sm",className:"h-7 gap-1 text-[10px] px-2 border-teal-300/60 text-teal-700 dark:text-teal-400 hover:bg-teal-50 dark:hover:bg-teal-950/30",onClick:()=>{I(!f),N(!1)},children:[e.jsx(et,{className:"h-3 w-3"}),"Adicionar"]}),f&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-10 bg-popover border rounded-md shadow-lg py-1 min-w-[200px]",children:[c.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-1 text-[9px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Existentes"}),c.map(A=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-muted/50 transition-colors flex items-center gap-2",onClick:()=>z(A.documentId),children:[e.jsx("span",{className:"truncate",children:A.nome}),A.progressivo&&e.jsx(je,{variant:"outline",className:"text-[8px] px-1 py-0 h-3.5 border-violet-300/60 text-violet-500 shrink-0",children:"prog"})]},A.documentId||A.id)),e.jsx("div",{className:"border-t my-1"})]}),e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-muted/50 transition-colors font-medium text-teal-700 dark:text-teal-400 flex items-center gap-1.5",onClick:()=>{N(!0),I(!1)},children:[e.jsx(et,{className:"h-3 w-3"}),"Criar novo tipo"]})]})]})]}),g&&e.jsxs("div",{className:"rounded-lg border border-teal-300/70 bg-teal-50/40 dark:bg-teal-950/15 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-teal-700 font-semibold",children:"Novo tipo de ingresso"}),e.jsx("button",{type:"button",onClick:()=>N(!1),className:"p-0.5 rounded hover:bg-destructive/10 text-muted-foreground
2/50 hover:text-destructive",children:e.jsx(yt,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("div",{className:"col-span-2 sm:col-span-1",children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Nome *"}),e.jsx(Te,{className:"h-7 text-xs",placeholder:"Ex: Meia, VIP, Camarote",value:b.nome,onChange:A=>C(S=>({...S,nome:A.target.value}))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Desconto %"}),e.jsx(Te,{type:"number",min:0,max:100,className:"h-7 text-xs",value:b.desconto_percentual,onChange:A=>C(S=>({...S,desconto_percentual:Number(A.target.value)||0}))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Qtd itens"}),e.jsx(Te,{type:"number",min:1,className:"h-7 text-xs",value:b.quantidade_itens,onChange:A=>C(S=>({...S,quantidade_itens:Math.max(1,Number(A.target.value)||1)}))})]})]}),e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs cursor-pointer",children:[e.jsx(Ls,{checked:b.progressivo,onCheckedChange:A=>C(S=>({...S,progressivo:A})),className:"scale-75 origin-left"}),"Progressivo"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs cursor-pointer",children:[e.jsx(Ls,{checked:b.requer_cpf,onCheckedChange:A=>C(S=>({...S,requer_cpf:A})),className:"scale-75 origin-left"}),"Requer CPF"]})]}),e.jsxs(w,{size:"sm",className:"h-7 gap-1.5 text-xs bg-teal-600 hover:bg-teal-700 text-white",onClick:D,disabled:h||!b.nome.trim(),children:[e.jsx(et,{className:"h-3 w-3"}),h?"Criando...":"Criar e vincular"]})]}),u.length>0?e.jsxs("div",{className:"rounded-lg border overflow-hidden",children:[e.jsx("div",{className:"hidden sm:block",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 bg-muted/30",children:[e.jsx("th",{className:"text-left font-medium px-3.5 py-1.5",children:"Nome"}),e.jsx("th",{className:"text-center font-medium px-2 py-1.5 w-[60px]",children:"Qtd itens"}),e.jsx("th",{className:"text-center font-medium px-2 py-1.5 w-[80px]",children:"Progressivo"}),e.jsx("th",{className:"text-right font-medium px-2 py-1.5 w-[80px]",children:"Desconto"}),e.jsx("th",{className:"text-right font-medium px-2 py-1.5",children:"Preco especifico"}),e.jsx("th",{className:"text-center font-medium px-2 py-1.5 w-[55px]",children:"Ativo"}),e.jsx("th",{className:"w-[28px]"})]})}),e.jsx("tbody",{className:"divide-y divide-border/20",children:u.map(A=>{const{tipo:S,tipoDocId:P}=vl(A,a),F=m.getVal(A.id,"preco_especifico"),ee=F??(A.preco_especifico!=null?String(A.preco_especifico):""),re=m.getVal(A.id,"ativo")??A.ativo!==!1,te=x.getVal(P,"quantidade_itens")??S.quantidade_itens??1,G=x.getVal(P,"progressivo")??S.progressivo??!1,y=x.getVal(P,"desconto_percentual")??S.desconto_percentual??0,$=F!==void 0||m.getVal(A.id,"ativo")!==void 0,W=!!P&&(x.getVal(P,"quantidade_itens")!==void 0||x.getVal(P,"progressivo")!==void 0||x.getVal(P,"desconto_percentual")!==void 0),ie=$||W;return e.jsxs("tr",{className:ls("transition-colors group/row",!re&&"opacity-40",ie&&"bg-teal-50/50 dark:bg-teal-950/15"),children:[e.jsx("td",{className:"px-3.5 py-2 font-medium",children:e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"truncate",children:S.nome||e.jsx("span",{className:"text-muted-foreground/50 italic",children:"sem nome"})})})}),e.jsx("td",{className:"px-2 py-1.5 text-center",children:e.jsx(Te,{type:"number",min:1,className:ls("h-6 w-12 text-xs text-center tabular-nums px-1 mx-auto",x.getVal(P,"quantidade_itens")!==void 0?"ring-1 ring-teal-400/70 border-teal-300":"border-border/50"),value:te,onChange:ke=>P&&x.setVal(P,"quantidade_itens",Math.max(1,Number(ke.target.value)||1)),disabled:!P})}),e.jsx("td",{className:"px-2 py-1.5 text-center",children:e.jsx(Ls,{checked:G,onCheckedChange:ke=>P&&x.setVal(P,"progressivo",ke),className:ls("scale-75 origin-center",G&&"data-[state=checked]:bg-violet-500"),disabled:!P})}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-end",children:[e.jsx(Te,{type:"number",min:0,max:100,step:"0.1",className:ls("h-6 w-16 text-xs text-right tabular-nums px-1",x.getVal(P,"desconto_percentual")!==void 0?"ring-1 ring-teal-400/70 border-teal-300":"border-border/50"),value:y,onChange:ke=>P&&x.setVal(P,"desconto_percentual",Number(ke.target.value)||0),disabled:!P}),e.jsx("span",{className:"text-[10px] text-muted-foreground ml-0.5",children:"%"})]})}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"preco do evento",className:ls("h-6 text-xs text-right tabular-nums px-2 max-w-[120px]","placeholder:text-muted-foreground
2/40 placeholder:text-[10px]",F!==void 0?"ring-1 ring-teal-400/70 border-teal-300":"border-border/50",ee!==""&&"font-semibold text-teal-800 dark:text-teal-300"),value:ee,onChange:ke=>m.setVal(A.id,"preco_especifico",ke.target.value)}),ee!==""&&e.jsx("button",{type:"button",onClick:()=>m.setVal(A.id,"preco_especifico",""),className:"p-0.5 rounded hover:bg-destructive/10 text-muted-foreground/50 hover:text-destructive transition-colors opacity-0 group-hover/row:opacity-100",children:e.jsx(yt,{className:"h-3 w-3"})})]})}),e.jsx("td",{className:"px-2 py-1.5 text-center",children:e.jsx(Ls,{checked:re,onCheckedChange:ke=>m.setVal(A.id,"ativo",ke),className:"scale-75 origin-center"})}),e.jsx("td",{className:"px-1 py-1.5",children:e.jsx("button",{type:"button",onClick:()=>E(A.id),className:"p-1 rounded hover:bg-destructive/10 text-muted-foreground/30 hover:text-destructive transition-colors opacity-0 group-hover/row:opacity-100",title:"Remover tipo deste evento",children:e.jsx(yt,{className:"h-3.5 w-3.5"})})})]},A.id)})})]})}),e.jsx("div",{className:"sm:hidden divide-y divide-border/30",children:u.map(A=>{const{tipo:S,tipoDocId:P}=vl(A,a),F=m.getVal(A.id,"preco_especifico"),ee=F??(A.preco_especifico!=null?String(A.preco_especifico):""),re=m.getVal(A.id,"ativo")??A.ativo!==!1,te=x.getVal(P,"quantidade_itens")??S.quantidade_itens??1,G=x.getVal(P,"progressivo")??S.progressivo??!1,y=x.getVal(P,"desconto_percentual")??S.desconto_percentual??0,$=F!==void 0||m.getVal(A.id,"ativo")!==void 0||P&&(x.getVal(P,"quantidade_itens")!==void 0||x.getVal(P,"progressivo")!==void 0);return e.jsxs("div",{className:ls("px-3 py-2.5 text-xs",!re&&"opacity-40",$&&"bg-teal-50/40 dark:bg-teal-950/15"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsx("span",{className:"font-semibold truncate",children:S.nome||e.jsx("span",{className:"text-muted-foreground/50 italic",children:"sem nome"})}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Ativo"}),e.jsx(Ls,{checked:re,onCheckedChange:W=>m.setVal(A.id,"ativo",W),className:"scale-[0.65] origin-center"}),e.jsx("button",{type:"button",onClick:()=>E(A.id),className:"p-0.5 rounded hover:bg-destructive/10 text-muted-foreground/50 hover:text-destructive",children:e.jsx(yt,{className:"h-3 w-3"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Qtd itens"}),e.jsx(Te,{type:"number",min:1,className:ls("h-6 text-[11px] text-center px-1",x.getVal(P,"quantidade_itens")!==void 0?"ring-1 ring-teal-400/70 border-teal-300":"border-border/50"),value:te,onChange:W=>P&&x.setVal(P,"quantidade_itens",Math.max(1,Number(W.target.value)||1)),disabled:!P})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Desconto %"}),e.jsx(Te,{type:"number",min:0,max:100,className:ls("h-6 text-[11px] text-right px-1",x.getVal(P,"desconto_percentual")!==void 0?"ring-1 ring-teal-400/70 border-teal-300":"border-border/50"),value:y,onChange:W=>P&&x.setVal(P,"desconto_percentual",Number(W.target.value)||0),disabled:!P})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Progressivo"}),e.jsx(Ls,{checked:G,onCheckedChange:W=>P&&x.setVal(P,"progressivo",W),className:ls("scale-75 origin-left",G&&"data-[state=checked]:bg-violet-500"),disabled:!P})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Preco especifico"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"evento",className:ls("h-6 text-[11px] text-right tabular-nums px-1.5 flex-1",F!==void 0?"ring-1 ring-teal-400/70 border-teal-300":"border-border/50",ee!==""&&"font-semibold text-teal-800 dark:text-teal-300"),value:ee,onChange:W=>m.setVal(A.id,"preco_especifico",W.target.value)}),ee!==""&&e.jsx("button",{type:"button",onClick:()=>m.setVal(A.id,"preco_especifico",""),className:"p-0.5 rounded hover:bg-destructive/10 text-muted-foreground
2/50 hover:text-destructive",children:e.jsx(yt,{className:"h-3 w-3"})})]})]})]})]},A.id)})})]}):e.jsxs("div",{className:"flex items-center gap-2 py-3 px-1 text-xs text-muted-foreground",children:[e.jsx(Ea,{className:"h-3.5 w-3.5"}),'Nenhum tipo vinculado. Use "Adicionar" para vincular.']}),q&&e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2.5 rounded-lg border bg-teal-50/80 dark:bg-teal-950/20 backdrop-blur-sm",children:[e.jsxs("span",{className:"text-[11px] text-teal-700 dark:text-teal-400 font-medium",children:[x.hasEdits&&m.hasEdits?"Alteracoes globais + por evento":x.hasEdits?"Alteracoes globais":"Alteracoes por evento"," · nao salvas"]}),e.jsxs(w,{size:"sm",className:"h-7 gap-1.5 text-xs bg-teal-600 hover:bg-teal-700 text-white",onClick:M,disabled:h,children:[e.jsx(Da,{className:"h-3 w-3"}),h?"Salvando...":"Salvar"]})]})]})}function gp({evento:s,onSaved:t,allTipos:a=[],refetchTipos:n}){const o=s?.attributes||s||{},{toast:i}=mt(),u=r.useMemo(()=>Array.isArray(o.lotes)?o.lotes:[],[o.lotes]),l=r.useMemo(()=>Array.isArray(o.datas_futuras)?o.datas_futuras:[],[o.datas_futuras]),c=r.useMemo(()=>a.map(U=>{const J=U?.attributes||U||{},T=U?.documentId??J?.documentId??"";return{id:String(U?.id??""),documentId:T,nome:J?.nome||"Ingresso",excecao_criancas:J?.excecao_criancas===!0}}).filter(U=>U.documentId),[a]),m=pn(),[x,h]=r.useState(!1),[p,f]=r.useState([]),I=r.useMemo(()=>{const U=l[0];return U?Et(U.data)||"__unknown":null},[l]),[g,N]=r.useState(new Set),[b,C]=r.useState(null),[q,L]=r.useState(null),[M,z]=r.useState(!1),[D,E]=r.useState(null),[A,S]=r.useState({nome:"",desconto_percentual:0,progressivo:!1,quantidade_itens:1,requer_cpf:!0}),[P,F]=r.useState(new Set),ee=p.length>0,re=P.size>0,te=m.hasEdits||ee||re,G=U=>N(J=>{const T=new Set(J);return T.has(U)?T.delete(U):T.add(U),T});r.useEffect(()=>{I&&N(U=>U.size>0?U:new Set([I]))},[I]);const y=r.useMemo(()=>{const U=[];for(const J of l){const T=Et(J?.data)||"__unknown";U.push({key:T,label:cn(J.data),dateValue:J.data?String(J.data).slice(0,10):null})}return U},[l]),$=r.useMemo(()=>{const U=cc(u,l);for(const J of p){const T=J._dateKey||I||"__unknown";U.has(T)&&U.get(T).lotes.push(J)}return U},[u,l,I,p]),W=r.useMemo(()=>Array.from($.entries()).filter(([,U])=>U.lotes.length===0).map(([,U])=>U.label),[$]),ie=U=>{const J={...U};return m.getVal(U.id,"quantidade_disponivel")!==void 0&&(J.quantidade_disponivel=Number(m.getVal(U.id,"quantidade_disponivel"))),m.getVal(U.id,"ativo")!==void 0&&(J.ativo=m.getVal(U.id,"ativo")),m.getVal(U.id,"manual_ativo")!==void 0&&(J.manual_ativo=m.getVal(U.id,"manual_ativo")),m.getVal(U.id,"is_upsell")!==void 0&&(J.is_upsell=m.getVal(U.id,"is_upsell")),m.getVal(U.id,"tipo_ingresso")!==void 0&&(J.tipo_ingresso=m.getVal(U.id,"tipo_ingresso")),J},ke=async()=>{h(!0);try{const U=o.documentId||s?.documentId,J=u.filter(we=>!P.has(we.id)).map(we=>un(ie(we))),T=p.map(we=>un(we)),{lotes:Ee,removed:Se}=Jm([...J,...T]),Ze=new Set(c.filter(we=>we.excecao_criancas).map(we=>we.documentId)),qe=Ym(Ee,Ze),Qe=await Fa(U,{lotes:[...Ee,...qe]});m.clearEdits(),f([]),F(new Set),i({title:"Lotes atualizados com sucesso",...Se>0?{description:`${Se} lote(s) "Criança" duplicado(s) removido(s).`}:{}}),t?.(Qe)}catch(U){i({title:"Erro ao salvar lotes",description:U?.response?.data?.error?.message||"Tente novamente.",variant:"destructive"})}finally{h(!1)}},Ae=()=>{if(!I)return;const U=$.get(I);if(!U||U.lotes.length===0){i({title:"Sem lotes na primeira data",description:"Crie lotes para a primeira data antes de sincronizar.",variant:"destructive"});return}if(U.lotes.filter(Ee=>!Ee._isNew&&!P.has(Ee.id)).length===0){i({title:"Sem lotes na primeira data",variant:"destructive"});return}let T=0;for(const[Ee,Se]of $.entries())Ee===I||Se.lotes.filter(qe=>qe._isNew||!P.has(qe.id)).length>0||(me(I,Ee),T++);T>0?i({title:`Lotes replicados para ${T} data${T>1?"s":""}`}):i({title:"Todas as datas já possuem lotes"})},be=U=>{const J=y.find(Se=>Se.key===U),T=u.reduce((Se,Ze)=>Math.max(Se,Number(Ze.ordem)||0),0),Ee={id:`new-${Date.now()}`,_dateKey:U,_isNew:!0,nome:"",tipo_ingresso:c[0]?.documentId||"",preco_lote:null,preco_upsell:null,quantidade_disponivel:0,ativo:!0,manual_ativo:!1,auto_por_data_evento:!1,ordem:T+1,data_evento:J?.dateValue||null,is_upsell:!1};f(Se=>[...Se,Ee]),C(null),N(Se=>{const Ze=new Set(Se);return Ze.add(U),Ze})},Fe=()=>{const U=u.reduce((T,Ee)=>Math.max(T,Number(Ee.ordem)||0),0),J=y.map((T,Ee)=>({id:`new-${Date.now()}-${Ee}`,_dateKey:T.key,_isNew:!0,nome:"",tipo_ingresso:c[0]?.documentId||"",preco_lote:null,preco_upsell:null,quantidade_disponivel:0,ativo:!0,manual_ativo:!1,auto_por_data_evento:!1,ordem:U+1+Ee,data_evento:T.dateValue||null,is_upsell:!1}));f(T=>[...T,...J]),C(null),N(new Set(y.map(T=>T.key)))},ae=(U,J,T)=>{f(Ee=>Ee.map(Se=>Se.id===U?{...Se,[J]:T}:Se))},K=U=>
2{f(J=>J.filter(T=>T.id!==U))},O=U=>{F(J=>{const T=new Set(J);return T.add(U),T})},oe=U=>{const J=$.get(U);J&&(F(T=>{const Ee=new Set(T);for(const Se of J.lotes)Se._isNew||Ee.add(Se.id);return Ee}),f(T=>T.filter(Ee=>Ee._dateKey!==U)))},ve=(U,J)=>{const T=$.get(U);if(T){for(const Ee of T.lotes)Ee._isNew||m.setVal(Ee.id,"ativo",J);f(Ee=>Ee.map(Se=>Se._dateKey===U?{...Se,ativo:J}:Se))}},me=(U,J)=>{const T=$.get(U);if(!T)return;const Se=y.find(Qe=>Qe.key===J)?.dateValue||null,qe=T.lotes.filter(Qe=>!Qe._isNew&&!P.has(Qe.id)).map((Qe,we)=>({id:`new-${Date.now()}-${we}`,_dateKey:J,_isNew:!0,nome:Qe.nome,tipo_ingresso:Qe.tipo_ingresso?.documentId??Qe.tipo_ingresso,preco_lote:Qe.preco_lote,preco_upsell:Qe.preco_upsell??null,quantidade_disponivel:Qe.quantidade_disponivel??0,ativo:Qe.ativo??!0,manual_ativo:Qe.manual_ativo??!1,auto_por_data_evento:Qe.auto_por_data_evento??!1,ordem:Qe.ordem??0,data_evento:Se,is_upsell:Qe.is_upsell??!1}));f(Qe=>[...Qe,...qe]),L(null),N(Qe=>{const we=new Set(Qe);return we.add(J),we})},fe=async()=>{if(A.nome.trim()){h(!0);try{const U=await $e.post("/tipo-ingressos",{data:{...A,ativo:!0,ordem:a.length}}),T=(U?.data?.data||U?.data)?.documentId;T&&D&&ae(D,"tipo_ingresso",T),S({nome:"",desconto_percentual:0,progressivo:!1,quantidade_itens:1,requer_cpf:!0}),z(!1),E(null),i({title:`"${A.nome}" criado com sucesso`}),n?.(),t?.()}catch{i({title:"Erro ao criar tipo de ingresso",variant:"destructive"})}finally{h(!1)}}},le=(U=null)=>{E(U),S({nome:"",desconto_percentual:0,progressivo:!1,quantidade_itens:1,requer_cpf:!0}),z(!0)},_e=Array.from($.entries());return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:W.length>0&&e.jsxs(w,{size:"sm",variant:"secondary",onClick:Ae,className:"h-8 gap-1.5 text-xs",children:[e.jsx(ta,{className:"h-3.5 w-3.5"}),`Criar lotes (${W.length})`]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.length>0&&e.jsxs("div",{className:"relative",children:[e.jsxs(w,{variant:"outline",size:"sm",className:"h-8 gap-1 text-xs px-2.5 border-blue-300/60 text-blue-700 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-950/30",onClick:()=>C(b?null:"__pick"),children:[e.jsx(et,{className:"h-3.5 w-3.5"}),"Novo lote"]}),b==="__pick"&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-10 bg-popover border rounded-md shadow-lg py-1 min-w-[200px]",children:[y.length>1&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-blue-50 dark:hover:bg-blue-950/30 transition-colors font-medium text-blue-700 dark:text-blue-400 flex items-center gap-1.5",onClick:()=>Fe(),children:[e.jsx(Ia,{className:"h-3 w-3"}),"Todas as datas"]}),e.jsx("div",{className:"border-t my-1"})]}),_e.map(([U,J])=>e.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-muted/50 transition-colors capitalize truncate",onClick:()=>be(U),children:J.label},U))]})]}),te&&e.jsxs(w,{size:"sm",onClick:ke,disabled:x,className:"h-8 gap-1.5 text-xs",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),x?"Salvando...":"Salvar"]})]})]}),_e.length>0?e.jsx("div",{className:"rounded-lg border overflow-hidden divide-y divide-border/50",children:_e.map(([U,J])=>{const T=J.lotes.filter(Ne=>Ne._isNew||!P.has(Ne.id)),Ee=T.filter(Ne=>!Ne._isNew),Se=T.length>0,Ze=g.has(U),qe=J.ingressosDisponiveis,Qe=J.limiteIngressos,we=qe!=null&&Qe!=null&&Qe>0,Me={},ks={};if(we)for(const Ne of Ee){if(m.getVal(Ne.id,"is_upsell")??Ne.is_upsell)continue;const ss=Ne.tipo_ingresso||{},We=Math.max(1,Number(ss.quantidade_itens||1));Me[Ne.id]=Math.floor(qe/We),ks[Ne.id]=Math.floor(Qe/We)}const xs=T.reduce((Ne,es)=>{const ss=es._isNew?Number(es.quantidade_disponivel||0):Number(Me[es.id]??m.getVal(es.id,"quantidade_disponivel")??es.quantidade_disponivel??0),We=Math.max(0,ss),hs=es.tipo_ingresso||{},Is=hs.progressivo===!0,Y=Math.max(1,Number(hs.quantidade_itens||1));return Ne+(Is&&Y>1?We*Y:We)},0),k=Se&&xs===0,De=Ee.length>0&&Ee.every(Ne=>(m.getVal(Ne.id,"ativo")??Ne.ativo)!==!1);return e.jsxs(ki,{open:Ze,onOpenChange:()=>G(U),children:[e.jsxs("div",{className:ls("flex items-center",k&&"opacity-50"),children:[e.jsx(Si,{asChild:!0,children:e.jsxs("button",{type:"button",className:ls("flex-1 flex items-center gap-3 px-4 py-3 text-left transition-colors","hover:bg-muted/40 focu
2s-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-inset"),children:[e.jsx(kr,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-semibold capitalize truncate",children:J.label}),!Se&&e.jsxs(je,{variant:"destructive",className:"text-[10px] px-1.5 py-0 gap-0.5",children:[e.jsx(Ya,{className:"h-2.5 w-2.5"})," Sem lotes"]}),Se&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[T.length," lote",T.length!==1&&"s"]}),k&&e.jsx(je,{variant:"outline",className:"text-[10px] px-1.5 py-0 gap-0.5 border-rose-300 text-rose-600 bg-rose-50 dark:bg-rose-950/30",children:"Esgotado"}),we&&e.jsxs("span",{className:"text-[10px] text-muted-foreground/70 tabular-nums",children:[qe," / ",Qe]})]}),we&&e.jsx("div",{className:"mt-1.5 h-1 rounded-full bg-muted overflow-hidden max-w-[33%]",children:e.jsx("div",{className:ls("h-full rounded-full transition-all duration-500",qe===0?"bg-rose-500":qe/Qe<=.15?"bg-amber-500":"bg-emerald-500"),style:{width:`${Math.min(100,Math.round(qe/Qe*100))}%`}})})]}),e.jsx(ra,{className:ls("h-4 w-4 text-muted-foreground shrink-0 transition-transform duration-200",Ze&&"rotate-180")})]})}),e.jsxs("div",{className:"flex items-center gap-1 pr-3 shrink-0",onClick:Ne=>Ne.stopPropagation(),children:[Ee.length>0&&e.jsx(Ls,{checked:De,onCheckedChange:Ne=>ve(U,Ne),className:"scale-75 origin-center",title:De?"Desativar todos desta data":"Ativar todos desta data"}),Se&&e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>L(q===U?null:U),className:"p-1 rounded hover:bg-blue-100 dark:hover:bg-blue-950/30 text-muted-foreground/40 hover:text-blue-600 transition-colors",title:"Replicar lotes para outra data",children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),q===U&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-popover border rounded-md shadow-lg py-1 min-w-[200px]",children:[e.jsx("div",{className:"px-3 py-1 text-[9px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Copiar para"}),_e.filter(([Ne])=>Ne!==U).map(([Ne,es])=>e.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-blue-50 dark:hover:bg-blue-950/30 transition-colors capitalize truncate",onClick:()=>me(U,Ne),children:es.label},Ne))]})]}),Se&&e.jsx("button",{type:"button",onClick:()=>oe(U),className:"p-1 rounded hover:bg-rose-100 dark:hover:bg-rose-950/30 text-muted-foreground/40 hover:text-rose-600 transition-colors",title:"Excluir lotes desta data",children:e.jsx(Xt,{className:"h-3.5 w-3.5"})})]})]}),e.jsx(Ii,{children:Se?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block border-t",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/30 text-xs text-muted-foreground uppercase tracking-wider",children:[e.jsx("th",{className:"text-left font-medium px-4 py-2",children:"Lote"}),e.jsx("th",{className:"text-left font-medium px-4 py-2",children:"Tipo"}),e.jsx("th",{className:"text-right font-medium px-4 py-2",children:"Preco"}),e.jsx("th",{className:"text-center font-medium px-4 py-2",children:"Estoque"}),e.jsx("th",{className:"text-center font-medium px-4 py-2",children:"Ativo"}),e.jsx("th",{className:"text-center font-medium px-4 py-2",children:"Manual"}),e.jsx("th",{className:"text-center font-medium px-4 py-2",children:"Pós-venda"}),e.jsx("th",{className:"w-[30px]"})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:T.map(Ne=>Ne._isNew?e.jsx(fp,{lote:Ne,eventTipos:c,updateNewLote:ae,removeNewLote:K,openCreateTipoDialog:le},Ne.id):e.jsx(vp,{lote:Ne,getVal:m.getVal,setVal:m.setVal,eventTipos:c,onDelete:O,derivedQty:Me[Ne.id],capacity:ks[Ne.id]},Ne.id))})]})}),e.jsx("div",{className:"md:hidden border-t divide-y divide-border/50",children:T.map(Ne=>Ne._isNew?e.jsx(jp,{lote:Ne,eventTipos:c,updateNewLote:ae,removeNewLote:K,openCreateTipoDialog:le},Ne.id):e.jsx(bp,{lote:Ne,getVal:m.getVal,setVal:m.setVal,eventTipos:c,onDelete:O,derivedQty:Me[Ne.id],capacity:ks[Ne.id]},Ne.id))})]}):e.jsxs("div",{className:"border-t px-4 py-6 text-center",children:[e.jsx(Oo,{className:"h-8 w-8 text-muted-foreground
2/40 mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Nenhum lote para esta data. Use "Novo lote" acima.'})]})})]},U)})}):e.jsxs("div",{className:"flex items-center gap-2 py-3 px-1 text-xs text-muted-foreground",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"}),'Nenhum lote cadastrado. Use "Novo lote" para criar.']}),te&&e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2.5 rounded-lg border bg-blue-50/80 dark:bg-blue-950/20 backdrop-blur-sm",children:[e.jsxs("span",{className:"text-[11px] text-blue-700 dark:text-blue-400 font-medium",children:[ee?`${p.length} novo${p.length>1?"s":""} lote${p.length>1?"s":""} · `:"",re?`${P.size} a excluir · `:"","Alteracoes nao salvas"]}),e.jsxs(w,{size:"sm",className:"h-7 gap-1.5 text-xs",onClick:ke,disabled:x,children:[e.jsx(Da,{className:"h-3 w-3"}),x?"Salvando...":"Salvar"]})]}),e.jsx(at,{open:M,onOpenChange:z,children:e.jsxs(rt,{className:"sm:max-w-md",children:[e.jsx(nt,{children:e.jsx(it,{className:"text-base",children:"Criar tipo de ingresso"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"Nome *"}),e.jsx(Te,{placeholder:"Ex: Meia, VIP, Camarote",value:A.nome,onChange:U=>S(J=>({...J,nome:U.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"Desconto %"}),e.jsx(Te,{type:"number",min:0,max:100,value:A.desconto_percentual,onChange:U=>S(J=>({...J,desconto_percentual:Number(U.target.value)||0}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"Qtd itens"}),e.jsx(Te,{type:"number",min:1,value:A.quantidade_itens,onChange:U=>S(J=>({...J,quantidade_itens:Math.max(1,Number(U.target.value)||1)}))})]})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Ls,{checked:A.progressivo,onCheckedChange:U=>S(J=>({...J,progressivo:U}))}),"Progressivo"]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Ls,{checked:A.requer_cpf,onCheckedChange:U=>S(J=>({...J,requer_cpf:U}))}),"Requer CPF"]})]})]}),e.jsxs(Ut,{children:[e.jsx(w,{variant:"outline",onClick:()=>z(!1),children:"Cancelar"}),e.jsxs(w,{onClick:fe,disabled:x||!A.nome.trim(),children:[e.jsx(et,{className:"h-4 w-4 mr-1.5"}),x?"Criando...":"Criar e vincular"]})]})]})})]})}function fp({lote:s,eventTipos:t,updateNewLote:a,removeNewLote:n,openCreateTipoDialog:o}){return e.jsxs("tr",{className:"bg-blue-50/60 dark:bg-blue-950/20",children:[e.jsx("td",{className:"px-4 py-2",children:e.jsx(Te,{placeholder:"Nome do lote",className:"h-7 text-xs px-2 max-w-[150px]",value:s.nome,onChange:i=>a(s.id,"nome",i.target.value)})}),e.jsx("td",{className:"px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(rs,{value:String(s.tipo_ingresso),onValueChange:i=>a(s.id,"tipo_ingresso",i),children:[e.jsx(ns,{className:"h-7 text-xs w-full max-w-[130px]",children:e.jsx(is,{})}),e.jsx(os,{children:t.map(i=>e.jsx(xe,{value:i.documentId,children:i.nome},i.documentId))})]}),e.jsx("button",{type:"button",onClick:()=>
2o(s.id),className:"p-1 rounded border border-dashed border-blue-300/70 text-blue-600 hover:bg-blue-100 dark:hover:bg-blue-950/40 transition-colors shrink-0",title:"Criar novo tipo de ingresso",children:e.jsx(et,{className:"h-3 w-3"})})]})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"0,00",className:"h-7 text-xs text-right tabular-nums px-2 max-w-[100px]",value:s.preco_lote??"",onChange:i=>a(s.id,"preco_lote",i.target.value===""?null:Number(i.target.value))})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(Te,{type:"number",min:0,className:"h-7 text-xs text-center tabular-nums px-2 w-20",value:s.quantidade_disponivel??0,onChange:i=>a(s.id,"quantidade_disponivel",Number(i.target.value)||0)})}),e.jsx("td",{className:"px-4 py-2 text-center",children:e.jsx(Ls,{checked:s.ativo!==!1,onCheckedChange:i=>a(s.id,"ativo",i),className:"scale-75 origin-center"})}),e.jsx("td",{className:"px-4 py-2 text-center",children:e.jsx(Ls,{checked:s.manual_ativo===!0,onCheckedChange:i=>a(s.id,"manual_ativo",i),className:"scale-75 origin-center"})}),e.jsx("td",{className:"px-1 py-2",children:e.jsx("button",{type:"button",onClick:()=>n(s.id),className:"p-1 rounded hover:bg-destructive/10 text-muted-foreground/50 hover:text-destructive transition-colors",children:e.jsx(yt,{className:"h-3.5 w-3.5"})})})]})}function jp({lote:s,eventTipos:t,updateNewLote:a,removeNewLote:n,openCreateTipoDialog:o}){return e.jsxs("div",{className:"px-4 py-3 space-y-2.5 bg-blue-50/40 dark:bg-blue-950/15",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[9px] uppercase tracking-wide text-blue-700 font-semibold",children:"Novo lote"}),e.jsx("button",{type:"button",onClick:()=>n(s.id),className:"p-0.5 rounded hover:bg-destructive/10 text-muted-foreground/50 hover:text-destructive",children:e.jsx(yt,{className:"h-3 w-3"})})]}),e.jsx(Te,{placeholder:"Nome",className:"h-7 text-xs",value:s.nome,onChange:i=>a(s.id,"nome",i.target.value)}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(rs,{value:String(s.tipo_ingresso),onValueChange:i=>a(s.id,"tipo_ingresso",i),children:[e.jsx(ns,{className:"h-7 text-xs flex-1",children:e.jsx(is,{})}),e.jsx(os,{children:t.map(i=>e.jsx(xe,{value:i.documentId,children:i.nome},i.documentId))})]}),e.jsx("button",{type:"button",onClick:()=>
2o(s.id),className:"p-1.5 rounded border border-dashed border-blue-300/70 text-blue-600 hover:bg-blue-100 dark:hover:bg-blue-950/40 transition-colors shrink-0",title:"Criar novo tipo",children:e.jsx(et,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Preco"}),e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"0,00",className:"h-6 text-[11px] text-right px-1.5",value:s.preco_lote??"",onChange:i=>a(s.id,"preco_lote",i.target.value===""?null:Number(i.target.value))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Estoque"}),e.jsx(Te,{type:"number",min:0,className:"h-6 text-[11px] text-center px-1.5",value:s.quantidade_disponivel??0,onChange:i=>a(s.id,"quantidade_disponivel",Number(i.target.value)||0)})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:["Ativo ",e.jsx(Ls,{checked:s.ativo!==!1,onCheckedChange:i=>a(s.id,"ativo",i),className:"scale-75 origin-left"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:["Manual ",e.jsx(Ls,{checked:s.manual_ativo===!0,onCheckedChange:i=>a(s.id,"manual_ativo",i),className:"scale-75 origin-left"})]})]})]})}function vp({lote:s,getVal:t,setVal:a,eventTipos:n,onDelete:o,derivedQty:i,capacity:u}){const l=s.tipo_ingresso||{},c=l.progressivo===!0,m=Math.max(1,Number(l.quantidade_itens||1)),x=m>1?m:null,h=t(s.id,"quantidade_disponivel"),f=h??i??s.quantidade_disponivel??0,I=c&&x?Number(f)*x:Number(f),g=t(s.id,"ativo")??s.ativo!==!1,N=t(s.id,"manual_ativo")??s.manual_ativo===!0,b=t(s.id,"is_upsell")??s.is_upsell===!0,C=t(s.id,"tipo_ingresso")??(l?.documentId?String(l.documentId):""),q=h!=null&&Number(h)!==(i??s.quantidade_disponivel??0),L=!C,M=I===0,z=u??(s.limite_lote?Math.floor(s.limite_lote/(c?m:1)):null),D=z!=null&&z>0,E=D?Math.min(100,Math.round((z-Number(f))/z*100)):0,A=D?100-E:100,S=M?"bg-rose-500":A<=15?"bg-amber-500":"bg-emerald-500",P=M?"text-rose-500":A<=15?"text-amber-500":"text-emerald-500";return e.jsxs("tr",{className:ls("transition-colors",!g&&"opacity-50",g&&M&&"opacity-60 bg-rose-50/40 dark:bg-rose-950/10"),children:[e.jsx("td",{className:"px-4 py-2.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"font-medium text-sm",children:s.nome||"-"}),x&&e.jsxs(je,{variant:"outline",className:ls("text-[10px] px-1.5 py-0",c?"border-violet-300 text-violet-600 bg-violet-50":"border-blue-300 text-blue-600 bg-blue-50"),children:[x,"x"]})]})}),e.jsx("td",{className:"px-4 py-2.5",children:n.length>0?e.jsxs(rs,{value:C,onValueChange:F=>a(s.id,"tipo_ingresso",F),children:[e.jsx(ns,{className:ls("h-7 text-xs w-full max-w-[140px]",L&&"border-amber-400 text-amber-700"),children:e.jsx(is,{placeholder:"Selecionar…"})}),e.jsx(os,{children:n.map(F=>e.jsx(xe,{value:F.documentId,children:F.nome},F.documentId))})]}):e.jsx("span",{className:ls("text-muted-foreground text-xs",L&&"text-amber-600"),children:L?"—":l.nome||l.titulo||"-"})}),e.jsx("td",{className:"px-4 py-2.5 text-right font-medium tabular-nums",children:Pr(s.preco_lote)}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:ls("text-sm font-semibold tabular-nums",P),children:f}),D&&e.jsxs("span",{className:"text-[10px] text-muted-foreground/60 tabular-nums",children:["/ ",z]}),c&&x&&e.jsxs("span",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:["= ",I," ing."]})]}),D&&e.jsx("div",{className:"w-full h-1.5 rounded-full bg-muted/60 overflow-hidden",children:e.jsx("div",{className:ls("h-full rounded-full transition-all duration-500",S),style:{width:`${A}%`}})}),q&&e.jsx("span",{className:"text-[9px] text-muted-foreground/50 line-through tabular-nums",children:s.quantidade_disponivel})]})}),e.jsx("td",{className:"px-4 py-2.5 text-center",children:e.jsx(Ls,{checked:g,onCheckedChange:F=>a(s.id,"ativo",F)})}),e.jsx("td",{className:"px-4 py-2.5 text-center",children:e.jsx(Ls,{checked:N,onCheckedChange:F=>a(s.id,"manual_ativo",F)})}),e.jsx("td",{className:"px-4 py-2.5 text-center",children:e.jsx(Ls,{checked:b,onCheckedChange:F=>a(s.id,"is_upsell",F)})}),e.jsx("td",{className:"px-1 py-2.5",children:e.jsx("button",{type:"button",onClick:()=>
2o(s.id),className:"p-1 rounded hover:bg-destructive/10 text-muted-foreground/50 hover:text-destructive transition-colors",title:"Excluir lote",children:e.jsx(yt,{className:"h-3.5 w-3.5"})})})]})}function bp({lote:s,getVal:t,setVal:a,eventTipos:n,onDelete:o,derivedQty:i,capacity:u}){const l=s.tipo_ingresso||{},c=l.progressivo===!0,m=Math.max(1,Number(l.quantidade_itens||1)),x=m>1?m:null,h=t(s.id,"quantidade_disponivel"),f=h??i??s.quantidade_disponivel??0,I=c&&x?Number(f)*x:Number(f),g=t(s.id,"ativo")??s.ativo!==!1,N=t(s.id,"manual_ativo")??s.manual_ativo===!0,b=t(s.id,"is_upsell")??s.is_upsell===!0,C=t(s.id,"tipo_ingresso")??(l?.documentId?String(l.documentId):""),q=h!=null&&Number(h)!==(i??s.quantidade_disponivel??0),L=!C,M=I===0,z=u??(s.limite_lote?Math.floor(s.limite_lote/(c?m:1)):null),D=z!=null&&z>0,E=D?Math.min(100,Math.round(Number(f)/z*100)):100,A=M?"bg-rose-500":E<=15?"bg-amber-500":"bg-emerald-500",S=M?"text-rose-500":E<=15?"text-amber-500":"text-emerald-500";return e.jsxs("div",{className:ls("px-4 py-3 space-y-2.5",!g&&"opacity-50",g&&M&&"opacity-60 bg-rose-50/40 dark:bg-rose-950/10"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm",children:s.nome||"-"}),x&&e.jsxs(je,{variant:"outline",className:ls("text-[10px] px-1.5 py-0",c?"border-violet-300 text-violet-600 bg-violet-50":"border-blue-300 text-blue-600 bg-blue-50"),children:[x,"x"]})]}),n.length>0?e.jsxs(rs,{value:C,onValueChange:P=>a(s.id,"tipo_ingresso",P),children:[e.jsx(ns,{className:ls("h-6 text-[11px] mt-1 w-full max-w-[180px]",L&&"border-amber-400 text-amber-700"),children:e.jsx(is,{placeholder:"Selecionar tipo…"})}),e.jsx(os,{children:n.map(P=>e.jsx(xe,{value:P.documentId,children:P.nome},P.documentId))})]}):e.jsx("p",{className:ls("text-xs text-muted-foreground mt-0.5",L&&"text-amber-600"),children:L?"Sem tipo":l.nome||l.titulo||"-"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("span",{className:"text-sm font-semibold tabular-nums",children:Pr(s.preco_lote)}),e.jsx("button",{type:"button",onClick:()=>
2o(s.id),className:"p-0.5 rounded hover:bg-destructive/10 text-muted-foreground/40 hover:text-destructive transition-colors",title:"Excluir lote",children:e.jsx(yt,{className:"h-3 w-3"})})]})]}),D&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:ls("text-xs font-semibold tabular-nums",S),children:f}),e.jsxs("span",{className:"text-[10px] text-muted-foreground/60 tabular-nums",children:["/ ",z]}),c&&x&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["= ",I," ing."]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted/60 overflow-hidden",children:e.jsx("div",{className:ls("h-full rounded-full transition-all duration-500",A),style:{width:`${E}%`}})})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[!D&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground uppercase tracking-wide font-medium",children:"Qtd"}),e.jsx("span",{className:ls("text-sm font-semibold tabular-nums",S),children:f}),c&&x&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["= ",I," ing."]}),q&&e.jsx("span",{className:"text-[10px] text-muted-foreground line-through tabular-nums",children:s.quantidade_disponivel})]}),e.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Ativo"}),e.jsx(Ls,{checked:g,onCheckedChange:P=>a(s.id,"ativo",P)})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Manual"}),e.jsx(Ls,{checked:N,onCheckedChange:P=>a(s.id,"manual_ativo",P)})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Pós-venda"}),e.jsx(Ls,{checked:b,onCheckedChange:P=>a(s.id,"is_upsell",P)})]})]})]})}function Np({evento:s,onSaved:t,allTipos:a=[],refetchTipos:n}){const o=s?.attributes||s||{},i=r.useMemo(()=>Array.isArray(o.lotes)?o.lotes:[],[o.lotes]),u=r.useMemo(()=>Array.isArray(o.datas_futuras)?o.datas_futuras:[],[o.datas_futuras]),l=r.useMemo(()=>(Array.isArray(o.tipos_ingresso)?o.tipos_ingresso:[]).map(me=>{const fe=me?.tipo_ingresso?.data||me?.tipo_ingresso||{},le=fe?.documentId??"";return{id:String(fe?.id??me?.id??""),documentId:le,nome:fe?.nome||"Ingresso"}}).filter(me=>me.documentId),[o.tipos_ingresso]),[c,m]=r.useState(o.upsell_limite_extra??2),[x,h]=r.useState(o.upsell_progressivo_continua??!1),p=pn(),[f,I]=r.useState([]),[g,N]=r.useState(!1),[b,C]=r.useState(new Set),[q,L]=r.useState(null),[M,z]=r.useState(!1),[D,E]=r.useState(null),[A,S]=r.useState({nome:"",desconto_percentual:0,progressivo:!1,quantidade_itens:1,requer_cpf:!0}),{toast:P}=mt(),F=c!==(o.upsell_limite_extra??2)||x!==(o.upsell_progressivo_continua??!1),ee=f.length>0,re=F||p.hasEdits||ee,te=ve=>C(me=>{const fe=new Set(me);return fe.has(ve)?fe.delete(ve):fe.add(ve),fe}),G=r.useMemo(()=>{const ve=[];for(const me of u){const fe=Et(me?.data)||"__unknown";ve.push({key:fe,label:cn(me.data),dateValue:me.data?String(me.data).slice(0,10):null})}return ve},[u]),y=r.useMemo(()=>{const ve=cc(i,u),me=ve.keys().next().value;for(const fe of f){const le=fe._dateKey||me;ve.has(le)&&ve.get(le).lotes.push(fe)}return b.size===0&&me&&C(new Set([me])),ve},[i,u,f]),$=ve=>{const me={...ve};if(p.getVal(ve.id,"preco_upsell")!==void 0){const fe=p.getVal(ve.id,"preco_upsell");me.preco_upsell=fe===""?null:Number(fe)}return p.getVal(ve.id,"ativo")!==void 0&&(me.ativo=p.getVal(ve.id,"ativo")),me},W=async()=>{N(!0);try{const ve=o.documentId||s?.documentId,me={upsell_limite_extra:Number(c)||0,upsell_progressivo_continua:x};if(p.hasEdits||ee){const le=i.map(U=>un($(U))),_e=f.map(U=>un(U));me.lotes=[...le,..._e]}const fe=await Fa(ve,me);p.clearEdits(),I([]),P({title:"Configuração de pós-venda salva"}),t?.(fe)}catch{P({title:"Erro ao salvar pós-venda",variant:"destructive"})}finally{N(!1)}},ie=ve=>{const me=G.find(_e=>_e.key===ve),fe=i.reduce((_e,U)=>Math.max(_e,Number(U.ordem)||0),0),le={id:`new-${Date.now()}`,_dateKey:ve,_isNew:!0,nome:"",tipo_ingresso:l[0]?.documentId||"",preco_lote:null,preco_upsell:null,quantidade_disponivel:0,ativo:!0,manual_ativo:!1,auto_por_data_evento:!1,ordem:fe+1,data_evento:me?.dateValue||null,is_upsell:!0};I(_e=>[..._e,le]),L(null),C(_e=>{const U=new Set(_e);return U.add(ve),U})},ke=()=>{const ve=i.reduce((fe,le)=>Math.max(fe,Number(le.ordem)||0),0),me=G.map((fe,le)=>({id:`new-${Date.now()}-${le}`,_dateKey:fe.key,_isNew:!0,nome:"",tipo_ingresso:l[0]?.documentId||"",preco_lote:null,preco_upsell:null,quantidade_disponivel:0,ativo:!0,manual_ativo:!1,auto_por_data_evento:!1,ordem:ve+1+le,data_evento:fe.dateValue||null,is_upsell:!0}));I(fe=>[...fe,...me]),L(null),C(new Set(G.map(fe=>fe.key)))},Ae=(ve,me,fe)=>{I(le=>le.map(_e=>_e.id===ve?{..._e,[me]:fe}:_e))},be=ve=>{I(me=>me.filter(fe=>fe.id!==ve))},Fe=async()=>
2{if(A.nome.trim()){N(!0);try{const ve=await $e.post("/tipo-ingressos",{data:{...A,ativo:!0,ordem:a.length}}),fe=(ve?.data?.data||ve?.data)?.documentId;let le;if(fe){const _e=o.documentId||s?.documentId,U=(Array.isArray(o.tipos_ingresso)?o.tipos_ingresso:[]).map(J=>Zr(J));U.push({tipo_ingresso:fe,preco_especifico:null,quantidade_disponivel:0,ativo:!0}),le=await Fa(_e,{tipos_ingresso:U}),D&&Ae(D,"tipo_ingresso",fe)}S({nome:"",desconto_percentual:0,progressivo:!1,quantidade_itens:1,requer_cpf:!0}),z(!1),E(null),P({title:`"${A.nome}" criado e vinculado`}),n?.(),t?.(le)}catch{P({title:"Erro ao criar tipo de ingresso",variant:"destructive"})}finally{N(!1)}}},ae=(ve=null)=>{E(ve),S({nome:"",desconto_percentual:0,progressivo:!1,quantidade_itens:1,requer_cpf:!0}),z(!0)},K=Array.from(y.entries()),O=K.filter(([,ve])=>ve.lotes.length>0),oe=K;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{}),re&&e.jsxs(w,{size:"sm",className:"h-8 gap-1.5 text-xs bg-amber-600 hover:bg-amber-700 text-white shadow-sm",onClick:W,disabled:g,children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),g?"Salvando...":"Salvar alteracoes"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"flex-1 flex items-center gap-3 px-3 py-2.5 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-semibold tracking-wide",children:"Limite extra"}),e.jsx("div",{className:"text-[10px] text-muted-foreground leading-tight mt-0.5",children:"Qtd alem do estoque"})]}),e.jsx(Te,{type:"number",min:0,className:"w-14 h-7 text-sm text-center tabular-nums font-semibold p-0 border-amber-300/60 focus-visible:ring-amber-400/40",value:c,onChange:ve=>m(Number(ve.target.value)||0)})]}),e.jsxs("div",{className:"flex-1 flex items-center gap-3 px-3 py-2.5 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-semibold tracking-wide",children:"Progressivo"}),e.jsx("div",{className:"text-[10px] text-muted-foreground leading-tight mt-0.5",children:x?"Continua do pedido anterior":"Recomeca do 1o lote"})]}),e.jsx(Ls,{checked:x,onCheckedChange:h,className:"data-[state=checked]:bg-amber-600"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between px-1 pb-1",children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-widest text-muted-foreground",children:"Lotes de pós-venda"}),l.length>0&&e.jsxs("div",{className:"relative",children:[e.jsxs(w,{variant:"outline",size:"sm",className:"h-6 gap-1 text-[10px] px-2 border-amber-300/60 text-amber-700 dark:text-amber-400 hover:bg-amber-50 dark:hover:bg-amber-950/30",onClick:()=>L(q?null:"__pick"),children:[e.jsx(et,{className:"h-3 w-3"}),"Novo lote"]}),q==="__pick"&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-10 bg-popover border rounded-md shadow-lg py-1 min-w-[180px]",children:[G.length>1&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-amber-50 dark:hover:bg-amber-950/30 transition-colors font-medium text-amber-700 dark:text-amber-400 flex items-center gap-1.5",onClick:()=>ke(),children:[e.jsx(Ia,{className:"h-3 w-3"}),"Todas as datas"]}),e.jsx("div",{className:"border-t my-1"})]}),oe.map(([ve,me])=>e.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-muted/50 transition-colors capitalize truncate",onClick:()=>ie(ve),children:me.label},ve))]})]})]}),O.length>0?e.jsx("div",{className:"rounded-lg border overflow-hidden divide-y divide-border/50",children:O.map(([ve,me])=>{const fe=b.has(ve),le=[...me.lotes].sort((U,J)=>{if(U._isNew&&!J._isNew)return 1;if(!U._isNew&&J._isNew)return-1;const T=U.preco_upsell??U.preco_lote??0,Ee=J.preco_upsell??J.preco_lote??0;return Number(T)-Number(Ee)}),_e=le.filter(U=>{if(U._isNew)return!0;const J=p.getVal(U.id,"preco_upsell"),T=U.preco_upsell;return J!==void 0&&J!==""||J===void 0&&T!=null}).length;return e.jsxs(ki,{open:fe,onOpenChange:()=>te(ve),children:[e.jsx(Si,{asChild:!0,children:e.jsxs("button",{type:"button",className:ls("w-full flex items-center gap-2.5 px-3.5 py-2.5 text-left transition-colors","hover:bg-muted/40",fe&&"bg-muted/20"),children:[e.jsx(ra,{className:ls("h-3.5 w-3.5 text-muted-foreground transition-transform duration-200 shrink-0",fe&&"rotate-180")}
2),e.jsx("span",{className:"text-xs font-semibold capitalize flex-1 truncate",children:me.label}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[_e>0&&e.jsx(je,{className:"text-[9px] px-1.5 py-0 h-4 bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-300 border-0",children:_e}),e.jsx(je,{variant:"secondary",className:"text-[9px] px-1.5 py-0 h-4 tabular-nums",children:le.length})]})]})}),e.jsxs(Ii,{children:[e.jsx("div",{className:"hidden sm:block border-t border-border/30",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70",children:[e.jsx("th",{className:"text-left font-medium px-3.5 py-1.5",children:"Lote"}),e.jsx("th",{className:"text-left font-medium px-3 py-1.5",children:"Tipo"}),e.jsx("th",{className:"text-right font-medium px-3 py-1.5",children:"Normal"}),e.jsx("th",{className:"text-right font-medium px-3 py-1.5",children:"Pós-venda"}),e.jsx("th",{className:"text-center font-medium px-3 py-1.5 w-[60px]",children:"Ativo"}),e.jsx("th",{className:"w-[30px]"})]})}),e.jsx("tbody",{className:"divide-y divide-border/20",children:le.map(U=>{if(U._isNew)return e.jsxs("tr",{className:"bg-amber-50/60 dark:bg-amber-950/20",children:[e.jsx("td",{className:"px-3.5 py-2",children:e.jsx(Te,{placeholder:"Nome do lote",className:"h-7 text-xs px-2 max-w-[150px]",value:U.nome,onChange:Me=>Ae(U.id,"nome",Me.target.value)})}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(rs,{value:String(U.tipo_ingresso),onValueChange:Me=>Ae(U.id,"tipo_ingresso",Me),children:[e.jsx(ns,{className:"h-7 text-xs w-full max-w-[130px]",children:e.jsx(is,{})}),e.jsx(os,{children:l.map(Me=>e.jsx(xe,{value:Me.documentId,children:Me.nome},Me.documentId))})]}),e.jsx("button",{type:"button",onClick:()=>ae(U.id),className:"p-1 rounded border border-dashed border-amber-300/70 text-amber-600 hover:bg-amber-100 dark:hover:bg-amber-950/40 transition-colors shrink-0",title:"Criar novo tipo de ingresso",children:e.jsx(et,{className:"h-3 w-3"})})]})}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"0,00",className:"h-7 text-xs text-right tabular-nums px-2 max-w-[100px]",value:U.preco_lote??"",onChange:Me=>Ae(U.id,"preco_lote",Me.target.value===""?null:Number(Me.target.value))})}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"mesmo",className:"h-7 text-xs text-right tabular-nums px-2 max-w-[100px] border-amber-300 font-semibold text-amber-800 dark:text-amber-300",value:U.preco_upsell??"",onChange:Me=>Ae(U.id,"preco_upsell",Me.target.value===""?null:Number(Me.target.value))})}),e.jsx("td",{className:"px-3 py-2 text-center",children:e.jsx(Ls,{checked:U.ativo!==!1,onCheckedChange:Me=>Ae(U.id,"ativo",Me),className:"scale-75 origin-center"})}),e.jsx("td",{className:"px-1 py-2",children:e.jsx("button",{type:"button",onClick:()=>be(U.id),className:"p-1 rounded hover:bg-destructive/10 text-muted-foreground/50 hover:text-destructive transition-colors",children:e.jsx(yt,{className:"h-3.5 w-3.5"})})})]},U.id);const J=U.tipo_ingresso||{},T=J.progressivo===!0,Ee=T?Math.max(1,Number(J.quantidade_itens||1)):null,Se=p.getVal(U.id,"preco_upsell"),Ze=Se??(U.preco_upsell!=null?String(U.preco_upsell):""),qe=p.getVal(U.id,"ativo")??U.ativo!==!1,Qe=Se!==void 0||p.getVal(U.id,"ativo")!==void 0,we=Ze!=="";return e.jsxs("tr",{className:ls("transition-colors group/row",!qe&&"opacity-40",Qe&&"bg-amber-50/50 dark:bg-amber-950/15"),children:[e.jsx("td",{className:"px-3.5 py-2 font-medium",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:ls("w-1 h-4 rounded-full shrink-0",we?"bg-amber-500":"bg-border")}),e.jsx("span",{className:"truncate",children:U.nome||"—"}),T&&e.jsxs(je,{variant:"outline",className:"text-[8px] px-1 py-0 h-3.5 border-violet-300/60 text-violet-500 font-mono shrink-0",children:[Ee,"x"]})]})}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground truncate",children:J.nome||J.titulo||"—"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-muted-foreground
2/70 line-through decoration-muted-foreground/30",children:Pr(U.preco_lote)}),e.jsx("td",{className:"px-3.5 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"mesmo preco",className:ls("h-7 text-xs text-right tabular-nums px-2 max-w-[130px]","placeholder:text-muted-foreground/40 placeholder:text-[10px]",Se!==void 0?"ring-1 ring-amber-400/70 border-amber-300":"border-border/50",we&&"font-semibold text-amber-800 dark:text-amber-300"),value:Ze,onChange:Me=>p.setVal(U.id,"preco_upsell",Me.target.value)}),we&&e.jsx("button",{type:"button",onClick:()=>p.setVal(U.id,"preco_upsell",""),className:"p-0.5 rounded hover:bg-destructive/10 text-muted-foreground/50 hover:text-destructive transition-colors opacity-0 group-hover/row:opacity-100",title:"Limpar preço de pós-venda",children:e.jsx(yt,{className:"h-3 w-3"})})]})}),e.jsx("td",{className:"px-3 py-1.5 text-center",children:e.jsx(Ls,{checked:qe,onCheckedChange:Me=>p.setVal(U.id,"ativo",Me),className:"scale-75 origin-center"})}),e.jsx("td",{})]},U.id)})})]})}),e.jsx("div",{className:"sm:hidden border-t border-border/30 px-3 py-2 space-y-2",children:le.map(U=>{if(U._isNew)return e.jsxs("div",{className:"rounded-lg border border-amber-300/70 bg-amber-50/40 dark:bg-amber-950/15 px-3 py-2.5 text-xs space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[9px] uppercase tracking-wide text-amber-700 font-semibold",children:"Novo lote"}),e.jsx("button",{type:"button",onClick:()=>be(U.id),className:"p-0.5 rounded hover:bg-destructive/10 text-muted-foreground/50 hover:text-destructive",children:e.jsx(yt,{className:"h-3 w-3"})})]}),e.jsx(Te,{placeholder:"Nome",className:"h-7 text-xs",value:U.nome,onChange:Me=>Ae(U.id,"nome",Me.target.value)}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(rs,{value:String(U.tipo_ingresso),onValueChange:Me=>Ae(U.id,"tipo_ingresso",Me),children:[e.jsx(ns,{className:"h-7 text-xs flex-1",children:e.jsx(is,{})}),e.jsx(os,{children:l.map(Me=>e.jsx(xe,{value:Me.documentId,children:Me.nome},Me.documentId))})]}),e.jsx("button",{type:"button",onClick:()=>ae(U.id),className:"p-1.5 rounded border border-dashed border-amber-300/70 text-amber-600 hover:bg-amber-100 dark:hover:bg-amber-950/40 transition-colors shrink-0",title:"Criar novo tipo",children:e.jsx(et,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Preco"}),e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"0,00",className:"h-6 text-[11px] text-right px-1.5",value:U.preco_lote??"",onChange:Me=>Ae(U.id,"preco_lote",Me.target.value===""?null:Number(Me.target.value))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase text-muted-foreground/60 font-medium mb-0.5",children:"Pós-venda"}),e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"mesmo",className:"h-6 text-[11px] text-right px-1.5 border-amber-300 font-semibold text-amber-800 dark:text-amber-300",value:U.preco_upsell??"",onChange:Me=>Ae(U.id,"preco_upsell",Me.target.value===""?null:Number(Me.target.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"Ativo"}),e.jsx(Ls,{checked:U.ativo!==!1,onCheckedChange:Me=>Ae(U.id,"ativo",Me),className:"scale-75 origin-center"})]})]},U.id);const J=U.tipo_ingresso||{},T=J.progressivo===!0,Ee=T?Math.max(1,Number(J.quantidade_itens||1)):null,Se=p.getVal(U.id,"preco_upsell"),Ze=Se??(U.preco_upsell!=null?String(U.preco_upsell):""),qe=p.getVal(U.id,"ativo")??U.ativo!==!1,Qe=Se!==void 0||p.getVal(U.id,"ativo")!==void 0,we=Ze!=="";return e.jsxs("div",{className:ls("rounded-lg border px-3 py-2.5 text-xs",!qe&&"opacity-40",Qe?"border-amber-300/70 bg-amber-50/40 dark:bg-amber-950/15":"bg-muted/10"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("div",{className:ls("w-1 h-4 rounded-full shrink-0",we?"bg-amber-500":"bg-border")}),e.jsx("span",{className:"font-semibold truncate",children:U.nome||"—"}),T&&e.jsxs(je,{variant:"outline",className:"text-[8px] px-1 py-0 h-3.5 border-violet-300/60 text-violet-500 font-mono shrink-0",children:[Ee,"x"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:J.nome||"—"}),e.jsx(Ls,{checked:qe,onCheckedChange:Me=>p.setVal(U.id,"ativo",Me),className:"scale-[0.6] origin-center"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wide text-muted-foreground
2/60 font-medium",children:"Normal"}),e.jsx("div",{className:"tabular-nums text-muted-foreground/70 line-through decoration-muted-foreground/30 text-[11px]",children:Pr(U.preco_lote)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wide text-muted-foreground/60 font-medium",children:"Pós-venda"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Te,{type:"number",min:0,step:"0.01",placeholder:"mesmo",className:ls("h-6 text-[11px] text-right tabular-nums px-1.5 flex-1","placeholder:text-muted-foreground/40",Se!==void 0?"ring-1 ring-amber-400/70 border-amber-300":"border-border/50",we&&"font-semibold text-amber-800 dark:text-amber-300"),value:Ze,onChange:Me=>p.setVal(U.id,"preco_upsell",Me.target.value)}),we&&e.jsx("button",{type:"button",onClick:()=>p.setVal(U.id,"preco_upsell",""),className:"p-0.5 rounded hover:bg-destructive/10 text-muted-foreground/50 hover:text-destructive transition-colors",children:e.jsx(yt,{className:"h-3 w-3"})})]})]})]})]},U.id)})})]})]},ve)})}):e.jsxs("div",{className:"flex items-center gap-2 py-3 px-1 text-xs text-muted-foreground",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"}),'Nenhum lote cadastrado. Use "Novo lote" para criar.']}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 px-1 italic",children:"Vazio = mesmo preco do lote normal. Toggle ativo controla se o lote aparece para pós-venda."})]}),re&&e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2.5 rounded-lg border bg-amber-50/80 dark:bg-amber-950/20 backdrop-blur-sm",children:[e.jsxs("span",{className:"text-[11px] text-amber-700 dark:text-amber-400 font-medium",children:[ee?`${f.length} novo${f.length>1?"s":""} lote${f.length>1?"s":""} · `:"","Alteracoes nao salvas"]}),e.jsxs(w,{size:"sm",className:"h-7 gap-1.5 text-xs bg-amber-600 hover:bg-amber-700 text-white",onClick:W,disabled:g,children:[e.jsx(Da,{className:"h-3 w-3"}),g?"Salvando...":"Salvar"]})]}),e.jsx(at,{open:M,onOpenChange:z,children:e.jsxs(rt,{className:"sm:max-w-md",children:[e.jsx(nt,{children:e.jsx(it,{className:"text-base",children:"Criar tipo de ingresso"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"Nome *"}),e.jsx(Te,{placeholder:"Ex: Meia, VIP, Camarote",value:A.nome,onChange:ve=>S(me=>({...me,nome:ve.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"Desconto %"}),e.jsx(Te,{type:"number",min:0,max:100,value:A.desconto_percentual,onChange:ve=>S(me=>({...me,desconto_percentual:Number(ve.target.value)||0}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"Qtd itens"}),e.jsx(Te,{type:"number",min:1,value:A.quantidade_itens,onChange:ve=>S(me=>({...me,quantidade_itens:Math.max(1,Number(ve.target.value)||1)}))})]})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Ls,{checked:A.progressivo,onCheckedChange:ve=>S(me=>({...me,progressivo:ve}))}),"Progressivo"]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Ls,{checked:A.requer_cpf,onCheckedChange:ve=>S(me=>({...me,requer_cpf:ve}))}),"Requer CPF"]})]})]}),e.jsxs(Ut,{children:[e.jsx(w,{variant:"outline",onClick:()=>z(!1),children:"Cancelar"}),e.jsxs(w,{onClick:Fe,disabled:g||!A.nome.trim(),children:[e.jsx(et,{className:"h-4 w-4 mr-1.5"}),g?"Criando...":"Criar e vincular"]})]})]})})]})}const yp=[{value:"lotes",label:"Lotes",icon:Ia,accent:"text-blue-400",activeBg:"bg-blue-500/10",activeBorder:"border-blue-500",glow:"shadow-[0_2px_8px_-2px_hsl(217,90%,60%,0.4)]"},{value:"tipos",label:"Tipos",icon:Ea,accent:"text-teal-400",activeBg:"bg-teal-500/10",activeBorder:"border-teal-500",glow:"shadow-[0_2px_8px_-2px_hsl(170,70%,50%,0.4)]"},{value:"upsell",label:"Pós-venda",icon:Nn,accent:"text-amber-400",activeBg:"bg-amber-500/10",activeBorder:"border-amber-500",glow:"shadow-[0_2px_8px_-2px_hsl(44,100%,50%,0.4)]"}];function wp({evento:s,onSaved:t}){const{data:a,refetch:n}=Ks(["all-tipo-ingressos"],"/tipo-ingressos?sort=ordem:asc&pagination[pageSize]=100"),o=a?.data||[],i=s?.attributes||s||{},u=Array.isArray(i.lotes)?i.lotes.length:0,l=Array.isArray(i.tipos_ingresso)?i.tipos_ingresso.length:0,c=r.useMemo(()=>({lotes:u,tipos:l,upsell:u>0&&Array.isArray(i.lotes)?i.lotes.filter(x=>x.preco_upsell!=null).length:0}),[u,l,i.lotes]),m=r.useMemo(()=>{const x=Array.isArray(i.datas_futuras)?i.datas_futuras:[];let h=0,p=0;for(const I of x)h+=Number(I.ingressos_disponiveis||0),p+=Number(I.limite_ingressos||0);const f=Math.max(0,p-h);return{totalDisp:h,totalLimite:p,sold:f}},[i.datas_futuras]);return e.jsx(he,{className:"overflow-hidden border-border/60",children:e.jsxs(Lr,{defaultValue:"lotes",children:[e.jsxs("div",{className:"relative px-5 pt-5 pb-0",children:[e.jsx("div",{className:"absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/30 to-transparent"}),e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"flex items-center justify-center w-8 h-8 rounded-lg bg-primary/10 ring-1 ring-primary/20",children:e.jsx(Ea,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-sm font-bold tracking-tight",children:"Ingressos"}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-none mt-0.5",children:"Lotes, tipos e configuração de pós-venda"})]}),m.totalLimite>0&&e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Oo,{className:ls("h-3.5 w-3.5",m.totalDisp===0?"text-rose-500":m.totalDisp<=10?"text-amber-500":"text-emerald-500")}),e.jsx("span",{className:ls("text-sm font-bold tabular-nums",m.totalDisp===0?"text-rose-600":m.totalDisp<=10?"text-amber-600":"text-foreground"),children:m.totalDisp.toLocaleStr
2ing("pt-BR")}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["/ ",m.totalLimite.toLocaleString("pt-BR")]})]}),e.jsx("p",{className:ls("text-[10px] tabular-nums mt-0.5",m.totalDisp===0?"text-rose-500":"text-muted-foreground"),children:m.sold>0?`${m.sold.toLocaleString("pt-BR")} vendidos`:"Nenhum vendido"})]})})]}),e.jsx(Mr,{className:"w-full justify-start h-auto bg-transparent p-0 gap-1 rounded-none",children:yp.map(x=>{const h=x.icon,p=c[x.value]||0;return e.jsxs(Gt,{value:x.value,className:ls("group relative rounded-t-lg rounded-b-none px-4 py-2.5","border border-transparent border-b-0","text-xs font-medium tracking-wide","text-muted-foreground/70 hover:text-foreground/90","transition-all duration-200","data-[state=active]:bg-muted/30 data-[state=active]:text-foreground","data-[state=active]:border-border/50","data-[state=active]:shadow-none","focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"),children:[e.jsx("span",{className:ls("absolute inset-x-2 -bottom-px h-0.5 rounded-full","opacity-0 transition-all duration-300","group-data-[state=active]:opacity-100",x.activeBorder.replace("border-","bg-"))}),e.jsx(h,{className:ls("h-3.5 w-3.5 mr-1.5 transition-colors duration-200","text-muted-foreground/50 group-hover:text-muted-foreground",`group-data-[state=active]:${x.accent}`)}),e.jsx("span",{children:x.label}),p>0&&e.jsx(je,{variant:"secondary",className:ls("ml-1.5 h-4 min-w-4 px-1 text-[9px] font-bold tabular-nums","bg-muted/60 text-muted-foreground/70 border-0","group-data-[state=active]:bg-foreground
2/10 group-data-[state=active]:text-foreground/80"),children:p})]},x.value)})})]}),e.jsx("div",{className:"h-px bg-border/60"}),e.jsxs(ge,{className:"p-5",children:[e.jsx(Ht,{value:"lotes",className:"mt-0 focus-visible:outline-none focus-visible:ring-0",children:e.jsx(gp,{evento:s,onSaved:t,allTipos:o,refetchTipos:n})}),e.jsx(Ht,{value:"tipos",className:"mt-0 focus-visible:outline-none focus-visible:ring-0",children:e.jsx(hp,{evento:s,onSaved:t,allTipos:o,refetchTipos:n})}),e.jsx(Ht,{value:"upsell",className:"mt-0 focus-visible:outline-none focus-visible:ring-0",children:e.jsx(Np,{evento:s,onSaved:t,allTipos:o,refetchTipos:n})})]})]})})}function cr({label:s,value:t,highlight:a=!1,small:n=!1}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-medium",children:s}),e.jsx("div",{className:ls("tabular-nums font-semibold",n?"text-xs":"text-sm",a&&"text-emerald-700 dark:text-emerald-400"),children:t})]})}function No({title:s,icon:t,rows:a,accentClass:n,emptyText:o,getOrdersDateLink:i,getPeopleDateLink:u,creditKey:l="credito",defaultOpen:c=!1}){const[m,x]=r.useState(c);return e.jsxs(ki,{open:m,onOpenChange:x,children:[e.jsx(Si,{asChild:!0,children:e.jsxs("button",{type:"button",className:"w-full flex items-center gap-2.5 px-4 py-3 hover:bg-muted/40 transition-colors text-left",children:[e.jsx(t,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm font-semibold flex-1",children:s}),e.jsx(je,{variant:"secondary",className:"text-xs tabular-nums mr-1",children:a.length}),e.jsx(ra,{className:ls("h-4 w-4 text-muted-foreground transition-transform duration-200 shrink-0",m&&"rotate-180")})]})}),e.jsx(Ii,{children:a.length===0?e.jsx("p",{className:"px-4 pb-4 text-sm text-muted-foreground",children:o}):e.jsx("div",{className:"divide-y divide-border/50",children:a.map(h=>{const p=h.date&&u?u(h.date):null,f=Number(h.convites||0)||0;return e.jsxs("div",{className:ls("border-l-2 px-4 py-3",n),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold truncate",children:h.date?cn(h.date):h.label}),h.note&&e.jsx("div",{className:"text-xs text-muted-foreground truncate mt-0.5",children:h.note})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2",children:[p?e.jsx(w,{asChild:!0,variant:"outline",size:"sm",className:"h-7 gap-1.5 text-xs",children:e.jsxs(lt,{to:p,children:[e.jsx(sr,{className:"h-3.5 w-3.5"}),"Ver pessoas desta data"]})}):null,e.jsx(w,{asChild:!0,variant:"outline",size:"sm",className:"h-7 text-xs",children:e.jsx(lt,{to:i(h.date),children:"Ver pedidos"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 sm:grid-cols-4",children:[e.jsx(cr,{label:"Pedidos",value:_a(h.pedidos)}),e.jsxs("div",{className:"flex flex-row gap-4",children:[e.jsx(cr,{label:"Ingressos",value:_a(h.ingressos)}),e.jsx(cr,{label:"Convites",value:_a(f)})]}),e.jsx(cr,{label:"Receita",value:Pr(h.receita),highlight:Number(h.receita)>0}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(cr,{label:"PIX",value:ci(h.paymentPercents?.pix),small:!0}),e.jsx(cr,{label:"Créd.",value:ci(h.paymentPercents?.[l]),small:!0})]})]})]},h.date||h.label)})})})]})}cr.propTypes={label:se.string.isRequired,value:se.oneOfType([se.string,se.number]).isRequired,highlight:se.bool,small:se.bool};No.propTypes={title:se.string.isRequired,icon:se.elementType.isRequired,rows:se.arrayOf(se.shape({date:se.string,label:se.string,note:se.string,pedidos:se.oneOfType([se.string,se.number]),ingressos:se.oneOfType([se.string,se.number]),convites:se.oneOfType([se.string,se.number]),receita:se.oneOfType([se.string,se.number]),paymentPercents:se.object})).isRequired,accentClass:se.string,emptyText:se.string,getOrdersDateLink:se.func.isRequired,getPeopleDateLink:se.func,creditKey:se.string,defaultOpen:se.bool};function _p({eventoId:s}){const{data:t}=Ks(["event-cupons-count",s],s?`/cupom-descontos?filters[evento][id][$eq]=${s}&filters[active][$eq]=true&pagination[pageSize]=1`:null,{enabled:!!s}),a=t?.meta?.pagination?.total??"—";return e.jsx(he,{children:e.jsxs(ge,{className:"p-4",children:[e.jsxs("div",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Cupons ativos"]}),e.jsx("div",{className:"text-xl font-semibold",children:a}),e.jsx("div",{className:"text-xs text-muted-foreground",children:e.jsx(lt,{to:"/dashboard/cupons",className:"underline hover:text-foreground",children:"Gerenciar cupons"})})]})})}function Cp({eventoId:s}){const{data:t,isLoading:a}=Ks(["event-cupons-list",s],`/cupom-descontos?filters[evento][id][$eq]=${s}&sort=createdAt:desc&pagination[pageSize]=50`,{enabled:!!s}),n=t?.data||[];return a||n.length===0?null:e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ze,{className:"text-base flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"})," Cupons de Desconto"]}),e.jsx(lt,{to:"/dashboard/cupons",children:e.jsx(w,{variant:"outline",size:"sm",children:"Ver todos"})})]})}),e.jsx(ge,{children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Código"}),e.jsx(ue,{children:"Desconto"}),e.jsx(ue,{children:"Usos"}),e.jsx(ue,{children:"Status"})]})}),e.jsx(Ct,{children:n.map(o=>{const i=o.active!==!1,u=o.max_uses!=null&&(o.used_count||0)>=o.max_uses;return e.jsxs($s,{children:[e.jsx(ye,{children:e.jsx("code",{className:"font-mono text-sm font-bold",children:o.codigo})}),e.jsx(ye,{className:"text-sm",children:o.tipo_desconto==="percentual"?`${o.valor_desconto}%`:Pr(o.valor_desconto)}),e.jsxs(ye,{className:"text-sm",children:[o.used_count||0,o.max_uses!=null?` / ${o.max_uses}`:""]}),e.jsx(ye,{children:e.jsx(je,{variant:i?u?"destructive":"default":"secondary",className:i&&!u?"bg-green-600 hover:bg-green-700":"",children:i?u?"Esgotado":"Ativo":"Inativo"})})]},o.id)})})]})})]})}const kp=!1,Sp=!0;function Ip(){const{documentId:s}=_i(),[t,a]=r.useState(!1),{formatPrice:n,convertFromBRL:o}=jn(),{user:i}=Zt(),{toast:u}=mt(),l=kp,c=Sp,m=na(),{data:x,isLoading:h,isError:p,refetch:f}=Ks(["dashboard-event",s],s?`/eventos/${s}/dashboard`:null,{retry:1,enabled:!!s}),I=x?.data??x??null,g=I?.id,{data:N}
2=Ks(["event-invites-count",g],g?`/link-convites?filters[evento][id][$eq]=${g}&pagination[pageSize]=1`:null,{enabled:!!g&&l});N?.meta?.pagination?.total;const b=xs=>{if(xs&&s){m.setQueryData(["dashboard-event",s],k=>({...k||{},data:xs}));return}f?.()},{data:C,isLoading:q}=bc(g,{period:"all",enabled:c}),{data:L,isLoading:M}=Rt({queryKey:["planejamentos",g],queryFn:()=>Nc(g),enabled:!!g&&c,staleTime:30*1e3});if(h)return null;if(p||!I)return e.jsx(Ga,{to:"/dashboard/eventos",replace:!0});const z=I.attributes||I||{},D=String(z?.moeda||"BRL").toUpperCase(),E=D==="USD"&&z?.usar_gateway_pagarme_usd===!0,A=xs=>{const k=Number(xs||0);return E?o(k,D):k},S=xs=>n(A(xs),D),P=Number(z.preco||0),F=S(P),ee=n(P,"BRL"),re=(i?.role?.name||i?.role?.type||i?.role?.code||"").toLowerCase(),te=re.includes("superadmin"),G=re.includes("supersuporte")&&!te,y=re.includes("admin")||te||G,$=y||te||G,W=dn(Bt(z)),ie=dc(Bt(z)),ke=qt(z?.imagem?.data?.attributes?.url||z?.imagem?.url||z?.imagem),Ae=Dr(z),be=li(z),Fe=!!(z?.usarLayoutCustomizado||z?.usar_layout_customizado);let ae=[];Array.isArray(z.layoutCustomizado)?ae=z.layoutCustomizado:Array.isArray(z.layout_customizado)&&(ae=z.layout_customizado);const K=pl(ae,Tm),O=pl(ae,$m),oe=!!(K&&O),ve=Rm(ae),me=z?.documentId||z?.document_id||g,fe=ve==="booking",le=[fe?"ON: Checkout ativo":"OFF: Formulario ativo",Fe?null:"Layout customizado sera ativado ao salvar."].filter(Boolean).join(" - "),_e=C?.kpis||{},U=C?.charts?.byTipoIngresso||[],J=C?.breakdowns?.byPayment||{},T=C?.breakdowns?.paymentPercents||{},Ee=C?.dates||{},Se=Ee?.future||[],Ze=Ee?.past||[],qe=xs=>{const k=new URLSearchParams;return z?.documentId&&k.set("event",z.documentId),xs&&k.set("eventDate",xs),`/dashboard/pedidos?${k.toString()}`},Qe=xs=>{const k=Et(xs);return!z?.documentId||!k?null:`/dashboard/eventos/${encodeURIComponent(z.documentId)}/data/${encodeURIComponent(k)}`},we=async xs=>{if(!(!me||!$||!xs)&&xs!==ve)try{a(!0),await $e.put(`/eventos/${encodeURIComponent(me)}/section-mode`,{data:{mode:xs}}),await f?.(),u({title:"Secao principal atualizada",description:xs==="booking"?"Booking Section habilitado e Formulario Palestra desabilitado.":"Formulario Palestra habilitado e Booking Section desabilitado."})}catch(k){u({title:"Falha ao atualizar secao",description:k?.response?.data?.error?.message||"Nao foi possivel salvar a configuracao do evento.",variant:"destructive"})}finally{a(!1)}},Me=async xs=>{await we(xs?"booking":"palestra")},ks=async()=>{try{const xs=await $e.get(`/eventos/${encodeURIComponent(z.documentId)}/participantes/export`,{responseType:"blob"}),k=new Blob([xs.data],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),De=URL.createObjectURL(k),Ne=document.createElement("a");Ne.href=De,Ne.download=`participantes-${z.documentId}.xlsx`,Ne.click(),URL.revokeObjectURL(De)}catch(xs){u({variant:"destructive",title:"Erro ao exportar",description:String(xs?.message||xs)})}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground",children:["Evento: ",z.titulo]}),e.jsx("p",{className:"text-muted-foreground",children:"Gerencie informacoes e metricas deste evento"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(w,{variant:"outline",asChild:!0,children:e.jsx(lt,{to:"/dashboard/eventos",children:"Voltar"})}),z.documentId?e.jsxs(e.Fragment,{children:[e.jsx(w,{variant:"outline",asChild:!0,children:e.jsx(lt,{to:`/dashboard/pedidos?event=${encodeURIComponent(z.documentId)}`,children:"Ver pedidos"})}),e.jsx(w,{variant:"outline",onClick:ks,children:"Exportar Excel"})]}):e.jsx(w,{variant:"outline",disabled:!0,children:"Ver pedidos"})]})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-base",children:"Informacoes Gerais"})}),e.jsxs(ge,{children:[$&&oe&&e.jsxs("div",{className:"mb-4 p-3 rounded-md border bg-muted/30",children:[e.jsx("div",{className:"text-sm font-medium mb-2",children:"Exibicao principal do evento"}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Vendas"}),e.jsx(Ls,{checked:fe,onCheckedChange:Me,disabled:t})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:le})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 items-center",children:[ke&&e.jsx("img",{src:ke,alt:z.titulo,className:"w-full max-w-sm rounded-md"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Data"}),e.jsx("div",{className:"font-medium",children:W?Us(W,"dd/MM/yyyy",{locale:Vs}):"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Limite de ingressos"}),e.jsx("div",{className:"font-medium",children:be!=null?`${_a(Ae??0)} / ${_a(be)}`:_a(Ae)}),be!=null&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disponiveis / Limite"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Local"}),e.jsx("div",{className:"font-medium",children:z.local||"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Preco ingresso"}),e.jsx("div",{className:"font-medium",children:F}),E&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Base BRL: ",ee]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Ingressos disponiveis"}),e.jsx("div",{className:"font-medium",children:Ae??"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Status do evento"}),e.jsx("div",{className:"font-medium",children:e.jsx(je,{variant:ie.variant,className:ie.className,children:ie.label})})]})]})]})]})]}),y&&I&&e.jsx(wp,{evento:I,onSaved:b}),l,l,e.jsxs(he,{className:"overflow-hidden",children:[e.jsx(Be,{className:"pb-3 border-b bg-muted/20",children:e.jsx(ze,{className:"text-base",children:"Datas"})}),e.jsxs(ge,{className:"p-0 space-y-0",children:[e.jsx(No,{title:"Proximas datas",icon:Sa,rows:Se,accentClass:"border-l-emerald-500 bg-emerald-50/30 dark:bg-emerald-950/10",emptyText:"Nenhuma data futura cadastrada.",getOrdersDateLink:qe,getPeopleDateLink:Qe,creditKey:"outros",defaultOpen:!0}),e.jsx("div",{className:"border-t"}),e.jsx(No,{title:"Datas passadas",icon:Za,rows:Ze,accentClass:"border-l-slate-400/60 bg-muted/10",emptyText:"Nenhuma data passada cadastrada.",getOrdersDateLink:qe,getPeopleDateLink:Qe,creditKey:"credito"})]})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-base",children:"Metricas"})}),e.jsxs(ge,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3 text-sm",children:[e.jsx(he,{children:e.jsxs(ge,{className:"p-4",children:[e.jsx("div",{className:"text-muted-foreground",children:"Publico"}),e.jsx("div",{className:"text-xl font-semibold",children:q?"—":_e.publico??0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Ingressos vendidos (proxy)"})]})}),e.jsx(he,{children:e.jsxs(ge,{className:"p-4",children:[e.jsx("div",{className:"text-muted-foreground",children:"Ticket medio ingresso"}),e.jsx("div",{className:"text-xl font-semibold",children:q?"—":S(_e.ticketMedioIngresso||0)}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Total vendido: ",S(_e.receitaIngresso||0)]})]})}),e.jsx(he,{children:e.jsxs(ge,{className:"p-4",children:[e.jsx("div",{className:"text-muted-foreground",children:"Receita total"}),e.jsx("div",{className:"text-xl font-semibold",children:q?"—":S(_e.receitaTotal||0)})]})}),e.jsx(_p,{eventoId:I?.id})]}),e.jsx("div",{className:"mt-4 h-[260px]",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(Xa,{data:U,children:[e.jsx(Ra,{strokeDasharray:"3 3"}),e.jsx(Ta,{dataKey:"label",tick:{fontSize:12}}),e.jsx($a,{allowDecimals:!1,tick:{fontSize:12}}),e.jsx(Aa,{formatter:(xs,k,De)=>k==="Receita"?[S(De?.payload?.receita||0),"Receita"]:[_a(xs),"Unidades"]}),e.jsx(Xr,{}),e.jsx(ha,{dataKey:"unidades",fill:"#0ea5e9",name:"Unidades",radius:[4,4,0,0]})]})})})]})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-base",children:"Pagamentos"})}),e.jsx(ge,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 text-sm",children:[e.jsx(he,{children:e.jsxs(ge,{className:"p-4",children:[e.jsx("div",{className:"text-muted-foreground",children:"PIX"}),e.jsx("div",{className:"text-xl font-semibold",children:q?"—":_a(J?.pix||0)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:q?"":`Participacao: ${ci(T?.pix)}`})]})}),e.jsx(he,{children:e.jsxs(ge,{className:"p-4",children:[e.jsx("div",{className:"text-muted-foreground",children:"Credito"}),e.jsx("div",{className:"text-xl font-semibold",children:q?"—":_a(J?.outros||0)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:q?"":`Participacao: ${ci(T?.outros)}`})]})})]})})]}),y&&I&&e.jsx(pp,{evento:I,onSaved:b}),y&&I&&e.jsx(dp,{evento:I,onSaved:b,analytics:C}),y&&z?.documentId&&e.jsx(Cp,{eventoId:I?.id})]})}const yo=s=>s?.grupo_publico||s?.metadata?.grupo_publico||null,rr=s=>{if(!s)return"—";const t=s.nome||"",a=s.indice??s.index??"";return t&&a!==""?`${t} (#${a})`:t||(a===""?"Grupo":`Grupo #${a}`)},hn=s=>s?.manualOverride===!0,hi=s=>{const t=Array.isArray(s)?s:[];for(const a of t){const n=yo(a);if(n&&!hn(n))return n}for(const a of t){const n=yo(a);if(n)return n}return null},gi=(s,t)=>{const a=yo(s);return hn(a)?a:t||a},Ap=new Set(["nome","cpf_passaporte","endereco","email","telefone","data_nascimento"]),Wn=s=>s?s.attributes&&typeof s.attributes=="object"?{id:s.id,...s.attributes}:s.data?Wn(s.data):s:null,sa=(...s)=>{for(const t of s)if(t!=null&&!(typeof t=="string"&&t.trim()==="")&&!(typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0))return t;return""},Ep=s=>s?typeof s=="string"?s:[s.logradouro||s.linha1||s.line_1,s.numero||s.number,s.complemento||s.c
2omplement].filter(Boolean).join(", "):"",Dp=s=>s&&typeof s=="object"&&(s.cidade||s.municipio||s.city||s.locality)||"",Pp=s=>s&&typeof s=="object"&&(s.estado||s.uf||s.state)||"",Rp=s=>{if(!s)return"";const t=String(s).slice(0,10),a=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);return a?`${a[3]}/${a[2]}/${a[1]}`:t},Tp=s=>{const t=String(s||"").toLowerCase();return t==="credit"||t==="credito"||t==="crédito"||t==="cartao"||t==="cartão"?"Crédito":t==="debit"||t==="debito"||t==="débito"?"Débito":t==="pix"?"Pix":s||""},Ic=s=>{if(!s)return"";const t=String(s).slice(0,10),a=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);return a?`${a[3]}/${a[2]}/${a[1]}`:String(s)};function $p(s,{dateKey:t,primaryDateKey:a}={}){const n=new Map,o=[],i=Array.isArray(s)?s:[];for(const l of i){if(String(l?.status_pedido||"").toLowerCase()!=="pago")continue;const c=l?.dados_faturamento||{},m=Wn(l?.usuario)||{},h=(Array.isArray(l?.items)?l.items:[]).filter(C=>{if((C?.item_tipo||"ingresso")!=="ingresso")return!1;const q=Et(C?.metadata?.data_evento)||a;return!t||q===t});if(h.length===0)continue;const p=hi(h);let f="";for(const C of h){const L=(Array.isArray(C?.holders)?C.holders:[]).find(M=>{const z=M?.campos_editado?.nome??M?.campos?.nome;return z&&String(z).trim()});if(L){f=L.campos_editado?.nome??L.campos?.nome;break}}f||(f=sa(c?.nome,m?.nome,"Participante"));const I=[];for(const C of h){const q=gi(C,p),L=q?rr(q):"",M=uc(C),z=M.filter(S=>!Ap.has(S.tipo));z.forEach(S=>{n.has(S.chave)||n.set(S.chave,S.nome||S.chave)});const D=S=>M.find(P=>P.tipo===S),E=Array.isArray(C?.holders)?C.holders:[],A=E.length>0?E.length:Math.max(1,Number(C?.quantidade||1));for(let S=0;S<A;S+=1){const P=E[S]||{},F=P?.campos||{},ee=P?.campos_editado||{},re=y=>Object.prototype.hasOwnProperty.call(ee,y)?ee[y]:F[y],te=y=>{const $=D(y);return $?re($.chave):void 0},G=sa(te("endereco"),F.endereco,c?.endereco)||{};I.push({nome:sa(re("nome"),te("nome"),F.nome,f),cpf:sa(te("cpf_passaporte"),F.cpf,F.cpf_passaporte,P?.cpf,C?.cpf,c?.cpf,c?.passaporte),rua:Ep(G),cidade:Dp(G),estado:Pp(G),email:sa(te("email"),F.email,c?.email),telefone:sa(te("telefone"),F.telefone,c?.telefone),dob:Rp(sa(te("data_nascimento"),F.data_nascimento,c?.dataNascimento)),grupo:L,extras:Object.fromEntries(z.map(y=>[y.chave,re(y.chave)??""]))})}}const g=Wn(l?.link_convite),N=Wn(g?.created_by_usuario),b=sa(l?.referral_code,N?.nome,c?.ponto_venda?"PDV":"","-");o.push({origem:"Pedido",pessoas:I.length,people:I,bruto:Number(l?.total||0),liquido:Number(l?.subtotal??l?.resumo_totais?.subtotal??0),banco:Tp(l?.metodo_pagamento||l?.pagamento),vendedor:b,dataVen
2da:Ic(l?.data_pagamento||l?.data_pedido||l?.createdAt),necessidades:sa(l?.necessidades,l?.necessidades_especiais)})}return{extraColumns:[...n.entries()].map(([l,c])=>({chave:l,nome:c})),groups:o}}function Lp(s,{dateKey:t,primaryDateKey:a}={}){const n=[],o=Array.isArray(s)?s:[];for(const i of o){if(String(i?.status_invite||"").toLowerCase()==="cancelado")continue;const l=(Array.isArray(i?.items)?i.items:[]).filter(h=>{if((h?.item_tipo||"ingresso")!=="ingresso")return!1;const p=Et(h?.metadata?.data_evento)||Et(i?.data_evento)||a;return!t||p===t});if(l.length===0)continue;const c=hi(l),m=sa(i?.nome,"Convidado"),x=[];for(const h of l){const p=gi(h,c),f=p?rr(p):"",I=Math.max(1,Number(h?.quantidade||1));for(let g=0;g<I;g+=1)x.push({nome:m,cpf:sa(i?.cpf,h?.cpf),rua:"",cidade:"",estado:"",email:sa(i?.email),telefone:sa(i?.telefone),dob:"",grupo:f,extras:{}})}n.push({origem:"Convite",pessoas:x.length,people:x,bruto:0,liquido:0,banco:"Cortesia",vendedor:sa(i?.criado_por?.nome,"-"),dataVenda:Ic(i?.aceito_em||i?.createdAt),necessidades:sa(i?.necessidades_especiais)})}return{groups:n}}const Mp=(s,t)=>{if(!t||typeof t!="object")return s==="endereco"?{}:"";switch(s){case"nome":return t.nome||"";case"cpf_passaporte":return t.cpf||t.passaporte||"";case"email":return t.email||"";case"telefone":return t.telefone||"";case"data_nascimento":return t.dataNascimento||"";case"endereco":return t.endereco&&typeof t.endereco=="object"?t.endereco:{};default:return""}},Fp=(s,t)=>{if(s==null||s==="")return t==null||t==="";if(typeof s=="object"||typeof t=="object")try{return JSON.stringify(s)===JSON.stringify(t)}catch{return!1}return String(s)===String(t)};function wo(s,t,a){const n=uc(s),o=n.some(l=>l.tipo==="nome")?n:[{chave:"nome",tipo:"nome",nome:"Nome",obrigatorio:!1},...n],i=t?.campos||{},u=t?.campos_editado||{};return o.map(l=>{const c=i[l.chave]!==void 0&&i[l.chave]!==null&&i[l.chave]!==""?i[l.chave]:Mp(l.tipo,a),m=Object.prototype.hasOwnProperty.call(u,l.chave),x=m?u[l.chave]:c;return{chave:l.chave,tipo:l.tipo,nome:l.nome,value:x,original:c,isEdited:m&&!Fp(x,c)}})}const Op=[["logradouro","Logradouro"],["numero","Número"],["bairro","Bairro"],["cidade","Cidade"],["estado","Estado (UF)"],["cep","CEP"]],qp=(s,t)=>t==null||t===""?"—":s==="endereco"&&typeof t=="object"?[t.logradouro||t.line_1,t.numero,t.bairro,t.cidade||t.city,t.estado||t.state,t.cep].filter(Boolean).join(", ")||"—":String(t),Dl=(s,t)=>{if((s==null||s==="")&&(t==null||t===""))return!0;if(typeof s=="object"||typeof t=="object")try{return JSON.stringify(s||{})===JSON.stringify(t||{})}catch{return!1}return String(s??"")===String(t??"")};function Ac({row:s,open:t,onOpenChange:a,onSaved:n}){const{toast:o}=mt(),[i,u]=r.useState(!1),l=r.useMemo(()=>s?._raw?wo(s._raw,s.holder,s.billing):[],[s]),[c,m]=r.useState({});r.useEffect(()=>{const f={};l.forEach(I=>{f[I.chave]=I.value??(I.tipo==="endereco"?{}:"")}),m(f)},[l,t]);const x=(f,I)=>m(g=>({...g,[f]:I})),h=(f,I,g)=>m(N=>({...N,[f]:{...N[f]||{},[I]:g}})),p=async()=>{if(!s?.pedidoDocumentId||s?.itemId==null||s?.holderIndex==null){o({title:"Não é possível editar",description:"Participante sem vínculo de pedido.",variant:"destructive"});return}const f={};if(l.forEach(I=>{const g=c[I.chave];Dl(g,I.original)?I.isEdited&&(f[I.chave]=null):f[I.chave]=g}),Object.keys(f).length===0){a(!1);return}u(!0);try{await $e.put("/pedidos/holders/edit",{documentId:s.pedidoDocumentId,itemId:s.itemId,holderIndex:s.holderIndex,edits:f}),o({title:"Dados atualizados",description:"As edições aparecem na exportação."}),a(!1),n?.()}catch(I){console.error("Falha ao salvar edição do participante",I),o({title:"Falha ao salvar",description:I?.response?.data?.error?.message||I?.message||"Tente novamente.",variant:"destructive"})}finally{u(!1)}};return e.jsx(at,{open:t,onOpenChange:a,children:e.jsxs(rt,{className:"sm:max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(nt,{children:e.jsx(it,{children:"Editar participante"})}),e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum campo para editar."}):l.map(f=>{const I=c[f.chave],g=!Dl(I,f.original);return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"text-sm",children:f.nome}),g?e.jsx("span",{className:"text-[10px] font-medium text-amber-600",children:"editado"}):null]}),f.tipo==="endereco"?e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Op.map(([N,b])=>e.jsx(Te,{placeholder:b,value:I&&I[N]||"",onChange:C=>h(f.chave,N,C.target.value)},N))}):e.jsx(Te,{type:f.tipo==="data_nascimento"?"date":f.tipo==="email"?"email":"text",value:I||"",onChange:N=>x(f.chave,N.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Original: ",e.jsx("span",{className:g?"line-through":"",children:qp(f.tipo,f.original)})]})]},f.chave)})}),e.jsxs(Ut,{children:[e.jsx(w,{variant:"outline",onClick:()=>a(!1),disabled:i,children:"Cancelar"}),e.jsxs(w,{onClick:p,disabled:i,children:[i?e.jsx(Cs,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Salvar"]})]})]})})}Ac.propTypes={row:se.object,open:se.bool,onOpenChange:se.func,onSaved:se.func};const zp=s=>{const t=Number(s);return Number.isFinite(t)?t:0},Ec=s=>s?s.attributes&&typeof s.attributes=="object"?{id:s.id,...s.attributes}:s.data?Ec(s.data):s:null,Pl=(s,t)=>Array.isArray(s)&&s.filter(a=>String(a?.itemId)===String(t)).sort((a,n)=>new Date(n?.ts||0).getTime()-new Date(a?.ts||0).getTime())[0]?.ts||null,Rl=s=>{if(!s)return"Não escaneado";try{return Us(new Date(s),"dd/MM/yyyy HH:mm",{locale:Vs})}catch{return String(s)}},_o=s=>{if(!s)return null;const t=String(s).slice(0,10),a=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);return a?`${a[3]}/${a[2]}/${a[1]}`:t},Up=s=>{const t=s.value;return t==null||t===""?"—":s.tipo==="endereco"&&typeof t=="object"?[t.logradouro||t.line_1,t.numero,t.bairro,t.cidade||t.city,t.estado||t.state,t.cep].filter(
2Boolean).join(", ")||"—":s.tipo==="data_nascimento"&&_o(t)||String(t)},Tl=(s,{owner:t={},fallbackNome:a}={})=>{const o=(Array.isArray(s?.holders)?s.holders:[]).filter(i=>i&&typeof i=="object"&&(i.campos&&Object.keys(i.campos).length||i.cpf));return o.length===0?[{nome:a||t?.nome||"Usuário sem nome",cpf:s?.cpf||t?.cpf||null,dataNascimento:null,quantidade:zp(s?.quantidade||1),holderIndex:null}]:o.map((i,u)=>({nome:i?.campos?.nome||a||t?.nome||"Usuário sem nome",cpf:i?.campos?.cpf||i?.cpf||s?.cpf||t?.cpf||null,dataNascimento:i?.campos?.data_nascimento||null,criancaGratuita:i?.crianca_gratuita===!0,quantidade:1,holderIndex:u}))},rn=s=>s&&qt(s.imagem||s.image)||null,or=s=>{if(!s)return"none";if(s.documentId)return`doc:${s.documentId}`;if(s.id)return`id:${s.id}`;const t=Number(s.indice??s.index??0);return Number.isFinite(t)&&t>0?`idx:${t}`:"none"},Bp=(s,t)=>{const a=Array.isArray(t)?t:[];if(!s||s==="none")return null;if(s.startsWith("doc:")){const n=s.slice(4);return a.find(i=>i?.documentId===n)?{groupDocumentId:n}:null}if(s.startsWith("id:")){const n=Number(s.slice(3));return a.find(i=>Number(i?.id)===n)?{groupId:n}:null}if(s.startsWith("idx:")){const n=Number(s.slice(4));return a.find(i=>Number(i?.indice??i?.index??0)===n)?{groupIndice:n}:null}return null},Vp=se.shape({nome:se.string,indice:se.oneOfType([se.string,se.number]),index:se.oneOfType([se.string,se.number]),imagem:se.oneOfType([se.string,se.object]),image:se.oneOfType([se.string,se.object])}),Co=s=>{const{groupData:t}=s,a=rn(t),n=rr(t);return t?e.jsxs("div",{className:"flex items-center gap-2",children:[a?e.jsx("img",{src:a,alt:n,className:"h-10 w-full rounded object-contain bg-muted flex-shrink-0"}):null,e.jsxs("div",{className:"min-w-0 text-sm",children:[e.jsx("div",{className:"truncate",children:n}),hn(t)?e.jsx("div",{className:"text-xs text-amber-700",children:"Override manual"}):null]})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})};Co.propTypes={groupData:Vp};const $l=s=>s==="pedido"?"border-sky-200 bg-sky-50 text-sky-700":"border-emerald-200 bg-emerald-50 text-emerald-700",Ll=s=>{const t=String(s||"").toLowerCase()==="usado";return{variant:t?"destructive":"secondary",label:t?"Usado":"Disponível"}},Ml=s=>s==="pedido"?"Pedido":"Convite",Gp=(s,t)=>s==="scan"||t==="scan"||s==="scanner"||t==="scanner"||s==="qr-scanner"||t==="qr-scanner"||s.includes("scanner"),Hp=s=>{const t=new Map;for(const a of s){const n=a.grupoPublico,o=n?rr(n):"__none__";t.has(o)||t.set(o,{key:o,label:n?rr(n):"Sem grupo",imageUrl:n?rn(n):null,total:0}),t.get(o).total+=a.quantidade}return Array.from(t.values()).sort((a,n)=>n.total-a.total)},Kp=({rows:s,searchTerm:t,typeFilter:a,scanFilter:n,groupFilter:o})=>{const i=t.trim().toLowerCase();return s.filter(u=>{const l=!i||[u.nome,u.cpf,u.tipoIngresso].filter(Boolean).join(" ").toLowerCase().includes(i),c=a==="all"||u.source===a,m=String(u.status||"").toLowerCase()==="usado",x=n==="all"||(n==="escaneado"?m:!m),h=u.grupoPublico?rr(u.grupoPublico):"__none__";return l&&c&&x&&(o==="all"||h===o)})},Qp=({orderRows:s,inviteRows:t,rows:a})=>({vendidos:s.reduce((n,o)=>n+o.quantidade,0),convites:t.reduce((n,o)=>n+o.quantidade,0),usados:a.filter(n=>String(n.status||"").toLowerCase()==="usado").reduce((n,o)=>n+o.quantidade,0),restantes:a.filter(n=>String(n.status||"").toLowerCase()!=="usado").reduce((n,o)=>n+o.quantidade,0)}),Wp=({loadingEvent:s,eventError:t,attrs:a,isScanner:n,requestedDateAllowed:o,nearestScannerDate:i,dateKey:u,documentId:l})=>{if(s)return null;if(t||!a)return n?"/dashboard/atividades":"/dashboard/eventos";if(!n)return null;const c=i?.value||null;return o?null:c?`/dashboard/eventos/${encodeURIComponent(l)}/data/${encodeURIComponent(c)}`:"/dashboard/atividades"},Jp=s=>{const t=dn(s);return t?Us(t,"EEEE, dd 'de' MMMM",{locale:Vs}):Va(s)},Yp=s=>{if(s===""||s==null)return"";const t=Number(s);return Number.isFinite(t)?String(t):""},Fl=(s={})=>(Array.isArray(s.groups)?s.groups:[]).map((a,n)=>{const o=a?.indice??a?.index??n+1;return{id:a?.id||null,documentId:a?.documentId||null,indice:String(o??n+1),nome:a?.nome||`Grupo ${o??n+1}`,capacidade:Yp(a?.capacidade),ativo:a?.ativo!==!1,imagem:a?.imagem||null,usage:Number(a?.usage||0),remaining:a?.remaining??null}});function Xp(){const{documentId:s,dateKey:t}=_i(),{toast:a}=mt(),n=na(),{user:o}=Zt(),[i,u]=r.useState(""),[l,c]=r.useState("all"),[m,x]=r.useState("all"),[h,p]=r.useState("all"),[f,I]=r.useState(null),[g,N]=r.useState(!1),[b,C]=r.useState(null),[q,L]=r.useState([]),[M,z]=r.useState(!1),[D,E]=r.useState(!1),[A,S]=r.useState({}),[P,F]=r.useState(null),ee=Q=>String(Q||"").toLowerCase().replace(/[^a-z]/g,""),re=ee(o?.role?.name||o?.role?.type),te=ee(o?.role?.code);re.includes("admin")||te.includes("admin");
2const G=re.includes("superadmin")||te.includes("superadmin"),y=(re.includes("supersuporte")||te.includes("supersuporte"))&&!G,$=Gp(re,te),W=G||y,ie=Rt({queryKey:["event-date-detail","public-groups",s],enabled:!!s&&W,queryFn:async()=>{const Q=new URLSearchParams({eventoDocumentId:s}),X=await $e.get(`/pedidos/grupos-publicos/summary?${Q.toString()}`);return X?.data?.summary||X?.data||null}}),{data:ke,isLoading:Ae,isError:be}=Ks(["event-date-detail","event",s],s?`/eventos/${s}/dashboard`:null,{enabled:!!s,retry:1}),Fe=ke?.data??ke??null,ae=Fe?.attributes||Fe||null,K=r.useMemo(()=>ae?Yu(ae,new Date,3):null,[ae]),O=r.useMemo(()=>ae?Ud(ae,t,new Date,3):!1,[ae,t]),oe=Wp({loadingEvent:Ae,eventError:be,attrs:ae,isScanner:$,requestedDateAllowed:O,nearestScannerDate:K,dateKey:t,documentId:s}),ve=Rt({queryKey:["event-date-detail","pedidos",s],enabled:!!s,queryFn:async()=>{const Q=new URLSearchParams({"filters[eventos][documentId][$eq]":s,"filters[status_pedido][$eq]":"pago","pagination[pageSize]":"200",sort:"createdAt:desc","populate[usuario]":"true","populate[eventos]":"true","populate[items][populate][tipo_ingresso][populate][campos_personalizados]":"true","populate[items][populate][evento]":"true","populate[link_convite][populate][created_by_usuario]":"true"}),X=await $e.get(`/pedidos?${Q.toString()}`);return Array.isArray(X.data?.data)?X.data.data:[]}}),me=ho({eventoDocumentId:s,dataEvento:t,pageSize:200},{enabled:!!s&&!!t}),fe=Et(ae?.data_evento),le=ie.data,_e=r.useMemo(()=>(le?.dates||[]).find(X=>X?.date===t)||null,[le,t]),U=r.useMemo(()=>(Array.isArray(_e?.groups)?_e.groups:[]).filter(X=>X?.ativo!==!1),[_e]),J=W&&U.length>0;r.useEffect(()=>{z(!1),S({})},[t]),r.useEffect(()=>{!_e||M||L(Fl(_e))},[_e,M]);const T=r.useMemo(()=>(Array.isArray(ve.data)?ve.data.filter(X=>String(X?.status_pedido||"").toLowerCase()==="pago"):[]).flatMap(X=>{const V=Ec(X?.usuario)||{},pe=Array.isArray(X?.items)?X.items:[],Ce=Array.isArray(X?.scan_logs)?X.scan_logs:[],Ue=pe.filter(Ve=>(Et(Ve?.metadata?.data_evento)||fe)===t),Xe=hi(Ue);return Ue.flatMap(Ve=>{const bs=gi(Ve,Xe),ts=Array.isArray(Ve?.holders)?Ve.holders:[];return Tl(Ve,{owner:V}).map((R,Le)=>{const as=R.holderIndex!=null&&ts[R.holderIndex]||null;let ms=R.nome,Ke=R.cpf,gs=R.dataNascimento;if(as?.campos_editado&&Object.keys(as.campos_editado).length){const fs=wo(Ve,as,X?.dados_faturamento),Ms=fs.find(ws=>ws.tipo==="nome"&&ws.isEdited),Fs=fs.find(ws=>ws.tipo==="cpf_passaporte"&&ws.isEdited),As=fs.find(ws=>ws.tipo==="data_nascimento"&&ws.isEdited);Ms&&(ms=Ms.value),Fs&&(Ke=Fs.value),As&&(gs=As.value)}return{rowId:`pedido-${X.id}-${Ve.id}${R.holderIndex!=null?`-${R.holderIndex}`:""}`,itemId:Ve?.id||null,source:"pedido",sourceId:X.id,documentId:X.documentId||null,nome:ms,cpf:Ke,dataNascimento:gs,criancaGratuita:R.criancaGratuita||!1,tipoIngresso:Ve?.tipo_ingresso?.nome||Ve?.nome_item||"Ingresso",status:Ve?.status||"disponivel",quantidade:R.quantidade,necessidades:X?.necessidades||X?.necessidades_especiais||null,vendedor:X?.referral_code||null,scanAt:Pl(Ce,Ve?.id),grupoPublico:bs,grupoImageUrl:rn(bs),isManualGroupOverride:hn(bs),pedidoDocumentId:X.documentId||null,holderIndex:R.holderIndex,holder:R.holderIndex!=null&&ts[R.holderIndex]||null,billing:X?.dados_faturamento||null,_raw:Ve}})})}),[ve.data,t,fe]),Ee=r.useMemo(()=>(me.data?.data||[]).flatMap(X=>{const V=Array.isArray(X?.items)?X.items:[],pe=Array.isArray(X?.scan_logs)?X.scan_logs:[],Ce=V.filter(Xe=>(Et(Xe?.metadata?.data_evento)||Et(X?.data_evento))===t),Ue=hi(Ce);return Ce.flatMap(Xe=>{const Ve=gi(Xe,Ue);return Tl(Xe,{owner:{nome:X?.nome,cpf:X?.cpf},fallbackNome:X?.nome||"Convidado"}).map(bs=>({rowId:`invite-${X.id}-${Xe.id}${bs.holderIndex!=null?`-${bs.holderIndex}`:""}`,itemId:Xe?.id||null,source:"convite",sourceId:X.id,documentId:X.documentId||null,nome:bs.nome,cpf:bs.cpf,dataNascimento:bs.dataNascimento,criancaGratuita:bs.criancaGratuita||!1,tipoIngresso:Xe?.tipo_ingresso?.nome||Xe?.nome_item||"Ingresso",status:Xe?.status||"disponivel",quantidade:bs.quantidade,necessidades:X?.necessidades_especiais||null,scanAt:Pl(pe,Xe?.id),grupoPublico:Ve,grupoImageUrl:rn(Ve),isManualGroupOverride:hn(Ve),_raw:Xe}))})}),[me.data,t]),Se=r.useMemo(()=>[...T,...Ee],[T,Ee]),Ze=r.useMemo(()=>
2Hp(Se),[Se]),qe=r.useMemo(()=>Kp({rows:Se,searchTerm:i,typeFilter:l,scanFilter:m,groupFilter:h}),[Se,m,i,l,h]),Qe=r.useMemo(()=>Qp({orderRows:T,inviteRows:Ee,rows:Se}),[Ee,T,Se]),we=(Q,X,V)=>{z(!0),L(pe=>pe.map((Ce,Ue)=>Ue===Q?{...Ce,[X]:V}:Ce))},Me=()=>{z(!0),L(Q=>{const X=Q.map(pe=>Number(pe.indice||0)).filter(pe=>Number.isFinite(pe)),V=Math.max(0,...X)+1;return[...Q,{id:null,documentId:null,indice:String(V),nome:`Grupo ${V}`,capacidade:"",ativo:!0,imagem:null,usage:0,remaining:null}]})},ks=Q=>{z(!0),L(X=>X.filter((V,pe)=>pe!==Q))},xs=()=>{if(z(!1),!_e){L([]);return}L(Fl(_e))},k=async()=>{if(!(!s||!t))try{E(!0);const Q={eventoDocumentId:s,dataEvento:t,groups:q.map(X=>({id:X.id||null,documentId:X.documentId||null,indice:Number(X.indice||0)||null,nome:X.nome||"",capacidade:X.capacidade===""?null:Number(X.capacidade),ativo:X.ativo!==!1,imagemId:X.imagem?.id||X.imagem?.data?.id||null}))};await $e.post("/pedidos/grupos-publicos/update",Q),await ie.refetch(),z(!1),a({title:"Grupos atualizados",description:"Alterações salvas para esta data."})}catch(Q){a({title:"Falha ao salvar grupos",description:Q?.response?.data?.error?.message||Q?.message||"Não foi possível atualizar os grupos.",variant:"destructive"})}finally{E(!1)}},De=async Q=>{if(!Q?.itemId)return;const X=Q.documentId?{documentId:Q.documentId,itemId:Q.itemId}:{pedidoId:Q.sourceId,itemId:Q.itemId};try{I(Q.rowId),await $e.post("/scanner/use",X),await Promise.all([n.invalidateQueries({queryKey:["event-date-detail"],exact:!1}),n.invalidateQueries({queryKey:["invites"],exact:!1})]),a({title:"Item marcado como usado",description:`${Q.nome} foi atualizado com sucesso.`})}catch(V){a({title:"Falha ao marcar como usado",description:V?.response?.data?.error?.message||V?.message||"Não foi possível atualizar o item.",variant:"destructive"})}finally{I(null)}},Ne=Q=>A[Q.rowId]||or(Q.grupoPublico),es=async Q=>{if(!s||!t||!Q?.itemId)return;const X=Ne(Q),V=Bp(X,U);if(!V){a({title:"Grupo inválido",description:"Selecione um grupo válido desta data.",variant:"destructive"});return}try{F(Q.rowId),await $e.post("/pedidos/grupos-publicos/override-item",{eventoDocumentId:s,dataEvento:t,source:Q.source,sourceId:Q.sourceId,documentId:Q.documentId,itemId:Q.itemId,...V}),S(pe=>{const Ce={...pe};return delete Ce[Q.rowId],Ce}),await Promise.all([n.invalidateQueries({queryKey:["event-date-detail"],exact:!1}),n.invalidateQueries({queryKey:["invites"],exact:!1}),n.invalidateQueries({queryKey:["event-date-detail","public-groups",s],exact:!1})]),a({title:"Grupo atualizado",description:"Override manual fixado neste grupo — o hotfix e os novos pagamentos não o movem mais. Para voltar ao automático, reatribua o participante."})}catch(pe){a({title:"Falha ao atualizar grupo",description:pe?.response?.data?.error?.message||pe?.message||"Não foi possível atualizar o grupo deste item.",variant:"destructive"})}finally{F(null)}},ss=async()=>{try{const{extraColumns:Q,groups:X}=$p(ve.data,{dateKey:t,primaryDateKey:fe}),{groups:V}=Lp(me.data?.data,{dateKey:t,primaryDateKey:fe}),pe=[...X,...V];if(pe.length===0){a({title:"Nada para exportar",description:"Nenhum pedido pago ou convite para esta data.",variant:"destructive"});return}const Ce=await $r(()=>import("./vendor-exceljs-AsZnDCZx.js").then(Rs=>Rs.e),__vite__mapDeps([0,1,2])),Ue=Ce.default||Ce,Xe=new Ue.Workbook,Ve=Xe.addWorksheet("Pessoas"),bs=Rs=>Number(Rs||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),ts=[{header:"Origem",key:"origem",width:12},{header:"Pessoas",key:"pessoas",width:9},{header:"Nome",key:"nome",width:28},{header:"CPF",key:"cpf",width:16},{header:"Endereço/Rua/Av",key:"rua",width:30},{header:"Cidade",key:"cidade",width:16},{header:"Estado",key:"estado",width:10},{header:"E-mail",key:"email",width:26},{header:"Telefone",key:"telefone",width:16},{header:"Data de nascimento",key:"dob",width:16},{header:"Grupo",key:"grupo",width:20},...Q.map(Rs=>({header:Rs.nome,key:`x_${Rs.chave}`,width:18})),{header:"Valor bruto pago",key:"bruto",width:16},{header:"Valor líquido",key:"liquido",width:16},{header:"Banco",key:"banco",width:12},{header:"Vendedor",key:"vendedor",width:14},{header:"Data da venda",key:"dataVenda",width:14},{header:"Necessidades",key:"necessidades",width:28}];Ve.columns=ts;const R={};
2ts.forEach((Rs,us)=>{R[Rs.key]=us+1});const Le=["origem","pessoas","bruto","liquido","banco","vendedor","dataVenda","necessidades"];let as=2;for(const Rs of pe){const us=as;Rs.people.forEach((Ss,ys)=>{const Ps={nome:Ss.nome,cpf:Ss.cpf,rua:Ss.rua,cidade:Ss.cidade,estado:Ss.estado,email:Ss.email,telefone:Ss.telefone,dob:Ss.dob,grupo:Ss.grupo||"Sem grupo"};Q.forEach(Bs=>{Ps[`x_${Bs.chave}`]=Ss.extras?.[Bs.chave]??""}),ys===0&&(Ps.origem=Rs.origem,Ps.pessoas=Rs.pessoas,Ps.bruto=bs(Rs.bruto),Ps.liquido=bs(Rs.liquido),Ps.banco=Rs.banco,Ps.vendedor=Rs.vendedor,Ps.dataVenda=Rs.dataVenda,Ps.necessidades=Rs.necessidades||""),Ve.addRow(Ps)});const Gs=us+Rs.people.length-1;Gs>us&&Le.forEach(Ss=>Ve.mergeCells(us,R[Ss],Gs,R[Ss])),Le.forEach(Ss=>{Ve.getCell(us,R[Ss]).alignment={vertical:"middle",horizontal:Ss==="pessoas"||Ss==="origem"?"center":"left",...Ss==="necessidades"?{wrapText:!0}:{}}}),as=Gs+1}Ve.getRow(1).font={bold:!0},Ve.getRow(1).alignment={vertical:"middle",horizontal:"center",wrapText:!0};const ms=ts.length,Ke=as-1,gs={style:"thin",color:{argb:"FFBFBFBF"}};for(let Rs=1;Rs<=Ke;Rs+=1)for(let us=1;us<=ms;us+=1)Ve.getCell(Rs,us).border={top:gs,left:gs,bottom:gs,right:gs};const fs=await Xe.xlsx.writeBuffer(),Ms=new Blob([fs],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),Fs=URL.createObjectURL(Ms),As=document.createElement("a");As.href=Fs,As.download=`evento-${s}-${t}.xlsx`,As.click(),URL.revokeObjectURL(Fs);const ws=pe.reduce((Rs,us)=>Rs+us.pessoas,0);a({title:"Exportação concluída",description:`${X.length} pedidos · ${V.length} convites · ${ws} pessoas.`})}catch(Q){console.error("Falha ao exportar lista por data",Q),a({title:"Falha ao exportar",description:Q?.message||"Não foi possível gerar o arquivo.",variant:"destructive"})}},We=async()=>{if(!(!s||!t||!window.confirm("Executar o hotfix de grupos para esta data?")))try{N(!0);const X={eventoDocumentId:s,dataEvento:t},pe=(await $e.post("/pedidos/hotfix-grupos-publicos/run",X))?.data||{};await Promise.all([n.invalidateQueries({queryKey:["event-date-detail"],exact:!1}),n.invalidateQueries({queryKey:["invites"],exact:!1})]),a({title:"Hotfix concluído",description:`Pedidos atualizados: ${pe.updatedPedidos||0}. Convites atualizados: ${pe.updatedInvites||0}.`})}catch(X){a({title:"Falha no hotfix",description:X?.response?.data?.error?.message||X?.message||"Não foi possível executar o hotfix.",variant:"destructive"})}finally{N(!1)}};if(Ae)return null;if(oe)return e.jsx(Ga,{to:oe,replace:!0});
2const hs=ve.isLoading||me.isLoading,Is=Jp(t);let Y=null;return hs?Y=e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Cs,{className:"h-4 w-4 animate-spin"})," Carregando pedidos e convites..."]}):qe.length===0?Y=e.jsx("div",{className:"rounded-md border border-dashed p-8 text-center text-sm text-muted-foreground",children:"Nenhum resultado encontrado para esta data."}):Y=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3 xl:hidden",children:qe.map(Q=>{const X=Ll(Q.status),V=Ne(Q),pe=V!==or(Q.grupoPublico);return e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-medium break-words",children:[Q.nome,Q.criancaGratuita?e.jsx("span",{className:"ml-2 text-[10px] font-normal text-muted-foreground",children:"(criança gratuita)"}):null]}),Q.dataNascimento?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Nasc.: ",_o(Q.dataNascimento)]}):null,e.jsxs("div",{className:"text-xs text-muted-foreground",children:["#",Q.sourceId]})]}),e.jsx(je,{variant:"outline",className:$l(Q.source),children:Ml(Q.source)})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"CPF"}),e.jsx("div",{className:"mt-1 text-sm break-all",children:Q.cpf||"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tipo ingresso"}),e.jsx("div",{className:"mt-1 text-sm break-words",children:Q.tipoIngresso})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx("div",{className:"mt-1",children:e.jsx(je,{variant:X.variant,children:X.label})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Quantidade"}),e.jsx("div",{className:"mt-1 text-sm",children:Q.quantidade})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Necessidades"}),e.jsx("div",{className:"mt-1 text-sm break-words",children:Q.necessidades||"—"})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Scan"}),e.jsx("div",{className:"mt-1 text-sm",children:Rl(Q.scanAt)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Grupo"}),e.jsxs("div",{className:"mt-1 space-y-2",children:[e.jsx(Co,{groupData:Q.grupoPublico}),J?e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs(rs,{value:V,onValueChange:Ce=>S(Ue=>({...Ue,[Q.rowId]:Ce})),children:[e.jsx(ns,{className:"w-full sm:max-w-xs",children:e.jsx(is,{placeholder:"Escolha o grupo"})}),e.jsx(os,{children:U.map(Ce=>e.jsx(xe,{value:or(Ce),children:rr(Ce)},or(Ce)))})]}),e.jsxs(w,{type:"button",size:"sm",variant:"outline",disabled:!pe||P===Q.rowId,onClick:()=>es(Q),children:[P===Q.rowId?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):null,e.jsx("span",{className:P===Q.rowId?"ml-2":"",children:"Salvar grupo"})]})]}):null]})]}),e.jsx("div",{className:"sm:col-span-2",children:e.jsxs(w,{type:"button",size:"sm",variant:String(Q.status||"").toLowerCase()==="usado"?"secondary":"outline",className:"w-full sm:w-auto",disabled:String(Q.status||"").toLowerCase()==="usado"||f===Q.rowId,onClick:()=>De(Q),children:[f===Q.rowId?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):e.jsx(wa,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:String(Q.status||"").toLowerCase()==="usado"?"Já usado":"Marcar como usado"})]})})]})]},Q.rowId)})}),e.jsx("div",{className:"hidden xl:block",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Nome"}),e.jsx(ue,{children:"CPF"}),e.jsx(ue,{children:"Campos"}),e.jsx(ue,{children:"Tipo"}),e.jsx(ue,{children:"Tipo Ingresso"}),e.jsx(ue,{children:"Status"}),e.jsx(ue,{children:"Vendedor"}),e.jsx(ue,{children:"Necessidades"}),e.jsx(ue,{children:"Scan"}),e.jsx(ue,{children:"Grupo"}),e.jsx(ue,{children:"Ações"})]})}),e.jsx(Ct,{children:qe.map(Q=>{const X=Ll(Q.status),V=Ne(Q),pe=V!==or(Q.grupoPublico);return e.jsxs($s,{children:[e.jsxs(ye,{children:[e.jsxs("div",{className:"font-medium",children:[Q.nome,Q.criancaGratuita?e.jsx("span",{className:"ml-2 text-[10px] font-normal text-muted-foreground",children:"(criança gratuita)"}):null]}),Q.dataNascimento?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Nasc.: ",_o(Q.dataNascimento)]}):null,e.jsxs("div",{className:"text-xs text-muted-foreground",children:["#",Q.sourceId]})]}),e.jsx(ye,{children:Q.cpf||"—"}),e.jsx(ye,{children:(()=>{const Ue=(Q._raw?wo(Q._raw,Q.holder,Q.billing):[]).filter(Xe=>!["nome","cpf_passaporte","data_nascimento"].includes(Xe.tipo));return Ue.length?e.jsx("div",{className:"space-y-0.5 max-w-[280px]",children:Ue.map(Xe=>e.jsxs("div",{className:"text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[Xe.nome,": "]}),e.jsx("span",{className:Xe.isEdited?"text-amber-600 font-medium":"",children:Up(Xe)})]},Xe.chave))}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})()}),e.jsx(ye,{children:e.jsx(je,{variant:"outline",className:$l(Q.source),children:Ml(Q.source)})}),e.jsx(ye,{children:Q.tipoIngresso}),e.jsx(ye,{children:e.jsx(je,{variant:X.variant,children:X.label})}),e.jsx(ye,{children:Q.vendedor||"—"}),e.jsx(ye,{children:Q.necessidades||"—"}),e.jsx(ye,{children:Rl(Q.scanAt)}),e.jsx(ye,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Co,{groupData:Q.grupoPublico}),J?e.jsxs("div",{className:"flex min-w-[220px] flex-col gap-2",children:[e.jsxs(rs,{value:V,onValueChange:Ce=>
2S(Ue=>({...Ue,[Q.rowId]:Ce})),children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Escolha o grupo"})}),e.jsx(os,{children:U.map(Ce=>e.jsx(xe,{value:or(Ce),children:rr(Ce)},or(Ce)))})]}),e.jsxs(w,{type:"button",size:"sm",variant:!pe||P===Q.rowId?"outline":"default",disabled:!pe||P===Q.rowId,onClick:()=>es(Q),children:[P===Q.rowId?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):null,e.jsx("span",{className:P===Q.rowId?"ml-2":"",children:"Salvar grupo"})]})]}):null]})}),e.jsx(ye,{children:e.jsxs("div",{className:"flex flex-col gap-2",children:[Q.source==="pedido"&&Q.holderIndex!=null?e.jsx(w,{type:"button",size:"sm",variant:"outline",onClick:()=>C(Q),children:"Editar"}):null,e.jsxs(w,{type:"button",size:"sm",variant:String(Q.status||"").toLowerCase()==="usado"?"secondary":"",disabled:String(Q.status||"").toLowerCase()==="usado"||f===Q.rowId,onClick:()=>De(Q),children:[f===Q.rowId?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):e.jsx(wa,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:String(Q.status||"").toLowerCase()==="usado"?"Já usado":"Marcar como usado"})]})]})})]},Q.rowId)})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:ae?.titulo||"Evento"}),e.jsx("p",{className:"text-muted-foreground",children:Is})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(w,{variant:"outline",asChild:!0,children:e.jsx(lt,{to:"/dashboard/eventos",children:"Voltar para eventos"})}),e.jsx(w,{variant:"outline",asChild:!0,children:e.jsx(lt,{to:`/dashboard/eventos/${encodeURIComponent(s)}`,children:"Painel do evento"})}),W?e.jsxs(w,{type:"button",variant:"outline",disabled:g,onClick:We,children:[g?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):null,e.jsx("span",{className:g?"ml-2":"",children:"Hotfix grupos"})]}):null,e.jsxs(w,{onClick:ss,className:"gap-2",children:[e.jsx(Oa,{className:"h-4 w-4"})," Exportar Excel"]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium",children:"Vendidos"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-bold",children:Qe.vendidos})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium",children:"Convites"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-bold",children:Qe.convites})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium",children:"Escaneados"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-bold text-emerald-600",children:Qe.usados})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium",children:"Restantes"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-bold text-amber-600",children:Qe.restantes})})]})]}),W?e.jsxs(he,{children:[e.jsx(Be,{className:"pb-4",children:e.jsx(ze,{className:"text-base",children:"Grupos públicos desta data"})}),e.jsxs(ge,{className:"space-y-4",children:[ie.isLoading?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Cs,{className:"h-4 w-4 animate-spin"})," Carregando grupos..."]}):null,!ie.isLoading&&ie.isError?e.jsx("div",{className:"text-sm text-destructive",children:"Não foi possível carregar os grupos desta data."}):null,!ie.isLoading&&!ie.isError&&!_e?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Nenhum grupo configurado para esta data."}):null,_e?e.jsx("div",{className:"space-y-3",children:q.map((Q,X)=>{const V=rn(Q);return e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-12 md:items-end",children:[e.jsxs("div",{className:"md:col-span-1",children:[e.jsx(Oe,{children:"Índice"}),e.jsx(Te,{type:"number",value:Q.indice,onChange:pe=>we(X,"indice",pe.target.value)})]}),e.jsxs("div",{className:"md:col-span-4",children:[e.jsx(Oe,{children:"Nome"}),e.jsx(Te,{value:Q.nome,onChange:pe=>we(X,"nome",pe.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(Oe,{children:"Capacidade"}),e.jsx(Te,{type:"number",value:Q.capacidade,onChange:pe=>we(X,"capacidade",pe.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(Oe,{children:"Ativo"}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(Ls,{checked:Q.ativo,onCheckedChange:pe=>we(X,"ativo",!!pe)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Q.ativo?"Ativo":"Inativo"})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(Oe,{children:"Uso"}),e.jsxs("div",{className:"pt-2 text-sm",children:[Q.usage," usados",Number.isFinite(Number(Q.remaining))?` · ${Q.remaining} restantes`:""]})]}),e.jsx("div",{className:"md:col-span-1 flex md:justify-end",children:e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>ks(X),children:"Remover"})})]}),V?e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx("img",{src:V,alt:Q.nome,className:"h-12 w-20 rounded object-contain bg-muted"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Imagem atual"})]}):null]},`${Q.id||"new"}-${X}`)})}):null,e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(w,{type:"button",variant:"outline",onClick:Me,children:"Adicionar grupo"}),e.jsx(w,{type:"button",variant:"outline",onClick:xs,disabled:!M,children:"Descartar alterações"}),e.jsxs(w,{type:"button",onClick:k,disabled:D||!M,children:[D?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):null,e.jsx("span",{className:D?"ml-2":"",children:"Salvar grupos"})]})]})]})]}):null,Ze.length>1&&e.jsx("div",{className:"flex flex-col gap-4 md:grid",style:{gridTemplateColumns:`repeat(${Math.min(Ze.length,5)}, minmax(0, 1fr))`},children:Ze.map(Q=>
2e.jsx(he,{className:`cursor-pointer transition-shadow hover:shadow-md ${h===Q.key?"ring-2 ring-primary":""}`,onClick:()=>p(h===Q.key?"all":Q.key),children:e.jsxs(ge,{className:"flex flex-col items-center gap-2 rounded-md",children:[Q.imageUrl?e.jsx("img",{src:Q.imageUrl,alt:Q.label,className:"w-full h-full object-contain rounded-xl  my-2"}):null,e.jsx("div",{className:"text-3xl font-bold",children:Q.total})]})},Q.key))}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-4",children:e.jsx(ze,{className:"text-base",children:"Filtros"})}),e.jsxs(ge,{className:"grid gap-3 lg:grid-cols-5",children:[e.jsxs("div",{className:"space-y-2 lg:col-span-2",children:[e.jsx(Oe,{htmlFor:"event-date-search",children:"Buscar por nome, CPF ou ingresso"}),e.jsx(Te,{id:"event-date-search",value:i,onChange:Q=>u(Q.target.value),placeholder:"Ex.: Maria, 12345678901, VIP"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Tipo"}),e.jsxs(rs,{value:l,onValueChange:c,children:[e.jsx(ns,{children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),e.jsx(xe,{value:"pedido",children:"Pedido"}),e.jsx(xe,{value:"convite",children:"Convite"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Status do scan"}),e.jsxs(rs,{value:m,onValueChange:x,children:[e.jsx(ns,{children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),e.jsx(xe,{value:"escaneado",children:"Escaneado"}),e.jsx(xe,{value:"nao-escaneado",children:"Não escaneado"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Grupo"}),e.jsxs(rs,{value:h,onValueChange:p,children:[e.jsx(ns,{children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),Ze.map(Q=>e.jsxs(xe,{value:Q.key,children:[Q.label," (",Q.total,")"]},Q.key))]})]})]})]})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-4",children:e.jsx(ze,{className:"text-base",children:"Pessoas desta data"})}),e.jsx(ge,{children:Y})]}),e.jsx(Ac,{row:b,open:!!b,onOpenChange:Q=>{Q||C(null)},onSaved:()=>n.invalidateQueries({queryKey:["event-date-detail","pedidos",s]})})]})}function Ol(s){return String(s).padStart(2,"0")}function Rn(s){if(!s)return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(s);if(!t)return null;const a=Number(t[1]),n=Number(t[2])-1,o=Number(t[3]),i=new Date(a,n,o);return Number.isNaN(i.valueOf())?null:i}function ql(s){return!(s instanceof Date)||Number.isNaN(s.valueOf())?"":`${s.getFullYear()}-${Ol(s.getMonth()+1)}-${Ol(s.getDate())}`}const zl={root:{base:"relative !w-full",input:{field:{base:"relative w-full",icon:{svg:"h-5 w-5 !text-muted-foreground"},input:{base:"block w-full border focus:outline-none focus:ring-1 disabled:cursor-not-allowed disabled:opacity-50",colors:{gray:"!border-input !bg-background !text-foreground !placeholder:text-muted-foreground focus:!border-ring focus:!ring-ring"},sizes:{md:"!px-3 !py-2 !text-sm"},withIcon:{on:"!pl-10",off:""},withAddon:{on:"!rounded-r-md",off:"!rounded-md"}}}}},popup:{root:{base:"absolute top-10 !z-50 block pt-2",inline:"relative top-0 z-auto",inner:"inline-block !rounded-lg !bg-popover !p-4 !text-popover-foreground !shadow-md"},header:{title:"!px-2 !py-3 text-center font-semibold !text-popover-foreground",selectors:{base:"!mb-2 flex justify-between",button:{base:"!rounded-lg !bg-background !px-5 !py-2.5 !text-sm font-semibold !text-foreground hover:!bg-accent focus:outline-none focus:!ring-2 focus:!ring-ring"}}},view:{base:"!p-1"},footer:{base:"!mt-2 flex !space-x-2",button:{base:"!w-full !rounded-lg !px-5 !py-2 text-center !text-sm font-medium focus:!ring-2 focus:!ring-ring",today:"!bg-primary !text-primary-foreground hover:!bg-primary/90",clear:"!border !border-input !bg-background !text-foreground hover:!bg-accent"}}},views:{days:{header:{title:"!h-6 text-center !text-sm font-medium leading-6 !text-muted-foreground"},items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}},months:{items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}},years:{items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}},decades:{items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}}}};function Dc(s){const t=s?.user?.role??s?.user?.data?.attributes?.role??s?.user?.data?.role??null,a=t?.data?.attributes??t?.data??t;return{roleName:String(a?.name||"").toLowerCase(),roleType:String(a?.type||"").toLowerCase()}}function Zp(s){return String(s||"").toLowerCase().includes("palestra")}function ko(s){const{roleName:t,roleType:a}=Dc(s);return t.includes("vendedor")||a.includes("vendedor")}function Gi(s,t){const a=Array.isArray(s)?s:[];return ko(t)?a.filter(n=>!Zp(n?.titulo)).map(n=>n.id):a.map(n=>n.id)}function eh(s){const t=String(s||"").trim().toLowerCase();return["pendente","pending","awaiting","aguardando"].includes(t)?"pendente":["cancelado","cancelada","canceled","cancelled","falha","falho","falhou","failed","payment_failed"].includes(t)?"cancelado":t}function sh(s){const t=String(s||"").trim();if(!t)return"";const a=Array.from(new Set([t,...Uo(t)]));return[{field:"nome",value:t},{field:"email",value:t},...a.map(o=>({field:"cpf",value:o}))].map((o,i)=>`filters[$or][${i}][${o.field}][$containsi]=${encodeURIComponent(o.value)}`).join("&")}function th(){const{token:s,user:t}
2=Zt(),{toast:a}=mt(),n=(t?.role?.name||t?.role?.type||"").toLowerCase(),o=(t?.role?.code||"").toLowerCase(),i=n.includes("vendedor")||o.includes("vendedor"),u=n.includes("gerente")&&n.includes("vendedor"),l=n.includes("comissao")||n.includes("comissão")||o.includes("comissao")||o.includes("comissão"),c=i||l,m=!(i||u||l),[x,h]=r.useState(""),[p,f]=r.useState(""),[I,g]=r.useState("all"),[N,b]=r.useState("all"),[C,q]=r.useState(""),[L,M]=r.useState(""),[z,D]=r.useState("all"),[E,A]=r.useState("all"),S=()=>{f(x.trim())};r.useEffect(()=>{const B=setTimeout(()=>f(x.trim()),5e3);return()=>clearTimeout(B)},[x]);const P=I!=="all"||N!=="all"||!!C||!!L||z!=="all"||E!=="all",F=P||c,ee=!!p||P||c,[re,te]=r.useState(()=>new Set),[G,y]=r.useState(!1),[$,W]=r.useState({sent:0,total:0}),[ie,ke]=r.useState("Olá {{nome}}, você deixou itens no carrinho na TicketTop. Clique no botão abaixo para concluir sua compra."),[Ae,be]=r.useState(1),Fe=10,ae=F?100:Fe,O=new URLSearchParams(typeof window<"u"?window.location.search:"").get("usuarioId"),oe=r.useRef({}),[ve,me]=r.useState([]),[fe,le]=r.useState(2),[_e,U]=r.useState(!1),[J,T]=r.useState([]),[Ee,Se]=r.useState(!1),[Ze,qe]=r.useState(null),[Qe,we]=r.useState(!1),[Me,ks]=r.useState(new Set),[xs,k]=r.useState(!1),[De,Ne]=r.useState(!0),[es,ss]=r.useState([]),[We,hs]=r.useState(!1),[Is,Y]=r.useState(!1),[Q,X]=r.useState([]),[V,pe]=r.useState(!1),Ce=r.useMemo(()=>Rn(C),[C]),Ue=r.useMemo(()=>Rn(L),[L]),Xe=F?1:Ae,{data:Ve,isLoading:bs,error:ts,refetch:R}=Vx(Xe,ae,{enabled:!!s,keepPreviousData:!0,search:p}),{data:Le,isLoading:as,error:ms,refetch:Ke}=Ks("pedidos-for-users","/pedidos?excludeSuperAdmin=true&populate[usuario]=true&populate[items]=true&fields[0]=id&fields[1]=status_pedido&fields[2]=status&fields[3]=total&fields[4]=createdAt&fields[5]=data_pedido&fields[6]=subtotal&fields[7]=taxa_servico&fields[8]=desconto_cupom",{enabled:!!s,keepPreviousData:!0}),{data:gs}=Ks("eventos-for-abandoned-images","/eventos?fields[0]=titulo&fields[1]=documentId&populate[mobile_imagem][fields][0]=url&populate[mobile_imagem][fields][1]=name&populate[mobile_imagem][fields][2]=formats&pagination[pageSize]=500&publicationState=preview",{enabled:!!s,keepPreviousData:!0});r.useEffect(()=>{s&&(R(),Ke())},[s,R,Ke]);const fs=Ve?.data||[],Ms=za(Le?.data||[],"pedido"),Fs=Ve?.meta?.pagination||{},As=r.useMemo(()=>{if(!ve.length)return fs;const B=new Map;return[...fs,...ve].forEach(de=>{de?.id&&!B.has(de.id)&&B.set(de.id,de)}),Array.from(B.values())},[fs,ve]);r.useEffect(()=>{if(!s)return;let B=!1;return(async()=>{try{let He=1,ps=1;const vs=[];for(;He<=ps&&!B;){const Es=`/usuarios?populate[avatar][fields][0]=url&populate[avatar][fields][1]=name&populate[user]=true&sort=createdAt:desc&pagination[page]=${He}&pagination[pageSize]=200`,cs=await $e.get(Es),qs=za(cs?.data?.data||[],"usuario");vs.push(...qs),ps=Number(cs?.data?.meta?.pagination?.pageCount||1),He+=1}B||T(vs)}catch{B||T([])}})(),()=>{B=!0}},[s]);const ws=Ms.reduce((B,de)=>{const Re=de.attributes.usuario?.data?.id;return Re&&(B[Re]||(B[Re]={totalOrders:0,totalSpent:0,lastOrder:null,paidOrders:0}),B[Re].totalOrders+=1,(de.attributes.status_pedido||de.attributes.status)==="pago"&&(B[Re].paidOrders+=1,B[Re].totalSpent+=Ua(de)),(!B[Re].lastOrder||new Date(de.attributes.createdAt)>new Date(B[Re].lastOrder))&&(B[Re].lastOrder=de.attributes.createdAt)),B},{}),Rs=r.useMemo(()=>{if(!c)return null;const B=new Set;return(Ms||[]).forEach(de=>{const Re=de?.attributes?.usuario?.data?.id;if(!Re)return;const He=eh(de?.attributes?.status_pedido||de?.attributes?.status);(He==="pendente"||He==="cancelado")&&B.add(Re)}),As.forEach(de=>{(Array.isArray(de?.attributes?.cart)?de.attributes.cart:[]).length&&B.add(de.id)}),B},[c,As,Ms]);r.useEffect(()=>{F&&be(1)},[I,N,C,L,z,E,F]),r.useEffect(()=>{be(1)},[p]),r.useEffect(()=>{me([]),le(2),U(!1)},[F,p,I,N,C,L,z,E]),r.useEffect(()=>{if(!O||!s)return;let B=!1;return(async()=>{try{const Re=(await $e.get(`/usuarios?filters[id][$eq]=${O}&fields[0]=email&fields[1]=nome&pagination[pageSize]=1`)).data?.data,He=Array.isArray(Re)?Re[0]:Re,ps=He?.attributes||He||{},vs=ps.email||ps.nome||"";
2!B&&vs&&h(vs)}catch{}})(),()=>{B=!0}},[O,s]),r.useEffect(()=>{if(O&&oe.current[O]){oe.current[O].scrollIntoView({behavior:"smooth",block:"center"}),oe.current[O].classList.add("ring-2","ring-primary");const B=oe.current[O],de=setTimeout(()=>B&&B.classList.remove("ring-2","ring-blue-500"),1500);return()=>clearTimeout(de)}},[O,fs]);const us=r.useMemo(()=>{const B=new Map;return(Ms||[]).forEach(Re=>{const He=Re?.attributes||{};if((He.status_pedido||He.status||"").toLowerCase()!=="pago")return;const vs=He.usuario?.data?.id;if(!vs)return;const Es=new Date(He.createdAt||He.data_pedido||He.updatedAt||Date.now());if(Number.isNaN(Es.getTime()))return;(Array.isArray(He.items)?He.items:[]).forEach(qs=>{const Qs=(()=>{const Je=qs?.evento?.data?.id||qs?.evento?.data?.attributes?.documentId;return qs?.eventoId||qs?.eventoDocumentId||qs?.metadata?.eventoId||qs?.metadata?.eventoDocumentId||Je||qs?.eventoDocumentId||qs?.eventoId||null})();if(!Qs)return;const j=B.get(vs)||new Map,Z=j.get(Qs);(!Z||Es>Z)&&j.set(Qs,Es),B.set(vs,j)})}),B},[Ms]),Gs=r.useMemo(()=>{const B=new Map,de=gs?.data||[];return(Array.isArray(de)?de:[]).forEach(Re=>{const He=Re?.attributes||Re||{},ps=He.documentId||Re?.documentId,vs=Re?.id,Es=He?.mobile_imagem?.data?.attributes?.url||He?.mobile_imagem?.url||He?.mobile_imagem||null;if(!Es)return;const cs=qt(Es);cs&&(ps&&B.set(String(ps),cs),vs!=null&&B.set(String(vs),cs))}),B},[gs]),Ss=7*24*60*60*1e3,ys=r.useMemo(()=>{const B=Date.now(),de={};return As.forEach(Re=>{const He=Re.id,ps=Array.isArray(Re.attributes?.cart)?Re.attributes.cart:[];if(!ps.length)return;const vs=us.get(He)||new Map,Es=ps.map(cs=>{const qs=cs?.eventoDocumentId||cs?.eventoId||cs?.metadata?.eventoDocumentId||cs?.metadata?.eventoId||cs?.evento?.attributes?.documentId||cs?.evento?.documentId||cs?.evento?.id||null,Qs=qs?vs.get(qs):null,j=Qs?new Date(Qs).getTime():null,Z=j?B-j<=Ss:!1;if(!(!Qs||!Z))return null;const js=cs?.eventoTitulo||cs?.evento?.attributes?.titulo||cs?.evento?.attributes?.nome||cs?.evento?.titulo||cs?.metadata?.eventoTitulo||cs?.metadata?.eventoNome||"Evento",zs=cs?.name||cs?.nome||cs?.metadata?.nome||"Item",Ge=Number(cs?.qty||cs?.quantidade||1),Ws=Number(cs?.price||cs?.preco||cs?.metadata?.precoFinal||cs?.metadata?.preco||0),jt=cs?.moeda||cs?.metadata?.moeda||"BRL",ma=cs?.metadata?.imagem?.url||cs?.metadata?.image||cs?.imagem||cs?.metadata?.eventoImagem||cs?.evento?.attributes?.imagem,Ot=ma?qt(ma):null,br=(qs!=null?Gs.get(String(qs)):null)||Ot,Ha=Qs?"Sem compra nos últimos 7 dias":"Nunca comprou este evento";return{id:cs?.id||`${qs||"evento"}-${zs}`,eventKey:qs,eventTitle:js,name:zs,qty:Ge,price:Ws,moeda:jt,imageUrl:br,reason:Ha,lastPaidAt:j?new Date(j):null,type:cs?.item_tipo||cs?.type||"ingresso"}}).filter(Boolean);Es.length&&(de[He]=Es)}),de},[As,us,Ss,Gs]),Ps=r.useMemo(()=>{if(!J.length)return null;const B=Date.now();let de=0;for(const Re of J){const He=Re?.id;if(!He)continue;const ps=Array.isArray(Re.attributes?.cart)?Re.attributes.cart:[];if(!ps.length)continue;const vs=us.get(He)||new Map;ps.some(cs=>{const qs=cs?.eventoDocumentId||cs?.eventoId||cs?.metadata?.eventoDocumentId||cs?.metadata?.eventoId||cs?.evento?.attributes?.documentId||cs?.evento?.documentId||cs?.evento?.id||null;if(!qs)return!1;const Qs=vs.get(qs);if(!Qs)return!0;const j=new Date(Qs).getTime();return Number.isNaN(j)?!0:B-j>Ss})&&(de+=1)}return de},[J,us,Ss]),Bs=B=>{te(de=>{const Re=new Set(de);return Re.has(B)?Re.delete(B):Re.add(B),Re})},dt=B=>{te(de=>{const Re=new Set(de),He=B.filter(vs=>ys[vs.id]?.length).map(vs=>vs.id);return He.every(vs=>Re.has(vs))?He.forEach(vs=>Re.delete(vs)):He.forEach(vs=>Re.add(vs)),Re})},Ts=As.reduce((B,de)=>(B[de.id]={inDate:!1,hasType:!1},B),{});try{const B=C?Rn(C):null,de=L?Rn(L):null;B&&B.setHours(0,0,0,0),de&&de.setHours(23,59,59,999),(Ms||[]).forEach(Re=>{const He=Re.attributes?.usuario?.data?.id;if(!He||!(He in Ts))return;const ps=Re.attributes?.data_pedido||Re.attributes?.createdAt,vs=ps?new Date(ps):null;if(!B&&!de)Ts[He].inDate=!0;else{const Es=vs&&(!B||vs>=B)&&(!de||vs<=de);Ts[He].inDate=Ts[He].inDate||!!Es}if(z==="all")Ts[He].hasType=!0;else{const cs=(Array.isArray(Re.attributes?.items)?Re.attributes.items:[]).some(qs=>{const Qs=String(qs?.item_tipo||"").toLowerCase();return z==="ingresso"?Qs==="ingresso":z==="bar"?Qs==="estoque"||Qs==="combo":!1});Ts[He].hasType=Ts[He].hasType||cs}}
2),!C&&!L&&z==="all"&&Object.keys(Ts).forEach(Re=>{Ts[Re].inDate=!0,Ts[Re].hasType=!0})}catch{}const Mt=x.trim(),Ys=Mt.toLowerCase(),ht=Array.from(new Set(Uo(Mt).map(B=>String(B).toLowerCase()))),ea=Array.from(new Set(ht.map(B=>xl(B)).filter(Boolean)));let Xs=As.filter(B=>{const de=B.attributes.nome?.toLowerCase()||"",Re=B.attributes.email?.toLowerCase()||"",He=B.attributes.cpf?.toLowerCase()||"",ps=xl(B.attributes.cpf),vs=!!ys[B.id]?.length;if(c&&!Rs?.has(B.id))return!1;const Es=!Ys||de.includes(Ys)||Re.includes(Ys)||He.includes(Ys)||ht.some(Qs=>He.includes(Qs))||ea.some(Qs=>ps.includes(Qs));if(N==="abandoned"&&!vs)return!1;if(I==="all"){const Qs=Ts[B.id]||{inDate:!0,hasType:!0};return Es&&Qs.inDate&&Qs.hasType}const cs=ws[B.id]?.totalOrders>0,qs=ws[B.id]?.lastOrder&&new Date(ws[B.id].lastOrder)>new Date(Date.now()-30*24*60*60*1e3);switch(I){case"active":return Es&&qs&&(Ts[B.id]?.inDate??!0)&&(Ts[B.id]?.hasType??!0);case"with-orders":return Es&&cs&&(Ts[B.id]?.inDate??!0)&&(Ts[B.id]?.hasType??!0);case"no-orders":return Es&&!cs&&(Ts[B.id]?.inDate??!0)&&(Ts[B.id]?.hasType??!0);default:return Es&&(Ts[B.id]?.inDate??!0)&&(Ts[B.id]?.hasType??!0)}});E==="top"&&(Xs=Xs.slice().sort((B,de)=>(ws[de.id]?.totalSpent||0)-(ws[B.id]?.totalSpent||0)).slice(0,10));const xt=(Ae-1)*Fe,ia=xt+Fe,oa=ia,st=F?Xs.slice(xt,ia):Xs;r.useEffect(()=>{if(!F||!s||bs||_e)return;const B=Number(Fs.pageCount||0),de=Number(fe||0);if(!B||de<1||Xs.length>=oa||de>B)return;U(!0);let Re=`/usuarios?populate[avatar][fields][0]=url&populate[avatar][fields][1]=name&populate[user]=true&sort=createdAt:desc&pagination[page]=${de}&pagination[pageSize]=${ae}`;const He=sh(p);He&&(Re+=`&${He}`);let ps=!1;return $e.get(Re).then(vs=>{if(ps)return;const Es=za(vs?.data?.data||[],"usuario");Es.length&&me(cs=>{const qs=new Map;return[...cs,...Es].forEach(Qs=>{Qs?.id&&!qs.has(Qs.id)&&qs.set(Qs.id,Qs)}),Array.from(qs.values())}),le(de+1)}).catch(()=>{le(de+1)}).finally(()=>{U(!1)}),()=>{ps=!0}},[F,p,s,bs,_e,fe,Xs.length,oa,Fs.pageCount,ae]);const wt=async()=>{Y(!0),pe(!0);try{const B=await $e.get("/usuarios/staff-permissions"),de=B?.data?.data||B?.data||[],Re=(Array.isArray(de)?de:[]).map(He=>({id:He.id,attributes:{...He.attributes||He}}));X(Re)}catch{}finally{pe(!1)}},va=async B=>{const de=B.attributes||B,Re=Array.isArray(de.eventosSelecionados)?de.eventosSelecionados.map(Number).filter(ps=>Number.isFinite(ps)&&ps>0):[],He=Re.length?Re:Gi(es,de);if(qe(B),we(!!de.restringirFormularios),Ne(de.podeVerFormularios===!0),ks(new Set(He)),Se(!0),!es.length&&!We){hs(!0);try{const ps=await $e.get("/eventos?fields[0]=titulo&fields[1]=id&pagination[pageSize]=200&sort=titulo:asc&publicationState=preview"),vs=ps?.data?.data||ps?.data||[],Es=(Array.isArray(vs)?vs:[]).map(cs=>({id:cs.id??cs?.attributes?.id,titulo:cs.attributes?.titulo||cs?.titulo||`Evento #${cs.id}`})).filter(cs=>cs.id);ss(Es),Re.length||ks(new Set(Gi(Es,de)))}catch{}finally{hs(!1)}}},la=async()=>{if(Ze){k(!0);try{const B=Qe?Array.from(Me).map(Number).filter(Re=>Number.isFinite(Re)&&Re>0):[],de=Ze.documentId||Ze.attributes?.documentId||Ze.id;await $e.put(`/usuarios/${de}`,{data:{podeVerFormularios:De,restringirFormularios:Qe,eventosSelecionados:B}}),a({title:"Permissões salvas com sucesso."}),Se(!1),R(),X(Re=>Re.map(He=>He.id===Ze.id?{...He,attributes:{...He.attributes,podeVerFormularios:De,restringirFormularios:Qe,eventosSelecionados:B}}:He))}catch(B){a({title:"Erro ao salvar permissões",description:B?.response?.data?.error?.message||B.message,variant:"destructive"})}finally{k(!1)}}},da=B=>{ks(de=>{const Re=new Set(de);return Re.has(B)?Re.delete(B):Re.add(B),Re})},Tt=B=>Xm(B),Js=B=>aa(B),Ft=B=>{const de=String(B||"").trim();if(!de)return"";const Re=de.replaceAll(/\D+/g,"");if(Re.length===11){const He=Re.slice(0,2),ps=Re.slice(2,7),vs=Re.slice(7);return`(${He}) ${ps}-${vs}`}return de},ba=B=>{const de=String(B||"").replaceAll(/\D+/g,"");return de?de.startsWith("55")?de:`55${de}`:""},Kt=B=>{const de=ws[B];return!de||de.totalOrders===0?{label:"Sem pedidos",variant:"secondary",className:"bg-gray-100 text-gray-800"}:de.lastOrder&&new Date(de.lastOrder)>new Date(Date.now()-30*24*60*60*1e3)?{label:"Ativo",variant:"default",className:"bg-green-100 text-green-800"}:{label:"Inativo",variant:"outline",className:"bg-yellow-100 text-yellow-800"}};if(bs||as)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600"})});const _t=ts||ms;if(_t)return e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsxs("div",{className:"text-center text-red-600",children:["Erro ao carregar usuários",_t.response?.status&&` (código ${_t.response.status})`,": ",_t.message,".",e.jsx("br",{}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Verifique a aba Network do navegador para detalhes e tente novamente."})]})})});const ca=Fs.total??As.length,Na=Object.keys(ys).length,Qt=Object.keys(ws).length;
2Object.values(ws).filter(B=>B.lastOrder&&new Date(B.lastOrder)>new Date(Date.now()-30*24*60*60*1e3)).length;const ua=Object.values(ws).reduce((B,de)=>B+de.totalSpent,0),pt=Object.values(ws).filter(B=>(B.paidOrders||0)>1).length,ft=ee?Xs:null,Wt=ee?ft.length:ca,Dt=ee?ft.filter(B=>ys[B.id]?.length).length:Ps??Na,gt=ee?ft.filter(B=>(ws[B.id]?.totalOrders||0)>0).length:Qt,d=ee?ft.reduce((B,de)=>B+(ws[de.id]?.totalSpent||0),0):ua,_=gt>0?d/gt:0,H=ee?ft.filter(B=>(ws[B.id]?.paidOrders||0)>1).length:pt,ce=(B,de="BRL")=>{try{return(B||0).toLocaleString("pt-BR",{style:"currency",currency:de})}catch{return`${de} ${Number(B||0).toFixed(2)}`}},Pe=(B=[])=>B.length?B.map(de=>`${de.eventTitle} ${de.name} • ${de.qty} un • ${ce(de.price,de.moeda)}`).join(`
3`):"",Ie=(B,de)=>{const Re=[];for(let He=0;He<B.length;He+=de)Re.push(B.slice(He,He+de));return Re},Ye=25,Ns=1e3,_s=B=>(B||[]).map(de=>({id:de.id,email:de.attributes?.email,name:de.attributes?.nome||"cliente",items:ys[de.id]||[]})).filter(de=>de.email&&de.items.length),Hs=async(B=null)=>{const de=B?Array.isArray(B)?B:[B]:Xs.filter(He=>re.has(He.id)),Re=_s(de);if(!Re.length){a({title:"Selecione usuários abandonados",description:"Escolha pelo menos um usuário com carrinho abandonado para enviar o email.",variant:"destructive"});return}y(!0),W({sent:0,total:Re.length});try{const He=Ie(Re,Ye);let ps=0;for(let vs=0;vs<He.length;vs+=1){const Es=He[vs],cs=await $e.post("/abandoned-mails/send",{targets:Es,message:ie}),qs=Number(cs?.data?.sent??Es.length);ps+=Number.isNaN(qs)?Es.length:qs,W({sent:ps,total:Re.length}),vs<He.length-1&&await new Promise(Qs=>setTimeout(Qs,Ns))}a({title:"Emails enviados",description:`${ps}/${Re.length} emails disparados via servidor.`})}catch(He){console.error("Falha ao enviar emails de abandono",He),a({title:"Erro ao enviar emails",description:He.message||"Tente novamente mais tarde.",variant:"destructive"})}finally{y(!1)}},Os=async()=>{try{const B=Xs.map(Je=>{const js=Je.attributes||{},zs=ws[Je.id]||{},Ge=zs.lastOrder?new Date(zs.lastOrder):null;let Ws="",jt="";return Ge&&!isNaN(Ge)&&(Ws=Ge.toLocaleDateString("pt-BR"),jt=Ge.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})),{ID:Je.id,Nome:js.nome||"",Email:js.email||"",CPF:js.cpf||"",Telefone:js.telefone||"","Total Pedidos":zs.totalOrders||0,Pagos:zs.paidOrders||0,"Total (BRL)":Number(zs.totalSpent||0),"Último Pedido - Data":Ws,"Último Pedido - Hora":jt}}),de=await $r(()=>import("./vendor-exceljs-AsZnDCZx.js").then(Je=>Je.e),__vite__mapDeps([0,1,2])),Re=de.default||de,He=new Re.Workbook,ps=He.addWorksheet("Usuários");ps.columns=[{header:"ID",key:"ID",width:8},{header:"Nome",key:"Nome",width:24},{header:"Email",key:"Email",width:30},{header:"CPF",key:"CPF",width:16},{header:"Telefone",key:"Telefone",width:18},{header:"Total Pedidos",key:"Total Pedidos",width:14},{header:"Pagos",key:"Pagos",width:10},{header:"Total (BRL)",key:"Total (BRL)",width:16},{header:"Último Pedido - Data",key:"Último Pedido - Data",width:16},{header:"Último Pedido - Hora",key:"Último Pedido - Hora",width:12}],B.forEach(Je=>ps.addRow(Je)),ps.getRow(1).font={bold:!0};for(let Je=2;Je<=B.length+1;Je++){const js=ps.getCell(`H${Je}`);typeof js.value=="number"&&(js.numFmt='"R$" #,##0.00')}const vs=new Date,Es=Je=>String(Je).padStart(2,"0"),cs=`usuarios_${vs.getFullYear()}-${Es(vs.getMonth()+1)}-${Es(vs.getDate())}.xlsx`,qs=await He.xlsx.writeBuffer(),Qs=new Blob([qs],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),j=URL.createObjectURL(Qs),Z=document.createElement("a");Z.href=j,Z.download=cs,document.body.appendChild(Z),Z.click(),Z.remove(),URL.revokeObjectURL(j)}catch(B){console.error("Falha ao exportar Excel de usuários:",B),alert("Falha ao exportar. Veja o console para detalhes.")}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Gerenciar Usuários"}),e.jsx("p",{className:"text-muted-foreground",children:"Visualize e gerencie todos os usuários do sistema"})]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:wt,children:[e.jsx(Li,{className:"mr-2 h-4 w-4"})," Permissões de Formulários"]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 ga
3p-3",children:[{label:"Total Usuários",value:Wt,icon:gr,color:"bg-primary"},{label:"Com compras",value:gt,icon:Cr,color:"bg-secondary"},{label:"Receita média",value:Js(_),icon:pr,color:"bg-accent"},{label:"Recorrentes",value:H,icon:nm,color:"bg-destructive"},{label:"Abandonados",value:Dt,icon:Mi,color:"bg-muted"}].map((B,de)=>e.jsx(he,{children:e.jsx(ge,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`${B.color} p-2 rounded-lg shrink-0`,children:e.jsx(B.icon,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground truncate",children:B.label}),e.jsx("p",{className:"text-base font-bold text-foreground truncate",children:B.value})]})]})})},de))}),e.jsx(he,{children:e.jsxs(ge,{className:"pt-6",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-7 gap-4",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(At,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(Te,{placeholder:"Buscar por nome, email ou CPF...",value:x,onChange:B=>h(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),S())},className:"pl-10"})]}),e.jsx(w,{type:"button",variant:"outline",onClick:S,className:"shrink-0",children:"Pesquisar"})]})}),e.jsx("div",{children:e.jsx(Rr,{language:"pt-BR",showClearButton:!1,showTodayButton:!1,title:"De",theme:zl,value:Ce,onChange:B=>{const de=B instanceof Date&&!Number.isNaN(B.valueOf())?B:null,Re=de?ql(de):"";q(Re),L&&Re&&Re>L&&M(Re)},className:"w-full","aria-label":"Data inicial"})}),e.jsx("div",{children:e.jsx(Rr,{language:"pt-BR",showClearButton:!1,showTodayButton:!1,title:"Até",theme:zl,value:Ue,minDate:Ce||void 0,onChange:B=>{const de=B instanceof Date&&!Number.isNaN(B.valueOf())?B:null,Re=de?ql(de):"";M(Re),C&&Re&&Re<C&&q(Re)},className:"w-full","aria-label":"Data final"})}),e.jsx("div",{children:e.jsxs(rs,{value:I,onValueChange:g,children:[e.jsxs(ns,{className:"w-full",children:[e.jsx(Ci,{className:"mr-2 h-4 w-4"}),e.jsx(is,{placeholder:"Status"})]}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),e.jsx(xe,{value:"active",children:"Ativos"}),e.jsx(xe,{value:"with-orders",children:"Com pedidos"}),e.jsx(xe,{value:"no-orders",children:"Sem pedidos"})]})]})}),e.jsx("div",{children:e.jsxs(rs,{value:z,onValueChange:D,children:[e.jsxs(ns,{className:"w-full",children:[e.jsx(Ea,{className:"mr-2 h-4 w-4"}),e.jsx(is,{placeholder:"Tipo de item"})]}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos itens"}),e.jsx(xe,{value:"ingresso",children:"Ingressos"})]})]})}),e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(rs,{value:E,onValueChange:A,children:[e.jsxs(ns,{className:"w-full",children:[e.jsx(im,{className:"mr-2 h-4 w-4"}),e.jsx(is,{placeholder:"Ranking"})]}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),e.jsx(xe,{value:"top",children:"Top Compradores (10)"})]})]})}),e.jsx("div",{children:e.jsxs(rs,{value:N,onValueChange:b,children:[e.jsxs(ns,{className:"w-full",children:[e.jsx(Mi,{className:"mr-2 h-4 w-4"}),e.jsx(is,{placeholder:"Abandono"})]}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),e.jsx(xe,{value:"abandoned",children:"Somente abandonados"})]})]})})]}),e.jsxs("div",{className:"mt-4 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[(C||L||I!=="all"||z!=="all"||E!=="all"||N!=="all")&&e.jsx(w,{variant:"ghost",type:"button",size:"sm",onClick:()=>{q(""),M(""),g("all"),D("all"),A("all"),b("all")},className:"flex-1 md:flex-none",children:"Limpar filtros"}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-2 w-full md:w-auto",children:[e.jsxs(w,{variant:"outline",onClick:Os,className:"w-full md:w-auto",children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"})," Exportar Excel"]}),e.jsx(w,{variant:"outline",className:"w-full md:w-auto",disabled:!Xs.some(B=>ys[B.id]?.length),onClick:()=>dt(Xs),children:"Selecionar abandonados"}),e.jsxs(w,{className:"w-full md:w-auto",onClick:Hs,disabled:!0,children:[G?e.jsx(Cs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pr,{className:"h-4 w-4 mr-2"}),"Enviar email (Indisponível no momento)",G&&$.total?` (${$.sent}/${$.total})`:""]})]})]})]})}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{children:["Usuários (",st.length,")"]})}),e.jsx(ge,{children:st.length===0?e.jsx("div",{className:"text-center py-8",children:e.jsx("p",{className:"text-muted-foreground",children:"Nenhum usuário encontrado"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"md:hidden space-y-3",children:st.map(B=>{const de=Kt(B.id),Re=ws[B.id]||{},He=(()=>{try{return zt(B.attributes.createdAt)}catch{return null}})();return e.jsxs("div",{className:"rounded-lg border p-4 overflow-hidden",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsxs(nn,{className:"h-9 w-9 shrink-0",children:[B.attributes.avatar?.data&&e.jsx(Zn,{src:qt(B.attributes.avatar.data.attributes.url),alt:B.attributes.nome}),e.jsx(on,{children:Tt(B.attributes.nome)})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-foreground truncate",children:B.attributes.nome||"N/A"}),e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:B.attributes.email}),Ft(B.attributes.telefone)&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:Ft(B.attributes.telefone)})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Ja,{checked:re.has(B.id),onCheckedChange:()=>Bs(B.id),"aria-label":"Selecionar usuário"}),e.jsx(je,{variant:de.variant,className:`${de.className} whitespace-nowrap text-xs`,children:de.label})]})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-x-4 gap-y-1 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Pedidos:"})," ",e.jsx("span",{className:"font-medium",children:Re.totalOrders||0})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Pagos:"})," ",e.jsx("span",{className:"font-medium",children:Re.paidOrders||0})]}),m&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Total:"})," ",e.jsx("span",{className:"font-medium",children:Js(Re.totalSpent)}
3)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Criado:"})," ",e.jsx("span",{className:"font-medium",children:He?Us(He,"dd/MM/yyyy",{locale:Vs}):"—"}),He&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:Us(He,"HH:mm",{locale:Vs})})]})]}),ys[B.id]?.length?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-amber-700",children:[e.jsx(Mi,{className:"h-4 w-4"})," Carrinho abandonado (",ys[B.id].length,")"]}),ys[B.id].map(ps=>e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border p-2 bg-muted/40 overflow-hidden",children:[e.jsx("div",{className:"w-12 h-12 shrink-0 rounded-md overflow-hidden bg-muted",children:ps.imageUrl?e.jsx("img",{src:ps.imageUrl,alt:ps.eventTitle,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full text-xs text-muted-foreground",children:ps.eventTitle?.slice(0,2)||"EV"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:ps.eventTitle}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[ps.name," • ",ps.qty," un • ",ce(ps.price,ps.moeda)]}),e.jsx("div",{className:"text-xs text-amber-700 truncate",children:ps.reason})]})]},ps.id))]}):null,e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(w,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/dashboard/pedidos?search=${encodeURIComponent(B.attributes.email||B.attributes.nome||"")}`,children:[e.jsx(Vt,{className:"h-4 w-4 mr-1"})," Ver pedidos"]})}),ys[B.id]?.length?e.jsx(w,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`https://wa.me/${encodeURIComponent(ba(B.attributes.telefone))}?text=${encodeURIComponent(Pe(ys[B.id]))}`,target:"_blank",rel:"noreferrer",children:[e.jsx(si,{className:"h-4 w-4 mr-1"})," ",e.jsx("span",{className:"truncate",children:"WhatsApp"})]})}):null]})]},B.id)})}),e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"w-10",children:e.jsx(Ja,{"aria-label":"Selecionar todos",checked:st.every(B=>re.has(B.id))&&st.length>0,onCheckedChange:()=>{const B=st.every(de=>re.has(de.id));te(de=>{const Re=new Set(de);return B?st.forEach(He=>Re.delete(He.id)):st.forEach(He=>Re.add(He.id)),Re})}})}),e.jsx(ue,{children:"Usuário"}),e.jsx(ue,{children:"Email"}),e.jsx(ue,{children:"Telefone"}),e.jsx(ue,{children:"Pedidos"}),m&&e.jsx(ue,{children:"Total Gasto"}),e.jsx(ue,{children:"Abandono"}),e.jsx(ue,{children:"Status"}),e.jsx(ue,{children:"Criado em"}),e.jsx(ue,{children:"Ações"})]})}),e.jsx(Ct,{children:st.map(B=>{const de=Kt(B.id),Re=ws[B.id]||{},He=(()=>{try{return zt(B.attributes.createdAt)}catch{return null}})(),ps=ys[B.id]||[],vs=ps.length>0;return e.jsxs($s,{ref:Es=>{Es&&(oe.current[B.id]=Es)},children:[e.jsx(ye,{children:e.jsx(Ja,{checked:re.has(B.id),onCheckedChange:()=>Bs(B.id),"aria-label":"Selecionar usuário"})}),e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(nn,{className:"h-8 w-8",children:[B.attributes.avatar?.data&&e.jsx(Zn,{src:qt(B.attributes.avatar.data.attributes.url),alt:B.attributes.nome}),e.jsx(on,{children:Tt(B.attributes.nome)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-foreground",children:B.attributes.nome||"N/A"}),B.attributes.cpf&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["CPF: ",B.attributes.cpf]})]})]})}),e.jsx(ye,{children:e.jsx("div",{className:"text-sm text-foreground",children:B.attributes.email})}),e.jsx(ye,{children:e.jsx("div",{className:"text-sm text-foreground",children:Ft(B.attributes.telefone)||"N/A"})}),e.jsx(ye,{children:e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium",children:[Re.totalOrders||0," pedidos"]}),Re.paidOrders>0&&e.jsxs("div",{className:"text-accent text-xs",children:[Re.paidOrders," pagos"]})]})}),m&&e.jsx(ye,{className:"font-medium",children:Js(Re.totalSpent)}
3),e.jsx(ye,{children:vs?e.jsxs("div",{className:"space-y-1",children:[e.jsxs(je,{variant:"destructive",children:[ps.length," itens"]}),e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:ps.slice(0,4).map(Es=>e.jsx("div",{className:"w-12 h-12 rounded-md overflow-hidden bg-muted flex-shrink-0",children:Es.imageUrl?e.jsx("img",{src:Es.imageUrl,alt:Es.eventTitle,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full text-[10px] text-muted-foreground px-1 text-center",children:Es.eventTitle?.slice(0,6)||"Evento"})},Es.id))}),e.jsx("div",{className:"text-xs text-amber-700",children:ps[0]?.reason})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Nenhum"})}),e.jsx(ye,{children:e.jsx(je,{variant:de.variant,className:de.className,children:de.label})}),e.jsxs(ye,{children:[e.jsx("div",{className:"text-sm text-foreground",children:He?Us(He,"dd/MM/yyyy",{locale:Vs}):"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:He?Us(He,"HH:mm",{locale:Vs}):""})]}),e.jsx(ye,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(w,{variant:"ghost",size:"sm",asChild:!0,children:e.jsx("a",{href:`/dashboard/pedidos?search=${encodeURIComponent(B.attributes.email||B.attributes.nome||"")}`,children:e.jsx(Vt,{className:"h-4 w-4"})})}),e.jsx(w,{variant:"ghost",size:"sm",disabled:!vs||G,onClick:()=>Hs(B),"aria-label":"Enviar email de abandono",children:G?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):e.jsx(pr,{className:"h-4 w-4"})})]})})]},B.id)})})]})}),(Fs.pageCount>1||F&&Xs.length>Fe)&&e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:F?`Página ${Ae} de ${Math.ceil(Xs.length/Fe)||1} (${Xs.length} filtrados)`:`Página ${Fs.page} de ${Fs.pageCount} (${Fs.total} total)`}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(w,{variant:"outline",size:"sm",onClick:()=>be(B=>Math.max(1,B-1)),disabled:F?Ae<=1:Fs.page<=1,children:"Anterior"}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>be(B=>B+1),disabled:!F&&Fs.page>=Fs.pageCount||F&&(()=>{const B=Number(Fs.pageCount||0),de=fe<=B,Re=st.length>=Fe;if(_e||!Re&&de)return!0;const He=Ae*Fe;return!de&&Xs.length<=He})(),children:"Próxima"})]})]})]})})]})]}),e.jsx(at,{open:Is,onOpenChange:Y,children:e.jsxs(rt,{className:"max-w-xl max-h-[85vh] flex flex-col",children:[e.jsx(nt,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Li,{className:"h-5 w-5"}),"Permissões de Formulários por Evento"]})}),e.jsxs("p",{className:"text-sm text-muted-foreground -mt-1",children:["Usuários com perfis customizados podem ter acesso restrito a formulários de palestrantes baseado nos eventos que selecionarmos para eles. Clique em ",e.jsx("strong",{children:"Configurar"})," para definir quais eventos cada um pode visualizar."]}),e.jsxs("div",{className:"overflow-y-auto flex-1 mt-2",children:[V&&e.jsxs("div",{className:"flex items-center gap-2 py-6 justify-center text-sm text-muted-foreground",children:[e.jsx(Cs,{className:"h-4 w-4 animate-spin"})," Carregando usuários…"]}),!V&&Q.length===0&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"Nenhum usuário com perfil customizado encontrado."}),!V&&Q.length>0&&e.jsx("div",{className:"divide-y",children:Q.map(B=>{const de=B.attributes||{},{roleName:Re,roleType:He}=Dc(de),ps=Re||He||"—",vs=ko(de),Es=de.podeVerFormularios===!0,cs=Es&&!!de.restringirFormularios,qs=Array.isArray(de.eventosSelecionados)?de.eventosSelecionados.length:0,Qs=qs===1?"evento":"eventos";return e.jsxs("div",{className:"flex items-center justify-between gap-3 py-3 px-1",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:de.nome||de.email||`#${B.id}`}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:de.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(je,{variant:"secondary",className:"text-xs",children:ps}),Es?cs?e.jsx(je,{variant:"outline",className:"text-xs border-amber-400 text-amber-700 dark:text-amber-400",children:`Restrito · ${qs} ${Qs}`}):vs?e.jsx(je,{variant:"outline",className:"text-xs text-muted-foreground",children:"Todos exceto Palestras"}):e.jsx(je,{variant:"outline",className:"text-xs text-muted-foreground",children:"Acesso total"}):e.jsx(je,{variant:"destructive",className:"text-xs",children:"Sem acesso"})]})]}),e.jsx(w,{variant:"outline",size:"sm",className:"shrink-0",onClick:()=>va(B),children:"Configurar"})]},B.id)})})]}),e.jsx(Ut,{className:"mt-3",children:e.jsx(w,{variant:"outline",onClick:()=>Y(!1),children:"Fechar"})})]})}),e.jsx(at,{open:Ee,onOpenChange:Se,children:e.jsxs(rt,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsx(nt,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Li,{className:"h-5 w-5"}),"Permissões – Formulários de Palestra"]})}),Ze&&e.jsxs("div",{className:"text-sm text-muted-foreground -mt-1 mb-2",children:["Usuário: ",e.jsx("span",{className:"font-medium text-foreground",children:Ze.attributes?.nome||Ze.attributes?.email||`#${Ze.id}`})]}),e.jsxs("div",{className:"flex flex-col gap-4 overflow-y-auto flex-1 pr-1",children:[e.jsxs("div",{className:`flex items-center justify-between rounded-lg border p-4 ${De?"":"border-destructive/40 bg-destructive/5"}`,children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Permitir acesso à aba Formulários"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Quando desativado, este usuário não poderá visualizar a aba de Formulários de Palestra."})]}),e.jsx(Ls,{checked:De,onCheckedChange:Ne,"aria-label":"Permitir acesso à aba Formulários"})]}
3),e.jsxs("div",{className:`flex flex-col gap-4 ${De?"":"opacity-40 pointer-events-none select-none"}`,children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Restringir por evento"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Quando ativo, este usuário vê apenas formulários dos eventos selecionados abaixo. Quando desativado, o usuário vê formulários de todos os eventos."})]}),e.jsx(Ls,{checked:Qe,onCheckedChange:we,"aria-label":"Ativar restrição por evento"})]}),e.jsxs("div",{className:Qe?"":"opacity-40 pointer-events-none select-none",children:[e.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center justify-between",children:[e.jsx("span",{children:"Eventos permitidos"}),Qe&&es.length>0&&e.jsxs("div",{className:"flex gap-2 text-xs",children:[e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>ks(new Set(Gi(es,Ze?.attributes||Ze||{}))),children:ko(Ze?.attributes||Ze||{})?"Todos exceto Palestras":"Todos"}),e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>ks(new Set),children:"Nenhum"})]})]}),We&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-3",children:[e.jsx(Cs,{className:"h-4 w-4 animate-spin"})," Carregando eventos…"]}),!We&&es.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground py-2",children:"Nenhum evento encontrado. Verifique as permissões da API de eventos."}),e.jsx("div",{className:"grid grid-cols-1 gap-1 max-h-64 overflow-y-auto",children:es.map(B=>e.jsxs("label",{className:"flex items-center gap-3 rounded-md px-3 py-2 hover:bg-accent cursor-pointer text-sm",children:[e.jsx(Ja,{checked:Me.has(B.id),onCheckedChange:()=>da(B.id),"aria-label":B.titulo}),e.jsx("span",{className:"flex-1 truncate",children:B.titulo}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:["#",B.id]})]},B.id))}),Qe&&Me.size===0&&!We&&e.jsx("div",{className:"mt-2 text-xs text-amber-600 font-medium",children:"⚠ Nenhum evento selecionado — o usuário não verá nenhum formulário."})]})]})]}),e.jsxs(Ut,{className:"mt-4",children:[e.jsx(w,{variant:"outline",onClick:()=>Se(!1),disabled:xs,children:"Cancelar"}),e.jsxs(w,{onClick:la,disabled:xs,children:[xs?e.jsx(Cs,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Salvar permissões"]})]})]})})]})}const vr="/estoques",ah=["id","documentId","nomeProdutoFisico","descricao","preco","desconto","quantidade","updatedAt"],rh=["id","url","alternativeText","caption","previewUrl","formats","mime","size","width","height"],Pc=(()=>{const s=new URLSearchParams;return ah.forEach((t,a)=>{s.append(`fields[${a}]`,t)}),rh.forEach((t,a)=>{s.append(`populate[imagem][fields][${a}]`,t)}),s.append("populate[categoria][fields][0]","id"),s.append("populate[categoria][fields][1]","nome"),s.append("populate[categoria][fields][2]","documentId"),s.append("populate[evento][fields][0]","id"),s.append("populate[evento][fields][1]","documentId"),s.append("populate[evento][fields][2]","titulo"),s.toString()})(),nh=(s={})=>{const{q:t="",sort:a="updatedAt:desc",categoriaId:n="",eventoId:o=""}=s;let i=`${vr}?sort=${encodeURIComponent(a)}`;return t&&(i+=`&filters[nomeProdutoFisico][$containsi]=${encodeURIComponent(t)}`),n&&(i+=`&filters[categoria][id][$eq]=${encodeURIComponent(n)}`),o&&(i+=`&filters[evento][id][$eq]=${encodeURIComponent(o)}`),i+=`&${Pc}`,Rt({queryKey:["estoque",{q:t,sort:a,categoriaId:n,eventoId:o}],queryFn:async()=>(await $e.get(i)).data,select:u=>u?.data||[]})},ih=()=>{const s=na();return fa({mutationFn:async(t={})=>(await $e.post(vr,{data:t})).data,onSuccess:()=>s.invalidateQueries({queryKey:["estoque"]})})},oh=()=>{const s=na();return fa({mutationFn:async({id:t,delta:a})=>(await $e.post(`${vr}/${t}/adjust`,{delta:a})).data,onMutate:async({id:t,delta:a})=>{await s.cancelQueries({queryKey:["estoque"]});const n=[];return s.setQueriesData({queryKey:["estoque"]},o=>{if(!Array.isArray(o))return o;const i=o;return n.push(i),o.map(u=>u?.id===t?{...u,quantidade:Math.max(0,(u.quantidade||0)+a)}:u)}),{snapshots:n}},onError:(t,a,n)=>{n?.snapshots&&s.invalidateQueries({queryKey:["estoque"]})},onSettled:()=>s.invalidateQueries({queryKey:["estoque"]})})},lh=()=>{const s=na();return fa({mutationFn:async({id:t,documentId:a,data:n})=>{try{return(await $e.put(`${vr}/${t}`,{data:n})).data}catch(o){if(o?.response?.status===404&&a)return(await $e.put(`${vr}/by-document/${encodeURIComponent(a)}`,{data:n})).data;throw o}},onSuccess:()=>s.invalidateQueries({queryKey:["estoque"]})})},dh=()=>{const s=na();return fa({mutationFn:async({id:t,documentId:a})=>{if(a)return(await $e.delete(`${vr}/by-document/${encodeURIComponent(a)}`)).data;if(t)return(await $e.delete(`${vr}/${t}`)).data;throw new Error("id or documentId is required")},onSuccess:()=>{s.invalidateQueries({queryKey:["estoque"]}),s.invalidateQueries({queryKey:["estoque-logs"]})}})},ch=(s,t=50)=>Rt({queryKey:["estoque-logs",s,t],enabled:!!s,queryFn:async()=>(await $e.get(`/estoque-logs?filters[estoqueId][$eq]=${s}&sort=createdAt:desc&pagination[pageSize]=${t}`)).data,select:a=>
3a?.data||[]}),uh=(s=100)=>Rt({queryKey:["estoque-logs","collection",s],queryFn:async()=>(await $e.get(`/estoque-logs?sort=createdAt:desc&pagination[pageSize]=${s}`)).data,select:t=>t?.data||[]}),Rc=()=>Rt({queryKey:["estoque-categorias"],queryFn:async()=>(await $e.get("/estoque-categorias?sort=nome:asc&pagination[pageSize]=500")).data,select:s=>s?.data||[]}),mh=()=>{const s=na();return fa({mutationFn:async({nome:t,descricao:a})=>(await $e.post("/estoque-categorias",{data:{nome:t,descricao:a}})).data,onSuccess:()=>s.invalidateQueries({queryKey:["estoque-categorias"]})})},xh={criar:"Criar",renomear:"Renomear",definir:"Definir",ajustar:"Ajustar",excluir:"Excluir",editar:"Editar",alternar:"Alternar",atualizar:"Atualizar",create:"Criar",rename:"Renomear",set:"Definir",adjust:"Ajustar",delete:"Excluir",toggle:"Alternar",update:"Atualizar"},ph={nome:"Nome",nomeProdutoFisico:"Nome do produto",quantidade:"Quantidade",preco:"Preço",desconto:"Desconto",descricao:"Descrição",alcoolico:"Alcoólico",ativo:"Ativo",categoria:"Categoria",evento:"Evento",imagem:"Imagem"};function Ei({logs:s=[]}){return!Array.isArray(s)||s.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sem registros"}):e.jsx("div",{className:"space-y-3",children:s.map(t=>e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium text-foreground",children:new Date(t.createdAt).toLocaleString("pt-BR")}),e.jsx("div",{className:"text-muted-foreground",children:(()=>{const a=[];t.action&&a.push(`Ação: ${xh[t.action]||t.action}`),t.field&&a.push(`Campo: ${ph[t.field]||t.field}`);const n=t.nomeProdutoFisico||t.nome;return n&&a.push(`Item: ${n}`),typeof t.delta=="number"&&a.push(`Δ ${t.delta}`),(typeof t.prev=="number"||typeof t.next=="number")&&a.push(`${t.prev??""} → ${t.next??""}`),(t.prevText||t.nextText)&&a.push(`"${t.prevText??""}" → "${t.nextText??""}"`),t.actorEmail&&a.push(`por ${t.actorEmail}`),a.join(", ")})()})]},t.id))})}function hh(){const s=zd(),[t,a]=r.useState(""),[n,o]=r.useState("updatedAt:desc"),[i,u]=r.useState(!1),[l,c]=r.useState(""),[m,x]=r.useState(0),[h,p]=r.useState(""),[f,I]=r.useState("0"),[g,N]=r.useState(""),{data:b=[]}=Rc(),C=mh(),[q,L]=r.useState(""),[M,z]=r.useState(null),[D,E]=r.useState(null),[A,S]=r.useState(!1),[P,F]=r.useState(null),[ee,re]=r.useState(""),[te,G]=r.useState(""),[y,$]=r.useState(null),[W,ie]=r.useState(""),[ke,Ae]=r.useState("0"),[be,Fe]=r.useState(""),[ae,K]=r.useState(""),{data:O=[]}=nh({q:t,sort:n,categoriaId:be,eventoId:ae}),[oe,ve]=r.useState([]);fn.useEffect(()=>{$e.get("/eventos?fields=id,documentId,titulo&pagination[pageSize]=200").then(T=>ve(T?.data?.data||[])).catch(()=>ve([]))},[]);const me=ih(),fe=oh(),le=lh(),_e=dh(),U=r.useMemo(()=>O,[O]),J=[-10,-5,-1,1,5,10];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Estoque"}),e.jsx("p",{className:"text-muted-foreground",children:"Gerencie produtos físicos e quantidades"})]}),e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-2",children:[e.jsxs(at,{open:i,onOpenChange:u,children:[e.jsx(vn,{asChild:!0,children:e.jsxs(w,{children:[e.jsx(et,{className:"mr-2 h-4 w-4"})," Novo produto"]})}),e.jsxs(rt,{children:[e.jsx(nt,{children:e.jsx(it,{children:"Novo produto"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Nome"}),e.jsx(Te,{value:l,onChange:T=>c(T.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Preço (R$)"}),e.jsx(Te,{type:"number",step:"0.01",min:0,value:h,onChange:T=>p(T.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Desconto (%)"}),e.jsx(Te,{type:"number",step:"0.1",min:0,max:100,value:f,onChange:T=>I(T.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Quantidade inicial"}),e.jsx(Te,{type:"number",min:0,value:m,onChange:T=>x(parseInt(T.target.value||"0",10))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm",children:"Categoria"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("select",{className:"border rounded px-2 py-1 
3w-full bg-background",value:g,onChange:T=>N(T.target.value),children:[e.jsx("option",{value:"",children:"— Selecione —"}),b.map(T=>e.jsx("option",{value:T.id,children:T.nome},T.id))]}),e.jsx(w,{type:"button",variant:"outline",onClick:async()=>{const T=await s.prompt("Nome da nova categoria:");if(!T)return;const Se=(await C.mutateAsync({nome:String(T).trim()}))?.data?.id;Se&&N(String(Se))},children:"Nova"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Evento"}),e.jsxs("select",{className:"border rounded px-2 py-1 w-full bg-background",value:q,onChange:T=>L(T.target.value),children:[e.jsx("option",{value:"",children:"— Nenhum —"}),oe.map(T=>e.jsx("option",{value:T.id,children:T.titulo},T.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Imagem"}),e.jsx("input",{className:"border rounded px-2 py-1 w-full bg-background",type:"file",accept:"image/*",onChange:T=>z(T.target.files?.[0]||null)})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(w,{variant:"outline",onClick:()=>u(!1),children:"Cancelar"}),e.jsx(w,{onClick:async()=>{let T;if(M){const Ze=new FormData;Ze.append("files",M),T=(await $e.post("/upload",Ze,{headers:{"Content-Type":"multipart/form-data"}}))?.data?.[0]?.id}const Ee=Math.max(0,Number(String(h).replace(",","."))||0),Se=Math.min(100,Math.max(0,Number(String(f).replace(",","."))||0));await me.mutateAsync({nomeProdutoFisico:l.trim(),quantidade:Math.max(0,Number(m)||0),preco:Ee,desconto:Se,categoria:g?Number(g):void 0,evento:q?Number(q):void 0,imagem:T}),c(""),x(0),p(""),I("0"),N(""),L(""),z(null),u(!1)},disabled:!l.trim(),children:"Salvar"})]})]})]})]}),e.jsxs(w,{variant:"outline",onClick:()=>S(!0),children:[e.jsx(xo,{className:"mr-2 h-4 w-4"})," Histórico geral"]})]})]}),e.jsx(he,{children:e.jsxs(ge,{className:"pt-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[e.jsx(Te,{placeholder:"Buscar produto…",value:t,onChange:T=>a(T.target.value),className:"sm:max-w-xs"}),e.jsxs("select",{className:"border rounded-lg px-2 py-1 bg-background",value:be,onChange:T=>Fe(T.target.value),children:[e.jsx("option",{value:"",children:"Todas categorias"}),b.map(T=>e.jsx("option",{value:T.id,children:T.nome},T.id))]}),e.jsxs("select",{className:"border rounded-lg px-2 py-1 bg-background",value:ae,onChange:T=>K(T.target.value),children:[e.jsx("option",{value:"",children:"Todos eventos"}),oe.map(T=>e.jsx("option",{value:T.id,children:T.titulo},T.id))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:"Ordenar:"}),e.jsx(w,{size:"sm",variant:n==="updatedAt:desc"?"default":"outline",onClick:()=>o("updatedAt:desc"),children:"Atualizado"}),e.jsx(w,{size:"sm",variant:n==="quantidade:desc"?"default":"outline",onClick:()=>o("quantidade:desc"),children:"Qtd ↓"}),e.jsx(w,{size:"sm",variant:n==="quantidade:asc"?"default":"outline",onClick:()=>o("quantidade:asc"),children:"Qtd ↑"})]})]}),U.length===0?e.jsx("div",{className:"text-center py-10 text-muted-foreground",children:"Nenhum item encontrado"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{}),e.jsx(ue,{children:"Produto"}),e.jsx(ue,{children:"Categoria"}),e.jsx(ue,{children:"Evento"}),e.jsx(ue,{children:"Preço"}),e.jsx(ue,{children:"Quantidade"}),e.jsx(ue,{children:"Atualizado"}),e.jsx(ue,{className:"text-right",children:"Ações"})]})}),e.jsx(Ct,{children:U.map(T=>{const Ee=Number(T.preco??T.attributes?.preco??0),Se=Math.min(100,Math.max(0,Number(T.desconto??T.attributes?.desconto??0))),Ze=Number((Ee*(1-Se/100)).toFixed(2));return e.jsxs($s,{children:[e.jsx(ye,{children:T.imagem?.url?e.jsx("img",{src:T.imagem.url,alt:"imagem",className:"h-12 w-12 object-cover rounded"}):"—"}),e.jsx(ye,{className:"max-w-[320px]",children:e.jsx("div",{className:"truncate font-medium text-foreground",title:T.nomeProdutoFisico,children:T.nomeProdutoFisico})}),e.jsx(ye,{className:"max-w-[200px]",children:e.jsx("div",{className:"truncate",title:T.categoria?.nome||"",children:T.categoria?.nome||"—"})}),e.jsx(ye,{className:"max-w-[260px]",children:e.jsx("div",{className:"truncate",title:T.evento?.titulo||"",children:T.evento?.titulo||"—"})}),e.jsx(ye,{className:"whitespace-nowrap",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:aa(Ze)}),Se>0&&e.jsx("span",{className:"text-xs text-muted-foreground line-through",children:aa(Ee)})]})}),e.jsx(ye,{children:e.jsx(je,{variant:"secondary",className:"text-base px-3 py-1",children:T.quantidade??0})}),e.jsx(ye,{className:"text-sm text-muted-foreground",children:new Date(T.updatedAt).toLocaleStr
3ing("pt-BR")}),e.jsxs(ye,{className:"text-right",children:[e.jsx("div",{className:"inline-flex flex-wrap gap-1 mr-2 align-middle",children:J.map(qe=>e.jsx(w,{size:"sm",variant:"ghost","aria-label":qe>0?`Adicionar ${qe}`:`Remover ${Math.abs(qe)}`,onClick:()=>fe.mutate({id:T.id,delta:qe}),disabled:fe.isPending,children:qe>0?`+${qe}`:qe},qe))}),e.jsxs(Sr,{children:[e.jsx(Ir,{asChild:!0,children:e.jsx(w,{size:"icon",variant:"outline","aria-label":"Mais ações",children:e.jsx(ai,{className:"h-4 w-4"})})}),e.jsxs(Ar,{align:"end",children:[e.jsx(tt,{onSelect:()=>E(T.id),children:"Ver histórico…"}),e.jsx(tt,{onSelect:async()=>{const qe=await s.prompt("Definir quantidade para:",String(T.quantidade??0));if(qe==null)return;const Qe=Math.max(0,parseInt(qe,10)||0);le.mutate({id:T.id,documentId:T.documentId,data:{quantidade:Qe}})},children:"Definir quantidade…"}),e.jsx(tt,{onSelect:async()=>{const qe=await s.prompt("Definir preço (R$):",String(T.preco??0));if(qe==null)return;const Qe=Math.max(0,Number(String(qe).replace(",","."))||0);le.mutate({id:T.id,documentId:T.documentId,data:{preco:Qe}})},children:"Definir preço…"}),e.jsx(tt,{onSelect:async()=>{const qe=await s.prompt("Renomear produto:",T.nomeProdutoFisico||"");if(qe==null)return;const Qe=String(qe).trim();Qe&&le.mutate({id:T.id,documentId:T.documentId,data:{nomeProdutoFisico:Qe}})},children:"Renomear…"}),e.jsx(tt,{onSelect:()=>{F(T),re(T.categoria?.id?String(T.categoria.id):""),G(T.evento?.id?String(T.evento.id):""),$(null),ie(String(T.preco??0))},children:"Editar detalhes…"}),e.jsx(tt,{className:"text-destructive",onSelect:async qe=>{qe.preventDefault(),await s.confirm("Excluir este item do estoque?")&&_e.mutate({id:T.id,documentId:T.documentId})},children:"Excluir"})]})]})]})]},T.id)})})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:U.map(T=>{const Ee=Number(T.preco??T.attributes?.preco??0),Se=Math.min(100,Math.max(0,Number(T.desconto??T.attributes?.desconto??0))),Ze=Number((Ee*(1-Se/100)).toFixed(2));return e.jsxs("div",{className:"border rounded-xl p-3 bg-card/50",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[T.imagem?.url?e.jsx("img",{src:T.imagem.url,alt:"imagem",className:"h-14 w-14 object-cover rounded"}):e.jsx("div",{className:"h-14 w-14 rounded bg-muted/50 flex items-center justify-center text-xs text-muted-foreground",children:"—"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium text-foreground truncate",title:T.nomeProdutoFisico,children:T.nomeProdutoFisico}),e.jsxs("div",{className:"text-sm text-muted-foreground truncate",children:[T.categoria?.nome||"—"," · ",T.evento?.titulo||"—"]}
3),e.jsxs("div",{className:"mt-1 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:aa(Ze)}),Se>0&&e.jsx("div",{className:"text-xs text-muted-foreground line-through",children:aa(Ee)})]}),e.jsx(je,{variant:"secondary",className:"text-sm px-2 py-0.5",children:T.quantidade??0})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Atualizado: ",new Date(T.updatedAt).toLocaleString("pt-BR")]})]}),e.jsxs(Sr,{children:[e.jsx(Ir,{asChild:!0,children:e.jsx(w,{size:"icon",variant:"ghost","aria-label":"Mais ações",children:e.jsx(ai,{className:"h-4 w-4"})})}),e.jsxs(Ar,{align:"end",children:[e.jsx(tt,{onSelect:()=>E(T.id),children:"Ver histórico…"}),e.jsx(tt,{onSelect:async()=>{const qe=await s.prompt("Definir quantidade para:",String(T.quantidade??0));if(qe==null)return;const Qe=Math.max(0,parseInt(qe,10)||0);le.mutate({id:T.id,documentId:T.documentId,data:{quantidade:Qe}})},children:"Definir quantidade…"}),e.jsx(tt,{onSelect:async()=>{const qe=await s.prompt("Definir preço (R$):",String(T.preco??0));if(qe==null)return;const Qe=Math.max(0,Number(String(qe).replace(",","."))||0);le.mutate({id:T.id,documentId:T.documentId,data:{preco:Qe}})},children:"Definir preço…"}),e.jsx(tt,{onSelect:async()=>{const qe=await s.prompt("Renomear produto:",T.nomeProdutoFisico||"");if(qe==null)return;const Qe=String(qe).trim();Qe&&le.mutate({id:T.id,documentId:T.documentId,data:{nomeProdutoFisico:Qe}})},children:"Renomear…"}),e.jsx(tt,{onSelect:()=>{F(T),re(T.categoria?.id?String(T.categoria.id):""),G(T.evento?.id?String(T.evento.id):""),$(null);const qe=Number(T.preco??T.attributes?.preco??0),Qe=Number(T.desconto??T.attributes?.desconto??0);ie(String(qe)),Ae(String(Qe))},children:"Editar detalhes…"}),e.jsx(tt,{className:"text-destructive",onSelect:async qe=>{qe.preventDefault(),await s.confirm("Excluir este item do estoque?")&&_e.mutate({id:T.id,documentId:T.documentId})},children:"Excluir"})]})]})]}),e.jsx("div",{className:"mt-3 -mx-1 overflow-x-auto",children:e.jsx("div",{className:"flex gap-1 px-1",children:J.map(qe=>e.jsx(w,{size:"sm",variant:"outline",className:"shrink-0","aria-label":qe>0?`Adicionar ${qe}`:`Remover ${Math.abs(qe)}`,onClick:()=>fe.mutate({id:T.id,delta:qe}),disabled:fe.isPending,children:qe>0?`+${qe}`:qe},qe))})})]},T.id)})})]})]})}),e.jsx(gh,{openId:D,onClose:()=>E(null)}),e.jsx(fh,{open:A,onClose:()=>S(!1)}),e.jsx(at,{open:!!P,onOpenChange:T=>{T||(F(null),$(null),ie(""),Ae("0"))},children:e.jsxs(rt,{children:[e.jsx(nt,{children:e.jsx(it,{children:"Editar detalhes"})}),P&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Preço (R$)"}),e.jsx(Te,{type:"number",step:"0.01",min:0,value:W,onChange:T=>ie(T.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Desconto (%)"}),e.jsx(Te,{type:"number",step:"0.1",min:0,max:100,value:ke,onChange:T=>Ae(T.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Categoria"}),e.jsxs("select",{className:"border rounded px-2 py-1 w-full bg-background",value:ee,onChange:T=>re(T.target.value),children:[e.jsx("option",{value:"",children:"— Nenhuma —"}),b.map(T=>e.jsx("option",{value:T.id,children:T.nome},T.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Evento"}),e.jsxs("select",{className:"border rounded px-2 py-1 w-full bg-background",value:te,onChange:T=>G(T.target.value),children:[e.jsx("option",{value:"",children:"— Nenhum —"}),oe.map(T=>e.jsx("option",{value:T.id,children:T.titulo},T.id))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm",children:"Imagem"}),e.jsxs("div",{className:"flex items-center gap-3",children:[P.imagem?.url?e.jsx("img",{src:P.imagem.url,alt:"imagem",className:"h-12 w-12 object-cover rounded"}):e.jsx("span",{className:"text-muted-foreground",children:"— Sem imagem —"}),e.jsx("input",{type:"file",accept:"image/*",onChange:T=>$(T.target.files?.[0]||null)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(w,{variant:"outline",onClick:()=>{F(null),$(null),ie(""),Ae("0")},children:"Cancelar"}),e.jsx(w,{onClick:async()=>{let T;if(y){const qe=new FormData;qe.append("files",y),T=(await $e.post("/upload",qe,{headers:{"Content-Type":"multipart/form-data"}}))?.data?.[0]?.id}const Ee={},Se=Math.max(0,Number(String(W).replace(",","."))||0),Ze=Math.min(100,Math.max(0,Number(String(ke).replace(",","."))||0));Ee.preco=Se,Ee.desconto=Ze,ee?Ee.categoria=Number(ee):Ee.categoria=null,te?Ee.evento=Number(te):Ee.evento=null,T!==void 0&&(Ee.imagem=T),await le.mutateAsync({id:P.id,documentId:P.documentId,data:Ee}),F(null),$(null),ie(""),Ae("0")},children:"Salvar"})]})]})]})})]})}function gh({openId:s,onClose:t}){const{data:a=[]}=ch(s||0);return e.jsx(at,{open:!!s,onOpenChange:n=>!n&&t?.(),children:e.jsxs(rt,{className:"max-w-2xl",children:[e.jsx(nt,{children:e.jsx(it,{children:"Histórico do produto"})}),e.jsx("div",{className:"max-h-[60vh] overflow-auto",children:e.jsx(Ei,{logs:a})})]})})}function fh({open:s,onClose:t,limit:a=100}){const{data:n=[]}=uh(a);return e.jsx(at,{open:!!s,onOpenChange:o=>!o&&t?.(),children:e.jsxs(rt,{className:"max-w-3xl",children:[e.jsx(nt,{children:e.jsx(it,{children:"Histórico geral do estoque"})}),e.jsx("div",{className:"max-h-[60vh] overflow-auto",children:e.jsx(Ei,{logs:n})})]})})}const jh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Hi=s=>typeof s=="string"&&jh.test(s.trim()),Ko=s=>{if(!s)return null;try{const t=String(s).length===10?`${s}T12:00:00`:s;return Us(zt(t),"dd/MM/yyyy",{locale:Vs})}catch{return String(s)}},vh=s=>{const t=s?.attributes||s,a=Array.isArray(t?.lotes?.data)?t.lotes.data.map(n=>({id:n.id,...n.attributes||n})):Array.isArray(t?.lotes)?t.lotes:[];return{id:s.id,documentId:t?.documentId||null,titulo:t?.titulo||"—",posGroupId:t?.posGroupId||null,data_evento:t?.data_evento||null,lotes:a.map(n=>({id:n.id,nome:n.nome||"—",preco_lote:n.preco_lote??null,ativo:n.ativo??!1,quantidade_disponivel:Number(n.quantidade_disponivel??0),posProductId:n.posProductId||null}))}},Tc=({src:s,alt:t=""})=>{const[a,n]=r.useState(!1);if(!s||a)return e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md border bg-muted text-muted-foreground",children:e.jsx(mo,{className:"h-4 w-4"})});const o=s.startsWith("data:")||s.startsWith("http")?s:`data:image/jpeg;base64,${s}`;return e.jsx("img",{src:o,alt:t,className:"h-10 w-10 shrink-0 rounded-md border object-cover",onError:()=>n(!0)})};Tc.propTypes={src:se.string,alt:se.string};const bh=()=>{const[s,t]=r.useState([]),[a,n]=r.useState(!1),[o,i]=r.useState(null),[u,l]=r.useState(new Set),[c,m]=r.useState({}),[x,h]=r.useState({}),[p,f]=r.useState([]),[I,g]=r.useState(!1),[N,b]=r.useState({}),C=r.useCallback(async()=>{n(!0),i(null);try{const E=await $e.get("/eventos?populate[lotes]=*&sort=titulo:asc&publicationState=preview&pagination[pageSize]=200"),A=Array.isArray(E?.data?.data)?E.data.data:Array.isArray(E?.data)?E.data:[];t(A.map(vh))}
3catch(E){i(E?.response?.data?.error?.message||E?.message||"Erro ao carregar eventos")}finally{n(!1)}},[]);r.useEffect(()=>{C()},[C]);const q=async()=>{if(!(p.length>0||I)){g(!0);try{const A=(await $e.get("/pos/productgroups"))?.data?.data||[];f(A.map(S=>({id:S?.id??S?.ProductGroup?.ProductGroupID??S?.ProductGroupID??"",name:S?.name??S?.ProductGroup?.Name??S?.Name??"?"})).filter(S=>S.id))}catch{}finally{g(!1)}}},L=E=>{l(A=>{const S=new Set(A);return S.has(E)?S.delete(E):S.add(E),S}),q()},M=async E=>{const A=E.documentId||String(E.id);m(S=>({...S,[A]:{loading:!0,result:null}}));try{const P=(await $e.post(`/pos/evento/${A}/push`,{forceActive:!1}))?.data||{};m(F=>({...F,[A]:{loading:!1,result:{ok:P.ok!==!1,message:P.ok!==!1?`${P.pushed??0} produto(s) enviado(s)`:P.error||"Falha ao enviar"}}})),P.ok!==!1&&await C()}catch(S){const P=S?.response?.data?.error?.message||S?.message||"Falha ao enviar";m(F=>({...F,[A]:{loading:!1,result:{ok:!1,message:P}}}))}},z=async E=>{h(A=>({...A,[E.id]:{loading:!0,result:null}}));try{await $e.post(`/pos/lote/${E.id}/deregister`),h(A=>({...A,[E.id]:{loading:!1,result:{ok:!0,message:"Vínculo removido"}}})),await C()}catch(A){const S=A?.response?.data?.error?.message||A?.message||"Falha ao remover vínculo";h(P=>({...P,[E.id]:{loading:!1,result:{ok:!1,message:S}}}))}},D=async E=>{const A=E.documentId||String(E.id),S=N[A]||{},P=S.selectedId||"";if(P){b(F=>({...F,[A]:{...S,loading:!0,result:null}}));try{const ee=(await $e.post(`/pos/evento/${A}/assign-group`,{groupId:P}))?.data||{};b(re=>({...re,[A]:{...re[A],loading:!1,result:{ok:ee.ok!==!1,message:ee.ok!==!1?"Grupo atribuído ✓":ee.error||"Falha ao atribuir"}}})),ee.ok!==!1&&await C()}catch(F){const ee=F?.response?.data?.error?.message||F?.message||"Falha ao atribuir grupo";b(re=>({...re,[A]:{...re[A],loading:!1,result:{ok:!1,message:ee}}}))}}};return e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between gap-2 pb-4",children:[e.jsxs("div",{children:[e.jsx(ze,{className:"text-base font-semibold",children:"Eventos POS"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:['Estado dos lotes no POS Controle. "Enviar" cria ou atualiza o produto no POS; o ícone ',e.jsx(po,{className:"inline h-3 w-3"})," remove apenas o vínculo interno (não apaga do POS)."]})]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:C,disabled:a,className:"shrink-0",children:[a?e.jsx(It,{size:14}):e.jsx(qo,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Atualizar"})]})]}),e.jsx(ge,{className:"space-y-2 pt-0",children:o?e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(tr,{className:"h-4 w-4 shrink-0"})," ",o]}):a&&s.length===0?e.jsxs("div",{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[e.jsx(It,{size:16})," Carregando eventos…"]}):s.length===0?e.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:"Nenhum evento encontrado."}):s.map(E=>{const A=E.documentId||String(E.id),S=u.has(E.id),P=c[A]||{},F=E.lotes.filter(ee=>Hi(ee.posProductId)).length;return e.jsxs("div",{className:"rounded-lg border overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>L(E.id),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-muted/40 transition-colors",children:[S?e.jsx(ra,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(er,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:E.titulo}),E.data_evento?e.jsx("p",{className:"text-xs text-muted-foreground",children:Ko(E.data_evento)}):null]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",onClick:ee=>ee.stopPropagation(),children:[Hi(E.posGroupId)?e.jsx(je,{variant:"outline",className:"text-xs text-green-700 border-green-500 hidden sm:flex",children:"Grupo ✓"}):e.jsx(je,{variant:"outline",className:"text-xs text-muted-foreground hidden sm:flex",children:"Sem grupo"}),e.jsxs(je,{variant:"secondary",className:"text-xs",children:[F,"/",E.lotes.length," lote",E.lotes.length!==1?"s":""]}),e.jsxs(w,{size:"sm",disabled:P.loading,onClick:()=>M(E),className:"h-7 text-xs",children:[P.loading?e.jsx(It,{size:12}):e.jsx(qa,{className:"h-3 w-3"}),e.jsx("span",{className:"ml-1.5",children:"Enviar"})]})]})]}),P.result?e.jsx("div",{className:`px-12 pb-2 -mt-1 text-xs ${P.result.ok?"text-green-700":"text-destructive"}`,children:P.result.message}):null,S?e.jsxs("div",{className:"border-t bg-muted/20 px-4 py-3 space-y-2",children:[(()=>{const ee=N[A]||{},re=p.find(te=>te.id===E.posGroupId);return e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pb-2 mb-1 border-b border-border/50",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground shrink-0",children:"Grupo POS:"}),re?e.jsx(je,{variant:"outline",className:"text-xs text-green-700 border-green-500 shrink-0",children:re.name}):E.posGroupId?e.jsxs(je,{variant:"outline",className:"text-xs shrink-0 font-mono",children:[E.posGroupId.slice(0,8),"…"]}):e.jsx("span",{className:"text-xs text-muted-foreground italic shrink-0",children:"Sem grupo"}),e.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[I?e.jsx(It,{size:12}):e.jsxs("select",{className:"h-7 rounded-md border border-input bg-background px-2 text-xs focus:outline-none focus:ring-1 focus:ring-ring",value:ee.selectedId||"",onChange:te=>b(G=>({...G,[A]:{...G[A],selectedId:te.target.value,result:null}})),children:[e.jsx("option",{value:"",children:"— escolher grupo —"}),p.map(te=>e.jsx("option",{value:te.id,children:te.name},te.id))]}),e.jsx(w,{size:"sm",variant:"outline",disabled:!ee.selectedId||ee.loading,onClick:()=>D(E),className:"h-7 text-xs",children:ee.loading?e.jsx(It,{size:12}):"Atribuir"})]}),ee.result?e.jsx("span",{className:`w-full text-xs ${ee.result.ok?"text-green-700":"text-destructive"}`,children:ee.result.message}):null]})})(),E.lotes.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nenhum lote cadastrado."}):E.lotes.map(ee=>{const re=x[ee.id]||{},te=Hi(ee.posProductId);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-background px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium",children:ee.nome}),ee.preco_lote!=null?e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:aa(ee.preco_lote)}):null,re.result?e.jsx("span",{className:`ml-2 text-xs ${re.result.ok?"text-green-600":"text-destructive"}`,children:re.result.message}):null]}),e.jsx(je,{variant:ee.ativo?"default":"secondary",className:"text-xs shrink-0",children:ee.ativo?"Ativo":"Inativo"}),te?e.jsxs(je,{variant:"outline",className:"text-xs text-green-700 border-green-500 shrink-0 hidden md:flex",children:[e.jsx(hr,{className:"h-3 w-3 mr-1"}),"POS ✓"]}):e.jsx(je,{variant:"outline",className:"text-xs text-muted-foreground shrink-0 hidden md:flex",children:"Sem vínculo"}),te?e.jsx(w,{size:"icon",variant:"ghost",title:"Remover vínculo POS (limpa posProductId)",disabled:re.loading,onClick:()=>z(ee),className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0",children:re.loading?e.jsx(It,{size:12}):e.jsx(po,{className:"h-3.5 w-3.5"})}):e.jsx("div",{className:"h-7 w-7 shrink-0"})]},ee.id)})]}):null]},E.id)})})]})},Ma=s=>s?.Product||s,Nh=()=>{const[s,t]=r.useState([]),[a,n]=r.useState([]),[o,i]=r.useState(!1),[u,l]=r.useState(null),[c,m]=r.useState(null),[x,h]=r.useState(!0),[p,f]=r.useState({}),[I,g]=r.useState({}),N=r.useCallback(async()=>{i(!0),l(null),m(null);try{const[L,M]=await Promise.all([$e.get("/pos/products"),$e.get("/pos/productgroups")]);t(Array.isArray(L?.data?.data)?L.data.data:[]),n(Array.isArray(M?.data?.data)?M.data.data:[])}catch(L){l(L?.response?.data?.error?.message||L?.message||"Falha ao carregar catálogo POS")}finally{i(!1)}},[]),b=L=>{const M=Ma(L);if(typeof M?.active=="boolean")return M.active;const z=String(M?.StatusName||"").toLowerCase();return!z.includes("desab")&&!z.includes("inact")},C=s.filter(L=>!(x&&!b(L)||c&&(Ma(L)?.ProductGroupID||"").toUpperCase()!==c.toUpperCase())).sort((L,M)=>{const z=Ma(L)?.ProductGroupID||"",D=Ma(M)?.ProductGroupID||"";if(z!==D)return z.localeCompare(D);const E=b(L)?0:1,A=b(M)?0:1;if(E!==A)return E-A;const S=(Ma(L)?.Name||"").toLowerCase(),P=(Ma(M)?.Name||"").toLowerCase();return S.localeCompare(P)}),q=async L=>{const M=Ma(L);if(!M?.ProductID)return;const z=b(L);f(D=>({...D,[M.ProductID]:!0})),g(D=>({...D,[M.ProductID]:null}));try{const D=await $e.post("/pos/product/status",{productId:M.ProductID,internalCode:M.InternalCode||void 0,active:!z}),E=D?.data?.ok!==!1,A=D?.data?.refCleared===!0;let S;E?S=z?A?"Desabilitado — vínculo POS removido":"Desabilitado":"Habilitado":S="Falha ao atualizar",g(P=>({...P,[M.ProductID]:{ok:E,message:S}})),E&&await N()}catch(D){g(E=>({...E,[M.ProductID]:{ok:!1,message:D?.response?.data?.error?.message||"Falha ao atualizar status."}}))}finally{f(D=>({...D,[M.ProductID]:!1}))}};return e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx(ze,{className:"text-base font-semibold",children:"Produtos POS (ao vivo)"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Catálogo atual no POS Controle. Filtre por grupo e alterne status. Desabilitar um lote remove automaticamente o vínculo no Strapi."})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"accent-primary",checked:x,onChange:L=>h(L.target.checked)}),"Ocultar inativos"]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:N,disabled:o,children:[o?e.jsx(It,{size:14}):e.jsx(qo,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Carregar"})]})]})]}),e.jsxs(ge,{className:"space-y-4",children:[u?e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(tr,{className:"h-4 w-4 shrink-0"})," ",u]}):null,a.length>0?e.jsxs("div",{children:[e.jsxs("p",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:["Grupos (",a.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("button",{onClick:()=>m(null),className:`flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs transition-colors ${c===null?"border-primary bg-primary text-primary-foreground":"border-border hover:border-primary/60"}`,children:["Todos (",s.filter(L=>!x||b(L)).length,")"]}),a.map(L=>{const M=L?.ProductGroup||L,z=M?.ProductGroupID||M?.id,D=M?.ImageGroupBase64||M?.imageBase64,E=s.filter(A=>(Ma(A)?.ProductGroupID||"").toUpperCase()===(z||"").toUpperCase()&&(!x||b(A))).length;return e.jsxs("button",{onClick:()=>m(z===c?null:z),className:`flex items-center gap-2 rounded-full border px-3 py-1 text-xs transition-colors ${c===z?"border-primary bg-primary text-primary-foreground":"border-border hover:border-primary/60"}`,children:[D?e.jsx("img",{src:D.startsWith("data:")||D.startsWith("http")?D:`data:image/png;base64,${D}`,alt:M?.Name||M?.name||"",className:"h-5 w-5 rounded-full object-cover border",onError:A=>{A.currentTarget.style.display="none"}}):null,e.jsx("span",{children:M?.Name||M?.name||z}),e.jsxs("span",{className:"opacity-60",children:["(",E,")"]})]},z)})]})]}
3):null,s.length>0||a.length>0?e.jsxs("div",{children:[e.jsxs("p",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:["Produtos — ",C.length,c?" neste grupo":" no total"]}),C.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum produto neste grupo."}):e.jsx("div",{className:"grid gap-2",children:C.map((L,M)=>{const z=Ma(L),D=z?.ProductID,E=b(L),A=p[D],S=I[D],P=z?.ProductGroupID,F=M>0?Ma(C[M-1])?.ProductGroupID:null,ee=!c&&(P||"").toUpperCase()!==(F||"").toUpperCase(),re=(P||"").toUpperCase(),te=a.find(G=>{const y=G?.ProductGroup||G;return(y?.ProductGroupID||"").toUpperCase()===re||(y?.id||"").toUpperCase()===re})?.Name||a.find(G=>{const y=G?.ProductGroup||G;return(y?.ProductGroupID||"").toUpperCase()===re||(y?.id||"").toUpperCase()===re})?.name||P||"Sem grupo";return e.jsxs(fn.Fragment,{children:[ee?e.jsx("div",{className:"mt-3 mb-1 first:mt-0",children:e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-primary/80 border-b pb-1",children:te})}):null,e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-2",children:[e.jsx(Tc,{src:z?.ImageBase64||null,alt:z?.Name||""}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:z?.Name||"—"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[z?.InternalCode,z?.SalePrice?` · R$ ${Number.parseFloat(z.SalePrice).toFixed(2)}`:""]}),S?e.jsx("p",{className:`mt-0.5 text-xs ${S.ok?"text-green-600":"text-destructive"}`,children:S.message}):null]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(je,{variant:E?"default":"secondary",className:"text-xs hidden sm:flex",children:E?"Ativo":"Inativo"}),e.jsx(w,{size:"icon",variant:"ghost",title:E?"Desativar no POS (remove vínculo Strapi para LOTE-xxx)":"Ativar no POS",disabled:A,onClick:()=>q(L),className:"h-8 w-8",children:A?e.jsx(It,{size:14}):E?e.jsx(om,{className:"h-5 w-5 text-primary"}):e.jsx(lm,{className:"h-5 w-5 text-muted-foreground"})})]})]})]},D)})})]}):o?e.jsxs("div",{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[e.jsx(It,{size:16})," Carregando…"]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:'Clique em "Carregar" para buscar produtos e grupos do POS.'})]})]})},yh=()=>{const[s,t]=r.useState([]),[a,n]=r.useState("all"),[o,i]=r.useState(""),[u,l]=r.useState(null),[c,m]=r.useState(null),[x,h]=r.useState(!1);r.useEffect(()=>{$e.get("/eventos?fields[0]=id&fields[1]=documentId&fields[2]=titulo&sort=titulo:asc&publicationState=preview&pagination[pageSize]=200").then(b=>{const C=Array.isArray(b?.data?.data)?b.data.data:Array.isArray(b?.data)?b.data:[];t(C.map(q=>({id:q.id,documentId:q.documentId||q.attributes?.documentId||null,titulo:q.titulo||q.attributes?.titulo||"—"})).filter(q=>q.id&&q.titulo))}).catch(()=>t([]))},[]);const p=(b,C)=>{const q=b||{},M=(Array.isArray(q.errors)?q.errors:[]).slice(0,6).map(D=>{const E=D?.type?`[${D.type}] `:"",A=D?.productId?` (${D.productId})`:"";return`${E}${D?.message||"Falha"}${A}`}),z=Array.isArray(q.summaryByType)?q.summaryByType:q.summaryByType&&typeof q.summaryByType=="object"?Object.entries(q.summaryByType):[];return q.ok===!1?{ok:!1,message:C,details:M,pushed:0,summaryByType:z}:{ok:!0,message:`Catálogo enviado (${q?.pushed??0} itens).`,details:M,pushed:Number(q?.pushed||0),summaryByType:z}},f=()=>a==="event"&&o?{scope:"event",eventId:o}:{scope:"all"},I=async(b=!1)=>{h(!0),l(null);try{const C=b?"/pos/catalog/push/force":"/pos/catalog/push",q=await $e.post(C,f());l(p(q?.data,"Falha ao enviar catálogo para o POS."))}catch(C){l(p(C?.response?.data,"Falha ao enviar catálogo para o POS."))}finally{h(!1)}},g=async()=>{h(!0),l(null);try{const b=await $e.post("/pos/catalog/republish",f()),C=p(b?.data,"Falha ao republish no POS.");l({...C,message:`Republish concluído (${b?.data?.pushed??0} itens).`})}catch(b){l(p(b?.response?.data,"Falha ao republish no POS."))}finally{h(!1)}},N=async()=>{h(!0),m(null);try{const b=new URLSearchParams(f()).toString(),C=await $e.get(`/pos/catalog/reconcile?${b}`);m(C?.data||null)}catch{m({ok:!1,error:"Falha ao reconciliar catálogo."})}finally{h(!1)}};return e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsx(ze,{className:"text-base font-semibold",children:"Operações em Lote"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Push completo do catálogo, republish (estoque > 0) e reconciliação de divergências."})]}),e.jsxs(ge,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-3 items-end",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Escopo"}),e.jsxs("select",{className:"border rounded px-2 py-1 bg-background text-sm",value:a,onChange:b=>n(b.target.value),children:[e.jsx("option",{value:"all",children:"Todos"}),e.jsx("option",{value:"event",children:"Evento"})]})]}),a==="event"?e.jsxs("select",{className:"border rounded px-2 py-1 bg-background text-sm",value:o,onChange:b=>i(b.target.value),children:[e.jsx("option",{value:"",children:"Selecione o evento"}),s.map(b=>e.jsx("option",{value:b.documentId||String(b.id),children:b.titulo},b.id))]}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(w,{size:"sm",onClick:()=>I(!1),disabled:x,children:"Enviar catálogo"}),e.jsx(w,{size:"sm",variant:"outline",onClick:g,disabled:x,children:"Republish (estoque > 0)"}),e.jsx(w,{size:"sm",variant:"outline",onClick:()=>I(!0),disabled:x,children:"Forçar sync"}),e.jsx(w,{size:"sm",variant:"secondary",onClick:N,disabled:x,children:"Reconciliar"})]}),u?e.jsxs("div",{className:"grid gap-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{variant:u.ok?"default":"destructive",children:u.ok?"OK":"Erro"}),e.jsx("span",{className:"text-muted-foreground",children:u.message})]}),Array.isArray(u.summaryByType)&&u.summaryByType.length>0?e.jsx("div",{className:"grid gap-0.5 text-xs text-muted-foreground",children:u.summaryByType.map(([b,C])=>e.jsxs("span",{children:[b,": ",C?.pushed||0," env. / ",C?.failed||0," falhas"]},b))}):null,Array.isArray(u.details)&&u.details.length>0?e.jsx("div",{className:"grid gap-0.5 text-xs text-destructive",children:u.details.map((b,C)=>e.jsx("span",{children:b},C))}):null]}):null,c?e.jsxs("div",{className:"grid gap-2 rounded-md border p-3 text-sm",children:[e.jsx(je,{variant:c.ok?"default":"outline",className:"w-fit",children:c.ok?"Sem divergências":"Divergências encontradas"}),c.error?e.jsx("span",{className:"text-xs text-destructive",children:c.error}):e.jsxs("div",{className:"grid gap-0.5 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Faltando no POS: ",c.missing?.length||0]}),e.jsxs("span",{children:["Status divergente: ",c.mismatchedStatus?.length||0]}),e.jsxs("span",{children:["Preço divergente: ",c.mismatchedPrice?.length||0]})]})]}):null]})]})},Ul=()=>new Date().toISOString().slice(0,10),wh=()=>{const[s,t]=r.useState(Ul()),[a,n]=r.useState(Ul()),[o,i]=r.useState([]),[u,l]=r.useState(!1),[c,m]=r.useState(null),[x,h]=r.useState(0),p=async()=>
3{if(!(!s||!a)){l(!0),m(null);try{const I=(await $e.get(`/pos/sales?from=${s}&to=${a}`))?.data||{};if(I.ok===!1)m(I.error||"Falha ao consultar vendas"),i([]),h(0);else{const g=Array.isArray(I.sales)?I.sales:[];i(g);const N=g.reduce((b,C)=>b+(Number(C?.amount)||0),0);h(N)}}catch(f){m(f?.response?.data?.error?.message||f?.message||"Falha ao consultar vendas POS"),i([]),h(0)}finally{l(!1)}}};return e.jsxs(he,{children:[e.jsx(Be,{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:e.jsxs("div",{children:[e.jsxs(ze,{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(ri,{className:"h-4 w-4"})," Vendas POS"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Consulte vendas registradas no POS Controle por período."})]})}),e.jsxs(ge,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"grid gap-1",children:[e.jsx("label",{htmlFor:"pos-sales-from",className:"text-xs text-muted-foreground",children:"De"}),e.jsx("input",{id:"pos-sales-from",type:"date",className:"h-8 rounded-md border border-input bg-background px-2 text-sm",value:s,onChange:f=>t(f.target.value)})]}),e.jsxs("div",{className:"grid gap-1",children:[e.jsx("label",{htmlFor:"pos-sales-to",className:"text-xs text-muted-foreground",children:"Até"}),e.jsx("input",{id:"pos-sales-to",type:"date",className:"h-8 rounded-md border border-input bg-background px-2 text-sm",value:a,onChange:f=>n(f.target.value)})]}),e.jsxs(w,{size:"sm",onClick:p,disabled:u,children:[u?e.jsx(It,{size:14}):e.jsx(At,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-1.5",children:"Consultar"})]})]}),c?e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(tr,{className:"h-4 w-4 shrink-0"})," ",c]}):null,o.length>0?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(je,{variant:"secondary",className:"text-xs",children:[o.length," venda",o.length!==1?"s":""]}),e.jsxs(je,{variant:"outline",className:"text-xs",children:["Total: ",aa(x)]})]}):null,o.length>0?e.jsx("div",{className:"max-h-96 overflow-y-auto space-y-1.5",children:o.map((f,I)=>{const g=f?.id||f?.SaleID||I,N=Number(f?.amount??f?.Amount??0),b=f?.timestamp||f?.SaleDate||f?.CreatedDate||"",C=f?.customer?.name||f?.Customer?.Name||"",q=f?.customer?.email||f?.Customer?.Email||"";return e.jsxs("div",{className:"flex items-center gap-3 rounded-md border bg-background px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium truncate",children:["#",typeof g=="string"?g.slice(0,8):g,C?` — ${C}`:""]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[b?Ko(b.slice(0,10)):"—",q?` · ${q}`:""]})]}),e.jsx(je,{variant:"outline",className:"text-xs shrink-0",children:aa(N)})]},g)})}):!u&&!c?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:'Selecione o período e clique em "Consultar" para ver vendas do POS.'}):null]})]})},_h=()=>{const[s,t]=r.useState([]),[a,n]=r.useState(!1),[o,i]=r.useState(null),[u,l]=r.useState(new Set),c=async()=>{n(!0),i(null);try{const h=(await $e.get("/pos/stock-summary"))?.data||{};h.ok===!1?(i(h.error||"Falha ao carregar resumo de estoque"),t([])):t(Array.isArray(h.data)?h.data:[])}catch(x){i(x?.response?.data?.error?.message||x?.message||"Falha ao carregar resumo de estoque"),t([])}finally{n(!1)}},m=x=>{l(h=>{const p=new Set(h);return p.has(x)?p.delete(x):p.add(x),p})};return e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between gap-2 pb-4",children:[e.jsxs("div",{children:[e.jsxs(ze,{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(Oo,{className:"h-4 w-4"})," Estoque / Lotes — Resumo"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Visão unificada de estoque e lotes por evento, com quantidades e vínculos POS."})]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:c,disabled:a,className:"shrink-0",children:[a?e.jsx(It,{size:14}):e.jsx(qo,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Carregar"})]})]}),e.jsx(ge,{className:"space-y-2 pt-0",children:o?e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(tr,{className:"h-4 w-4 shrink-0"})," ",o]}):a&&s.length===0?e.jsxs("div",{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[e.jsx(It,{size:16})," Carregando resumo…"]}):s.length===0?e.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:'Clique em "Carregar" para ver o resumo de estoque por evento.'}):s.map(x=>{const h=x.evento||{},p=u.has(h.id),f=x.totals||{};return e.jsxs("div",{className:"rounded-lg border overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>m(h.id),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-muted/40 transition-colors",children:[p?e.jsx(ra,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(er,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:h.titulo||"—"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.data_evento?Ko(h.data_evento):"Sem data",h.posLinked?" · Grupo POS ✓":""]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(je,{variant:"secondary",className:"text-xs",children:[f.loteCount||0," lote",(f.loteCount||0)!==1?"s":""]}),e.jsxs(je,{variant:"outline",className:"text-xs",children:[f.estoqueCount||0," estoque"]}),e.jsxs(je,{variant:"outline",className:"text-xs font-mono",children:["Σ ",f.loteQtyTotal||0," ingr · ",f.estoqueQtyTotal||0," prod"]})]})]}),p?e.jsxs("div",{className:"border-t bg-muted/20 px-4 py-3 space-y-3",children:[(x.lotes||[]).length>0?e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-primary/80 mb-1.5",children:["Lotes (",x.lotes.length,")"]}),e.jsx("div",{className:"space-y-1",children:x.lotes.map(I=>e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-background px-3 py-1.5 text-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium",children:I.nome}),I.preco_lote!=null?e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:aa(I.preco_lote)}):null]}),e.jsx(je,{variant:I.ativo?"default":"secondary",className:"text-xs",children:I.ativo?"Ativo":"Inativo"}),e.jsxs("span",{className:"text-xs font-mono tabular-nums",children:["Qty: ",I.quantidade_disponivel]}),I.posLinked?e.jsxs(je,{variant:"outline",className:"text-xs text-green-700 border-green-500",children:[e.jsx(hr,{className:"h-3 w-3 mr-1"})," POS"]}
3):e.jsx(je,{variant:"outline",className:"text-xs text-muted-foreground",children:"—"})]},I.id))})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sem lotes."}),(x.estoques||[]).length>0?e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-primary/80 mb-1.5",children:["Estoque (",x.estoques.length,")"]}),e.jsx("div",{className:"space-y-1",children:x.estoques.map(I=>e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-background px-3 py-1.5 text-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium",children:I.nomeProdutoFisico}),I.categoria?e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",I.categoria,")"]}):null,I.preco!=null?e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:aa(I.preco)}):null]}),e.jsxs("span",{className:`text-xs font-mono tabular-nums ${I.quantidade===0?"text-destructive font-semibold":I.quantidade<=10?"text-yellow-600":""}`,children:["Qty: ",I.quantidade]}),I.posLinked?e.jsxs(je,{variant:"outline",className:"text-xs text-green-700 border-green-500",children:[e.jsx(hr,{className:"h-3 w-3 mr-1"})," POS"]}):e.jsx(je,{variant:"outline",className:"text-xs text-muted-foreground",children:"—"})]},I.id))})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sem estoque."})]}):null]},h.id)})})]})};function Ch(){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"POS Controle"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gestão de eventos e lotes no POS Controle. Envie por evento, consulte o catálogo ao vivo ou execute operações em lote."})]}),e.jsx(bh,{}),e.jsx(Nh,{}),e.jsx(wh,{}),e.jsx(_h,{}),e.jsx(yh,{})]})}const Bl="Ainda estou em fase de desenvolvimento, mas em breve estarei pronto para mostrar insights em tempo real sobre suas vendas e eventos! 💡",kh="relative min-h-[60vh] md:min-h-[70vh] overflow-hidden rounded-2xl border border-border shadow-[0_0_80px_-40px_theme(colors.sky.500/60)]",Sh=[{className:"absolute -inset-10 rounded-[36px] bg-gradient-to-r from-fuchsia-500/60 via-purple-500/40 to-sky-500/60 blur-[60px]",duration:"16s",delay:"0s",animation:"wave-glide",opacity:1},{className:"absolute inset-[6%] rounded-[32px] bg-gradient-to-br from-blue-500/50 via-violet-500/35 to-cyan-400/40 blur-[50px]",duration:"12s",delay:"-3.5s",animation:"wave-glide-alt",opacity:.8},{className:"absolute left-1/2 top-1/2 h-[160%] w-[160%] -translate-x-1/2 -translate-y-1/2 rounded-full bg-gradient-to-bl from-purple-500/45 via-fuchsia-500/30 to-sky-500/35 blur-[70px]",duration:"20s",delay:"-6s",animation:"wave-orbit",opacity:.7}],Vl="bg-gradient-to-br from-purple-500/80 via-fuchsia-500/80 to-blue-500/80 text-white shadow-[0_10px_30px_-15px_rgba(168,85,247,0.9)]",Ih="bg-white/80 text-slate-900 shadow-[0_10px_35px_-20px_rgba(255,255,255,0.9)]",Gl={initial:{opacity:0,y:12},animate:{opacity:1,y:0,transition:{duration:.4,ease:"easeOut"}},exit:{opacity:0,y:-8,transition:{duration:.2,ease:"easeIn"}}};function Ah(){const{profile:s,user:t}=Zt(),[a,n]=r.useState([]),[o,i]=r.useState(null),[u,l]=r.useState(""),[c,m]=r.useState(!1),x=r.useRef(null),h=r.useRef(null),{mode:p}=qd(),f=p==="light",I=r.useMemo(()=>s?.nome||t?.username||t?.email||"visitante",[s,t]),g=r.useMemo(()=>[{id:"assistant-welcome",role:"assistant",content:`🤖 Olá! ${I}! Eu sou o Robôzinho da TicketTop — seu consultor particular para eventos, vendas e muito mais!`},{id:"assistant-prompt",role:"assistant",content:"Em breve vou te ajudar a acompanhar estoques, custos, eventos passados e previsões de sucesso! 🔥"}],[I]);r.useEffect(()=>{n(q=>!q||q.length===0||q[0]?.id==="assistant-welcome"&&q[1]?.id==="assistant-prompt"?g:q)},[g]);const N=r.useMemo(()=>!!o||c,[o,c]),b=r.useCallback(()=>{x.current&&x.current.scrollTo({top:x.current.scrollHeight,behavior:"smooth"})},[]);r.useEffect(()=>{b()},[a,o,b]),r.useEffect(()=>{if(!o)return;const q=setTimeout(()=>{n(L=>[...L,{id:o.id,role:"assistant",content:o.target??Bl}]),i(null),m(!1)},o.duration||1600);return()=>clearTimeout(q)},[o,n]);const C=r.useCallback(q=>{if(q.preventDefault(),N)return;const L=u.trim();if(!L)return;const z={id:`user-${Date.now()}`,role:"user",content:L};n(D=>[...D,z]),l(""),m(!0),setTimeout(()=>{i({id:`assistant-${Date.now()}`,role:"assistant",target:Bl,duration:1800})},450)},[N,u]);return e.jsxs("section",{className:kh,children:[e.jsx("style",{children:`
4        @keyframes wave-glide {
5          0%, 100% { transform: translate3d(-8%, -6%, 0) scale(1); opacity: .55; }
6          45% { transform: translate3d(6%, 8%, 0) scale(1.08); opacity: .85; }
7          60% { transform: translate3d(2%, -4%, 0) scale(1.04); opacity: .75; }
8        }
9        @keyframes wave-glide-alt {
10          0%, 100% { transform: translate3d(4%, -4%, 0) scale(.96) rotate(-2deg); opacity: .45; }
11          50% { transform: translate3d(-6%, 6%, 0) scale(1.05) rotate(3deg); opacity: .72; }
12        }
13        @keyframes wave-orbit {
14          0% { transform: translate3d(-50%, -50%, 0) rotate(0deg) scale(.9); }
15          50% { transform: translate3d(-50%, -50%, 0) rotate(20deg) scale(1.03); }
16          100% { transform: translate3d(-50%, -50%, 0) rotate(360deg) scale(.9); }
17        }
18
19        /* ===== Vidro de amplificação/“refração” =====
20           - intensifica as cores do fundo (sem linhas)
21           - leve offset/parallax interno prá simular distorção */
22        .glass-card {
23          position: relative;
24          isolation: isolate;
25          contain: paint;
26          overflow: hidden;
27          border-radius: 1.5rem;
28          border: 1px solid rgba(255,255,255,.18);
29          /* base escura (dark) vai receber override inline quando claro */
30          background: linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,.02));
31          backdrop-filter: blur(16px) saturate(170%) contrast(1.08) brightness(1.05);
32          -webkit-backdrop-filter: blur(16px) saturate(170%) contrast(1.08) brightness(1.05);
33          box-shadow:
34            inset 0 1px 0 rgba(255,255,255,.20),
35            0 16px 40px -24px rgba(14, 164, 233, 0.671),
36            0 28px 80px -40px rgba(169, 85, 247, 0.651);
37        }
38
39        /* camada “lens” interna: pega o fundo do próprio container
40           com um leve scale/translate animado para parecer refração */
41        .glass-lens {
42          position: absolute;
43          inset: -2%;
44          border-radius: inherit;
45          pointer-events: none;
46          /* Renderiza o MESMO conteúdo do container (via backdrop + blend),
47             mas com sutil offset para parecer que o vidro “entorta” o fundo */
48          backdrop-filter: blur(5px) saturate(180%) contrast(1.46);
49          -webkit-backdrop-filter: blur(5px) saturate(180%) contrast(1.46);
50          mix-blend-mode: lighten;
51          opacity: .9;
52          transform: translate3d(0,0,0) scale(1.57);
53          animation: lens-shift 8s ease-in-out infinite;
54        }
55        @keyframes lens-shift {
56          0%, 100% { transform: translate3d(-0.4%, -0.3%, 0) scale(1.018); }
57          50% { transform: translate3d(0.5%, 0.4%, 0) scale(1.025); }
58        }
59
60        /* brilho/glare suave */
61        .glass-card:before {
62          content: "";
63          position: absolute;
64          inset: -30%;
65          border-radius: inherit;
66          background:
67            radial-gradient(60% 40% at 20% 0%, rgba(255,255,255,.25), rgba(255,255,255,0) 60%),
68            conic-gradient(from 210deg at 70% 0%, rgba(255,255,255,.12), rgba(255,255,255,0) 40% 75%, rgba(255,255,255,.12));
69          mix-blend-mode: soft-light;
70          filter: blur(10px);
71          animation: glare-move 14s ease-in-out infinite;
72          pointer-events: none;
73        }
74        @keyframes glare-move {
75          0%, 100% { transform: translate3d(-3%, -2%, 0) rotate(0deg) }
76          50% { transform: translate3d(2%, 2%, 0) rotate(8deg) }
77        }
78
79        /* ruído leve clipado para realismo */
80        .glass-noise {
81          position: absolute; inset: 0; pointer-events: none; opacity: .16; mix-blend-mode: soft-light;
82          border-radius: inherit;
83          opacity: 0.12;
84          background-image:
85            url("data:image/svg+xml;utf8,${encodeURIComponent("<svg xmlns='http://www.w3.org/2000/svg' width='140' height='140' viewBox='0 0 140 140'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix type='saturate' values='0'/><feComponentTransfer><feFuncA type='table' tableValues='0 0 0 0 0 0 0.05 0'/></feComponentTransfer></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>")}");
86        }
87
88        @media (prefers-reduced-motion: reduce) {
89          .glass-card:before, .glass-lens { animation: none !important; }
90        }
91      `}),Sh.map((q,L)=>e.jsx("div",{className:`pointer-events-none absolute ${q.className}`,style:{animation:`${q.animation} ${q.duration} ease-in-out infinite`,animationDelay:q.delay,opacity:q.opacity}},L)),e.jsxs("div",{ref:h,className:"relative z-10 mx-auto flex max-w-4xl flex-col gap-6 px-4 pb-6 pt-10 md:px-8 md:pb-10",children:[e.jsxs("header",{className:"flex flex-col items-start gap-4 roun
91ded-3xl border border-white/10 bg-white/5 p-6 backdrop-blur-xl",children:[e.jsxs("div",{className:"flex items-center gap-2 rounded-full bg-gradient-to-r from-fuchsia-500 via-purple-500 to-blue-500 px-4 py-1 text-xs font-semibold text-white shadow-lg",children:[e.jsx(dm,{className:"h-3.5 w-3.5"}),"IA • Dashboard"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight text-white drop-shadow md:text-4xl",children:"Conversa com o assistente"}),e.jsx("p",{className:"mt-2 max-w-xl text-sm text-white/90 md:text-base",children:"Interaja com o protótipo do chat. Em breve novas funcionalidades."})]})]}),e.jsxs("div",{className:"relative rounded-3xl border border-white/5 shadow-[0_25px_45px_-30px_rgba(59,130,246,0.45)]",children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-10 -top-1 h-[2px] rounded-full bg-gradient-to-r from-transparent via-white/30 to-transparent opacity-60"}),e.jsxs("div",{className:"glass-card",style:f?{background:"linear-gradient(180deg, rgba(255, 255, 255, 0.144), rgba(255, 255, 255, 0.007))",backdropFilter:"blur(12px) saturate(150%)",WebkitBackdropFilter:"blur(12px) saturate(150%)",border:"1px solid rgba(15,23,42,0.08)"}:void 0,children:[e.jsx("div",{className:"glass-lens"}),e.jsx("div",{className:"glass-noise"}),e.jsx("div",{ref:x,className:"relative z-10 flex h-[45vh] flex-col gap-4 overflow-y-auto px-4 pb-8 pt-6 md:px-8",style:f?{background:"linear-gradient(180deg, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.116))",backdropFilter:"blur(10px) saturate(140%)",WebkitBackdropFilter:"blur(10px) saturate(140%)",borderTopLeftRadius:"1.5rem",borderTopRightRadius:"1.5rem"}:{background:"linear-gradient(180deg, rgba(6, 10, 18, 0.404), rgba(6,10,18,0.02))"},children:e.jsxs(lx,{initial:!1,children:[a.map(q=>e.jsx(Br.div,{variants:Gl,initial:"initial",animate:"animate",exit:"exit",className:`flex ${q.role==="user"?"justify-end":"justify-start"}`,children:e.jsx(Br.div,{className:`max-w-[78%] rounded-3xl px-5 py-3 text-sm leading-relaxed md:text-base ${q.role==="user"?Ih:Vl}`,style:{backdropFilter:"blur(6px) saturate(140%)",WebkitBackdropFilter:"blur(6px) saturate(140%)",border:q.role==="user"?"1px solid rgba(255,255,255,.35)":"1px solid rgba(255,255,255,.22)"},children:q.content})},q.id)),o&&e.jsx(Br.div,{variants:Gl,initial:"initial",animate:"animate",exit:"exit",className:"flex justify-start",children:e.jsxs(Br.div,{className:`relative flex w-[190px] flex-col items-center gap-3 rounded-3xl px-4 py-2 text-sm leading-relaxed md:text-base ${Vl}`,style:{backdropFilter:"blur(6px) saturate(140%)",WebkitBackdropFilter:"blur(6px) saturate(140%)",border:"1px solid rgba(255,255,255,.22)"},children:[e.jsx(ox,{src:"https://lottie.host/4faf67b6-2025-4857-97e2-72e61c98495a/cyuMYgTwJU.lottie",autoplay:!0,loop:!0,className:"h-12 w-48 filter brightness-0 invert"}),e.jsx("div",{className:"absolute -bottom-3 left-8 h-6 w-6 rotate-12 rounded-full bg-fuchsia-500/20 blur-lg"})]})},o.id)]})}),e.jsxs("form",{onSubmit:C,className:"relative z-10 flex flex-col gap-3 border-t rounded-b-3xl border-white/10 p-4 md:flex-row md:items-center md:gap-4 md:p-6",style:f?{background:"linear-gradient(180deg, rgba(255, 255, 255, 0.521), rgba(255, 255, 255, 0.226))",backdropFilter:"blur(8px) saturate(130%)",WebkitBackdropFilter:"blur(8px) saturate(130%)"}:{background:"rgba(255,255,255,0.045)",backdropFilter:"blur(10px) saturate(160%)",WebkitBackdropFilter:"blur(10px) saturate(160%)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 rounded-2xl bg-gradient-to-r from-fuchsia-500/15 via-transparent to-blue-500/15 blur-xl"}),e.jsx("input",{type:"text",value:u,onChange:q=>l(q.target.value),placeholder:"Pergunte algo sobre seus eventos, vendas ou público...",className:"relative w-full rounded-2xl border px-5 py-3 text-sm shadow-inner outline-none transition focus:border-fuchsia-400 focus:ring-2 focus:ring-fuchsia-300/60 md:text-base",style:f?{backgroundColor:"rgba(255, 255, 255, 0.705)",color:"#0f172a",borderColor:"rgba(15,23,42,0.08)"}:{backgroundColor:"rgba(255,255,255,0.70)",color:"#0f172a",borderColor:"rgba(255,255,255,0.25)"},disabled:N}),e.jsx("span",{className:"pointer-events-none absolute right-5 top-1/2 -translate-y-1/2 text-xs uppercase tracking-[0.2em] text-slate-600/70",children:"ALPHA"})]}),e.jsxs("button",{type:"submit",disabled:N,className:"group relative inline-flex shrink-0 items-center justify-center gap-2 overflow-hidden rounded-2xl bg-gradient-to-r from-fuchsia-500 via-purple-500 to-blue-500 px-6 py-3 text-sm font-semibold text-white shadow-lg transition focus:outline-none focus:ring-2 focus:ring-fuchsia-300/60 disabled:cursor-not-allowed disabled:opacity-70 md:text-base",children:[e.jsx("span",{className:"relative z-10",children:"Enviar pergunta"}),e.jsx(cm,{className:"relative z-10 h-4 w-4 transition-transform group-hover:translate-x-1"}
91),e.jsx(Br.div,{"aria-hidden":!0,className:"absolute inset-0 bg-white/20",initial:{opacity:0},animate:{opacity:[0,.35,0]},transition:{duration:2,repeat:1/0}})]})]})]})]})]})]})}const Ki="/placeholder.svg",$c=(()=>{const s=()=>`row-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return()=>{try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return s()}})(),Tn=()=>({rowKey:$c(),estoqueId:"",estoqueDocumentId:"",quantidade:1,ignorarEstoque:!1,componentId:null}),Eh=s=>{if(s==null||s==="")return null;const t=Number(s);return Number.isInteger(t)?t:null},wr=({src:s,alt:t,className:a="h-16 w-16"})=>{const n=s||Ki;return e.jsx("div",{className:ls("relative overflow-hidden rounded-md border border-border bg-muted",a),children:e.jsx("img",{src:n,alt:t||"Pré-visualização",className:"h-full w-full object-cover",onError:o=>{o.currentTarget.src!==Ki&&(o.currentTarget.src=Ki)}})})},So=s=>{if(!s)return{label:"Item de estoque",imageUrl:null};const t=s?.attributes??s,a=s?.id??t?.id??"",n=t?.nomeProdutoFisico||t?.nome||t?.titulo||t?.label||(a?`Item ${a}`:"Item de estoque"),i=(t?.categoria?.data?.attributes||t?.categoria||null)?.nome,u=t?.imagem?.data??t?.imagem??null,l=Array.isArray(u)?u[0]?.attributes??u[0]:u?.attributes??u,c=l?.url||l?.formats?.thumbnail?.url||null;return{label:i?`${n} — ${i}`:n,imageUrl:c?qt(c):null}},Hl=s=>{const t=Number(typeof s?.preco<"u"?s.preco:s?.attributes?.preco??0),a=Math.min(100,Math.max(0,Number(typeof s?.desconto<"u"?s.desconto:s?.attributes?.desconto??0))),n=Number((t*(1-a/100)).toFixed(2));return{precoBase:t,descontoPercentual:a,precoFinal:n}},Kl=s=>s?(a=>{if(!a)return{id:null,url:null};const n=Array.isArray(a?.data)?a.data?.[0]:a?.data??a;if(!n)return{id:null,url:null};const o=n?.attributes??n,i=o?.url||o?.src||o?.formats?.thumbnail?.url||null;return{id:n?.id??o?.id??null,url:i?qt(i):null}})(s):{id:null,url:null},Ql=s=>{if(!s)return null;const t=s?.data??s;if(!t)return null;const a=t?.attributes??t;return{id:t?.id??a?.id??null,nome:a?.nome??a?.title??null,titulo:a?.titulo??a?.nome??null,documentId:a?.documentId??null}},Dh=(s,t={})=>{const{byId:a,byDocumentId:n}=t,o=s?.attributes??{},i={...o,...s},u=Kl(i?.imagem),l=Ql(i?.categoria),c=Ql(i?.evento),x=(i?.itens?.data??i?.itens??[]).map((h,p)=>{const f=h?.attributes??h??{},I=f?.estoque??null,g=I&&typeof I=="object"&&"data"in I&&I.data||(I&&typeof I=="object"&&!("data"in I)?I:null),N=g?.attributes??(typeof g=="object"?g:{}),b=typeof I=="number"&&I||g?.id||N?.id||null,C=N?.documentId??(typeof f?.estoqueDocumentId=="string"?f.estoqueDocumentId:null)??g?.documentId??null;let q=null;(!N||Object.keys(N).length===0)&&(C&&n?.get&&(q=n.get(C)),!q&&b&&a?.get&&(q=a.get(String(b))));const L=q?.attributes??q??{},M=Object.keys(N||{}).length?N:L,z=b??q?.id??L?.id??(typeof M?.id<"u"?M.id:null),D=C??q?.documentId??L?.documentId??M?.documentId??null,E=Kl(N?.imagem??g?.imagem??M?.imagem),A=So({...M,id:z}),S=M?.nomeProdutoFisico||M?.nome||M?.titulo||A.label||`Item ${p+1}`,P=Eh(f?.componentId??h?.componentId),F=f?.uniqueKey||h?.uniqueKey||f?.id||h?.id||`${i?.id||"combo"}:${D||z||p}:${p}`;return{id:F,uniqueKey:F,rowKey:F,componentId:P,quantidade:Number(f?.quantidade??1)||1,ignorarEstoque:!!f?.ignorarEstoque,estoqueId:z,estoqueDocumentId:D,nome:S,imagemUrl:E.url||A.imageUrl}});return{id:s?.id??o?.id??null,documentId:i?.documentId??null,nome:i?.nome??"",descricao:i?.descricao??"",preco:Number(i?.preco??0)||0,desconto:Number(i?.desconto??0)||0,ativo:i?.ativo??!0,imagemUrl:u.url,imagemId:u.id,categoria:l,evento:c,itens:x}};function Ph(){const{toast:s}=mt(),[t,a]=r.useState(""),[n]=r.useState("updatedAt:desc"),[o,i]=r.useState(!1),[u,l]=r.useState("create"),[c,m]=r.useState(null),[x,h]=r.useState(""),[p,f]=r.useState(""),[I,g]=r.useState(""),[N,b]=r.useState("0"),[C,q]=r.useState(""),[L,M]=r.useState(""),[z,D]=r.useState([]),[E,A]=r.useState(null),[S,P]=r.useState(null),[F,ee]=r.useState(null),[re,te]=r.useState(!0),[G,y]=r.useState([Tn()]),$=zd(),{data:W=[]}=Rc(),{data:ie=[],isLoading:ke}=dx({sort:n}),{data:Ae=[]}=Rt({queryKey:["estoque","options"],queryFn:async()=>(await $e.get(`/estoques?pagination[pageSize]=200&${Pc}`))?.data?.data||[],staleTime:1e3*60});r.useEffect(()=>{$e.get("/eventos?fields=id,documentId,titulo&pagination[pageSize]=200").then(k=>D(k?.data?.data||[])).catch(()=>D([]))},[]);const be=cx(),Fe=ux(),ae=mx(),[K,O]=r.useState(null),[oe,ve]=r.useState(!1),me=async(k,De)=>{try{await ae.mutateAsync({id:k.id,documentId:k.documentId,data:{ativo:De}}),s({title:De?"Combo ativado":"Combo desativado",description:De?"O combo está ativo novamente.":"O combo não estará disponível nas vendas."})}catch(Ne){s({variant:"destructive",title:"Falha ao alterar status",description:Ne?.response?.data?.error?.message||Ne.message||"Verifique a conexão e tente novamente."})}},fe=async k=>
91{if(await $.confirm(`Excluir o combo "${k.nome}"?`))try{await Fe.mutateAsync({id:k.id,documentId:k.documentId}),s({title:"Combo excluído",description:"O combo foi removido com sucesso."}),setTimeout(()=>{window.location.reload()},300)}catch(Ne){s({variant:"destructive",title:"Não foi possível excluir",description:Ne?.response?.data?.error?.message||Ne.message||"Tente novamente em instantes."})}};r.useEffect(()=>()=>{S&&S.startsWith("blob:")&&URL.revokeObjectURL(S)},[S]);const le=r.useMemo(()=>{const k=new Map,De=new Map;return(Ae||[]).forEach(Ne=>{const es=String(Ne?.id??Ne?.attributes?.id??"");es&&k.set(es,Ne);const ss=Ne?.attributes?.documentId??Ne?.documentId??null;ss&&De.set(ss,Ne)}),{byId:k,byDocumentId:De}},[Ae]),_e=r.useMemo(()=>Array.isArray(ie)?ie.map(k=>Dh(k,le)):[],[ie,le]),U=r.useMemo(()=>{if(!t.trim())return _e;const k=t.trim().toLowerCase();return _e.filter(De=>{const Ne=De?.nome||"",es=De?.descricao||"";return Ne.toLowerCase().includes(k)||es.toLowerCase().includes(k)})},[_e,t]),J=le.byId,T=le.byDocumentId,Ee=()=>{h(""),f(""),g(""),b("0"),q(""),M(""),A(null),P(null),ee(null),te(!0),y([Tn()]),l("create"),m(null)},Se=k=>{y(De=>De.filter((Ne,es)=>es!==k))},Ze=r.useCallback(k=>{if(!k)return;h(k.nome||""),f(k.descricao||""),g(String(k.preco??"")),b(String(k.desconto??"0")),q(k?.categoria?.id?String(k.categoria.id):""),M(k?.evento?.id?String(k.evento.id):""),te(k?.ativo??!0),ee(k.imagemId?{id:k.imagemId,url:k.imagemUrl}:null),P(k.imagemUrl||null);const De=k.itens.length?k.itens.map((Ne,es)=>{const ss=Ne.estoqueDocumentId&&T.get(Ne.estoqueDocumentId),We=Ne.estoqueId&&J.get(String(Ne.estoqueId)),hs=Ne.estoqueId||ss?.id||ss?.attributes?.id||We?.id||We?.attributes?.id||null,Is=Ne.estoqueDocumentId||ss?.attributes?.documentId||ss?.documentId||We?.attributes?.documentId||We?.documentId||"",Y=Number(Ne.componentId),Q=Number.isInteger(Y)?Y:null;return{rowKey:Ne.uniqueKey||Ne.id||`${k.id||"combo"}:${es}`||$c(),componentId:Q,estoqueId:hs?String(hs):"",estoqueDocumentId:Is,quantidade:Ne.quantidade,ignorarEstoque:!!Ne.ignorarEstoque}}):[Tn()];y(De)},[T,J]),qe=k=>{i(k),k||Ee()},Qe=k=>{if(A(k),k){const De=URL.createObjectURL(k);P(De)}else P(F?.url||null)},we=()=>{S&&S.startsWith("blob:")&&URL.revokeObjectURL(S),P(null),A(null),ee(null)},Me=async()=>{const k=G.map(We=>{const hs=We.estoqueId?Number(We.estoqueId):null,Is=!hs&&We.estoqueDocumentId?T.get(We.estoqueDocumentId):null,Y=hs??Is?.id??Is?.attributes?.id??null;return{...We,resolvedEstoqueId:Y}}).filter(We=>We.resolvedEstoqueId);if(k.length===0){await $.alert("Selecione pelo menos um item de estoque para o combo.");return}let De;if(E){const We=new FormData;We.append("files",E),De=(await $e.post("/upload",We,{headers:{"Content-Type":"multipart/form-data"}}))?.data?.[0]?.id}!De&&F?.id&&(De=F.id);const Ne=Math.max(0,Number(String(I).replace(",","."))||0),es=Math.min(100,Math.max(0,Number(String(N).replace(",","."))||0)),ss={nome:x.trim(),descricao:p.trim()||void 0,preco:Ne,desconto:es,ativo:!!re,categoria:C?Number(C):void 0,evento:L?Number(L):void 0,imagem:De,itens:k.map(We=>{const hs=Math.max(1,parseInt(We.quantidade,10)||1),Is=Number(We.componentId),Y={estoque:Number(We.resolvedEstoqueId),quantidade:hs,ignorarEstoque:!!We.ignorarEstoque};return Number.isInteger(Is)&&Is>0&&(Y.id=Is),Y})};try{u==="edit"&&c?(await ae.mutateAsync({id:c,documentId:_e.find(We=>We.id===c)?.documentId||null,data:ss}),s({title:"Combo atualizado",description:"As alterações foram salvas com sucesso."})):(await be.mutateAsync(ss),s({title:"Combo criado",description:"O combo está disponível para uso."})),i(!1),Ee()}catch(We){s({variant:"destructive",title:"Não foi possível salvar o combo",description:We?.response?.data?.error?.message||We.message||"Tente novamente em instantes."})}},ks=k=>{l("edit"),m(k.id),Ze(k),i(!0)},xs=be.isPending||ae.isPending;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-2 md:gap-0 md:flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Combos"}),e.jsx("p",{className:"text-muted-foreground",children:"Monte ofertas agrupando itens de estoque com quantidades definidas."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(at,{open:o,onOpenChange:qe,children:[e.jsx(vn,{asChild:!0,children:e.jsxs(w,{onClick:()=>{l("create"),m(null),Ee()},children:[e.jsx(et,{className:"mr-2 h-4 w-4"})," Novo combo"]})}),e.jsxs(rt,{className:"w-[95vw] sm:max-w-4xl max-h-[85vh] overflow-y-auto",children:[e.jsx(nt,{children:e.jsx(it,{children:u==="edit"?"Editar combo":"Novo combo"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Nome"}),e.jsx(Te,{value:x,onChange:k=>h(k.target.value)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-6 md:pt-0",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Ativo"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disponível para venda"})]}),e.jsx(Ls,{checked:re,onCheckedChange:te})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Descrição"}),e.jsx(yn,{rows:3,value:p,onChange:k=>f(k.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Preç
91o (R$)"}),e.jsx(Te,{type:"number",step:"0.01",min:0,value:I,onChange:k=>g(k.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm",children:"Desconto (%)"}),e.jsx(Te,{type:"number",step:"0.1",min:0,max:100,value:N,onChange:k=>b(k.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm",children:"Categoria"}),e.jsxs("select",{className:"border rounded px-2 py-1 w-full bg-background",value:C,onChange:k=>q(k.target.value),children:[e.jsx("option",{value:"",children:"— Selecione —"}),W.map(k=>e.jsx("option",{value:k.id,children:k.nome},k.id))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm",children:"Evento"}),e.jsxs("select",{className:"border rounded px-2 py-1 w-full bg-background",value:L,onChange:k=>M(k.target.value),children:[e.jsx("option",{value:"",children:"— Nenhum —"}),z.map(k=>e.jsx("option",{value:k.id,children:k.titulo},k.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm",children:"Imagem"}),e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center",children:[e.jsx(wr,{src:S||F?.url,alt:x||"Pré-visualização do combo",className:"h-20 w-20"}),e.jsxs("div",{className:"flex flex-1 flex-col gap-2",children:[e.jsx("input",{className:"border rounded px-2 py-1 w-full bg-background",type:"file",accept:"image/*",onChange:k=>Qe(k.target.files?.[0]||null)}),(S||F)&&e.jsx(w,{variant:"ghost",size:"sm",className:"self-start",onClick:we,children:"Remover imagem"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-medium",children:"Itens do combo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Selecione itens do estoque, defina a quantidade e, se necessário, ignore a baixa de estoque."})]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>y(k=>[...k,Tn()]),children:[e.jsx(et,{className:"mr-1 h-4 w-4"})," Adicionar item"]})]}),e.jsx("div",{className:"space-y-2",children:G.map((k,De)=>{const Ne=k.estoqueId?String(k.estoqueId):"",es=Ne&&J.get(Ne)||(k.estoqueDocumentId?T.get(k.estoqueDocumentId):null),ss=So(es);return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_auto] gap-3 items-start border border-border rounded-lg p-3 bg-card/60",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm",children:"Produto de estoque"}),e.jsxs("select",{className:"border rounded px-2 py-1 w-full bg-background",value:k.estoqueId,onChange:We=>{const hs=We.target.value,Is=hs?J.get(String(hs)):null,Y=Is?.attributes?.documentId??Is?.documentId??"";y(Q=>Q.map((X,V)=>V===De?{...X,estoqueId:hs,estoqueDocumentId:Y,ignorarEstoque:X.ignorarEstoque}:X))},children:[e.jsx("option",{value:"",children:"— Selecione —"}),Ae.map(We=>e.jsx("option",{value:We.id,children:So(We).label},We.id))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm",children:"Quantidade"}),e.jsx(Te,{type:"number",min:1,value:k.quantidade,onChange:We=>{const hs=We.target.value;y(Is=>Is.map((Y,Q)=>Q===De?{...Y,quantidade:hs}:Y))}})]}),e.jsx(w,{type:"button",variant:"ghost",size:"icon",onClick:()=>Se(De),disabled:G.length===1,"aria-label":"Remover item",children:e.jsx(Xt,{className:"h-4 w-4"})}),e.jsx("div",{className:"md:col-span-3 space-y-2 border-t border-border pt-2",children:e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsx(Ls,{checked:!!k.ignorarEstoque,onCheckedChange:We=>{y(hs=>hs.map((Is,Y)=>Y===De?{...Is,ignorarEstoque:!!We}:Is))}}),"Não abater quantidade do estoque ao vender este item."]}),k.estoqueId?e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsx(wr,{src:ss.imageUrl,alt:ss.label,className:"h-12 w-12"}),e.jsx("span",{children:ss.label})]}):null]})})]},k.rowKey||`${De}`)})})]}),e.jsx("div",{className:"sticky bottom-0 -mx-6 px-6 pb-4 pt-3 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-t border-border",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(w,{variant:"outline",onClick:()=>i(!1),children:"Cancelar"}),e.jsx(w,{onClick:Me,disabled:!x.trim()||xs,children:xs?"Salvando…":"Salvar"})]})})]})]})]}),e.jsxs(w,{variant:"outline",onClick:()=>ve(!0),children:[e.jsx(xo,{className:"mr-2 h-4 w-4"})," Histórico geral"]})]})]}),e.jsx(he,{children:e.jsxs(ge,{className:"pt-6",children:[e.jsx("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:e.jsx(Te,{placeholder:"Buscar combos…",value:t,onChange:k=>a(k.target.value),className:"sm:max-w-xs"})}),ke?e.jsx("div",{className:"text-center py-10 text-muted-foreground",children:"Carregando combos..."}):U.length===0?e.jsx("div",{className:"text-center py-10 text-muted-foreground",children:"Nenhum combo encontrado"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-4 md:hidden",children:U.map(k=>{const{precoBase:De,descontoPercentual:Ne,precoFinal:es}=Hl(k);return e.jsxs(he,{className:"overflow-hidden",children:[e.jsxs(Be,{className:"flex flex-row items-center gap-4",children:[e.jsx(wr,{src:k.imagemUrl,alt:k.nome,className:"h-20 w-20"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx(ze,{className:"text-lg leading-tight",children:k.nome}),k.descricao?e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:k.descricao}):null]}),e.jsxs(Sr,{children:[e.jsx(Ir,{asChild:!0,children:e.jsx(w,{size:"icon",variant:"outline","aria-label":"Mais ações",children:e.jsx(ai,{className:"h-4 w-4"})})}),e.jsxs(Ar,{align:"end",children:[e.jsxs(tt,{onSelect:()=>O(k.id),children:[e.jsx(xo,{className:"mr-2 h-4 w-4"})," Ver histórico…"]}),e.jsx(tt,{onSelect:async ss=>
91{ss.preventDefault(),await me(k,!k.ativo)},children:k.ativo?"Desativar combo":"Ativar combo"}),e.jsxs(tt,{onSelect:()=>ks(k),children:[e.jsx(ol,{className:"mr-2 h-4 w-4"})," Editar rapidamente"]}),e.jsxs(tt,{className:"text-destructive",onSelect:async ss=>{ss.preventDefault(),await fe(k)},children:[e.jsx(Xt,{className:"mr-2 h-4 w-4"})," Excluir"]})]})]})]}),e.jsxs(ge,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-foreground",children:"Preço:"})," ",aa(es),Ne>0&&e.jsx("span",{className:"ml-2 text-xs line-through",children:aa(De)})]}),k.categoria?.nome&&e.jsxs("div",{children:["Categoria: ",k.categoria.nome]}),k.evento?.titulo&&e.jsxs("div",{children:["Evento: ",k.evento.titulo]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground",children:"Itens"}),e.jsx("ul",{className:"space-y-2",children:k.itens.map(ss=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(wr,{src:ss.imagemUrl,alt:ss.nome,className:"h-12 w-12"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:ss.nome}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs(je,{variant:"secondary",children:["x",ss.quantidade]}),ss.ignorarEstoque&&e.jsx(je,{variant:"outline",children:"Ignora estoque"})]})]})]},`${k.id}-mobile-${ss.uniqueKey||ss.id}`))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(je,{variant:k.ativo?"default":"outline",children:k.ativo?"Ativo":"Inativo"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Ls,{checked:k.ativo,onCheckedChange:ss=>me(k,ss),disabled:ae.isPending,"aria-label":k.ativo?"Desativar combo":"Ativar combo"}),e.jsx("span",{children:k.ativo?"Ativo":"Inativo"})]})]})]})]},`card-${k.id}`)})}),e.jsx("div",{className:"overflow-x-auto hidden md:block",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Combo"}),e.jsx(ue,{children:"Detalhes"}),e.jsx(ue,{children:"Itens"}),e.jsx(ue,{children:"Status"}),e.jsx(ue,{className:"text-right",children:"Ações"})]})}),e.jsx(Ct,{children:U.map(k=>{const De=k?.nome,Ne=k?.ativo?"Ativo":"Inativo",{precoBase:es,descontoPercentual:ss,precoFinal:We}=Hl(k);return e.jsxs($s,{children:[e.jsx(ye,{className:"align-top",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(wr,{src:k.imagemUrl,alt:De}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-foreground",children:De}),k?.descricao?e.jsx("div",{className:"text-sm text-muted-foreground max-w-[280px] truncate",children:k.descricao}):null]})]})}),e.jsxs(ye,{className:"align-top text-sm text-muted-foreground space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-foreground",children:"Preço:"})," ",aa(We),ss>0&&e.jsx("span",{className:"ml-2 text-xs line-through",children:aa(es)})]}),k?.categoria?.nome&&e.jsxs("div",{children:["Categoria: ",k.categoria.nome]}),k?.evento?.titulo&&e.jsxs("div",{children:["Evento: ",k.evento.titulo]})]}),e.jsx(ye,{className:"align-top text-sm",children:e.jsx("ul",{className:"space-y-1",children:k.itens.map((hs,Is)=>e.jsxs("li",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(wr,{src:hs.imagemUrl,alt:hs.nome,className:"h-10 w-10"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(je,{variant:"secondary",children:["x",hs.quantidade]}),e.jsx("span",{className:"text-foreground/90",children:hs.nome}),hs.ignorarEstoque&&e.jsx(je,{variant:"outline",children:"Ignora estoque"})]})]},`${k.id}-${hs.uniqueKey||hs.id||Is}`))})}),e.jsx(ye,{className:"align-top",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(je,{variant:Ne==="Ativo"?"default":"outline",children:Ne}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Ls,{checked:k.ativo,onCheckedChange:hs=>me(k,hs),disabled:ae.isPending,"aria-label":k.ativo?"Desativar combo":"Ativar combo"}),e.jsx("span",{children:k.ativo?"Ativo":"Inativo"})]})]})}
91),e.jsx(ye,{className:"text-right align-top",children:e.jsxs(Sr,{children:[e.jsx(Ir,{asChild:!0,children:e.jsx(w,{size:"icon",variant:"outline","aria-label":"Mais ações",children:e.jsx(ai,{className:"h-4 w-4"})})}),e.jsxs(Ar,{align:"end",children:[e.jsx(tt,{onSelect:()=>O(k.id),children:"Ver histórico…"}),e.jsx(tt,{onSelect:async hs=>{hs.preventDefault(),await me(k,!k.ativo)},children:k.ativo?"Desativar combo":"Ativar combo"}),e.jsxs(tt,{onSelect:()=>ks(k),children:[e.jsx(ol,{className:"mr-2 h-4 w-4"})," Editar rapidamente"]}),e.jsx(tt,{className:"text-destructive",onSelect:async hs=>{hs.preventDefault(),await fe(k)},children:"Excluir"})]})]})})]},k.id)})})]})})]})]})}),e.jsx(Rh,{openId:K,onClose:()=>O(null)}),e.jsx(Th,{open:oe,onClose:()=>ve(!1)})]})}function Rh({openId:s,onClose:t}){const{data:a=[]}=xx(s||0);return e.jsx(at,{open:!!s,onOpenChange:n=>!n&&t?.(),children:e.jsxs(rt,{className:"max-w-2xl",children:[e.jsx(nt,{children:e.jsx(it,{children:"Histórico do combo"})}),e.jsx("div",{className:"max-h-[60vh] overflow-auto",children:e.jsx(Ei,{logs:a})})]})})}function Th({open:s,onClose:t,limit:a=100}){const{data:n=[]}=px(a);return e.jsx(at,{open:!!s,onOpenChange:o=>!o&&t?.(),children:e.jsxs(rt,{className:"max-w-3xl",children:[e.jsx(nt,{children:e.jsx(it,{children:"Histórico geral dos combos"})}),e.jsx("div",{className:"max-h-[60vh] overflow-auto",children:e.jsx(Ei,{logs:n})})]})})}const $h="/eventos?pagination[pageSize]=200&sort=titulo:asc&populate[datas_futuras]=true&populate[datas_passadas]=true&populate[lotes][populate][tipo_ingresso]=true&populate[tipos_ingresso][populate][tipo_ingresso]=true",ga=12,Lh=(s="")=>s.replace(/[\s_-]+/g,""),Mh=(s="")=>{const t=Lh(s);return t.includes("superadmin")||t.includes("supersuporte")||t.includes("suporte")},Fh={tipo_ingresso:"",lote_id:"",quantidade:1};let Wl=0;const Lc=()=>(Wl+=1,{draftKey:`invite-item-${Wl}`,...Fh}),Io=()=>({eventoDocumentId:"",data_evento:"",descontar_estoque:!1,gerar_link_aceite:!0,expires_at:"",observacoes:"",items:[Lc()]}),Oh={expires_at:"",observacoes:""},fi=se.oneOfType([se.string,se.number]),qh=se.shape({nome:se.string}),Mc=se.shape({id:fi,draftKey:se.string,quantidade:se.oneOfType([se.string,se.number]),status:se.string,nome_item:se.string,lote_id:fi,tipo_ingresso:se.oneOfType([se.string,qh])}),Qo=se.shape({id:fi,documentId:se.string,nome:se.string,cpf:se.string,email:se.string,telefone:se.string,status_invite:se.string,data_evento:se.string,descontar_estoque:se.bool,estoque_baixado:se.bool,necessidades_especiais:se.string,observacoes:se.string,codigo_convite:se.string,evento:se.shape({titulo:se.string,local:se.string}),items:se.arrayOf(Mc)}),ji=se.shape({key:se.string.isRequired,data:se.string,observacao:se.string,source:se.oneOf(["past","future"]),ingressos_disponiveis:se.number,limite_ingressos:se.number,usageCount:se.number}),Fc=se.shape({id:fi,documentId:se.string,titulo:se.string,datas_futuras:se.arrayOf(ji),datas_passadas:se.arrayOf(ji)}),zh=se.shape({eventoDocumentId:se.string,data_evento:se.string,descontar_estoque:se.bool,gerar_link_aceite:se.bool,expires_at:se.string,observacoes:se.string,items:se.arrayOf(Mc)}),Uh=se.shape({expires_at:se.string,observacoes:se.string}),Jn=s=>s?s.attributes&&typeof s.attributes=="object"?{id:s.id,...s.attributes}:s.data?Jn(s.data):s:null,vi=s=>{const t=String(s||"").toLowerCase();return t==="ativo"?{label:"Ativo",className:"bg-emerald-50 text-emerald-700 border-emerald-200"}:t==="pendente"?{label:"Pendente",className:"bg-amber-50 text-amber-700 border-amber-200"}:t==="cancelado"?{label:"Cancelado",className:"bg-rose-50 text-rose-700 border-rose-200"}:{label:s||"Desconhecido",className:"bg-muted text-muted-foreground border-border"}},Bh=s=>{const t=Jn(s),a=(l,c="future")=>Array.isArray(l)?l.map(m=>({id:m?.id||null,data:m?.data||null,observacao:m?.observacao||null,key:Et(m?.data),source:c,ingressos_disponiveis:Number.isFinite(Number(m?.ingressos_disponiveis))?Number(m.ingressos_disponiveis):null,limite_ingressos:Number.isFinite(Number(m?.limite_ingressos))?Number(m.limite_ingressos):null})).filter(m=>m.key):[],n=a(t?.datas_futuras,"future"),o=a(t?.datas_passadas,"past"),i=Array.isArray(t?.lotes)?t.lotes.map(l
91=>{const c=Jn(l?.tipo_ingresso);return{id:l?.id||null,nome:l?.nome||null,data_evento:l?.data_evento||null,quantidade_disponivel:l?.quantidade_disponivel??0,ativo:l?.ativo!==!1,tipo_ingresso:c?{id:c.id||null,documentId:c.documentId||null,nome:c.nome||c.titulo||null,quantidade_itens:c.quantidade_itens??null}:null}}):[],u=new Map;for(const l of i){if(!l?.tipo_ingresso)continue;const c=l.tipo_ingresso.documentId||String(l.tipo_ingresso.id||"");!c||u.has(c)||u.set(c,l.tipo_ingresso)}for(const l of Array.isArray(t?.tipos_ingresso)?t.tipos_ingresso:[]){const c=Jn(l?.tipo_ingresso);if(!c)continue;const m=c.documentId||String(c.id||"");!m||u.has(m)||u.set(m,{id:c.id||null,documentId:c.documentId||null,nome:c.nome||c.titulo||null,quantidade_itens:c.quantidade_itens??null})}return{id:t?.id||null,documentId:t?.documentId||null,titulo:t?.titulo||"Evento",local:t?.local||null,datas_futuras:n,datas_passadas:o,lotes:i,tipos_ingresso:Array.from(u.values())}},Oc=s=>!s||!globalThis.location?.origin?"":`${globalThis.location.origin}/convite-direto/${s}`,gn=s=>s?.documentId||String(s?.id||""),Vh=s=>{const t=dn(s);if(!t)return!1;const a=new Date;return a.setHours(0,0,0,0),t>=a},qc=s=>{if(!s)return[];const t=new Map,a=(n=[])=>{n.forEach(o=>{!o?.key||t.has(o.key)||t.set(o.key,o)})};return a(s.datas_futuras||[]),a(s.datas_passadas||[]),Array.from(t.values()).sort((n,o)=>n.key.localeCompare(o.key))},Gh=s=>qc(s).filter(t=>Vh(t?.data||t?.key)),zc=(s={})=>{const t=s?.ingressos_disponiveis,a=s?.limite_ingressos;return t===null&&a===null?null:`${t??"—"}/${a??"—"} ingressos`},Uc=(s={},t=0)=>{const a=Va(s?.data),n=s?.observacao?` - ${s.observacao}`:"",o=zc(s),i=o?` | ${o}`:"";return`${a}${n} (${t}/${ga} convites${i})`},Bc=s=>Math.max(1,Number(s?.quantidade_itens??1)||1)===1,Vc=(s,t)=>{if(!s)return[];const n=(Array.isArray(s.lotes)?s.lotes:[]).filter(u=>{const l=Et(u?.data_evento);return!t||l===t}).map(u=>u.tipo_ingresso).filter(Boolean),o=n.length>0?n:s.tipos_ingresso||[],i=new Map;for(const u of o){const l=gn(u);!l||i.has(l)||Bc(u)&&i.set(l,u)}return Array.from(i.values())},Gc=(s,t,a)=>s?(Array.isArray(s.lotes)?s.lotes:[]).filter(n=>{const o=Et(n?.data_evento),i=gn(n?.tipo_ingresso);return(!t||o===t)&&(!a||i===a)&&Bc(n?.tipo_ingresso)}):[],Hc=(s,t)=>`${s||""}::${t||""}`,Ao=s=>{const t=Number(s?.quantidade||0);return Number.isFinite(t)&&t>0?t:0},Hh=(s,t)=>Et(t?.metadata?.data_evento||s?.data_evento),Kh=(s=[])=>{const t=new Map;return s.forEach(a=>{if(String(a?.status_invite||"").toLowerCase()==="cancelado")return;const n=a?.evento?.documentId||"";if(!n)return;(Array.isArray(a?.items)?a.items:[]).forEach(i=>{const u=Hh(a,i);if(!u)return;const l=Hc(n,u);t.set(l,(t.get(l)||0)+Ao(i))})}),t},Gr=(s,t,a)=>!s||!t||!a?0:s.get(Hc(t,a))||0,Qh=(s,t,a)=>{const n=Math.max(1,Number(s?.quantidade||1)||1);if(!t||!a)return{...s,quantidade:n,tipo_ingresso:"",lote_id:""};const o=Vc(t,a),i=String(s?.tipo_ingresso||""),u=o.some(I=>gn(I)===i),l=o[0]?gn(o[0]):"",c=u?i:l,m=Gc(t,a,c),x=String(s?.lote_id||""),h=m.some(I=>String(I?.id)===x),p=m[0]?String(m[0].id):"";return{...s,quantidade:n,tipo_ingresso:c,lote_id:h?x:p}},Hr=(s,t)=>({...s,descontar_estoque:!1,gerar_link_aceite:!0,items:(Array.isArray(s.items)?s.items:[]).map(a=>Qh(a,t,s.data_evento))}),Eo=s=>s?.nome||(s?.status_invite==="pendente"?"Aguardando aceite":"Sem nome"),Wh=s=>({eventoDocumentId:s.eventoDocumentId,data_evento:s.data_evento,descontar_estoque:!1,gerar_link_aceite:!0,expires_at:s.expires_at||null,observacoes:s.observacoes||null,items:s.items.map(t=>({tipo_ingresso:t.tipo_ingresso,quantidade:Number(t.quantidade||1),metadata:{data_evento:s.data_evento,lote_id:Number(t.lote_id)}}))}),Jh=(s,{currentDateUsage:t=0,canBypassInviteCap:a=!1}={})=>{if(!s.eventoDocumentId)return"Selecione um evento";if(!s.data_evento)return"Selecione a data do evento";if(s.items.some(i=>{const u=Number(i.quantidade||0);return!i.tipo_ingresso||!i.lote_id||!Number.isFinite(u)||u<1}))return"Preencha todos os itens do convite";const o=s.items.reduce((i,u)=>i+Math.max(1,Number(u.quantidade||1)||1),0);return!a&&t+o>ga?`A data selecionada ultrapassa o limite de ${ga} convites (${t+o}/${ga})`:null},Yh=s=>({...Io(),eventoDocumentId:s,descontar_estoque:!1,gerar_link_aceite:!0}),Xh=(s,t)=>({...s,data_evento:t,items:s.items.map(a=>({...a,lote_id:""}))}),Zh=(s,t,a,n)=>({...s,items:s.items.map((o,i)=>i!==t?o:a==="tipo_ingresso"?{...o,tipo_ingresso:n,lote_id:""}:{...o,[a]:n})}),eg=s=>({...s,items:[...s.items,Lc()]}),sg=(s,t)=>({...s,items:s.items.filter((a,n)=>n!==t)}),tg=async({createForm:s,createInvite:t,toast:a,resetCreateForm:n,canBypassInviteCap:o})=>{const i=Jh(s,{currentDateUsage:s.currentDateUsage||0,canBypassInviteCap:o});if(i){a({title:i,variant:"destructive"});return}const u=Array.isArray(s.items)?s.items.reduce((c,m)=>c+Math.max(1,Number(m.quantidade||1)||1),0):0,l=Number(s.currentDateUsage||0)+u;o&&l>ga&&a({title:`Limite ultrapassado (${l}/${ga})`,description:"Seu perfil permite criar convites acima do limite por data."});try{const c=await t.mutateAsync(Wh(s));a({title:"Convite pendente criado",description:c?.codigo_convite?`Código ${c.codigo_convite}`:void 0}),n()}catch(c){a({title:"Erro ao criar convite",description:c?.response?.data?.error?.message||c?.message||"Tente novamente.",variant:"destructive"})}},ag=async({editingInvite:s,editForm:t,updateInvite:a,toast:n,closeDialog:o})=>{if(s?.documentId)try{await a.mutateAsync({documentId:s.documentId,data:ig(t)}),n({title:"Convite atualizado"}),o()}catch(i){n({title:"Erro ao atualizar convite",description:i?.response?.data?.error?.message||i?.message||"Tente novamente.",variant:"destructive"})}},rg=async({invite:s,cancelInvite:t,toast:a})=>{if(!(!s?.documentId||!globalThis.confirm?.(`Cancelar o convite ${s.codigo_convite||s.documentId||"selecionado"}?`)))try{await t.mutateAsync(s.documentId),a({title:"Convite cancelado"})}catch(o){a({title:"Erro ao cancelar convite",description:o?.response?.data?.error?.message||o?.message||"Tente novamente.",variant:"destructive"})}},ng=async({invite:s,toast:t})=>{const a=Oc(s?.codigo_convite);if(!a){t({title:"Link indisponível",variant:"destructive"});return}try{await navigator.clipboard.writeText(a),t({title:"Link copiado"})}catch(n){console.error("Falha ao copiar link de convite",n),t({title:"Não foi possível copiar o link",variant:"destructive"})}};function Kc({stats:s}){return e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium",children:"Total"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-bold",children:s.total})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium",children:"Pendentes"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-bold text-amber-600",children:s.pendente})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium",children:"Ativos"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-bold text-emerald-600",children:s.ativo})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium",children:"Cancelados"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-bold text-rose-600",children:s.cancelado})})]})]})}Kc.propTypes={stats:se.shape({total:se.number.isRequired,pendente:se.number.isRequired,ativo:se.number.isRequired,cancelado:se.number.isRequired}).isRequired};function Qc({filters:s,setFilters:t,searchTerm:a,setSearchTerm:n,eventsData:o,dateOptions:i,onClear:u}){const l=c=>{t(m=>({...m,eventoDocumentId:c,dataEvento:""}))};return e.jsxs(he,{children:[e.jsx(Be,{className:"pb-4",children:e.jsx(ze,{className:"text-base",children:"Filtros"})}),e.jsxs(ge,{className:"grid gap-3 lg:grid-cols-4",children:[e.jsxs("div",{className:"space-y-2 lg:col-span-2",children:[e.jsx(Oe,{htmlFor:"invite-search",children:"Buscar por código, convidado ou evento"}),e.jsxs("div",{className:"relative",children:[e.jsx(At,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(Te,{id:"invite-search",value:a,onChange:c=>n(c.target.value),placeholder:"Ex.: INV-..., aguardando aceite, Festa de Sábado",className:"pl-9"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Evento"}),e.jsxs(rs,{value:s.eventoDocumentId,onValueChange:l,children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Todos os eventos"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos os eventos"}),o.map(c=>
91e.jsx(xe,{value:c.documentId||String(c.id),children:c.titulo},c.documentId||c.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Status"}),e.jsxs(rs,{value:s.status,onValueChange:c=>t(m=>({...m,status:c})),children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Todos os status"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos os status"}),e.jsx(xe,{value:"pendente",children:"Pendente"}),e.jsx(xe,{value:"ativo",children:"Ativo"}),e.jsx(xe,{value:"cancelado",children:"Cancelado"})]})]})]}),s.eventoDocumentId==="all"?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Data do evento"}),e.jsxs(rs,{value:s.dataEvento||"all",onValueChange:c=>t(m=>({...m,dataEvento:c==="all"?"":c})),children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Todas as datas"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todas as datas"}),i.map(c=>e.jsx(xe,{value:c.key,children:Uc(c,c.usageCount||0)},c.key))]})]})]}),e.jsx("div",{className:"flex items-end",children:e.jsx(w,{variant:"outline",className:"w-full",onClick:u,children:"Limpar filtros"})})]})]})}Qc.propTypes={filters:se.shape({eventoDocumentId:se.string.isRequired,status:se.string.isRequired,dataEvento:se.string.isRequired}).isRequired,setFilters:se.func.isRequired,searchTerm:se.string.isRequired,setSearchTerm:se.func.isRequired,eventsData:se.arrayOf(Fc).isRequired,dateOptions:se.arrayOf(ji).isRequired,onClear:se.func.isRequired};function Wc({loading:s,filteredInvites:t,setDetailsInvite:a,openEditDialog:n,handleCopyLink:o,handleCancelInvite:i}){let u=null;return s?u=e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Cs,{className:"h-4 w-4 animate-spin"})," Carregando convites..."]}):t.length===0?u=e.jsx("div",{className:"rounded-md border border-dashed p-8 text-center text-sm text-muted-foreground",children:"Nenhum convite encontrado para os filtros atuais."}):u=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"md:hidden space-y-3",children:t.map(l=>{const c=vi(l?.status_invite),m=l?.status_invite==="cancelado",x=l?.dateUsageCount||0,h=Array.isArray(l?.items)?l.items.reduce((p,f)=>p+Ao(f),0):0;return e.jsxs("div",{className:"rounded-md border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:l?.codigo_convite||"Sem código"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Eo(l)})]}),e.jsx(je,{variant:"outline",className:`shrink-0 ${c.className}`,children:c.label})]}),e.jsxs("div",{className:"text-sm text-muted-foreground space-y-0.5",children:[e.jsx("div",{className:"truncate",children:l?.evento?.titulo||"Evento não encontrado"}),e.jsx("div",{children:Va(l?.data_evento)}),e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-0.5",children:[e.jsxs("span",{children:[Jl(l)," • ",h," item(ns)"]}),e.jsxs(je,{variant:x>=ga?"destructive":"secondary",className:"text-xs",children:[x,"/",ga]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>a(l),children:[e.jsx(Vt,{className:"mr-1.5 h-3.5 w-3.5"})," Detalhes"]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>n(l),children:[e.jsx(ln,{className:"mr-1.5 h-3.5 w-3.5"})," Editar"]}),l?.status_invite==="pendente"?e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>o(l),children:[e.jsx(Pa,{className:"mr-1.5 h-3.5 w-3.5"})," Link"]}):null,m?null:e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>i(l),children:[e.jsx(ni,{className:"mr-1.5 h-3.5 w-3.5"})," Cancelar"]})]})]},l.documentId||l.id)})}),e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Código"}),e.jsx(ue,{children:"Evento"}),e.jsx(ue,{children:"Data"}),e.jsx(ue,{children:"Tipo Ingresso"}),e.jsx(ue,{children:"Qtd itens"}),e.jsx(ue,{children:"Status"}),e.jsx(ue,{children:"Limite data"}),e.jsx(ue,{className:"text-right",children:"Ações"})]})}),e.jsx(Ct,{children:t.map(l=>{const c=vi(l?.status_invite),m=l?.status_invite==="cancelado",x=l?.dateUsageCount||0;return e.jsxs($s,{children:[e.jsxs(ye,{children:[e.jsx("div",{className:"font-medium",children:l?.codigo_convite||"Sem código"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Eo(l)})]}),e.jsx(ye,{children:l?.evento?.titulo||"Evento não encontrado"}),e.jsx(ye,{children:Va(l?.data_evento)}),e.jsx(ye,{children:Jl(l)}),e.jsx(ye,{children:Array.isArray(l?.items)?l.items.reduce((h,p)=>h+Ao(p),0):0}),e.jsx(ye,{children:e.jsx(je,{variant:"outline",className:c.className,children:c.label})}),e.jsx(ye,{children:e.jsxs(je,{variant:x>=ga?"destructive":"secondary",children:[x,"/",ga]})}),e.jsx(ye,{children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(w,{variant:"outline",size:"icon",onClick:()=>a(l),"aria-label":"Ver detalhes",children:e.jsx(Vt,{className:"h-4 w-4"})}),e.jsx(w,{variant:"outline",size:"icon",onClick:()=>n(l),"aria-label":"Editar convite",children:e.jsx(ln,{className:"h-4 w-4"})}),l?.status_invite==="pendente"?e.jsx(w,{variant:"outline",size:"icon",onClick:()=>o(l),"aria-label":"Copiar link",children:e.jsx(Pa,{className:"h-4 w-4"})}):null,m?null:e.jsx(w,{variant:"outline",size:"icon",onClick:()=>i(l),"aria-label":"Cancelar convite",children:e.jsx(ni,{className:"h-4 w-4"})})]})})]},l.documentId||l.id)})})]})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-4",children:e.jsx(ze,{className:"text-base",children:"Lista de convites"})}),e.jsx(ge,{children:u})]})}Wc.propTypes={loading:se.bool.isRequired,filteredInvites:se.arrayOf(Qo).isRequired,setDetailsInvite:se.func.isRequired,openEditDialog:se.func.isRequired,handleCopyLink:se.func.isRequired,handleCancelInvite:se.func.isRequired};
91function Jc({createOpen:s,setCreateOpen:t,resetCreateForm:a,createForm:n,eventsData:o,handleCreateEventChange:i,dateOptions:u,handleCreateDateChange:l,selectedEvent:c=null,setCreateForm:m,addCreateItem:x,updateCreateItem:h,removeCreateItem:p,dateUsageCount:f,requestedItemCount:I,canBypassInviteCap:g,createInvite:N,handleCreateSubmit:b}){const C=u.find(L=>L.key===n.data_evento)||null,q=f+I>ga;return e.jsx(at,{open:s,onOpenChange:L=>{L?t(!0):a()},children:e.jsxs(rt,{className:"w-[calc(100vw-2rem)] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(nt,{children:[e.jsx(it,{children:"Novo convite"}),e.jsx(Ba,{children:"Crie um link de aceite com estoque desligado e preenchimento de dados apenas no aceite."})]}),e.jsxs("div",{className:"grid gap-6 grid-cols-1 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Evento"}),e.jsxs(rs,{value:n.eventoDocumentId||void 0,onValueChange:i,children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione um evento"})}),e.jsx(os,{children:o.map(L=>e.jsx(xe,{value:L.documentId||String(L.id),children:L.titulo},L.documentId||L.id))})]})]}),e.jsx("div",{className:"space-y-2",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Oe,{children:"Data do evento"}),e.jsxs(rs,{value:n.data_evento||void 0,onValueChange:l,children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione a data"})}),e.jsx(os,{children:u.map(L=>e.jsx(xe,{value:L.key,children:Uc(L,L.usageCount||0)},L.key))})]}),n.data_evento?e.jsxs("div",{className:"rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground space-y-1",children:[e.jsxs("div",{children:["Este convite adiciona ",I," item(ns). Limite desta data: ",f,"/",ga," convites."]}),q?e.jsx("div",{className:g?"text-emerald-600":"text-destructive",children:g?"Seu perfil permite ultrapassar o limite por data.":`A data selecionada ultrapassa o limite de ${ga} convites.`}):null,e.jsx("div",{children:C?`Disponibilidade das vendas do evento: ${zc(C)||"sem limite informado"}`:"Disponibilidade do evento: sem limite informado"})]}):null]}):null}),e.jsxs("div",{className:"space-y-4 rounded-md border p-4",children:[e.jsx("div",{children:e.jsx("div",{className:"font-medium",children:"Configuração do convite"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"invite-expire",children:"Expira em"}),e.jsx(Te,{id:"invite-expire",type:"datetime-local",value:n.expires_at,onChange:L=>m(M=>({...M,expires_at:L.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"invite-observacoes",children:"Observacoes"}),e.jsx(yn,{id:"invite-observacoes",rows:4,value:n.observacoes,onChange:L=>m(M=>({...M,observacoes:L.target.value})),placeholder:"Observacoes internas do convite"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nome, CPF, telefone, e-mail, observações e necessidades especiais serão preenchidos apenas quando o convidado aceitar o link."})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsx("h3",{className:"font-medium",children:"Itens do convite"})}),e.jsxs(w,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(et,{className:"mr-2 h-4 w-4"}),"Adicionar item"]})]}),e.jsx("div",{className:"space-y-3",children:n.items.map((L,M)=>{const z=Vc(c,n.data_evento),D=Gc(c,n.data_evento,L.tipo_ingresso),E=z.find(P=>gn(P)===L.tipo_ingresso)||z[0]||null,A=D.find(P=>String(P?.id)===String(L.lote_id))||D[0]||null;let S=null;return n.data_evento&&(S=A?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Lote aplicado automaticamente: ",A.nome||`Lote ${A.id}`," • ",A.quantidade_disponivel??0," disponíveis"]}):e.jsx("div",{className:"text-xs text-destructive",children:"Nenhum lote disponível para o tipo selecionado automaticamente."})),e.jsxs("div",{className:"rounded-md border p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-medium",children:["Item ",M+1]}),n.items.length>1?e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>p(M),children:"Remover"}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Tipo de ingresso"}),e.jsx("div",{className:"rounded-md border bg-muted/30 px-3 py-2 text-sm font-medium",children:E?.nome||(n.data_evento?"Nenhum tipo disponível para esta data":"Selecione a data do evento")}),S]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Quantidade"}),e.jsx(Te,{type:"number",min:1,value:L.quantidade,onChange:P=>h(M,"quantidade",P.target.value)})]})]},L.draftKey)})})]})]}),e.jsxs(Ut,{children:[e.jsx(w,{variant:"outline",onClick:a,children:"Cancelar"}),e.jsxs(w,{onClick:b,disabled:N.isPending,children:[N.isPending?e.jsx(Cs,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Criar convite pendente"]})]})]})})}Jc.propTypes={createOpen:se.bool.isRequired,setCreateOpen:se.func.isRequired,resetCreateForm:se.func.isRequired,createForm:zh.isRequired,eventsData:se.arrayOf(Fc).isRequired,handleCreateEventChange:se.func.isRequired,dateOptions:se.arrayOf(ji).isRequired,handleCreateDateChange:se.func.isRequired,selectedEvent:se.object,setCreateForm:se.func.isRequired,addCreateItem:se.func.isRequired,updateCreateItem:se.func.isRequired,removeCreateItem:se.func.isRequired,dateUsageCount:se.number.isRequired,requestedItemCount:se.number.isRequired,canBypassInviteCap:se.bool.isRequired,createInvite:se.shape({isPending:se.bool.isRequired}).isRequired,handleCreateSubmit:se.func.isRequired};function Yc({detailsInvite:s=null,dateUsageCount:t,setDetailsInvite:a,handleCopyLink:n}){return e.jsx(at,{open:!!s,onOpenChange:o=>{o||a(null)},children:e.jsxs(rt,{className:"w-[calc(100vw-2rem)] max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(nt,{children:[e.jsx(it,{children:"Detalhes do convite"}),e.jsx(Ba,{className:"break-all",children:s?.codigo_convite||"Sem código"})]}),s?e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-1 sm:grid-cols-2",children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm",children:"Convite"})}),e.jsxs(ge,{className:"space-y-1",children:[e.jsx("div",{className:"font-medium break-all",children:s.codigo_convite||"Sem código"}),e.jsx("div",{className:"text-muted-foreground",children:Eo(s)}),e.jsx("div",{className:"text-muted-foreground",children:"Aceite via link"}),e.jsxs("div",{className:"text-muted-foreground",children:["Expira em: ",s.expires_at?String(s.expires_at).slice(0,16).replace("T"," "):"Sem expiração"]})]})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm",children:"Evento"})}),e.jsxs(ge,{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:s?.evento?.titulo||"Evento não encontrado"}),e.jsx("div",{className:"text-muted-foreground",children:Va(s?.data_evento)}),e.jsx("div",{className:"text-muted-foreground",children:s?.evento?.local||"L
91ocal não informado"})]})]})]}),e.jsxs("div",{className:"rounded-md border p-4 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(je,{variant:"outline",className:vi(s.status_invite).className,children:vi(s.status_invite).label}),e.jsxs(je,{variant:"secondary",children:["Limite da data: ",t,"/",ga]}),e.jsx(je,{variant:"outline",children:"Estoque desligado"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium mb-1",children:"Itens"}),e.jsx("div",{className:"space-y-2",children:(s.items||[]).map(o=>e.jsxs("div",{className:"rounded-md border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:o?.tipo_ingresso?.nome||o?.nome_item||"Ingresso"}),e.jsxs("div",{className:"text-muted-foreground",children:["Qtd: ",o?.quantidade||0," • Status: ",o?.status||"disponivel"]})]},o.id))})]}),s.observacoes?e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Observacoes"}),e.jsx("div",{className:"mt-1 whitespace-pre-wrap rounded-md border bg-muted/20 px-3 py-2 text-muted-foreground",children:s.observacoes})]}):null,s.codigo_convite?e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Link de aceite"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Te,{readOnly:!0,value:Oc(s.codigo_convite),className:"min-w-0 text-xs sm:text-sm"}),e.jsx(w,{variant:"outline",size:"icon",className:"shrink-0",onClick:()=>n(s),children:e.jsx(Pa,{className:"h-4 w-4"})})]})]}):null,s.documentId&&s.status_invite==="ativo"?e.jsx("div",{className:"pt-2",children:e.jsx(lt,{to:`/ingresso-convite/${s.documentId}`,target:"_blank",children:e.jsxs(w,{variant:"outline",className:"w-full gap-1.5",children:[e.jsx(sr,{className:"h-4 w-4"}),"Ver Detalhe do Ingresso"]})})}):null]})]}):null]})})}Yc.propTypes={detailsInvite:Qo,dateUsageCount:se.number.isRequired,setDetailsInvite:se.func.isRequired,handleCopyLink:se.func.isRequired};function Xc({editingInvite:s=null,setEditingInvite:t,editForm:a,setEditForm:n,handleEditSubmit:o,updateInvite:i}){return e.jsx(at,{open:!!s,onOpenChange:u=>{u||t(null)},children:e.jsxs(rt,{className:"w-[calc(100vw-2rem)] max-w-2xl",children:[e.jsxs(nt,{children:[e.jsx(it,{children:"Editar convite"}),e.jsx(Ba,{children:"Atualize apenas a validade do link sem alterar os itens já emitidos."})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"edit-invite-expire",children:"Expira em"}),e.jsx(Te,{id:"edit-invite-expire",type:"datetime-local",value:a.expires_at,onChange:u=>n(l=>({...l,expires_at:u.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"edit-invite-observacoes",children:"Observacoes"}),e.jsx(yn,{id:"edit-invite-observacoes",rows:4,value:a.observacoes,onChange:u=>n(l=>({...l,observacoes:u.target.value})),placeholder:"Observacoes internas do convite"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Os dados pessoais do convidado continuam sendo preenchidos somente no aceite."})]}),e.jsxs(Ut,{children:[e.jsx(w,{variant:"outline",onClick:()=>t(null),children:"Cancelar"}),e.jsxs(w,{onClick:o,disabled:i.isPending,children:[i.isPending?e.jsx(Cs,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Salvar alterações"]})]})]})})}Xc.propTypes={editingInvite:Qo,setEditingInvite:se.func.isRequired,editForm:Uh.isRequired,setEditForm:se.func.isRequired,handleEditSubmit:se.func.isRequired,updateInvite:se.shape({isPending:se.bool.isRequired}).isRequired};const ig=s=>({expires_at:s.expires_at||null,observacoes:s.observacoes||null}),Jl=s=>{const t=Array.isArray(s?.items)?s.items:[];if(!t.length)return"Sem itens";const a=t.map(n=>n?.tipo_ingresso?.nome||n?.nome_item||"Ingresso").filter(Boolean);return a.slice(0,2).join(", ")+(a.length>2?` +${a.length-2}`:"")};function og(){const{toast:s}=mt(),{user:t}=Zt(),a=String(t?.role?.type||t?.role?.name||t?.role?.code||"").toLowerCase(),n=Mh(a),[o,i]=r.useState({eventoDocumentId:"all",status:"all",dataEvento:"",pageSize:200}),[u,l]=r.useState(""),[c,m]=r.useState(!1),[x,h]=r.useState(null),[p,f]=r.useState(null),[I,g]=r.useState(Io),[N,b]=r.useState(Oh),{data:C=[],isLoading:q}=Ks(["invite-events-options"],$h,{select:J=>(Array.isArray(J?.data)?J.data:[]).map(Bh),staleTime:5*60*1e3}),{data:L,isLoading:M}=ho({eventoDocumentId:o.eventoDocumentId,status:o.status,dataEvento:o.dataEvento,pageSize:o.pageSize}),{data:z,isLoading:D}=ho({pageSize:1e3}),E=rx(),A=nx(),S=ix(),P=L?.data||[],F=z?.data||P,ee=r.useMemo(()=>Kh(F),[F]),re=r.useMemo(()=>{const J=u.trim().toLowerCase(),T=P.map(Ee=>({...Ee,dateUsageCount:Gr(ee,Ee?.evento?.documentId,Et(Ee?.data_evento))}));return J?T.filter(Ee=>[Ee?.codigo_convite,Ee?.nome,Ee?.cpf,Ee?.email,Ee?.evento?.titulo].filter(
91Boolean).join(" ").toLowerCase().includes(J)):T},[P,ee,u]),te=r.useMemo(()=>{const J={total:P.length,pendente:0,ativo:0,cancelado:0};for(const T of P){const Ee=String(T?.status_invite||"").toLowerCase();Ee in J&&(J[Ee]+=1)}return J},[P]),G=r.useMemo(()=>C.find(J=>J.documentId===I.eventoDocumentId)||null,[C,I.eventoDocumentId]),y=r.useMemo(()=>C.find(J=>J.documentId===o.eventoDocumentId)||null,[C,o.eventoDocumentId]),$=r.useMemo(()=>Gh(G).map(J=>({...J,usageCount:Gr(ee,G?.documentId,J.key)})),[ee,G]),W=r.useMemo(()=>qc(y).map(J=>({...J,usageCount:Gr(ee,y?.documentId,J.key)})),[ee,y]),ie=r.useMemo(()=>Gr(ee,G?.documentId,I.data_evento),[I.data_evento,ee,G]),ke=r.useMemo(()=>Array.isArray(I.items)?I.items.reduce((J,T)=>J+Math.max(1,Number(T?.quantidade||1)||1),0):0,[I.items]),Ae=()=>{g(Io()),m(!1)},be=J=>{const T=C.find(Ee=>(Ee.documentId||String(Ee.id))===J)||null;g(Hr(Yh(J),T))},Fe=J=>{g(T=>Hr(Xh(T,J),G))},ae=(J,T,Ee)=>{g(Se=>Hr(Zh(Se,J,T,Ee),G))},K=()=>{g(J=>Hr(eg(J),G))},O=J=>{g(T=>Hr(sg(T,J),G))},oe=async()=>{await tg({createForm:{...I,currentDateUsage:ie},createInvite:E,toast:s,resetCreateForm:Ae,canBypassInviteCap:n})},ve=J=>{f(J),b({expires_at:J?.expires_at?String(J.expires_at).slice(0,16):"",observacoes:J?.observacoes||""})},me=async()=>{await ag({editingInvite:p,editForm:N,updateInvite:A,toast:s,closeDialog:()=>f(null)})},fe=async J=>{await rg({invite:J,cancelInvite:S,toast:s})},le=async J=>{await ng({invite:J,toast:s})},_e=q||M||D,U=()=>{l(""),i({eventoDocumentId:"all",status:"all",dataEvento:"",pageSize:200})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Convites"}),e.jsx("p",{className:"text-muted-foreground",children:"Gerencie cortesias, links de aceite e o consumo por data."})]}),e.jsxs(w,{onClick:()=>m(!0),className:"gap-2",children:[e.jsx(et,{className:"h-4 w-4"}),"Novo convite"]})]}),e.jsx(Kc,{stats:te}),e.jsx(Qc,{filters:o,setFilters:i,searchTerm:u,setSearchTerm:l,eventsData:C,dateOptions:W,onClear:U}),e.jsx(Wc,{loading:_e,filteredInvites:re,setDetailsInvite:h,openEditDialog:ve,handleCopyLink:le,handleCancelInvite:fe}),e.jsx(Jc,{createOpen:c,setCreateOpen:m,resetCreateForm:Ae,createForm:I,eventsData:C,handleCreateEventChange:be,dateOptions:$,handleCreateDateChange:Fe,selectedEvent:G,setCreateForm:g,addCreateItem:K,updateCreateItem:ae,removeCreateItem:O,dateUsageCount:ie,requestedItemCount:ke,canBypassInviteCap:n,createInvite:E,handleCreateSubmit:oe}),e.jsx(Yc,{detailsInvite:x,dateUsageCount:Gr(ee,x?.evento?.documentId,Et(x?.data_evento)),setDetailsInvite:h,handleCopyLink:le}),e.jsx(Xc,{editingInvite:p,setEditingInvite:f,editForm:N,setEditForm:b,handleEditSubmit:me,updateInvite:A})]})}function Yl(s){return s?.content?s.content.map(lg).filter(Boolean):[]}function lg(s){switch(s.type){case"paragraph":return{type:"paragraph",children:Yn(s.content)};case"heading":return{type:"heading",level:s.attrs?.level||1,children:Yn(s.content)};case"bulletList":return{type:"list",format:"unordered",children:(s.content||[]).map(t=>({type:"list-item",children:Xl(t)}))};case"orderedList":return{type:"list",format:"ordered",children:(s.content||[]).map(t=>({type:"list-item",children:Xl(t)}))};case"blockquote":return{type:"quote",children:Yn(s.content?.[0]?.content)};default:return{type:"paragraph",children:[{type:"text",text:""}]}}}function Xl(s){if(!s?.content)return[{type:"text",text:""}];const t=[];for(const a of s.content)a.type==="paragraph"&&t.push(...Yn(a.content));return t.length?t:[{type:"text",text:""}]}function Yn(s){return!s||!s.length?[{type:"text",text:""}]:s.map(t=>{if(t.type==="text"){const a={type:"text",text:t.text||""};if(t.marks?.length){for(const n of t.marks)if(n.type==="bold"&&(a.bold=!0),n.type==="italic"&&(a.italic=!0),n.type==="code"&&(a.code=!0),n.type==="link")return{type:"link",url:n.attrs?.href||"",children:[{type:"text",text:t.text||""}]}}return a}return{type:"text",text:""}})}function lr({active:s,onClick:t,children:a,title:n}){return e.jsx(w,{type:"button",variant:"ghost",size:"sm",className:ls("h-7 w-7 p-0",s&&"bg-muted"),onClick:t,title:n,children:a})}function dg({editor:s,onClose:t}){const a=s?.getAttributes("link").href||"",[n,o]=r.useState(a),i=r.useRef(null);r.useEffect(()=>{i.current?.focus()},[]);const u=()=>{s&&(n.trim()?s.chain().focus().extendMarkRange("link").setLink({href:n.trim()}).run():s.chain().focus().extendMarkRange("link").unsetLink().run(),t())},l=()=>{s&&(s.chain().focus().extendMarkRange("link").unsetLink().run(),t())};return e.jsxs("div",{className:"flex items-center gap-1 px-1 py-1",children:[e.jsx(Te,{ref:i,value:n,onChange:c=>o(c.target.value),onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),u()),c.key==="Escape"&&(c.preventDefault(),t())},placeholder:"https://...",className:"h-7 text-xs flex-1"}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600",onClick:u,title:"Aplicar",children:e.jsx(ti,{className:"h-3.5 w-3.5"})}),a&&e.jsx(w,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-red-500",onClick:l,title:"Remover link",children:e.jsx(po,{className:"h-3.5 w-3.5"})}),e.jsx(w,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:t,title:"Cancelar",children:e.jsx(yt,{className:"h-3.5 w-3.5"})})]})}function Zc({content:s,onChange:t,placeholder:a="Escreva aqui...",className:n}){const[o,i]=r.useState(!1),u=hx({extensions:[gx.configure({heading:{levels:[2,3]},bulletList:{keepMarks:!0,keepAttributes:!1},orderedList:{keepMarks:!0,keepAttributes:!1}}),fx.configure({openOnClick:!1}),jx.configure({placeholder:a})],content:s||"",onUpdate:({editor:l})=>{t?.(l.getJSON())},editorProps:{attributes:{class:"prose prose-sm dark:prose-invert max-w-none focus:outline-none min-h-[100px] px-3 py-2 [&_ol]:list-decimal [&_ul]:list-disc [&_ol]:ml-4 [&_ul]:ml-4 [&_li]:pl-1"}}});return u?e.jsxs("div",{className:ls("rounded-md border",n),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 border-b px-1 py-1",children:[e.jsx(lr,{active:u.isActive("bold"),onClick:()=>u.chain().focus().toggleBold().run(),title:"Negrito",children:e.jsx(um,{className:"h-3.5 w-3.5"})}),e.jsx(lr,{active:u.isActive("italic"),onClick:()=>u.chain().focus().toggleItalic().run(),title:"Itálico",children:e.jsx(mm,{className:"h-3.5 w-3.5"})}),e.jsx(lr,{active:u.isActive("bulletList"),onClick:()=>u.chain().focus().toggleBulletList().run(),title:"Lista",children:e.jsx(xm,{className:"h-3.5 w-3.5"})}),e.jsx(lr,{active:u.isActive("orderedList"),onClick:()=>u.chain().focus().toggleOrderedList().run(),title:"Lista numerada",children:e.jsx(pm,{className:"h-3.5 w-3.5"})}),e.jsx(lr,{active:u.isActive("link"),onClick:()=>i(l=>!l),title:"Link",children:e.jsx(hr,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"mx-1 h-4 w-px bg-border"}),e.jsx(lr,{onClick:()=>
91u.chain().focus().undo().run(),title:"Desfazer",children:e.jsx(hm,{className:"h-3.5 w-3.5"})}),e.jsx(lr,{onClick:()=>u.chain().focus().redo().run(),title:"Refazer",children:e.jsx(gm,{className:"h-3.5 w-3.5"})})]}),o&&e.jsx("div",{className:"border-b",children:e.jsx(dg,{editor:u,onClose:()=>i(!1)})}),e.jsx(vx,{editor:u})]}):null}const eu=1,cg=50,ug=s=>{const t=s?.data&&s?.meta?s:s?.data||s,a=Array.isArray(t?.data)?t.data:t,n=Array.isArray(a)?a:[];return{data:n,meta:t?.meta||{pagination:{page:eu,pageSize:n.length,pageCount:n.length?1:0,total:n.length}}}},mg=(s={})=>{const t={sort:s.sort||"updatedAt:desc","pagination[page]":s.page||eu,"pagination[pageSize]":s.pageSize||cg,"populate[mensagens][populate][0]":"anexos","populate[usuario][populate][0]":"user","populate[atendente][populate][0]":"user"};return s.departamento&&s.departamento!=="all"&&(t["filters[departamento][$eq]"]=s.departamento),s.prioridade&&s.prioridade!=="all"&&(t["filters[prioridade][$eq]"]=s.prioridade),s.status&&s.status!=="all"&&(t["filters[status][$eq]"]=s.status),t},Di=s=>{s.invalidateQueries({queryKey:["chamados"],exact:!1})},xg=(s={},t={})=>Rt({queryKey:["chamados",s],queryFn:async()=>{const a=await $e.get("/chamados",{params:mg(s)});return ug(a.data)},...t}),su=async s=>{if(!s||s.length===0)return[];const t=new FormData;for(const n of s)t.append("files",n);return((await $e.post("/upload",t,{headers:{"Content-Type":"multipart/form-data"}})).data||[]).map(n=>n.id)},pg=()=>{const s=na();return fa({mutationFn:async({anexos:t,...a})=>{const n=await su(t),o=await $e.post("/chamados",{data:{...a,mensagem:{...a.mensagem,anexos:n}}});return o.data?.data||o.data},onSuccess:()=>Di(s)})},hg=()=>{const s=na();return fa({mutationFn:async({documentId:t,data:a,anexos:n})=>{if(!t)throw new Error("documentId é obrigatório");const o=await su(n),i=await $e.post(`/chamados/${encodeURIComponent(t)}/reply`,{data:{...a,anexos:o}});return i.data?.data||i.data},onSuccess:()=>Di(s)})},gg=()=>{const s=na();return fa({mutationFn:async t=>{if(!t)throw new Error("documentId é obrigatório");const a=await $e.put(`/chamados/${encodeURIComponent(t)}/close`);return a.data?.data||a.data},onSuccess:()=>Di(s)})},fg=()=>{const s=na();return fa({mutationFn:async({documentId:t,status:a})=>{if(!t)throw new Error("documentId é obrigatório");const n=await $e.put(`/chamados/${encodeURIComponent(t)}/status`,{data:{status:a}});return n.data?.data||n.data},onSuccess:()=>Di(s)})},Wo=[{value:"tecnico",label:"Técnico"},{value:"financeiro",label:"Financeiro"},{value:"comercial",label:"Comercial"}],tu=[{value:"baixa",label:"Baixa"},{value:"media",label:"Média"},{value:"alta",label:"Alta"}],bi={aberto:{label:"Aberto",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300"},respondido:{label:"Respondido",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300"},em_progresso:{label:"Em Progresso",className:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300"},fechado:{label:"Fechado",className:"bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-300"}},Zl={baixa:{label:"Baixa",className:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"},media:{label:"Média",className:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300"},alta:{label:"Alta",className:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300"}},ed={assunto:"",departamento:"",prioridade:"media",texto:null,anexos:[]},au=".jpg,.gif,.jpeg,.png,.pdf,.webp",_r=s=>bi[s]||bi.aberto,jg=s=>Zl[s]||Zl.media,vg=s=>Wo.find(t=>t.value===s)?.label||s||"—",ru=s=>{if(!s)return"—";try{const t=new Date(s);if(isNaN(t.getTime()))return"—";const a=String(t.getDate()).padStart(2,"0"),n=String(t.getMonth()+1).padStart(2,"0"),o=t.getFullYear(),i=String(t.getHours()).padStart(2,"0"),u=String(t.getMinutes()).padStart(2,"0");return`${a}/${n}/${o} (${i}:${u})`}catch{return"—"}},bg=s=>{const t=(s?.role?.name||s?.role?.type||"").toLowerCase(),a=(s?.role?.code||"").toLowerCase();return t.includes("admin")||a.includes("admin")||t.includes("supersuporte")||a.includes("supersuporte")},nu=se.oneOfType([se.string,se.number]),Ng=se.shape({autor_nome:se.string,autor_role:se.string,autor_user_id:nu,data_envio:se.string,texto:se.string});se.shape({id:nu,documentId:se.string,codigo:se.string,assunto:se.string,departamento:se.string,prioridade:se.string,status:se.string,mensagens:se.arrayOf(Ng),createdAt:se.string,updatedAt:se.string});function iu({stats:s}){const t=[{key:"aberto",..._r("aberto"),count:s.aberto},{key:"respondido",..._r("respondido"),count:s.respondido},{key:"em_progresso",..._r("em_progresso"),count:s.em_progresso},{key:"fechado",..._r("fechado"),count:s.fechado}];return e.jsx("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:t.map(a=>e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium text-muted-foreground",children:a.label})}),e.jsx(ge,{children:e.jsx("p",{className:"text-2xl font-bold",children:a.count})})]},a.key))})}iu.propTypes={stats:se.shape({aberto:se.number,respondido:se.number,em_progresso:se.number,fechado:se.number}).isRequired};function ou({filters:s,setFilters:t,searchTerm:a,setSearchTerm:n,onClear:o}){return e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(Oe,{htmlFor:"chamado-search",children:"Buscar"}),e.jsxs("div",{className:"relative",children:[e.jsx(At,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(Te,{id:"chamado-search",placeholder:"Código ou assunto...",value:a,onChange:i=>n(i.target.value),className:"pl-9"})]})]}),e.jsxs("div",{className:"w-full md:w-40",children:[e.jsx(Oe,{children:"Departamento"}),e.jsxs(rs,{value:s.departamento,onValueChange:i=>t(u=>({...u,departamento:i})),children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Todos"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),Wo.map(i=>e.jsx(xe,{value:i.value,children:i.label},i.value))]})]})]}),e.jsxs("div",{className:"w-full md:w-36",children:[e.jsx(Oe,{children:"Prioridade"}),e.jsxs(rs,{value:s.prioridade,onValueChange:i=>t(u=>({...u,prioridade:i}
91)),children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Todas"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todas"}),tu.map(i=>e.jsx(xe,{value:i.value,children:i.label},i.value))]})]})]}),e.jsxs("div",{className:"w-full md:w-40",children:[e.jsx(Oe,{children:"Status"}),e.jsxs(rs,{value:s.status,onValueChange:i=>t(u=>({...u,status:i})),children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Todos"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),Object.entries(bi).map(([i,u])=>e.jsx(xe,{value:i,children:u.label},i))]})]})]}),e.jsxs(w,{variant:"ghost",size:"sm",onClick:o,className:"gap-1",children:[e.jsx(ni,{className:"h-4 w-4"})," Limpar"]})]})})})}ou.propTypes={filters:se.object.isRequired,setFilters:se.func.isRequired,searchTerm:se.string.isRequired,setSearchTerm:se.func.isRequired,onClear:se.func.isRequired};function yg({chamado:s,replyText:t,setReplyText:a,replyFiles:n,setReplyFiles:o,onReply:i,isReplying:u,onCloseTicket:l,isClosing:c,onChangeStatus:m,isChangingStatus:x,isPrivileged:h}){const p=s.mensagens||[],f=s.status==="fechado",[I,g]=r.useState(()=>{if(p.length>0){const b=p[p.length-1];return new Set([b.id??p.length-1])}return new Set}),N=b=>{g(C=>{const q=new Set(C);return q.has(b)?q.delete(b):q.add(b),q})};return e.jsxs("div",{className:"space-y-4 p-4 pt-0",children:[e.jsx("div",{className:"space-y-2 max-h-[50vh] overflow-y-auto pr-1",children:p.map((b,C)=>{const q=b.autor_role==="suporte",L=b.id??C,M=I.has(L),z=Array.isArray(b.anexos)&&b.anexos.length>0;return e.jsxs("div",{className:`rounded-lg border overflow-hidden ${q?"border-blue-200 bg-blue-50 dark:border-blue-800 dark:bg-blue-950/30":"border-border bg-muted/30"}`,children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-2 p-3 text-left hover:bg-muted/30 transition-colors",onClick:()=>N(L),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ra,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${M?"rotate-180":""}`}),e.jsx("span",{className:"text-sm font-medium truncate",children:b.autor_nome||"Usuário"}),e.jsx(je,{variant:"outline",className:"text-xs shrink-0",children:q?"Suporte":"Proprietário"}),z&&e.jsx(Yr,{className:"h-3 w-3 text-muted-foreground shrink-0"})]}),e.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:ru(b.data_envio)})]}),M&&e.jsxs("div",{className:"border-t px-3 pb-3 pt-2",children:[e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert",children:Array.isArray(b.texto)?e.jsx(bx,{content:b.texto}):e.jsx("p",{className:"whitespace-pre-wrap",children:b.texto})}),z&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:b.anexos.map(D=>{const E=qt(D),A=D.name||"Anexo",S=(D.mime||"").startsWith("image/");return e.jsxs("a",{href:E,target:"_blank",rel:"noopener noreferrer",className:"group inline-flex items-center gap-1.5 rounded border px-2 py-1 text-xs hover:bg-muted transition-colors",children:[S?e.jsx("img",{src:E,alt:A,className:"h-10 w-10 rounded object-cover"}):e.jsx(Yr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"max-w-[120px] truncate",children:A})]},D.id||A)})})]})]},L)})}),!f&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx(Zc,{content:t,onChange:b=>a(b),placeholder:"Escreva sua resposta..."}),n.length>0&&e.jsx("div",{className:"mt-1 space-y-1",children:n.map((b,C)=>e.jsxs("div",{className:"flex items-center gap-2 rounded border px-2 py-1 text-sm",children:[e.jsx(Yr,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate flex-1",children:b.name}),e.jsx(w,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0",onClick:()=>o(q=>q.filter((L,M)=>M!==C)),children:e.jsx(yt,{className:"h-3 w-3"})})]},C))}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs(w,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{const b=document.createElement("input");b.type="file",b.accept=au,b.multiple=!0,b.onchange=C=>{const q=Array.from(C.target.files||[]);o(L=>[...L,...q])},b.click()},children:[e.jsx(Yr,{className:"h-3.5 w-3.5"}),"Anexar"]}),e.jsxs(w,{onClick:i,disabled:u||!t,className:"gap-2",children:[u&&e.jsx(Cs,{className:"h-4 w-4 animate-spin"}),e.jsx(qa,{className:"h-4 w-4"}),"Enviar"]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-t pt-3",children:[h&&!f&&e.jsxs(rs,{value:s.status,onValueChange:b=>m(b),disabled:x,children:[e.jsx(ns,{className:"w-44",children:e.jsx(is,{})}),e.jsx(os,{children:Object.entries(bi).filter(([b])=>b!=="fechado").map(([b,C])=>e.jsx(xe,{value:b,children:C.label},b))})]}),!f&&e.jsxs(w,{variant:"destructive",size:"sm",onClick:l,disabled:c,
91className:"gap-2",children:[c&&e.jsx(Cs,{className:"h-4 w-4 animate-spin"}),e.jsx(yt,{className:"h-4 w-4"}),"Fechar Ticket"]}),f&&h&&e.jsx(w,{variant:"outline",size:"sm",onClick:()=>m("aberto"),disabled:x,children:"Reabrir Ticket"})]})]})}function wg({loading:s,chamados:t,expandedId:a,onToggle:n,replyText:o,setReplyText:i,replyFiles:u,setReplyFiles:l,onReply:c,isReplying:m,onCloseTicket:x,isClosing:h,onChangeStatus:p,isChangingStatus:f,isPrivileged:I}){return s?e.jsx(he,{children:e.jsx(ge,{className:"flex items-center justify-center py-12",children:e.jsx(Cs,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):t.length?e.jsx("div",{className:"space-y-3",children:t.map(g=>{const N=g.documentId||g.id,b=a===N,C=_r(g.status),q=jg(g.prioridade),L=(g.mensagens||[]).length;return e.jsxs(he,{className:"overflow-hidden",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center gap-3 p-4 text-left hover:bg-muted/50 transition-colors",onClick:()=>n(N),children:[e.jsx(ra,{className:`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${b?"rotate-180":""}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:g.codigo}),e.jsx(je,{variant:"outline",className:C.className,children:C.label}),e.jsx(je,{variant:"outline",className:q.className,children:q.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:vg(g.departamento)})]}),e.jsx("p",{className:"mt-0.5 truncate font-medium",children:g.assunto})]}),e.jsxs("div",{className:"hidden shrink-0 text-right text-xs text-muted-foreground sm:block",children:[e.jsxs("p",{children:[L," ",L===1?"mensagem":"mensagens"]}),e.jsx("p",{children:ru(g.updatedAt)})]})]}),b&&e.jsx(yg,{chamado:g,replyText:o,setReplyText:i,replyFiles:u,setReplyFiles:l,onReply:c,isReplying:m,onCloseTicket:x,isClosing:h,onChangeStatus:p,isChangingStatus:f,isPrivileged:I})]},N)})}):e.jsx(he,{children:e.jsx(ge,{className:"py-12 text-center text-muted-foreground",children:"Nenhum chamado encontrado."})})}function lu({open:s,onOpenChange:t,form:a,setForm:n,onSubmit:o,isSubmitting:i}){const u=fn.useRef(null),l=m=>{const x=Array.from(m.target.files||[]);x.length&&n(h=>({...h,anexos:[...h.anexos,...x]})),u.current&&(u.current.value="")},c=m=>{n(x=>({...x,anexos:x.anexos.filter((h,p)=>p!==m)}))};return e.jsx(at,{open:s,onOpenChange:t,children:e.jsxs(rt,{className:"max-w-lg",children:[e.jsx(nt,{children:e.jsx(it,{children:"Novo Chamado"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Oe,{htmlFor:"create-assunto",children:"Assunto"}),e.jsx(Te,{id:"create-assunto",value:a.assunto,onChange:m=>n(x=>({...x,assunto:m.target.value})),placeholder:"Descreva brevemente o problema",maxLength:200,className:"mt-2"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(Oe,{children:"Departamento"}),e.jsxs(rs,{value:a.departamento,onValueChange:m=>n(x=>({...x,departamento:m})),className:"mt-2",children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione"})}),e.jsx(os,{children:Wo.map(m=>e.jsx(xe,{value:m.value,children:m.label},m.value))})]})]}),e.jsxs("div",{children:[e.jsx(Oe,{children:"Prioridade"}),e.jsxs(rs,{value:a.prioridade,onValueChange:m=>n(x=>({...x,prioridade:m})),className:"mt-2",children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione"})}),e.jsx(os,{children:tu.map(m=>e.jsx(xe,{value:m.value,children:m.label},m.value))})]})]})]}),e.jsxs("div",{children:[e.jsx(Oe,{children:"Mensagem"}),e.jsx(Zc,{content:a.texto,onChange:m=>n(x=>({...x,texto:m})),placeholder:"Descreva o problema em detalhes...",className:"mt-2"})]}),e.jsxs("div",{children:[e.jsx(Oe,{children:"Anexos"}),e.jsx("input",{ref:u,type:"file",accept:au,multiple:!0,onChange:l,className:"hidden"}),a.anexos.length>0&&e.jsx("div",{className:"mt-1 space-y-1",children:a.anexos.map((m,x)=>e.jsxs("div",{className:"flex items-center gap-2 rounded border px-2 py-1 text-sm",children:[e.jsx(Yr,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate flex-1",children:m.name}),e.jsxs("span",{className:"text-muted-foreground text-xs shrink-0",children:[(m.size/1024).toFixed(0)," KB"]}
91),e.jsx("button",{type:"button",onClick:()=>c(x),className:"text-muted-foreground hover:text-destructive shrink-0",children:e.jsx(yt,{className:"h-3 w-3"})})]},x))}),e.jsx("div",{className:"flex flex-col",children:e.jsxs(w,{type:"button",variant:"outline",size:"sm",className:"mt-2 gap-2",onClick:()=>u.current?.click(),children:[e.jsx(et,{className:"h-3 w-3"})," Adicionar Anexo"]})})]})]}),e.jsxs(Ut,{children:[e.jsx(w,{variant:"outline",onClick:()=>t(!1),children:"Cancelar"}),e.jsxs(w,{onClick:o,disabled:i||!a.assunto.trim()||!a.departamento||!a.texto,className:"gap-2 mb-2",children:[i&&e.jsx(Cs,{className:"h-4 w-4 animate-spin"}),"Enviar"]})]})]})})}lu.propTypes={open:se.bool.isRequired,onOpenChange:se.func.isRequired,form:se.object.isRequired,setForm:se.func.isRequired,onSubmit:se.func.isRequired,isSubmitting:se.bool.isRequired};function _g(){const{toast:s}=mt(),{user:t}=Zt(),a=bg(t),[n,o]=r.useState({departamento:"all",prioridade:"all",status:"all",pageSize:50}),[i,u]=r.useState(""),[l,c]=r.useState(!1),[m,x]=r.useState({...ed}),[h,p]=r.useState(null),[f,I]=r.useState(null),[g,N]=r.useState([]),{data:b,isLoading:C}=xg(n),q=pg(),L=hg(),M=gg(),z=fg(),D=b?.data||[],E=r.useMemo(()=>{const y=i.trim().toLowerCase();return y?D.filter($=>[$.codigo,$.assunto].filter(Boolean).join(" ").toLowerCase().includes(y)):D},[D,i]),A=r.useMemo(()=>
91{const y={aberto:0,respondido:0,em_progresso:0,fechado:0};for(const $ of D){const W=String($.status||"").toLowerCase();W in y&&(y[W]+=1)}return y},[D]),S=()=>{u(""),o({departamento:"all",prioridade:"all",status:"all",pageSize:50})},P=async()=>{try{const y=Yl(m.texto);await q.mutateAsync({assunto:m.assunto.trim(),departamento:m.departamento,prioridade:m.prioridade,mensagem:{texto:y},anexos:m.anexos}),s({title:"Chamado criado com sucesso"}),x({...ed}),c(!1)}catch(y){s({title:"Erro ao criar chamado",description:y?.response?.data?.error?.message||y.message,variant:"destructive"})}},F=y=>{h===y?(p(null),I(null),N([])):(p(y),I(null),N([]))},ee=E.find(y=>(y.documentId||y.id)===h),re=async()=>{if(!(!ee?.documentId||!f))try{const y=Yl(f);await L.mutateAsync({documentId:ee.documentId,data:{texto:y},anexos:g}),s({title:"Resposta enviada"}),I(null),N([])}catch(y){s({title:"Erro ao enviar resposta",description:y?.response?.data?.error?.message||y.message,variant:"destructive"})}},te=async()=>{if(ee?.documentId)try{await M.mutateAsync(ee.documentId),s({title:"Chamado fechado"})}catch(y){s({title:"Erro ao fechar chamado",description:y?.response?.data?.error?.message||y.message,variant:"destructive"})}},G=async y=>{if(ee?.documentId)try{await z.mutateAsync({documentId:ee.documentId,status:y}),s({title:`Status alterado para ${_r(y).label}`})}catch($){s({title:"Erro ao alterar status",description:$?.response?.data?.error?.message||$.message,variant:"destructive"})}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Chamados"}),e.jsx("p",{className:"text-muted-foreground",children:"Abra e acompanhe seus tickets de suporte."})]}),e.jsxs(w,{onClick:()=>c(!0),className:"gap-2",children:[e.jsx(et,{className:"h-4 w-4"}),"Novo chamado"]})]}),e.jsx(iu,{stats:A}),e.jsx(ou,{filters:n,setFilters:o,searchTerm:i,setSearchTerm:u,onClear:S}
91),e.jsx(wg,{loading:C,chamados:E,expandedId:h,onToggle:F,replyText:f,setReplyText:I,replyFiles:g,setReplyFiles:N,onReply:re,isReplying:L.isPending,onCloseTicket:te,isClosing:M.isPending,onChangeStatus:G,isChangingStatus:z.isPending,isPrivileged:a}),e.jsx(lu,{open:l,onOpenChange:c,form:m,setForm:x,onSubmit:P,isSubmitting:q.isPending})]})}const du=r.forwardRef(({className:s,children:t,...a},n)=>e.jsxs(oc,{ref:n,className:ls("relative overflow-hidden",s),...a,children:[e.jsx(Km,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(cu,{}),e.jsx(Qm,{})]}));du.displayName=oc.displayName;const cu=r.forwardRef(({className:s,orientation:t="vertical",...a},n)=>e.jsx(lc,{ref:n,orientation:t,className:ls("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...a,children:e.jsx(Wm,{className:"relative flex-1 rounded-full bg-border"})}));cu.displayName=lc.displayName;const Cg={admin:"Administrador",scan:"Funcionário Portaria",bar:"Funcionário Bar"},Kr=(s,t)=>s&&Cg[String(s).toLowerCase()]||t,sd=s=>`${String(s).padStart(2,"0")}h`,td=(s,t)=>(Number(s)+t+24)%24,kg=s=>{try{if(!s)return 0;const t=new Date(s);return Number.isNaN(t.getTime())?0:t.getHours()-t.getUTCHours()}catch{return 0}},dr=({title:s,value:t,description:a,icon:n})=>{const o=typeof t=="number"?t.toLocaleString("pt-BR"):t;return e.jsx(he,{children:e.jsx(ge,{className:"p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:s}),e.jsx("p",{className:"mt-1 text-2xl font-semibold text-foreground",children:o}),a?e.jsx("p",{className:"mt-2 text-xs text-muted-foreground leading-relaxed",children:a}):null]}),n?e.jsx(n,{className:"h-9 w-9 text-muted-foreground"}):null]})})})},Sg=s=>{if(!s)return"--";try{return Us(zt(s),"dd/MM/yyyy HH:mm",{locale:Vs})}catch{return s}},Ig=s=>{if(!s)return"";try{return Us(zt(s),"dd 'de' MMMM 'às' HH:mm",{locale:Vs})}catch{return s}},$n=s=>s,uu=s=>s?s.attributes&&typeof s.attributes=="object"?{id:s.id,...s.attributes}:s.data?uu(s.data):s:null,Ag=s=>{const t=uu(s),a=i=>Array.isArray(i)?i.map(u=>({value:Et(u?.data),data:u?.data||null,observacao:u?.observacao||null})).filter(u=>u.value):[],n=a(t?.datas_futuras),o=a(t?.datas_passadas);return{id:t?.id||null,documentId:t?.documentId||null,title:t?.titulo||"Evento",mainDate:Et(t?.data_evento),futureDates:n,pastDates:o}},Eg=s=>{const t=Va(s?.data||s?.value);return s?.observacao?`${t} - ${s.observacao}`:t},Dg=s=>{if(!s)return[];const t=new Map;s.mainDate&&t.set(s.mainDate,{value:s.mainDate,label:`Data principal - ${Va(s.mainDate)}`});const a=(n=[])=>{n.forEach(o=>{!o?.value||t.has(o.value)||t.set(o.value,{value:o.value,label:Eg(o)})})};return a(s.futureDates||[]),a(s.pastDates||[]),Array.from(t.values()).sort((n,o)=>n.value.localeCompare(o.value))},Pg=({eventDocumentId:s,dateKey:t})=>{const a=new URLSearchParams({limit:"1000"});return s&&s!=="all"&&a.set("eventDocumentId",s),t&&t!=="all"&&a.set("dateKey",t),`/scanner/activity?${a.toString()}`},Rg=(s,t)=>!s||s==="all"||!t||t==="all"?null:`/dashboard/eventos/${encodeURIComponent(s)}/data/${encodeURIComponent(t)}`;function Tg(){const[s,t]=r.useState("all"),[a,n]=r.useState("all"),o=r.useMemo(()=>Pg({eventDocumentId:s,dateKey:a}),[a,s]),{data:i,isLoading:u,isError:l,error:c}=Ks(["scanner-activity",s,a],o),{data:m=[]}=Ks(["scanner-activity-events"],"/scanner/activity/events",{staleTime:5*60*1e3,refetchOnWindowFocus:!1,select:K=>(Array.isArray(K?.data)?K.data:[]).map(Ag).filter(oe=>oe.documentId)}),[x,h]=r.useState("all"),[p,f]=r.useState("all"),I=i||{},g=I.summary||{},N=I.charts||{},b=I.filters||{},C=Array.isArray(I.logs)?I.logs:[],q=r.useMemo(()=>m.find(K=>K.documentId===s)||null,[m,s]),L=r.useMemo(()=>Dg(q),[q]),M=r.useMemo(()=>Rg(s,a),[a,s]),z=r.useMemo(()=>!q||!a||a==="all"?!1:Ud(q,a,new Date,3),[a,q]),D=r.useMemo(()=>kg(g.firstActivity||g.lastActivity),[g.firstActivity,g.lastActivity]),E=r.useMemo(()=>
91(Array.isArray(N.byHour)?N.byHour:[]).map(oe=>{const ve=typeof oe.hour=="number"?oe.hour:(()=>{const fe=String(oe.label||"").match(/(\d{1,2})/);return fe?Number(fe[1]):0})(),me=td(ve,D);return{scans:oe.scans||0,uses:oe.uses||0,total:oe.total||(oe.scans||0)+(oe.uses||0),hour:me,label:sd(me)}}).sort((oe,ve)=>oe.hour-ve.hour),[N.byHour,D]),A=r.useMemo(()=>Array.isArray(b.users)?x==="all"?b.users:b.users.filter(K=>K.roleKey===x):[],[b.users,x]);r.useEffect(()=>{a!=="all"&&(L.some(K=>K.value===a)||n("all"))},[a,L]),r.useEffect(()=>{p!=="all"&&(A.some(K=>String(K.value)===p)||f("all"))},[p,A]);const S=r.useMemo(()=>{let K=C;return x!=="all"&&(K=K.filter(O=>O?.user?.role?.key===x)),p!=="all"&&(K=K.filter(O=>String(O?.user?.id)===p)),K},[C,x,p]),P=g.totalLogs||0,F=g.totalScans||0,ee=g.totalUses||0,re=g.uniqueUsers||0,te=g?.peakHour||null,G=te?.count||0,y=te&&typeof te.hour=="number"?sd(td(te.hour,D)):te?.label||"--",$=Math.max((F||0)-(ee||0),0),W=r.useMemo(()=>{const K=Array.isArray(C)?[...C]:[];return K.sort((O,oe)=>{const ve=new Date(O?.timestamp||0).getTime();return new Date(oe?.timestamp||0).getTime()-ve}),K[0]||null},[C]),ie=r.useMemo(()=>{const K=Date.now(),O=60*60*1e3,me=(Array.isArray(C)?C:[]).filter(le=>{const _e=new Date(le?.timestamp||0).getTime();return Number.isFinite(_e)&&K-_e<=O}).length/60,fe=Math.round((me||0)*10)/10;return Number.isFinite(fe)?fe:0},[C]),ke=r.useMemo(()=>{const K=["admin","scan","bar"];return(Array.isArray(N.byRole)?N.byRole:[]).map(oe=>{const ve=String(oe?.roleKey||oe?.key||oe?.value||"").toLowerCase();return{roleKey:ve,label:Kr(ve,oe?.label||"—"),total:(oe?.total??0)||(oe?.scans??0)+(oe?.uses??0)}}).sort((oe,ve)=>{const me=K.indexOf(oe.roleKey),fe=K.indexOf(ve.roleKey);return me!==-1&&fe!==-1&&me!==fe?me-fe:me!==-1?-1:fe!==-1?1:oe.label.localeCompare(ve.label)})},[N.byRole]),[Ae,be]=r.useState({}),Fe=K=>be(O=>({...O,[K]:!O[K]})),ae=async()=>{try{const K=(S||[]).map(Se=>{const Ze=Se?.timestamp?new Date(Se.timestamp):null,qe=Se?.source==="convite"?Se?.inviteId:Se?.pedidoId;return{Data:Ze?Ze.toLocaleDateString("pt-BR"):"—",Hora:Ze?Ze.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"—",Colaborador:Se?.user?.name||Se?.user?.email||"—",Papel:Kr(Se?.user?.role?.key,Se?.user?.role?.label||"—"),Origem:Se?.sourceLabel||"—",Registro:qe??"",Ação:Se?.actionLabel||Se?.action||"—",Evento:Se?.event?.title||"","Data do evento":Se?.event?.dateKey?Va(Se.event.dateKey):"","Item #":Se?.itemId??"",Email:Se?.user?.email||""}}),O=await $r(()=>import("./vendor-exceljs-AsZnDCZx.js").then(Se=>Se.e),__vite__mapDeps([0,1,2])),oe=O.default||O,ve=new oe.Workbook,me=ve.addWorksheet("Scanner Logs");me.columns=[{header:"Data",key:"Data",width:12},{header:"Hora",key:"Hora",width:10},{header:"Colaborador",key:"Colaborador",width:28}
91,{header:"Papel",key:"Papel",width:16},{header:"Origem",key:"Origem",width:14},{header:"Registro",key:"Registro",width:10},{header:"Ação",key:"Ação",width:18},{header:"Evento",key:"Evento",width:28},{header:"Data do evento",key:"Data do evento",width:20},{header:"Item #",key:"Item #",width:10},{header:"Email",key:"Email",width:28}],K.forEach(Se=>me.addRow(Se)),me.getRow(1).font={bold:!0};const fe=new Date,le=Se=>String(Se).padStart(2,"0"),_e=`scanner_logs_${fe.getFullYear()}-${le(fe.getMonth()+1)}-${le(fe.getDate())}_${le(fe.getHours())}-${le(fe.getMinutes())}.xlsx`,U=await ve.xlsx.writeBuffer(),J=new Blob([U],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),T=URL.createObjectURL(J),Ee=document.createElement("a");Ee.href=T,Ee.download=_e,document.body.appendChild(Ee),Ee.click(),Ee.remove(),URL.revokeObjectURL(T)}catch(K){console.error("Falha ao exportar relatório do scanner:",K),alert("Falha ao exportar relatório. Confira o console para detalhes.")}};return u?e.jsx("div",{className:"flex h-64 items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(It,{size:32,thickness:4}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando atividades de scanner..."})]})}):l?e.jsx(he,{children:e.jsxs(ge,{className:"py-10 text-center text-red-500",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Não foi possível carregar as atividades"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:c?.message||"Tente novamente mais tarde."})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Atividades de Scanner"}),e.jsx("p",{className:"text-muted-foreground",children:"Acompanhe em tempo real as ações realizadas pelos times de scanner e estoque."})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-4",children:e.jsx(ze,{children:"Filtro por evento e data"})}),e.jsxs(ge,{className:"flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between",children:[e.jsxs("div",{className:"grid flex-1 gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Evento"}),e.jsxs(rs,{value:s,onValueChange:K=>{t(K),n("all")},children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione um evento"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos os eventos"}),m.map(K=>e.jsx(xe,{value:K.documentId,children:K.title},K.documentId))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Data do evento"}),e.jsxs(rs,{value:a,onValueChange:n,disabled:!q,children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione uma data"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todas as datas"}),L.map(K=>e.jsx(xe,{value:K.value,children:K.label},K.value))]})]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:M&&z?e.jsx(w,{asChild:!0,variant:"outline",className:"gap-2",children:e.jsxs(lt,{to:M,children:[e.jsx(sr,{className:"h-4 w-4"}),"Ver pessoas desta data"]})}):e.jsxs(w,{variant:"outline",className:"gap-2",disabled:!0,title:"Disponível apenas para datas dentro da janela de 3 dias.",children:[e.jsx(sr,{className:"h-4 w-4"}),"Ver pessoas desta data"]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-4",children:[e.jsx(dr,{title:"Total de atividades",value:P,description:"Eventos registrados pelos times monitorados.",icon:lo}),e.jsx(dr,{title:"Leituras de QR",value:F,description:"Quantidade de validações de QR Code executadas.",icon:fm}),e.jsx(dr,{title:"Colaboradores únicos",value:re,description:"Quantidade de colaboradores que realizaram atividades.",icon:gr}),e.jsx(dr,{title:"Pico de leitura",value:y,description:`Horário de maior movimento (${G} leituras).`,icon:Za})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(dr,{title:"✅ Entradas confirmadas",value:ee,description:"Total de itens confirmados.",icon:gr}),e.jsx(dr,{title:"⏳ Pendentes",value:$,description:"Leituras ainda não confirmadas.",icon:jm}),e.jsx(he,{children:e.jsx(ge,{className:"p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"🕓 Última leitura"}),e.jsx("p",{className:"mt-1 text-2xl font-semibold text-foreground",children:W?.timestamp?Us(zt(W.timestamp),"HH:mm",{locale:Vs}):"--:--"}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground leading-relaxed",children:W?.user?.name||W?.user?.email||"—"})]}),e.jsx(Za,{className:"h-9 w-9 text-muted-foreground"})]})})}),e.jsx(dr,{title:"🧠 Fluxo médio/min",value:ie,description:"Média dos últimos 60 minutos.",icon:Bd})]}),ke.length?e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(ei,{className:"h-5 w-5"})," Leituras por ponto de acesso"]})}),e.jsx(ge,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:ke.map((K,O)=>e.jsxs(je,{variant:"secondary",className:"text-sm",children:[K.label,": ",e.jsx("span",{className:"ml-1 font-medium",children:K.total})]},`${K.label}-${O}`))})})]}):null,e.jsxs("div",{className:"grid grid-cols-1 gap-6 xl:grid-cols-3",children:[e.jsxs(he,{className:"xl:col-span-2",children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{children:"Leituras por dia"})}),e.jsx(ge,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(Om,{data:N.byDay||[],children:[e.jsx(Ra,{strokeDasharray:"3 3"}),e.jsx(Ta,{dataKey:"label",tick:{fontSize:12}}),e.jsx($a,{tick:{fontSize:12}}),e.jsx(Aa,{formatter:$n}),e.jsx(Xr,{}),e.jsx(jl,{type:"monotone",dataKey:"scans",stroke:"#2563eb",name:"Leituras",strokeWidth:2}),e.jsx(jl,{type:"monotone",dataKey:"uses",stroke:"#16a34a",name:"Entradas",strokeWidth:2})]})})})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{children:"Pico por horário"})}),e.jsx(ge,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(Xa,{data:E,children:[e.jsx(Ra,{strokeDasharray:"3 3"}),e.jsx(Ta,{dataKey:"label",tick:{fontSize:12}}),e.jsx($a,{allowDecimals:!1,tick:{fontSize:12}}),e.jsx(Aa,{formatter:$n}),e.jsx(Xr,{}),e.jsx(ha,{dataKey:"scans",stackId:"a",fill:"#0ea5e9",name:"Leituras",radius:[4,4,0,0]}),e.jsx(ha,{dataKey:"uses",stackId:"a",fill:"#16a34a",name:"Entradas",radius:[4,4,0,0]})]})})})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{children:"Atividades por papel"})}),e.jsx(ge,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(Xa,{data:N.byRole||[],children:[e.jsx(Ra,{strokeDasharray:"3 3"}),e.jsx(Ta,{dataKey:"label",tick:{fontSize:12}}),e.jsx($a,{allowDecimals:!1,tick:{fontSize:12}}),e.jsx(Aa,{formatter:$n}),e.jsx(Xr,{}
91),e.jsx(ha,{dataKey:"total",fill:"#6366f1",name:"Total",radius:[4,4,0,0]}),e.jsx(ha,{dataKey:"scans",fill:"#10b981",name:"Leituras",radius:[4,4,0,0]})]})})})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{children:"Top colaboradores"})}),e.jsx(ge,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(Xa,{data:(N.byUser||[]).slice(0,8),layout:"vertical",children:[e.jsx(Ra,{strokeDasharray:"3 3"}),e.jsx(Ta,{type:"number",allowDecimals:!1}),e.jsx($a,{type:"category",dataKey:"name",width:120}),e.jsx(Aa,{formatter:$n}),e.jsx(Xr,{}),e.jsx(ha,{dataKey:"scans",fill:"#22c55e",name:"Leituras",radius:[0,4,4,0]}),e.jsx(ha,{dataKey:"uses",fill:"#f97316",name:"Entradas",radius:[0,4,4,0]})]})})})})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{className:"pb-4",children:[e.jsx(ze,{children:"Registro de atividades"}),e.jsx("div",{className:"mt-2",children:e.jsxs("button",{type:"button",onClick:ae,className:"inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm hover:bg-accent",children:[e.jsx(Oa,{className:"h-4 w-4"}),"Exportar relatório do scanner"]})}),e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Última atualização:"}),e.jsx("span",{children:g.lastActivity?Ig(g.lastActivity):"--"})]}),e.jsxs("div",{className:"flex flex-1 flex-wrap gap-3 lg:justify-end",children:[e.jsxs(rs,{value:x,onValueChange:K=>{h(K),f("all")},children:[e.jsx(ns,{className:"w-[210px]",children:e.jsx(is,{placeholder:"Filtrar por papel"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos os papéis"}),(b.roles||[]).map(K=>e.jsx(xe,{value:K.value,children:Kr(K.value,K.label)},K.value))]})]}),e.jsxs(rs,{value:p,onValueChange:f,children:[e.jsx(ns,{className:"w-[240px]",children:e.jsx(is,{placeholder:"Filtrar por usuário"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos os usuários"}),A.map(K=>e.jsx(xe,{value:String(K.value),children:K.label},K.value))]})]})]})]})]}),e.jsx(ge,{className:"p-0",children:e.jsx(du,{className:"h-[420px]",children:e.jsx("div",{className:"px-6 py-4",children:S.length?S.map((K,O)=>{const oe=K.source==="convite"?K.inviteId:K.pedidoId,ve=[oe?`${K.sourceLabel} #${oe}`:null,K.itemId?`Item #${K.itemId}`:null].filter(Boolean).join(" · "),me=K.id||`${K.timestamp}-${O}`,fe=K?.event?.dateKey?Va(K.event.dateKey):null;return e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(je,{variant:"outline",children:K.actionLabel}),e.jsx(je,{variant:"secondary",children:Kr(K.user?.role?.key,K.user?.role?.label)}),e.jsx(je,{variant:"outline",children:K.sourceLabel||"Registro"}),K?.event?.title?e.jsx(je,{variant:"outline",children:K.event.title}):null,fe?e.jsx(je,{variant:"outline",children:fe}):null,ve?e.jsx(je,{variant:"outline",children:ve}):null,e.jsx("button",{type:"button",onClick:()=>Fe(me),className:"ml-auto text-xs underline underline-offset-2 hover:text-foreground",children:Ae[me]?"Ocultar detalhes":"Ver detalhes"})]}),e.jsx("div",{className:"mt-2 text-sm font-medium text-foreground",children:K.user?.name||"Usuário"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Sg(K.timestamp),K.user?.email?` · ${K.user.email}`:""]}),Ae[me]?e.jsxs("div",{className:"mt-2 rounded-md border bg-muted/30 p-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Ação:"})," ",K.actionLabel||K.action||"—"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Papel:"})," ",Kr(K.user?.role?.key,K.user?.role?.label||K.user?.role?.key||"—")]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Origem:"})," ",K.sourceLabel||"—"," ",oe?`#${oe}`:""]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Evento:"})," ",K?.event?.title||"—"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Data do evento:"})," ",fe||"—"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Item:"})," ",K.itemId??"—"]}),e.jsx("div",{className:"mt-1 overflow-x-auto whitespace-pre-wrap",children:(()=>{try{return e.jsx("pre",{children:JSON.stringify(K,null,2)})}catch{return null}})()})]}):null,O<S.length-1?e.jsx(io,{className:"mt-3"}):null]},me)}):e.jsx("div",{className:"rounded-md border border-dashed border-border/60 p-6 text-center text-sm text-muted-foreground",children:"Nenhuma atividade encontrada para os filtros selecionados."})})})})]})]})}const Qi="#2f9e63",Wi="#f07f2f",Ji=367,Ln=5,ad={admin:{label:"Admin",
91subtitle:"POROROCA STUDIOS LTDA"},afiliado:{label:"Afiliado",subtitle:"Conta de comissionamento"},primary:{label:"TicketTop",subtitle:"Conta principal da plataforma"}};function Pt(s=0){return new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format((Number(s)||0)/100)}function $g(s=0){return new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",notation:"compact",maximumFractionDigits:1}).format((Number(s)||0)/100)}function Lg(s){if(!s)return"-";const t=new Date(s);return Number.isNaN(t.getTime())?"-":t.toLocaleString("pt-BR")}function ur(s){if(!s)return null;const t=new Date(s);return Number.isNaN(t.getTime())?null:t}function Yi(s){return String(s||"").toLowerCase().trim()}function rd(s){const t=String(s||"").toLowerCase();return t==="pending_transfer"?"Aguardando transferência":t==="transferred"?"Transferida":t==="failed"?"Falhou":t==="processing"?"Processando":t==="canceled"?"Cancelada":t==="paid"?"Recebido":s||"—"}const Mg=new Set(["paid","captured","succeeded","approved","settled","completed","success"]),Fg=new Set(["failed","canceled","cancelled","cancelado","cancelada","denied","declined","chargeback","chargebacked","chargedback","refunded","refund","estornado","estornada","estorno","reembolsado","reembolsada","reembolso","reversed","reversal","dispute","disputed"]),Do=/(charge_?back|refund|reembolso|reembolsad|estorno|estornad|cancelad|cancel|fail|deni|declin|disput|revers)/;function Og(s){return String(s||"").toLowerCase().trim().replaceAll("-","_").replaceAll(" ","_")}function qg(s){const t=[s?.status,s?.metadata?.status,s?.metadata?.order_status,s?.metadata?.charge_status,s?.metadata?.payment_status,s?.metadata?.split_status];for(const a of t){const n=Og(a);if(n)return n}return""}function zg(s){const t=[s?.status,s?.type,s?.description,s?.title,s?.metadata?.status,s?.metadata?.order_status,s?.metadata?.charge_status,s?.metadata?.payment_status,s?.metadata?.split_status].map(n=>String(n||"").toLowerCase()).filter(Boolean).join(" "),a=JSON.stringify(s?.metadata||{}).toLowerCase();return Do.test(t)||Do.test(a)}function Ug(s){if((Number(s?.amount)||0)<=0)return!1;const a=String(s?.direction||"").toLowerCase();if(a&&a!=="in"||zg(s))return!1;const n=qg(s);return n?Fg.has(n)||Do.test(n)?!1:Mg.has(n)?!0:/(paid|captur|settled|succeed|approv|complete|success)/.test(n):!0}function nd({movements:s=[],range:t="week"}){const a=new Date,n=Array.isArray(s)?s:[];if(t==="all"){const c=n.filter(g=>ur(g?.created_at||g?.date_created));if(!c.length)return{labels:["Tudo"],series:[n.reduce((g,N)=>g+Math.max(0,Number(N?.amount)||0),0)]};const m=c.reduce((g,N)=>{const b=ur(N?.created_at||N?.date_created)?.getTime()||Number.MAX_SAFE_INTEGER;return Math.min(g,b)},Number.MAX_SAFE_INTEGER),x=new Date(m);x.setDate(1),x.setHours(0,0,0,0);const h=(a.getFullYear()-x.getFullYear())*12+(a.getMonth()-x.getMonth()),p=Math.min(Math.max(h+1,1),36),f=Array.from({length:p},(g,N)=>{const b=new Date(x);return b.setMonth(x.getMonth()+N),{key:`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}`,label:b.toLocaleDateString("pt-BR",{month:"short",year:"2-digit"}),value:0}}),I=new Map(f.map(g=>[g.key,g]));return n.forEach(g=>{const N=ur(g?.created_at||g?.date_created);if(!N)return;const b=`${N.getFullYear()}-${String(N.getMonth()+1).padStart(2,"0")}`,C=I.get(b);C&&(C.value+=Math.max(0,Number(g?.amount)||0))}),{labels:f.map(g=>g.label),series:f.map(g=>g.value)}}if(t==="day"){const c=new Date(a);c.setMinutes(0,0,0),c.setHours(c.getHours()-22);const m=Array.from({length:12},(x,h)=>{const p=new Date(c.getTime()+h*2*60*60*1e3);return{key:p.getTime(),label:p.toLocaleTimeString("pt-BR",{hour:"2-digit"}).replace(":00","h"),value:0}});return n.forEach(x=>{const h=ur(x?.created_at||x?.date_created);if(!h||h<c||h>a)return;const p=h.getTime()-c.getTime(),f=Math.floor(p/(2*60*60*1e3));f<0||f>=m.length||(m[f].value+=Math.max(0,Number(x?.amount)||0))}),{labels:m.map(x=>x.label),series:m.map(x=>x.value)}}const o=t==="month"?30:7,i=new Date(a);i.setHours(0,0,0,0),i.setDate(i.getDate()-(o-1));const u=Array.from({length:o},(c,m)=>{const x=new Date(i);x.setDate(i.getDate()+m);const h=x.toISOString().slice(0,10),p=t==="month"?x.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}):x.toLocaleDateString("pt-BR",{weekday:"short"});return{key:h,label:p,value:0}}),l=new Map(u.map(c=>[c.key,c]));
91return n.forEach(c=>{const m=ur(c?.created_at||c?.date_created);if(!m||m<i||m>a)return;const x=m.toISOString().slice(0,10),h=l.get(x);h&&(h.value+=Math.max(0,Number(c?.amount)||0))}),{labels:u.map(c=>c.label),series:u.map(c=>c.value)}}function Bg({range:s,pagarmeMovements:t,pagbankMovements:a}){const n=nd({movements:t,range:s}),o=nd({movements:a,range:s});return n.labels.map((i,u)=>({label:i,pagarme:n.series[u]||0,pagbank:o.series[u]||0}))}function id(s){return s==="day"?"24h":s==="week"?"7d":s==="month"?"30d":"Tudo"}function od(){return e.jsxs("div",{className:"space-y-4 text-left",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Processamento seguro"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"As transferências são executadas exclusivamente via TED. Por motivos de segurança e conformidade bancária, solicitações enviadas após as 15h (horário de Brasília) são automaticamente agendadas para o processamento no próximo dia útil."})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Taxa de segurança reembolsável"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Cada transferência inclui uma taxa de segurança de R$ 3,67. Esse valor é integralmente reembolsado pela TicketTop assim que o status da transferência é atualizado para "Pago".'})]})]})}function mu(){const{toast:s}=mt(),[t,a]=r.useState(!1),[n,o]=r.useState(""),[i,u]=r.useState("admin"),[l,c]=r.useState(!1),[m,x]=r.useState(!1),[h,p]=r.useState("week"),[f,I]=r.useState(1),[g,N]=r.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("extratoHubTransferInfoAck")==="true"}catch{return!1}}),b=Rt({queryKey:["extrato-hub-overview-v2",60],queryFn:()=>mc({count:60}),refetchOnWindowFocus:!1}),{config:C}=Fr({refetchOnWindowFocus:!1}),q=b.data?.roles?.[i]||{aggregate:{notes:[]},sources:[]},L=i==="afiliado",M=Array.isArray(q.sources)?q.sources:[],z=r.useMemo(()=>{if(!L)return null;const we=M.find(Me=>Yi(Me?.provider)==="internal");return we||M[0]||null},[L,M]),D=r.useMemo(()=>{const we=M.find(Me=>Yi(Me?.provider)==="pagarme");return we||M.find(Me=>Me?.transferEnabled)||null},[M]),E=r.useMemo(()=>M.find(we=>Yi(we?.provider)==="pagbank")||null,[M]),A=r.useMemo(()=>L?z:D?.transferEnabled?D:M.find(we=>we?.transferEnabled)||null,[z,L,D,M]),S=ad[i]||ad.admin,P=z?.label||D?.recipient?.name||D?.recipient?.id||E?.account?.id||S.subtitle,F=r.useMemo(()=>new Intl.NumberFormat("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2}),[]),ee=r.useMemo(()=>{const we=C?.total_reembolsado_taxa_antecipacao_brl;if(we==null||we==="")return 0;const Me=Number(we),ks=Number(String(we).replace(/\./g,"").replace(",",".")),xs=Number.isFinite(Me)?Me:ks;return!Number.isFinite(xs)||xs<0?0:Math.round(xs*100)},[C?.total_reembolsado_taxa_antecipacao_brl]),re=C?.exibir_texto_total_reembolsado_taxa_antecipacao!==!1,te=r.useMemo(()=>{const we=Number(A?.available_amount);if(Number.isFinite(we))return Math.max(0,Math.floor(we-Ji))},[A?.available_amount]),G=r.useMemo(()=>{const we=String(n||"").replaceAll(/\D/g,"");return we?Number.parseInt(we,10):0},[n]),y=r.useMemo(()=>n?F.format(G/100):"",[n,G,F]),$=r.useMemo(()=>Array.isArray(D?.movements)?D.movements:[],[D]),W=r.useMemo(()=>Array.isArray(E?.movements)?E.movements:[],[E]),ie=r.useMemo(()=>W.filter(we=>Ug(we)),[W]),ke=r.useMemo(()=>Bg({range:h,pagarmeMovements:$,pagbankMovements:ie}),[h,$,ie]),Ae=r.useMemo(()=>ke.reduce((we,Me)=>(we.pagarme+=Number(Me?.pagarme)||0,we.pagbank+=Number(Me?.pagbank)||0,we),{pagarme:0,pagbank:0}),[ke]),be=ie,Fe=be.length,ae=be.reduce((we,Me)=>we+(Number(Me?.amount)||0),0),K=Fe>0?Math.round(ae/Fe):0,O=Number(z?.available_amount)||0,oe=Number(z?.waiting_funds_amount)||0,ve=Number(z?.transferred_amount)||0,me=O+oe+ve,fe=r.useMemo(()=>(Array.isArray(A?.movements)?A.movements:[]).filter(Me=>String(Me?.direction||"out").toLowerCase()!=="in").sort((Me,ks)=>{const xs=ur(Me?.created_at||Me?.date_created)?.getTime()||0;return(ur(ks?.created_at||ks?.date_created)?.getTime()||0)-xs}),[A]),le=Math.max(1,Math.ceil(fe.length/Ln)),_e=Math.min(f,le),U=r.useMemo(()=>{const we=(_e-1)*Ln;return fe.slice(we,we+Ln)},[_e,fe]),J=Array.isArray(q.aggregate?.notes)?q.aggregate.notes:[],T=we=>{u(we),o(""),I(1)},Ee=we=>{const Me=String(we.target.value||"").replaceAll(/\D/g,"").slice(0,11);if(!Me){o("");return}let ks=Number.parseInt(Me,10);Number.isNaN(ks)&&(ks=0),typeof te=="number"&&(ks=Math.min(ks,te)),o(String(ks))},Se=async()=>
91{if(!(!A||!G||G<1)){if(typeof te=="number"&&G>te){s({title:"Valor acima do máximo",description:`Máximo disponível para transferência: ${Pt(te)}.`,variant:"destructive"});return}a(!0);try{const we=await xc({amount:G,provider:A.provider,kind:i}),Me=we?.id||we?.data?.id,ks=we?.status||we?.data?.status;s({title:"Transferência solicitada",description:`${Me?`ID ${Me} · `:""}${ks?`Status: ${rd(ks)} · `:""}Valor: ${Pt(G)}.`}),o(""),I(1),await b.refetch()}catch(we){const Me=we?.response?.data?.error?.message||we?.response?.data?.message||we?.message;s({title:"Falha ao criar transferência",description:Me?String(Me):"Tente novamente em instantes.",variant:"destructive"})}finally{a(!1)}}},Ze=async we=>{if(we.preventDefault(),!g){x(!0),c(!0);return}await Se()},qe=async()=>{N(!0);try{typeof window<"u"&&window.localStorage.setItem("extratoHubTransferInfoAck","true")}catch{}m&&(x(!1),await Se()),c(!1)},Qe=we=>{!we&&!g&&x(!1),c(we)};return e.jsxs(e.Fragment,{children:[e.jsx(at,{open:l,onOpenChange:Qe,children:e.jsxs(rt,{className:"max-w-lg",children:[e.jsxs(nt,{children:[e.jsx(it,{children:"Diretrizes das transferências"}),e.jsx(Ba,{asChild:!0,children:e.jsx(od,{})})]}),e.jsxs(Ut,{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(w,{variant:"outline",onClick:()=>Qe(!1),disabled:m&&!g,children:"Fechar"}),e.jsx(w,{onClick:qe,disabled:t&&m,children:"Estou ciente"})]})]})}),e.jsxs("div",{className:"space-y-5 sm:space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:"Extratos"}),e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground",children:"Hub Admin com visão por perfil e por gateway"})]}),e.jsx(Lr,{value:i,onValueChange:T,className:"w-full",children:e.jsxs(Mr,{className:"grid w-full grid-cols-3 h-10",children:[e.jsx(Gt,{value:"admin",children:"Admin"}),e.jsx(Gt,{value:"afiliado",children:"Afiliado"}),e.jsx(Gt,{value:"primary",children:"TicketTop"})]})}),e.jsx(he,{className:"border-border/60 bg-card/95 shadow-[var(--shadow-card)]",children:e.jsx(ge,{className:"p-4 sm:p-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-md bg-primary/15 flex items-center justify-center shrink-0",children:e.jsx(bn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-base font-semibold leading-tight",children:S.label}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:P})]})]})})}),L?e.jsxs(he,{className:"overflow-hidden border-[rgba(47,158,99,0.35)] bg-card/95 shadow-[var(--shadow-card)]",children:[e.jsx(Be,{className:"border-b border-border/50 pb-3",children:e.jsxs(ze,{className:"flex items-center justify-between gap-3 text-sm sm:text-base",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[rgb(47,158,99)]"}),"AFILIADO"]}),e.jsx("span",{className:"text-[10px] sm:text-[11px] uppercase tracking-wide rounded border border-[rgba(47,158,99,0.35)] bg-[rgba(47,158,99,0.12)] px-2 py-1 text-[rgb(135,220,171)]",children:"Fonte única"})]})}),e.jsxs(ge,{className:"space-y-5 p-4 sm:p-5",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Comissão líquida"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Pt(me)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Disponível"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Pt(O)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Processando"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Pt(oe)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Transferido"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Pt(ve)})]})]}),e.jsx("div",{className:"rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground leading-relaxed",children:"Comissão calculada por pedido em fonte única: 10% de 7% do valor total recebido. Cancelamentos com estorno/chargeback são descontados automaticamente."}),A?e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-bold mb-2",children:"Nova transferência"}),e.jsxs("form",{onSubmit:Ze,className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-semibold pointer-events-none",children:"R$"}),e.jsx(Te,{className:"h-10 pl-9",type:"text",inputMode:"numeric",autoComplete:"off",value:y,onChange:Ee,placeholder:"0,00"})]}),e.jsx(w,{type:"submit",className:"h-10 whitespace-nowrap",disabled:t||G<1||typeof te=="number"&&G>te,children:"Transferir"})]}),e.jsxs("div",{className:"mt-2 text-[10px] sm:text-[11px] text-muted-foreground leading-snug",children:["Fonte: ",A.label,". Taxa por transferência: ",Pt(Ji),".",typeof te=="number"?e.jsxs("span",{className:"ml-1",children:["Máximo: ",Pt(te),"."]}):null]})]}):null]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[e.jsxs(he,{className:"overflow-hidden border-[rgba(47,158,99,0.35)] bg-card/95 shadow-[var(--shadow-card)]",children:[e.jsx(Be,{className:"border-b border-border/50 pb-3",children:e.jsxs(ze,{className:"flex items-center justify-between gap-3 text-sm sm:text-base",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[rgb(47,158,99)]"}),"PAGAR.ME"]}),e.jsx("span",{className:"text-[10px] sm:text-[11px] uppercase tracking-wide rounded border border-[rgba(47,158,99,0.35)] bg-[rgba(47,158,99,0.12)] px-2 py-1 text-[rgb(135,220,171)]",children:"Gateway online legado"})]})}),e.jsxs(ge,{className:"space-y-5 p-4 sm:p-5",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Disponível"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Pt(D?.available_amount||0)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Processando"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Pt(D?.waiting_funds_amount||0)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Transferido"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Pt(D?.transferred_amount||0)})]})]}),re?e.jsxs("div",{className:"rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-[11px] sm:text-xs text-muted-foreground",children:["Total reembolsado por taxa de antecipação:"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Pt(ee)})]}):null,A?e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-bold mb-2",children:"Nova transferência"}),e.jsxs("form",{onSubmit:Ze,className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-semibold pointer-events-none",children:"R$"}),e.jsx(Te,{className:"h-10 pl-9",type:"text",inputMode:"numeric",autoComplete:"off",value:y,onChange:Ee,placeholder:"0,00"})]}),e.jsx(w,{type:"submit",className:"h-10 whitespace-nowrap",disabled:t||G<1||typeof te=="number"&&G>te,children:"Transferir"})]}),e.jsxs("div",{className:"mt-2 text-[10px] sm:text-[11px] text-muted-foreground leading-snug",children:["Fonte: ",A.label,". Taxa por transferência: ",Pt(Ji),".",typeof te=="number"?e.jsxs("span",{className:"ml-1",children:["Máximo: ",Pt(te),"."]}):null]})]}):e.jsx("div",{className:"rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:"Não há conta legado habilitada para transferência neste perfil."})]})]}),e.jsxs(he,{className:"overflow-hidden border-[rgba(240,127,47,0.4)] bg-card/95 shadow-[0_0_0_1px_rgba(240,127,47,0.12),var(--shadow-card)]",children:[e.jsx(Be,{className:"border-b border-border/50 pb-3",children:e.jsxs(ze,{className:"flex items-center justify-between gap-3 text-sm sm:text-base",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[rgb(240,127,47)]"}),"PAGBANK"]}),e.jsx("span",{className:"text-[10px] sm:text-[11px] uppercase tracking-wide rounded border border-[rgba(240,127,47,0.35)] bg-[rgba(240,127,47,0.12)] px-2 py-1 text-[rgb(255,188,131)]",children:"Gateway online atual"})]})}),e.jsxs(ge,{className:"space-y-4 p-4 sm:p-5",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Vendas confirmadas"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Fe.toLocaleStr
91ing("pt-BR")})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Faturamento bruto"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Pt(ae)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Ticket médio"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:b.isLoading?"—":Pt(K)})]})]}),e.jsx("div",{className:"rounded-lg border border-[rgba(240,127,47,0.32)] bg-[rgba(240,127,47,0.08)] px-3 py-3 text-[11px] sm:text-xs text-foreground/85",children:e.jsxs("p",{className:"flex items-start gap-2 leading-relaxed",children:[e.jsx(tr,{className:"h-4 w-4 shrink-0 mt-0.5 text-[rgb(240,127,47)]"}),e.jsxs("span",{children:["Saldo, recebimentos e transferências ficam ",e.jsx("strong",{className:"text-foreground",children:"apenas no app PagBank"}),"."]})]})}),e.jsx("a",{href:"https://pagseguro.uol.com.br/",target:"_blank",rel:"noreferrer noopener",className:"inline-flex h-10 w-full items-center justify-center rounded-md bg-[linear-gradient(135deg,rgb(240,127,47),rgb(255,149,74))] px-4 text-sm font-bold text-white shadow-[0_4px_14px_rgba(240,127,47,0.35)] transition hover:translate-y-[-1px] hover:shadow-[0_6px_20px_rgba(240,127,47,0.5)]",children:"Abrir app PagBank"})]})]})]}),e.jsx(he,{className:"border-border/50 bg-card/95 shadow-[var(--shadow-card)]",children:e.jsxs(ge,{className:"p-4 sm:p-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg sm:text-xl font-bold leading-tight",children:"Vendas por gateway"}),e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground",children:"Pagar.me e PagBank (ambos online)"})]}),e.jsx("div",{className:"flex gap-1 rounded-lg p-1 bg-muted/40 border border-border/60",children:[{id:"day",label:"Dia"},{id:"week",label:"Semana"},{id:"month",label:"Mês"},{id:"all",label:"Tudo"}].map(we=>e.jsx(w,{type:"button",size:"sm",variant:h===we.id?"default":"ghost",className:"h-8 px-3 text-xs",onClick:()=>p(we.id),children:we.label},we.id))})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 mb-3 text-xs flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[rgb(47,158,99)]"}),e.jsx("span",{className:"font-semibold",children:"Pagar.me"}),e.jsx("span",{className:"text-muted-foreground hidden sm:inline",children:"· gateway online"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[rgb(240,127,47)]"}),e.jsx("span",{className:"font-semibold",children:"PagBank"}),e.jsx("span",{className:"text-muted-foreground hidden sm:inline",children:"· gateway online"})]})]}),e.jsx("div",{className:"h-[260px] sm:h-[320px] w-full",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(rc,{data:ke,margin:{top:10,right:8,left:0,bottom:0},children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"hub-pagarme",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Qi,stopOpacity:.26}),e.jsx("stop",{offset:"100%",stopColor:Qi,stopOpacity:0})]}),e.jsxs("linearGradient",{id:"hub-pagbank",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Wi,stopOpacity:.3}),e.jsx("stop",{offset:"100%",stopColor:Wi,stopOpacity:0})]})]}),e.jsx(Ra,{strokeDasharray:"3 3",stroke:"hsl(var(--border) / 0.55)"}),e.jsx(Ta,{dataKey:"label",stroke:"hsl(var(--muted-foreground))",tick:{fontSize:11}}),e.jsx($a,{stroke:"hsl(var(--muted-foreground))",tick:{fontSize:11},width:56,tickFormatter:we=>$g(we)}),e.jsx(Aa,{contentStyle:{backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))",borderRadius:10},formatter:we=>Pt(we)}),e.jsx(di,{type:"monotone",dataKey:"pagarme",name:"Pagar.me",stroke:Qi,fill:"url(#hub-pagarme)",strokeWidth:2.5,dot:{r:3},activeDot:{r:5}}),e.jsx(di,{type:"monotone",dataKey:"pagbank",name:"PagBank",stroke:Wi,fill:"url(#hub-pagbank)",strokeWidth:2.5,dot:{r:3},activeDot:{r:5}})]})})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mt-4 pt-4 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-[rgb(47,158,99)] shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[10px] sm:text-[11px] uppercase tracking-wider text-muted-foreground font-bold truncate",children:["Pagar.me · ",id(h)]}),e.jsx("div",{className:"font-bold text-sm sm:text-lg leading-tight",children:Pt(Ae.pagarme)})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-[rgb(240,127,47)] shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[10px] sm:text-[11px] uppercase tracking-wider text-muted-foreground font-bold truncate",children:["PagBank · ",id(h)]}),e.jsx("div",{className:"font-bold text-sm sm:text-lg leading-tight",children:Pt(Ae.pagbank)})]})]})]})]})})]}),e.jsxs(he,{className:"border-border/50 bg-card/95 shadow-[var(--shadow-card)]",children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between gap-3 border-b border-border/50",children:[e.jsxs("div",{children:[e.jsx(ze,{className:"text-lg sm:text-xl",children:"Transferências"}),e.jsxs("p",{className:"text-[11px] sm:text-xs text-muted-foreground mt-1",children:[A?.label||"Pagar.me legado"," · saídas para conta configurada"]})]}),e.jsxs(at,{children:[e.jsx(vn,{asChild:!0,children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Ver orientações sobre transferências",children:e.jsx(ii,{className:"h-4 w-4"})})}),e.jsx(rt,{className:"max-w-lg",children:e.jsxs(nt,{children:[e.jsx(it,{children:"Diretrizes das transferências"}),e.jsx(Ba,{asChild:!0,children:e.jsx(od,{})})]})})]})]}),e.jsxs(ge,{className:"p-3 sm:p-5 space-y-2",children:[b.isLoading?e.jsx("div",{className:"py-8 text-sm text-center text-muted-foreground",children:"Carregando transferências…"}):U.length===0?e.jsx("div",{className:"py-8 text-sm text-center text-muted-foreground",children:"Nenhuma transferência encontrada."}):U.map(we=>e.jsxs("div",{className:"rounded-md border border-border p-3 transition hover:bg-muted/25 border-l-[3px] border-l-[rgba(47,158,99,0.55)]",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold",children:we?.id||we?.de
91scription||"Transferência"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:Lg(we?.created_at||we?.date_created)})]}),e.jsxs("div",{className:"mt-1.5 flex items-center justify-between text-sm gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:"Valor"}),e.jsxs("span",{className:"font-semibold inline-flex items-center gap-2",children:[String(we?.direction||"out").toLowerCase()==="in"?e.jsx(Wd,{className:"h-4 w-4 text-emerald-500"}):e.jsx(Jd,{className:"h-4 w-4 text-amber-500"}),Pt(we?.amount||0)]})]}),e.jsxs("div",{className:"mt-1.5 text-[11px] text-muted-foreground",children:["Status: ",rd(we?.status)]})]},we?.id||`${we?.created_at||we?.date_created}-${we?.amount}`)),fe.length>Ln?e.jsxs("div",{className:"pt-2 flex items-center justify-end gap-2",children:[e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>I(we=>Math.max(1,we-1)),disabled:_e<=1,children:"Anterior"}),e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>I(we=>Math.min(le,we+1)),disabled:_e>=le,children:"Próxima"})]}):null,e.jsx("div",{className:"pt-2 border-t border-border/40",children:e.jsxs("div",{className:"text-[11px] text-muted-foreground leading-relaxed flex items-start gap-2",children:[e.jsx(ii,{className:"h-3.5 w-3.5 shrink-0 mt-0.5 text-[rgb(240,127,47)]"}),e.jsx("span",{children:L?"Nesta aba, a lista mostra apenas solicitações de transferência da comissão do afiliado.":"Transferências do PagBank são feitas direto pelo app da operadora e não aparecem nesta lista."})]})})]})]}),e.jsx(he,{className:"border-[rgba(255,208,92,0.35)] bg-[rgba(255,208,92,0.08)] shadow-[var(--shadow-card)]",children:e.jsxs(ge,{className:"p-4 sm:p-5",children:[e.jsx("div",{className:"text-[10px] sm:text-[11px] uppercase tracking-widest text-[hsl(var(--accent))] font-bold mb-2",children:"Notas da proposta"}),e.jsxs("ul",{className:"text-[11px] sm:text-xs text-foreground/85 space-y-1.5 leading-relaxed list-disc list-inside",children:[L?e.jsxs(e.Fragment,{children:[e.jsxs("li",{children:["O afiliado usa ",e.jsx("strong",{children:"fonte única"})," sem separação por gateway."]}),e.jsxs("li",{children:["A comissão é calculada por pedido como ",e.jsx("strong",{children:"10% de 7%"})," do valor total recebido."]}),e.jsx("li",{children:"Pedidos cancelados com estorno/chargeback geram desconto automático na comissão líquida."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Pagar.me"})," mostra dados completos (disponível, processando, transferido) porque temos integração de API."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"PagBank"})," exibe vendas online confirmadas por status; chargeback, cancelamento e falhas não entram nas métricas."]}),e.jsxs("li",{children:["O gráfico ",e.jsx("strong",{children:"Vendas por gateway"})," compara Pagar.me e PagBank em Dia, Semana e Mês para o perfil selecionado."]})]}),J.map((we,Me)=>e.jsx("li",{children:we},`${we}-${Me}`))]})]})}),!b.isLoading&&(L?!z:!D&&!E)?e.jsx(he,{className:"border-dashed",children:e.jsx(ge,{className:"py-8 text-sm text-muted-foreground text-center",children:"Nenhuma fonte financeira configurada para este perfil no momento."})}):null,e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground flex-wrap",children:[e.jsx(kr,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:["Gateway ativo: ",b.data?.active_gateway||"—","."]}),b.data?.providers?.pagbank_splits_disabled?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Yd,{className:"h-3.5 w-3.5"}),"Split PagBank desabilitado no ambiente."]}):null]})]})]})}const Xi="#2f9e63",Zi="#f07f2f",ld=367;function xa(s=0){return new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format((Number(s)||0)/100)}function Vg(s=0){return new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",notation:"compact",maximumFractionDigits:1}).format((Number(s)||0)/100)}function Gg(s){if(!s)return"-";const t=new Date(s);return Number.isNaN(t.getTime())?"-":t.toLocaleString("pt-BR")}function mr(s){if(!s)return null;const t=new Date(s);return Number.isNaN(t.getTime())?null:t}function dd(s){return String(s||"").toLowerCase().trim()}function cd(s){const t=String(s||"").toLowerCase();return t==="pending_transfer"?"Aguardando transferência":t==="transferred"?"Transferida":t==="failed"?"Falhou":t==="processing"?"Processando":t==="canceled"?"Cancelada":t==="paid"?"Recebido":s||"—"}
91const Hg=new Set(["paid","captured","succeeded","approved","settled","completed","success"]),Kg=new Set(["failed","canceled","cancelled","cancelado","cancelada","denied","declined","chargeback","chargebacked","chargedback","refunded","refund","estornado","estornada","estorno","reembolsado","reembolsada","reembolso","reversed","reversal","dispute","disputed"]),Po=/(charge_?back|refund|reembolso|reembolsad|estorno|estornad|cancelad|cancel|fail|deni|declin|disput|revers)/;function Qg(s){return String(s||"").toLowerCase().trim().replaceAll("-","_").replaceAll(" ","_")}function Wg(s){const t=[s?.status,s?.metadata?.status,s?.metadata?.order_status,s?.metadata?.charge_status,s?.metadata?.payment_status,s?.metadata?.split_status];for(const a of t){const n=Qg(a);if(n)return n}return""}function Jg(s){const t=[s?.status,s?.type,s?.description,s?.title,s?.metadata?.status,s?.metadata?.order_status,s?.metadata?.charge_status,s?.metadata?.payment_status,s?.metadata?.split_status].map(n=>String(n||"").toLowerCase()).filter(Boolean).join(" "),a=JSON.stringify(s?.metadata||{}).toLowerCase();return Po.test(t)||Po.test(a)}function Yg(s){if((Number(s?.amount)||0)<=0)return!1;const a=String(s?.direction||"").toLowerCase();if(a&&a!=="in"||Jg(s))return!1;const n=Wg(s);return n?Kg.has(n)||Po.test(n)?!1:Hg.has(n)?!0:/(paid|captur|settled|succeed|approv|complete|success)/.test(n):!0}function ud({movements:s=[],range:t="week"}){const a=new Date,n=Array.isArray(s)?s:[];if(t==="all"){const c=n.filter(g=>mr(g?.created_at||g?.date_created));if(!c.length)return{labels:["Tudo"],series:[n.reduce((g,N)=>g+Math.max(0,Number(N?.amount)||0),0)]};const m=c.reduce((g,N)=>{const b=mr(N?.created_at||N?.date_created)?.getTime()||Number.MAX_SAFE_INTEGER;return Math.min(g,b)},Number.MAX_SAFE_INTEGER),x=new Date(m);x.setDate(1),x.setHours(0,0,0,0);const h=(a.getFullYear()-x.getFullYear())*12+(a.getMonth()-x.getMonth()),p=Math.min(Math.max(h+1,1),36),f=Array.from({length:p},(g,N)=>{const b=new Date(x);return b.setMonth(x.getMonth()+N),{key:`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}`,label:b.toLocaleDateString("pt-BR",{month:"short",year:"2-digit"}),value:0}}),I=new Map(f.map(g=>[g.key,g]));return n.forEach(g=>{const N=mr(g?.created_at||g?.date_created);if(!N)return;const b=`${N.getFullYear()}-${String(N.getMonth()+1).padStart(2,"0")}`,C=I.get(b);C&&(C.value+=Math.max(0,Number(g?.amount)||0))}),{labels:f.map(g=>g.label),series:f.map(g=>g.value)}}if(t==="day"){const c=new Date(a);c.setMinutes(0,0,0),c.setHours(c.getHours()-22);const m=Array.from({length:12},(x,h)=>{const p=new Date(c.getTime()+h*2*60*60*1e3);return{key:p.getTime(),label:p.toLocaleTimeString("pt-BR",{hour:"2-digit"}).replace(":00","h"),start:p,end:new Date(p.getTime()+2*60*60*1e3),value:0}});return n.forEach(x=>{const h=mr(x?.created_at||x?.date_created);if(!h||h<c||h>a)return;const p=h.getTime()-c.getTime(),f=Math.floor(p/(2*60*60*1e3));f<0||f>=m.length||(m[f].value+=Math.max(0,Number(x?.amount)||0))}),{labels:m.map(x=>x.label),series:m.map(x=>x.value)}}const o=t==="month"?30:7,i=new Date(a);i.setHours(0,0,0,0),i.setDate(i.getDate()-(o-1));const u=Array.from({length:o},(c,m)=>{const x=new Date(i);x.setDate(i.getDate()+m);const h=x.toISOString().slice(0,10),p=t==="month"?x.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}):x.toLocaleDateString("pt-BR",{weekday:"short"});return{key:h,label:p,value:0}}),l=new Map(u.map(c=>[c.key,c]));return n.forEach(c=>{const m=mr(c?.created_at||c?.date_created);if(!m||m<i||m>a)return;const x=m.toISOString().slice(0,10),h=l.get(x);h&&(h.value+=Math.max(0,Number(c?.amount)||0))}),{labels:u.map(c=>c.label),series:u.map(c=>c.value)}}function Xg({range:s,pagarmeMovements:t,pagbankMovements:a}){const n=ud({movements:t,range:s}),o=ud({movements:a,range:s});return n.labels.map((i,u)=>({label:i,pagarme:n.series[u]||0,pagbank:o.series[u]||0}))}function md(s){return s==="day"?"24h":s==="week"?"7d":s==="month"?"30d":"Tudo"}function xd(){return e.jsxs("div",{className:"space-y-4 text-left",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Processamento seguro"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"As transferências são executadas exclusivamente via TED. Por motivos de segurança e conformidade bancária, solicitações envi
91adas após as 15h (horário de Brasília) são automaticamente agendadas para o processamento no próximo dia útil."})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Taxa de segurança reembolsável"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Cada transferência inclui uma taxa de segurança de R$ 3,67. Esse valor é integralmente reembolsado pela TicketTop assim que o status da transferência é atualizado para "Pago".'})]})]})}function Zg(){const{toast:s}=mt(),[t,a]=r.useState(!1),[n,o]=r.useState(""),[i,u]=r.useState(!1),[l,c]=r.useState(!1),[m,x]=r.useState("week"),[h,p]=r.useState(1),[f,I]=r.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("extratoTransferInfoAck")==="true"}catch{return!1}}),g=Rt({queryKey:["extrato-admin-overview-v2",60],queryFn:()=>mc({count:60}),refetchOnWindowFocus:!1}),{config:N}=Fr({refetchOnWindowFocus:!1}),b=g.data?.roles?.admin||{aggregate:{notes:[]},sources:[]},C=Array.isArray(b.sources)?b.sources:[],q=r.useMemo(()=>{const le=C.find(_e=>dd(_e?.provider)==="pagarme");return le||C.find(_e=>_e?.transferEnabled)||null},[C]),L=r.useMemo(()=>C.find(le=>dd(le?.provider)==="pagbank")||null,[C]),M=r.useMemo(()=>q?.transferEnabled?q:C.find(le=>le?.transferEnabled)||null,[q,C]),z=r.useMemo(()=>new Intl.NumberFormat("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2}),[]),D=r.useMemo(()=>{const le=N?.total_reembolsado_taxa_antecipacao_brl;if(le==null||le==="")return 0;const _e=Number(le),U=Number(String(le).replace(/\./g,"").replace(",",".")),J=Number.isFinite(_e)?_e:U;return!Number.isFinite(J)||J<0?0:Math.round(J*100)},[N?.total_reembolsado_taxa_antecipacao_brl]),E=N?.exibir_texto_total_reembolsado_taxa_antecipacao!==!1,A=r.useMemo(()=>{const le=Number(M?.available_amount);if(Number.isFinite(le))return Math.max(0,Math.floor(le-ld))},[M?.available_amount]),S=r.useMemo(()=>{const le=String(n||"").replaceAll(/\D/g,"");return le?Number.parseInt(le,10):0},[n]),P=r.useMemo(()=>n?z.format(S/100):"",[n,S,z]),F=r.useMemo(()=>Array.isArray(q?.movements)?q.movements:[],[q]),ee=r.useMemo(()=>Array.isArray(L?.movements)?L.movements:[],[L]),re=r.useMemo(()=>ee.filter(le=>Yg(le)),[ee]),te=r.useMemo(()=>Xg({range:m,pagarmeMovements:F,pagbankMovements:re}),[m,F,re]),G=r.useMemo(()=>te.reduce((le,_e)=>(le.pagarme+=Number(_e?.pagarme)||0,le.pagbank+=Number(_e?.pagbank)||0,le),{pagarme:0,pagbank:0}),[te]),y=re,$=y.length,W=y.reduce((le,_e)=>le+(Number(_e?.amount)||0),0),ie=$>0?Math.round(W/$):0,ke=r.useMemo(()=>(Array.isArray(M?.movements)?M.movements:[]).filter(_e=>String(_e?.direction||"out").toLowerCase()!=="in").sort((_e,U)=>{const J=mr(_e?.created_at||_e?.date_created)?.getTime()||0;return(mr(U?.created_at||U?.date_created)?.getTime()||0)-J}),[M]),Ae=5,be=Math.max(1,Math.ceil(ke.length/Ae)),Fe=Math.min(h,be),ae=r.useMemo(()=>{const le=(Fe-1)*Ae;return ke.slice(le,le+Ae)},[Fe,ke]),K=le=>{const _e=String(le.target.value||"").replaceAll(/\D/g,"").slice(0,11);if(!_e){o("");return}let U=Number.parseInt(_e,10);Number.isNaN(U)&&(U=0),typeof A=="number"&&(U=Math.min(U,A)),o(String(U))},O=async()=>{if(!(!M||!S||S<1)){if(typeof A=="number"&&S>A){s({title:"Valor acima do máximo",description:`Máximo disponível para transferência: ${xa(A)}.`,variant:"destructive"});return}a(!0);try{const le=await xc({amount:S,provider:M.provider,kind:"admin"}),_e=le?.id||le?.data?.id,U=le?.status||le?.data?.status;s({title:"Transferência solicitada",description:`${_e?`ID ${_e} · `:""}${U?`Status: ${cd(U)} · `:""}Valor: ${xa(S)}.`}),o(""),p(1),await g.refetch()}catch(le){const _e=le?.response?.data?.error?.message||le?.response?.data?.message||le?.message;s({title:"Falha ao criar transferência",description:_e?String(_e):"Tente novamente em instantes.",variant:"destructive"})}finally{a(!1)}}},oe=async le=>{if(le.preventDefault(),!f){c(!0),u(!0);return}await O()},ve=async()=>{I(!0);try{typeof window<"u"&&window.localStorage.setItem("extratoTransferInfoAck","true")}catch{}l&&(c(!1),await O()),u(!1)},me=le=>{!le&&!f&&c(!1),u(le)},fe=Array.isArray(b.aggregate?.notes)?b.aggregate.notes:[];return e.jsxs(e.Fragment,{children:[e.jsx(at,{open:i,onOpenChange:me,children:e.jsxs(rt,{className:"max-w-lg",children:[e.jsxs(nt,{children:[e.jsx(it,{children:"Diretrizes das transferências"}),e.jsx(Ba,{asChild:!0,children:e.jsx(xd,{})})]}),e.jsxs(Ut,{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(w,{variant:"outline",onClick:()=>me(!1),disabled:l&&!f,children:"Fechar"}),e.jsx(w,{onClick:ve,disabled:t&&l,children:"Estou ciente"})]})]})}),e.jsxs("div",{className:"space-y-5 sm:space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:"Extratos"}),e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground",children:"Admin, Afiliado e TicketTop"})]}),e.jsx(he,{className:"border-border/60 bg-card/95 shadow-[var(--shadow-card)]",children:e.jsx(ge,{className:"p-4 sm:p-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-md bg-primary/15 flex items-center justify-center shrink-0",children:e.jsx(bn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-base font-semibold leading-tight",children:"Admin"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:"POROROCA STUDIOS LTDA"})]})]})})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[e.jsxs(he,{className:"overflow-hidden border-[rgba(47,158,99,0.35)] bg-card/95 shadow-[var(--shadow-card)] px-2",children:[e.jsx(Be,{className:"border-b border-border/50 pb-3",children:e.jsxs(ze,{className:"flex items-center justify-between gap-3 text-sm sm:text-base",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[rgb(47,158,99)]"}),"PAGAR.ME"]}),e.jsx("span",{className:"text-[10px] sm:text-[11px] uppercase tracking-wide rounded border border-[rgba(47,158,99,0.35)] bg-[rgba(47,158,99,0.12)] px-2 py-1 text-[rgb(135,220,171)]",children:"Gateway online legado"})]})}),e.jsxs(ge,{className:"space-y-5 p-4 sm:p-5",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Disponível"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:g.isLoading?"—":x
91a(q?.available_amount||0)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Processando"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:g.isLoading?"—":xa(q?.waiting_funds_amount||0)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Transferido"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:g.isLoading?"—":xa(q?.transferred_amount||0)})]})]}),E?e.jsxs("div",{className:"rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-[11px] sm:text-xs text-muted-foreground",children:["Total reembolsado por taxa de antecipação:"," ",e.jsx("span",{className:"font-semibold text-foreground",children:xa(D)})]}):null,M?e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-bold mb-2",children:"Nova transferência"}),e.jsxs("form",{onSubmit:oe,className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-semibold pointer-events-none",children:"R$"}),e.jsx(Te,{className:"h-10 pl-9",type:"text",inputMode:"numeric",autoComplete:"off",value:P,onChange:K,placeholder:"0,00"})]}),e.jsx(w,{type:"submit",className:"h-10 whitespace-nowrap",disabled:t||S<1||typeof A=="number"&&S>A,children:"Transferir"})]}),e.jsxs("div",{className:"mt-2 text-[10px] sm:text-[11px] text-muted-foreground leading-snug",children:["Fonte: ",M.label,". Taxa por transferência: ",xa(ld),".",typeof A=="number"?e.jsxs("span",{className:"ml-1",children:["Máximo: ",xa(A),"."]}):null]})]}):e.jsx("div",{className:"rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:"Não há conta legado habilitada para transferência neste momento."})]})]}),e.jsxs(he,{className:"px-2 overflow-hidden border-[rgba(240,127,47,0.4)] bg-card/95 shadow-[0_0_0_1px_rgba(240,127,47,0.12),var(--shadow-card)]",children:[e.jsx(Be,{className:"border-b border-border/50 pb-3",children:e.jsxs(ze,{className:"flex items-center justify-between gap-3 text-sm sm:text-base",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[rgb(240,127,47)]"}),"PAGBANK"]}),e.jsx("span",{className:"text-[10px] sm:text-[11px] uppercase tracking-wide rounded border border-[rgba(240,127,47,0.35)] bg-[rgba(240,127,47,0.12)] px-2 py-1 text-[rgb(255,188,131)]",children:"Gateway online atual"})]})}),e.jsxs(ge,{className:"space-y-4 p-4 sm:p-5",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Vendas confirmadas"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:g.isLoading?"—":$.toLocaleString("pt-BR")})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Faturamento bruto"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:g.isLoading?"—":x
91a(W)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] sm:text-xs text-muted-foreground mb-1",children:"Ticket médio"}),e.jsx("div",{className:"font-semibold text-sm sm:text-lg leading-tight",children:g.isLoading?"—":xa(ie)})]})]}),e.jsx("div",{className:"rounded-lg border border-[rgba(240,127,47,0.32)] bg-[rgba(240,127,47,0.08)] px-3 py-3 text-[11px] sm:text-xs text-foreground/85",children:e.jsxs("p",{className:"flex items-start gap-2 leading-relaxed",children:[e.jsx(tr,{className:"h-4 w-4 shrink-0 mt-0.5 text-[rgb(240,127,47)]"}),e.jsxs("span",{children:["Saldo, recebimentos e transferências ficam ",e.jsx("strong",{className:"text-foreground",children:"apenas no app PagBank"}),"."]})]})}),e.jsx("a",{href:"https://pagseguro.uol.com.br/",target:"_blank",rel:"noreferrer noopener",className:"inline-flex h-10 w-full items-center justify-center rounded-md bg-[linear-gradient(135deg,rgb(240,127,47),rgb(255,149,74))] px-4 text-sm font-bold text-white shadow-[0_4px_14px_rgba(240,127,47,0.35)] transition hover:translate-y-[-1px] hover:shadow-[0_6px_20px_rgba(240,127,47,0.5)]",children:"Abrir app PagBank"})]})]})]}),e.jsx(he,{className:"border-border/50 bg-card/95 shadow-[var(--shadow-card)]",children:e.jsxs(ge,{className:"p-4 sm:p-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg sm:text-xl font-bold leading-tight",children:"Vendas por gateway"}),e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground",children:"Pagar.me e PagBank (ambos online)"})]}),e.jsx("div",{className:"flex gap-1 rounded-lg p-1 bg-muted/40 border border-border/60",children:[{id:"day",label:"Dia"},{id:"week",label:"Semana"},{id:"month",label:"Mês"},{id:"all",label:"Tudo"}].map(le=>e.jsx(w,{type:"button",size:"sm",variant:m===le.id?"default":"ghost",className:"h-8 px-3 text-xs",onClick:()=>x(le.id),children:le.label},le.id))})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 mb-3 text-xs flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[rgb(47,158,99)]"}),e.jsx("span",{className:"font-semibold",children:"Pagar.me"}),e.jsx("span",{className:"text-muted-foreground hidden sm:inline",children:"· gateway online"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[rgb(240,127,47)]"}),e.jsx("span",{className:"font-semibold",children:"PagBank"}),e.jsx("span",{className:"text-muted-foreground hidden sm:inline",children:"· gateway online"})]})]}),e.jsx("div",{className:"h-[260px] sm:h-[320px] w-full",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(rc,{data:te,margin:{top:10,right:8,left:0,bottom:0},children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"extrato-pagarme",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Xi,stopOpacity:.26}),e.jsx("stop",{offset:"100%",stopColor:Xi,stopOpacity:0})]}),e.jsxs("linearGradient",{id:"extrato-pagbank",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Zi,stopOpacity:.3}),e.jsx("stop",{offset:"100%",stopColor:Zi,stopOpacity:0})]})]}),e.jsx(Ra,{strokeDasharray:"3 3",stroke:"hsl(var(--border) / 0.55)"}),e.jsx(Ta,{dataKey:"label",stroke:"hsl(var(--muted-foreground))",tick:{fontSize:11}}),e.jsx($a,{stroke:"hsl(var(--muted-foreground))",tick:{fontSize:11},width:56,tickFormatter:le=>Vg(le)}),e.jsx(Aa,{contentStyle:{backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))",borderRadius:10},formatter:le=>xa(le)}),e.jsx(di,{type:"monotone",dataKey:"pagarme",name:"Pagar.me",stroke:Xi,fill:"url(#extrato-pagarme)",strokeWidth:2.5,dot:{r:3},activeDot:{r:5}}),e.jsx(di,{type:"monotone",dataKey:"pagbank",name:"PagBank",stroke:Zi,fill:"url(#extrato-pagbank)",strokeWidth:2.5,dot:{r:3},activeDot:{r:5}})]})})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mt-4 pt-4 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-[rgb(47,158,99)] shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[10px] sm:text-[11px] uppercase tracking-wider text-muted-foreground font-bold truncate",children:["Pagar.me · ",md(m)]}),e.jsx("div",{className:"font-bold text-sm sm:text-lg leading-tight",children:xa(G.pagarme)})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-[rgb(240,127,47)] shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[10px] sm:text-[11px] uppercase tracking-wider text-muted-foreground font-bold truncate",children:["PagBank · ",md(m)]}),e.jsx("div",{className:"font-bold text-sm sm:text-lg leading-tight",children:xa(G.pagbank)})]})]})]})]})}),e.jsxs(he,{className:"border-border/50 bg-card/95 shadow-[var(--shadow-card)]",children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between gap-3 border-b border-border/50",children:[e.jsxs("div",{children:[e.jsx(ze,{className:"text-lg sm:text-xl",children:"Transferências"}),e.jsxs("p",{className:"text-[11px] sm:text-xs text-muted-foreground mt-1",children:[M?.label||"Pagar.me legado"," · saídas para conta configurada"]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(at,{children:[e.jsx(vn,{asChild:!0,children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Ver orientações sobre transferências",children:e.jsx(ii,{className:"h-4 w-4"})})}),e.jsx(rt,{className:"max-w-lg",children:e.jsxs(nt,{children:[e.jsx(it,{children:"Diretrizes das transferências"}),e.jsx(Ba,{asChild:!0,children:e.jsx(xd,{})})]})})]})})]}),e.jsxs(ge,{className:"p-3 sm:p-5 space-y-2",children:[g.isLoading?e.jsx("div",{className:"py-8 text-sm text-center text-muted-foreground",children:"Carregando transferências…"}):ae.length===0?e.jsx("div",{className:"py-8 text-sm text-center text-muted-foreground",children:"Nenhuma transferência encontrada."}):ae.map(le=>e.jsxs("div",{className:"rounded-md border border-border p-3 transition hover:bg-muted/25 border-l-[3px] border-l-[rgba(47,158,99,0.55)]",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold",children:le?.id||le?.description||"Transferência"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:Gg(le?.created_at||le?.date_created)})]}),e.jsxs("div",{className:"mt-1.5 flex items-center justify-between text-sm gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:"Valor"}),e.jsxs("span",{className:"font-semibold inline-flex items-center gap-2",children:[String(le?.direction||"out").toLowerCase()==="in"?e.jsx(Wd,{className:"h-4 w-4 text-emerald-500"}):e.jsx(Jd,{className:"h-4 w-4 text-amber-500"}),xa(le?.amount||0)]})]}),e.jsxs("div",{className:"mt-1.5 text-[11px] text-muted-foreground",children:["Status: ",cd(le?.status)]})]},le?.id||`${le?.created_at||le?.date_created}-${le?.amount}`)),ke.length>Ae?e.jsxs("div",{className:"pt-2 flex items-center justify-end gap-2",children:[e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>p(le=>
91Math.max(1,le-1)),disabled:Fe<=1,children:"Anterior"}),e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>p(le=>Math.min(be,le+1)),disabled:Fe>=be,children:"Próxima"})]}):null,e.jsx("div",{className:"pt-2 border-t border-border/40",children:e.jsxs("div",{className:"text-[11px] text-muted-foreground leading-relaxed flex items-start gap-2",children:[e.jsx(ii,{className:"h-3.5 w-3.5 shrink-0 mt-0.5 text-[rgb(240,127,47)]"}),e.jsx("span",{children:"Transferências do PagBank são feitas direto pelo app da operadora e não aparecem nesta lista."})]})})]})]}),e.jsx(he,{className:"border-[rgba(255,208,92,0.35)] bg-[rgba(255,208,92,0.08)] shadow-[var(--shadow-card)]",children:e.jsxs(ge,{className:"p-4 sm:p-5",children:[e.jsx("div",{className:"text-[10px] sm:text-[11px] uppercase tracking-widest text-[hsl(var(--accent))] font-bold mb-2",children:"Notas da proposta"}),e.jsxs("ul",{className:"text-[11px] sm:text-xs text-foreground/85 space-y-1.5 leading-relaxed list-disc list-inside",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Pagar.me"})," mostra dados completos (disponível, processando, transferido) porque temos integração de API."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"PagBank"})," exibe vendas online confirmadas por status; chargeback, cancelamento e falhas não entram nas métricas."]}),e.jsxs("li",{children:["O gráfico ",e.jsx("strong",{children:"Vendas por gateway"})," compara Pagar.me e PagBank em Dia, Semana e Mês."]}),e.jsx("li",{children:"Ambos os blocos representam gateways online, sem separação por canal presencial."}),fe.map((le,_e)=>e.jsx("li",{children:le},`${le}-${_e}`))]})]})}),!g.isLoading&&!q&&!L?e.jsx(he,{className:"border-dashed",children:e.jsx(ge,{className:"py-8 text-sm text-muted-foreground text-center",children:"Nenhuma fonte financeira configurada para o extrato no momento."})}):null,e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx(kr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Atualização em tempo real ao abrir a tela."}),g.data?.providers?.pagbank_splits_disabled?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Yd,{className:"h-3.5 w-3.5"}),"Split PagBank desabilitado no ambiente."]}):null]})]})]})}async function ef({pageSize:s=50,eventoId:t,eventoDocumentId:a,dataEvento:n}={}){const o={pageSize:s};return t&&(o.eventoId=t),a&&(o.eventoDocumentId=a),n&&(o.dataEvento=n),(await $e.post("/pedidos/payment-email/resend",o)).data}async function sf({pageSize:s=50,eventoId:t,eventoDocumentId:a,dataEvento:n}={}){const o={pageSize:s};return t&&(o.eventoId=t),a&&(o.eventoDocumentId=a),n&&(o.dataEvento=n),(await $e.post("/pedidos/payment-email/resend-all",o)).data}async function tf({dataEvento:s,skipAlreadySent:t=!0,eventoId:a,eventoDocumentId:n}={}){const o=new URLSearchParams;return s&&o.set("dataEvento",s),t||o.set("skipAlreadySent","false"),a&&o.set("eventoId",String(a)),n&&o.set("eventoDocumentId",n),(await $e.get(`/pedidos/event-reminder/preview?${o.toString()}`)).data}async function af({dataEvento:s,skipAlreadySent:t=!0,eventoId:a,eventoDocumentId:n}={}){return(await $e.post("/pedidos/event-reminder/send",{dataEvento:s,skipAlreadySent:t,eventoId:a,eventoDocumentId:n})).data}async function rf({limit:s=50}={}){const t=new URLSearchParams;s&&t.set("limit",String(s));const a=t.toString()?`?${t.toString()}`:"";return(await $e.get(`/pedidos/upsell-repair/preview${a}`)).data}async function pd({pedidoIds:s,childReference:t,originalDocumentId:a}={}){const n={};return Array.isArray(s)&&s.length>0&&(n.pedidoIds=s),t&&(n.childReference=t),a&&(n.originalDocumentId=a),(await $e.post("/pedidos/upsell-repair/run",n)).data}async function nf({provider:s,limit:t}={}){const a=new URLSearchParams;s&&a.set("provider",s),t&&a.set("limit",String(t));const n=a.toString()?`?${a.toString()}`:"";return(await $e.get(`/pedidos/gateway/reconcile-status${n}`)).data}async function of({provider:s,limit:t}={}){const a={};return s&&(a.provider=s),t&&(a.limit=t),(await $e.post("/pedidos/gateway/reconcile-status",a)).data}async function lf({eventoId:s,eventoDocumentId:t}={}){const a={};return s!=null&&s!==""&&(a.eventoId=s),t&&(a.eventoDocumentId=String(t).trim()),(await $e.post("/cart/admin/refresh-prices",a)).data}async function df({eventoId:s,eventoDocumentId:t}={}){const a={};return s!=null&&s!==""&&(a.eventoId=s),t&&(a.eventoDocumentId=String(t).trim()),(await $e.post("/cart/admin/clear-all",a)).data}const cf=typeof window<"u"?window.location.origin:"",xu=s=>`${cf}/c/${encodeURIComponent(s)}`,Ni=s=>{if(!s)return"—";try{return Us(new Date(s),"dd/MM/yyyy HH:mm",{locale:Vs})}catch{return s}},Ro=(s="")=>String(s||"").toUpperCase().replace(/[^A-Z0-9_-]/g,""),hd=s=>{const t=Ro(s?.preset_coupon_code);return t?`Fixo: ${t}`:s?.allow_coupon_input===!1?"Oculto":"Livre"},uf=async()=>(await $e.get("/link-checkouts?populate[evento][fields][0]=id&populate[evento][fields][1]=titulo&populate[items][populate][tipo_ingresso][fields][0]=id&populate[items][populate][tipo_ingresso][fields][1]=nome&populate[target_user][fields][0]=id&populate[target_user][fields][1]=nome&sort=createdAt:desc&pagination[pageSize]=200")).data,mf=async s=>{if(!s)return null;const t=await $e.get(`/eventos/${s}?populate[datas_futuras][fields][0]=data&populate[datas_futuras][fields][1]=ativo&populate[lotes][fields][0]=id&populate[lotes][fields][1]=nome&populate[lotes][fields][2]=data_evento&populate[lotes][fields][3]=ativo&populate[lotes][populate][tipo_ingresso][fields][0]=id&populate[lotes][populate][tipo_ingresso][fields][1]=nome&populate[lotes][populate][tipo_ingresso][fields][2]=progressivo&populate[lotes][populate][tipo_ingresso][fields][3]=quantidade_itens`);return t.data?.data||t.data||null},xf=s=>{if(!s)return[];const t=new Set,a=[],n=s.attributes||s,o=Array.isArray(n.lotes?.data)?n.lotes.data:Array.isArray(n.lotes)?n.lotes:[];for(const u of o){const l=u.attributes?.tipo_ingresso?.data||u.tipo_ingresso,c=l?.attributes||l,m=l?.id||c?.id,x=c?.nome||`Tipo #${m}`;m&&!t.has(String(m))&&(t.add(String(m)),a.push({id:m,nome:x,progressivo:c?.progressivo??!1,quantidade_itens:Number(c?.quantidade_itens??1)||1}))}const i=Array.isArray(n.tipos_ingresso?.data)?n.tipos_ingresso.data:Array.isArray(n.tipos_ingresso)?n.tipos_ingresso:[];for(const u of i){const l=u.attributes||u,c=l?.tipo_ingresso?.data||l?.tipo_ingresso,m=c?.attributes||c,x=c?.id||m?.id,h=m?.nome||`Tipo #${x}`;x&&!t.has(String(x))&&(t.add(String(x)),a.push({id:x,nome:h,progressivo:m?.progressivo??!1,quantidade_itens:Number(m?.quantidade_itens??1)||1}))}return a},pf=(s,t,a)=>{if(!s||!t)return[];const n=s.attributes||s;return(Array.isArray(n.lotes?.data)?n.lotes.data:Array.isArray(n.lotes)?n.lotes:[]).filter(i=>{const u=i.attributes||i;if(u.ativo===!1)return!1;const l=u.tipo_ingresso?.data||u.tipo_ingresso,c=l?.id??l?.attributes?.id;return!(String(c)!==String(t)||a&&u.data_evento&&u.data_evento!==a)}).map(i=>{const u=i.attributes||i;return{id:i.id,nome:u.nome||`Lote #${i.id}`,data_evento:u.data_evento}})},gd=(s,t)=>{const a=Number(s);return!Number.isFinite(a)||t<=1?Math.max(1,Math.round(a)||1):Math.max(t,Math.ceil(a/t)*t)},eo={label:"",customCode:"",eventoId:"",selectedDate:"",targetUserId:"",expires_at:"",max_uses:"",allowCouponInput
91:!0,presetCouponCode:"",items:[{tipoIngressoId:"",loteId:"",qty:1}]},hf=({open:s,onClose:t,eventos:a,queryClient:n})=>{const{toast:o}=mt(),[i,u]=r.useState(eo),[l,c]=r.useState(null),m=r.useMemo(()=>a.find(M=>String(M.id)===String(i.eventoId))||null,[a,i.eventoId]),x=Rt({queryKey:["link-checkout-event-detail",m?.documentId],queryFn:()=>mf(m?.documentId),enabled:!!m?.documentId,staleTime:6e4}),h=r.useMemo(()=>xf(x.data),[x.data]),p=r.useMemo(()=>{const M=x.data?.attributes||x.data||{},D=(Array.isArray(M.datas_futuras)?M.datas_futuras:[]).filter(E=>E.ativo!==!1&&E.data).map(E=>E.data);return[...new Set(D)].sort()},[x.data]),f=fa({mutationFn:M=>$e.post("/link-checkouts",{data:M}),onSuccess:M=>{const z=M.data?.data,D=M.data?.shareUrl||xu(z?.code||"");c({code:z?.code,shareUrl:D}),n.invalidateQueries({queryKey:["link-checkouts"]}),o({title:"Link criado com sucesso!"})},onError:M=>{o({title:"Erro ao criar link",description:M?.response?.data?.error?.message||M.message,variant:"destructive"})}}),I=(M,z,D)=>{u(E=>{const A=[...E.items],S={...A[M],[z]:D,...z==="tipoIngressoId"?{loteId:""}:{}};if(z==="tipoIngressoId"){const P=h.find(F=>String(F.id)===String(D));P?.progressivo&&P.quantidade_itens>1?S.qty=P.quantidade_itens:S.qty=1}return A[M]=S,{...E,items:A}})},g=()=>u(M=>({...M,items:[...M.items,{tipoIngressoId:"",loteId:"",qty:1}]})),N=M=>u(z=>({...z,items:z.items.filter((D,E)=>E!==M)})),b=M=>{M.preventDefault();const z=Ro(i.presetCouponCode),D=i.items.filter(E=>E.tipoIngressoId&&E.loteId&&Number(E.qty)>=1);if(!i.eventoId){o({title:"Selecione um evento",variant:"destructive"});return}if(D.length===0){o({title:"Adicione ao menos um tipo de ingresso",variant:"destructive"});return}f.mutate({label:i.label||void 0,customCode:i.customCode.trim().toUpperCase()||void 0,eventoId:Number(i.eventoId),items:D.map(E=>{const A=h.find(P=>String(P.id)===String(E.tipoIngressoId)),S=A?.progressivo&&A.quantidade_itens>1?A.quantidade_itens:1;return{tipo_ingresso:Number(E.tipoIngressoId),lote_id:E.loteId?Number(E.loteId):void 0,data_evento:i.selectedDate||void 0,qty:gd(E.qty,S)}}),targetUserId:i.targetUserId?Number(i.targetUserId):void 0,expires_at:i.expires_at||void 0,max_uses:i.max_uses?Number(i.max_uses):void 0,allow_coupon_input:z?!1:i.allowCouponInput,preset_coupon_code:z||void 0})},C=()=>{u(eo),c(null),t()},q=M=>{navigator.clipboard?.writeText(M).then(()=>{o({title:"Link copiado!"})})},L=f.isPending;return e.jsx(at,{open:s,onOpenChange:M=>{M||C()},children:e.jsxs(rt,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(nt,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(zo,{className:"h-5 w-5"})," Novo Link de Compra"]}),e.jsx(Ba,{children:"Crie um link que pre-seleciona ingressos no carrinho e redireciona ao checkout."})]}),l?e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsx(ui,{className:"border-primary/30 bg-primary/10",children:e.jsxs(mi,{className:"flex flex-col gap-3",children:[e.jsxs("span",{children:["Link ",e.jsx("strong",{children:l.code})," criado com sucesso!"]}),e.jsx("code",{className:"block rounded-md bg-background px-2 py-1 text-xs font-medium break-all",children:l.shareUrl}),e.jsxs(w,{type:"button",size:"sm",variant:"outline",onClick:()=>q(l.shareUrl),className:"w-full sm:w-auto",children:[e.jsx(Pa,{className:"mr-2 h-4 w-4"})," Copiar link"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(w,{variant:"outline",onClick:()=>{u(eo),c(null)},children:"Criar outro"}),e.jsx(w,{onClick:C,children:"Fechar"})]})]}):e.jsxs("form",{onSubmit:b,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Evento *"}),e.jsxs(rs,{value:i.eventoId,onValueChange:M=>u(z=>({...z,eventoId:M,selectedDate:"",items:[{tipoIngressoId:"",loteId:"",qty:1}]})),disabled:L,children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione um evento"})}),e.jsx(os,{children:a.map(M=>e.jsx(xe,{value:String(M.id),children:M.titulo||M.nome||`Evento #${M.id}`},M.id))})]})]}),i.eventoId&&p.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Data do evento *"}),e.jsxs(rs,{value:i.selectedDate,onValueChange:M=>u(z=>({...z,selectedDate:M,items:z.items.map(D=>({...D,loteId:""}))})),disabled:L,children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione a data"})}),e.jsx(os,{children:p.map(M=>e.jsx(xe,{value:M,children:new Date(M+"T12:00:00").toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})},M))})]})]}),i.eventoId&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Ingressos *"}),x.isLoading&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Cs,{className:"h-3 w-3 animate-spin"})," Carregando tipos de ingresso…"]}),i.items.map((M,z)=>{const D=h.find(S=>String(S.id)===String(M.tipoIngressoId)),E=D?.progressivo===!0,A=E&&D.quantidade_itens>1?D.quantidade_itens:1;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsxs(rs,{value:M.tipoIngressoId,onValueChange:S=>I(z,"tipoIngressoId",S),disabled:L||x.isLoading,children:[e.jsx(ns,{className:"text-xs",children:e.jsx(is,{placeholder:"Tipo de ingresso"})}),e.jsx(os,{children:h.map(S=>e.jsxs(xe,{value:String(S.id),children:[S.nome,S.progressivo?` (x${S.quantidade_itens})`:""]},S.id))})]})}),e.jsx("div",{className:"flex-1",children:e.jsxs(rs,{value:M.loteId,onValueChange:S=>I(z,"loteId",S),disabled:L||x.isLoading||!M.tipoIngressoId,children:[e.jsx(ns,{className:"text-xs",children:e.jsx(is,{placeholder:"Lote"})}),e.jsx(os,{children:pf(x.data,M.tipoIngressoId,i.selectedDate).map(S=>e.jsx(xe,{value:String(S.id),children:S.nome},S.id))})]})}),E&&e.jsxs(je,{variant:"secondary",className:"shrink-0 px-1 text-xs",children:["x",A]}),e.jsx(Te,{type:"number",min:A,step:A,value:M.qty,onChange:S=>I(z,"qty",S.target.value),onBlur:S=>I(z,"qty",gd(S.target.value,A)),className:"w-16 text-center",disabled:L,inputMode:"numeric"}),e.jsx(w,{type:"button",variant:"ghost",size:"icon",onClick:()=>N(z),disabled:L||i.items.length<=1,className:"shrink-0",children:e.jsx(Xt,{className:"h-4 w-4"})})]},z)}),e.jsxs(w,{type:"button",variant:"outline",size:"sm",onClick:g,disabled:L,className:"mt-1",children:[e.jsx(et,{className:"mr-1 h-3 w-3"})," Adicionar tipo"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"link-label",children:"Motivo (opcional)"}),e.jsx(Te,{id:"link-label",value:i.label,onChange:M=>u(z=>({...z,label:M.target.value})),placeholder:"Ex.: VIP Mesa 12",disabled:L})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"link-custom-code",children:"Código personalizado (opcional)"}),e.jsx(Te,{id:"link-custom-code",value:i.customCode,onChange:M=>u(z=>({...z,customCode:M.target.value.toUpperCase().replace(/[^A-Z0-9_-]/g,"")})),placeholder:"Ex.: VIP2026 (gerado automaticamente se vazio)",disabled:L,maxLength:32})]}),e.jsxs("div",{className:"rounded-lg border border-dashed border-border p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{htmlFor:"link-allow-coupon",children:"Permitir cupom no checkout"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Exibe o campo para o comprador inserir um cupom manualmente."})]}),e.jsx(Ls,{id:"link-allow-coupon",checked:i.presetCouponCode?!1:i.allowCouponInput,onCheckedChange:M=>u(z=>
91({...z,allowCouponInput:M})),disabled:L||!!i.presetCouponCode})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"link-preset-coupon",children:"Cupom fixo do link (opcional)"}),e.jsx(Te,{id:"link-preset-coupon",value:i.presetCouponCode,onChange:M=>u(z=>({...z,presetCouponCode:Ro(M.target.value)})),placeholder:"Ex.: VIP10",disabled:L,maxLength:32}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Se preenchido, o cupom é aplicado automaticamente e o campo fica oculto no checkout."})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"link-max-uses",children:"Limite de usos (opcional)"}),e.jsx(Te,{id:"link-max-uses",type:"number",min:1,value:i.max_uses,onChange:M=>u(z=>({...z,max_uses:M.target.value})),disabled:L,inputMode:"numeric"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"link-expires",children:"Expira em (opcional)"}),e.jsx(Te,{id:"link-expires",type:"datetime-local",value:i.expires_at,onChange:M=>u(z=>({...z,expires_at:M.target.value})),disabled:L})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(Oe,{htmlFor:"link-target-user",children:"ID do usuário alvo (opcional)"}),e.jsx(Te,{id:"link-target-user",type:"number",min:1,value:i.targetUserId,onChange:M=>u(z=>({...z,targetUserId:M.target.value})),placeholder:"Deixe vazio para link genérico",disabled:L,inputMode:"numeric"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Se preenchido, apenas o usuário especificado poderá usar o link."})]})]}),e.jsxs(Ut,{children:[e.jsx(w,{type:"button",variant:"outline",onClick:C,disabled:L,children:"Cancelar"}),e.jsx(w,{type:"submit",disabled:L,children:f.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Cs,{className:"mr-2 h-4 w-4 animate-spin"})," Criando…"]}):"Criar link"})]})]})]})})},fd=s=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(Number(s)||0),yi=s=>{if(!s)return"—";try{return Us(new Date(s),"dd/MM HH:mm:ss",{locale:Vs})}catch{return String(s)}},jd={all:{label:"Todos",icon:Nm,color:"text-foreground"},admin:{label:"Admin",icon:bm,color:"text-blue-600"},resolve:{label:"Resolve",icon:zo,color:"text-violet-600"},use:{label:"Use",icon:Er,color:"text-emerald-600"},client:{label:"Frontend",icon:Xd,color:"text-amber-600"},errors:{label:"Erros",icon:Ya,color:"text-red-600"}},vd={error:"border-l-red-500 bg-red-50/60",warn:"border-l-yellow-500 bg-yellow-50/60",info:"border-l-blue-400 bg-transparent"},so={nome:"Nome completo",email:"E-mail",telefone:"Telefone",cpf:"CPF",dataNascimento:"Data de nascimento",cep:"CEP",estado:"Estado",cidade:"Cidade",logradouro:"Endereço",cardNumber:"Número do cartão",cardHolder:"Nome no cartão",cardExpiry:"Validade do cartão",cardCvv:"CVV",cupom:"Cupom de desconto",allow_coupon_input:"Permitir cupom no checkout",preset_coupon_code:"Cupom fixo do link",paymentMethod:"Forma de pagamento"},gf=s=>{const t=s.action||"",a=s;if(t==="checkout.input.blur"||t==="client.checkout.input.blur"){const n=so[a.field]||a.field||"campo",o=a.value;return!o||o===""?`Deixou o campo "${n}" vazio`:`Preencheu "${n}" com: ${o}`}if(t==="checkout.input.paymentMethod"||t==="client.checkout.input.paymentMethod")return`Escolheu pagar com ${a.paymentMethod==="pix"?"PIX":a.paymentMethod==="credit"?"Cartão de crédito":a.paymentMethod}`;if(t.includes("pageLoaded"))return"Abriu a página do link de compra";if(t==="checkout.resolve.success"||t==="client.checkout.resolve.success")return"Link verificado com sucesso";if(t.includes("resolve.error"))return`Erro ao verificar link: ${a.errorMsg||"falha desconhecida"}`;if(t.includes("use.started"))return"Começou a preparar o pedido";if(t.includes("use.success"))return`Pedido preparado com ${a.cartItemCount||"?"} ingresso(s)`;if(t.includes("use.error"))return`Erro ao preparar pedido: ${a.errorMsg||"falha"}`;if(t.includes("cupom.attempt"))return`Tentou aplicar cupom "${a.cupomCode||"?"}"`;if(t.includes("cupom.applied"))return`Cupom "${a.cupomCode}" aplicado com desconto de R$ ${a.desconto?.toFixed?.(2)||"?"}`;if(t.includes("cupom.error"))return`Cupom "${a.cupomCode||"?"}" inválido: ${a.errorMsg||""}`;if(t.includes("submit.started"))return`Enviou o formulário para pagar com ${a.paymentMethod==="pix"?"PIX":"Cartão"} — total: R$ ${a.total?.toFixed?.(2)||"?"}`;if(t.includes("validation.failed"))return`Campo obrigatório inválido: "${so[a.formErrors]||a.formErrors||"?"}"`;if(t.includes("card.tokenizing"))return"Processando dados do cartão...";if(t.includes("card.tokenized"))return"Dados do cartão validados com sucesso";if(t.includes("card.tokenError"))return`Erro no cartão: ${a.errorMsg||"falha na validação"}`;if(t.includes("api.sending"))return"Enviando pedido para o servidor...";if(t.includes("api.error"))return`Servidor retornou erro: ${a.errorMsg||"falha"}`;if(t.includes("pix.generated"))return"QR Code PIX gerado com sucesso!";if(t.includes("checkout.success"))return"Compra finalizada com sucesso!";if(t.includes("submit.exception"))return`Erro inesperado: ${a.errorMsg||"falha"}`;if(t==="link-checkout.created")return"Link criado por um administrador";if(t==="link-checkout.updated"){const n=a.changes;return n?.length?`Admin alterou: ${n.map(o=>so[o]||o).join(", ")}`:"Admin atualizou o link"}return t==="link-checkout.deleted"?"Link excluído por um administrador":t==="link-checkout.listed"?"Admin listou os links":t==="link-checkout.found"?"Admin visualizou detalhes do link":t==="link-checkout.resolved"?"Alguém acessou o link":t==="link-checkout.used"?"Alguém usou o link para criar um pedido":t.replace(/^(client\.|checkout\.|link-checkout\.)/,"").replace(/\./g," › ")},pu=s=>{const t=s.action||"",a=s.httpStatus;if(a){const n=Number(a);return n>=200&&n<300?{code:n,label:`${n} OK`,color:"bg-green-100 text-green-700"}:n===404?{code:n,label:"404 Not Found",color:"bg-yellow-100 text-yellow-700"}:n===410?{code:n,label:"410 Gone",color:"bg-orange-100 text-orange-700"}:n===403?{code:n,label:"403 Forbidden",color:"bg-red-100 text-red-700"}:n>=500?{code:n,label:`${n} Error`,color:"bg-red-100 text-red-700"}:{code:n,label:`${n}`,color:"bg-gray-100 text-gray-700"}}return t.includes(".success")||t.includes(".tokenized")||t.includes(".applied")||t.includes(".generated")||t==="checkout.success"?{co
91de:200,label:"200 OK",color:"bg-green-100 text-green-700"}:t.includes(".error")||t.includes(".exception")||t.includes(".tokenError")?s.errorMsg?.includes("não encontrado")||s.errorMsg?.includes("404")?{code:404,label:"404 Not Found",color:"bg-yellow-100 text-yellow-700"}:s.errorMsg?.includes("expirado")||s.errorMsg?.includes("esgotado")?{code:410,label:"410 Gone",color:"bg-orange-100 text-orange-700"}:{code:500,label:"500 Error",color:"bg-red-100 text-red-700"}:t.includes("validation.failed")?{code:422,label:"422 Validation",color:"bg-yellow-100 text-yellow-700"}:null},ff=({event:s})=>{const t=s.level||(s.action?.includes(".error")?"error":s.action?.includes("validation.failed")?"warn":"info"),a=gf(s),n=pu(s),o=t==="error"?"bg-red-50 border-red-200":t==="warn"?"bg-yellow-50 border-yellow-200":" border-gray-100",i=t==="error"?"text-red-500":t==="warn"?"text-yellow-500":"text-green-500",u=t==="error"?"!":t==="warn"?"?":"✓";return e.jsx("div",{className:`rounded-lg border px-4 py-3 ${o}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:`text-base font-bold mt-0.5 shrink-0 ${i}`,children:u}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-gray-800 leading-snug",children:a}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[e.jsx("span",{className:"text-[11px] text-gray-400",children:yi(s.timestamp)}),n&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${n.color}`,children:n.label})]})]})]})})},jf=({event:s})=>{const[t,a]=r.useState(!1),n=s.level||(s.action?.includes(".error")?"error":"info"),o=vd[n]||vd.info,i=pu(s),u=s.action||"unknown",l=[];(s.userId||s.userEmail)&&l.push(`user:${s.userEmail||s.userId}`),s.ip&&l.push(`ip:${s.ip}`),s.durationMs!=null&&l.push(`${s.durationMs}ms`),(s.error||s.errorMsg)&&l.push(s.error||s.errorMsg);const c=s.changes,m=s.activeToggle,x=Object.entries(s).filter(([h])=>!["timestamp","ingestionTime","id","env","host","app","domain","action","level"].includes(h));return e.jsxs("div",{className:`border-l-[3px] rounded-r-md px-3 py-2 ${o}`,children:[e.jsxs("button",{type:"button",className:"w-full flex items-start gap-2 text-left",onClick:()=>a(!t),children:[t?e.jsx(ra,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}):e.jsx(er,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-mono text-xs font-semibold",children:u}),n==="error"&&e.jsx(je,{variant:"destructive",className:"text-[10px] px-1 py-0",children:"error"}),n==="warn"&&e.jsx(je,{className:"text-[10px] px-1 py-0 bg-yellow-200 text-yellow-800 hover:bg-yellow-200",children:"warn"}),i&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0 rounded ${i.color}`,children:i.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground ml-auto shrink-0",children:yi(s.timestamp)})]}),l.length>0&&e.jsx("p",{className:"text-[11px] text-muted-foreground truncate mt-0.5",children:l.join(" · ")}),c&&c.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[c.map(h=>e.jsx(je,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:h},h)),m&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["active: ",String(m.from)," → ",String(m.to)]})]})]})]}),t&&e.jsx("div",{className:"mt-2 ml-5 rounded bg-muted/40 p-2 text-[11px] font-mono overflow-x-auto max-h-48 overflow-y-auto",children:x.map(([h,p])=>e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("span",{className:"text-muted-foreground shrink-0",children:[h,":"]}),e.jsx("span",{className:"break-all",children:typeof p=="object"?JSON.stringify(p,null,1):String(p??"")})]},h))})]})},vf=({open:s,onClose:t,linkId:a})=>{const[n,o]=r.useState("stats"),[i,u]=r.useState("all"),[l,c]=r.useState("simple"),m=Rt({queryKey:["link-checkout-stats",a],queryFn:async()=>{const N=await $e.get(`/link-checkouts/${a}/stats`);return N.data?.data||N.data},enabled:!!a&&s,staleTime:15e3}),x=Rt({queryKey:["link-checkout-logs",a],queryFn:async()=>{const N=await $e.get(`/link-checkouts/${a}/logs?limit=300`);return N.data?.data||N.data},enabled:!!a&&s&&n==="logs",staleTime:2e4}),h=m.data,p=x.data,f=r.useMemo(()=>p?i==="all"?p.events||[]:p.categorized?.[i]||[]:[],[p,i]),I=r.useMemo(()=>p?.categorized?{all:p.totalEvents||0,admin:p.categorized.admin?.length||0,resolve:p.categorized.resolve?.length||0,use:p.categorized.use?.length||0,client:p.categorized.client?.length||0,errors:p.categorized.errors?.length||0}:{},[p]),g=()=>{o("stats"),u("all"),c("simple"),t()};return e.jsx(at,{open:s,onOpenChange:N=>{N||g()},children:e.jsxs(rt,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(nt,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(ri,{className:"h-5 w-5"})," Detalhes do Link",h?.code&&e.jsxs("span",{className:"font-mono text-xs text-muted-foreground",children:["(",h.code,")"]})]}),e.jsx(Ba,{children:"Estatísticas, pedidos e logs de atividade deste link."})]}),e.jsxs("div",{className:"flex gap-1 border-b",children:[e.jsx("button",{type:"button",className:`px-3 py-2 text-sm font-medium border-b-2 transition-colors ${n==="stats"?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>o("stats"),children:"Estatísticas"}),e.jsxs("button",{type:"button",className:`px-3 py-2 text-sm font-medium border-b-2 transition-colors ${n==="logs"?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>o("logs"),children:["Logs",I.errors>0&&e.jsx(je,{variant:"destructive",className:"ml-1.5 text-[10px] px-1 py-0",children:I.errors})]})]}),n==="stats"&&e.jsx(e.Fragment,{children:m.isLoading?e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[e.jsx(Cs,{className:"mr-2 h-5 w-5 animate-spin"})," Carregando…"]}):m.isError?e.jsx(ui,{variant:"destructive",children:e.jsx(mi,{children:"Erro ao carregar estatísticas."})}):h?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Código"}),e.jsx("p",{className:"font-mono text-sm font-bold",children:h.code})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status"}),e.jsx(je,{variant:h.active?"default":"secondary",className:"mt-1",children:h.active?"Ativo":"Inativo"})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Usos"}),e.jsxs("p",{className:"text-lg font-bold",children:[h.used_count,h.max_uses?`/${h.max_uses}`:""]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Criado em"}),e.jsx("p",{className:"text-xs font-medium",children:Ni(h.createdAt)})]})]}),h.label&&e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Motivo"}),e.jsx("p",{className:"text-sm font-medium",children:h.label})]}),h.evento&&e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Evento"}),e.jsx("p",{className:"text-sm font-medium",children:h.evento?.titulo||`#${h.evento?.id}`})]}),Array.isArray(h.items)&&h.items.length>0&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Itens configurados"}),h.items.map((N,b)=>{const C=N?.tipo_ingresso;return e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:C?.nome||`Tipo #${C?.id||"?"}`}),e.jsxs("span",{className:"font-medium",children:["x",N.qty||1]})]},b)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[h.created_by_usuario&&e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Criado por"}),e.jsx("p",{className:"text-xs font-medium",children:h.created_by_usuario.nome||h.created_by_usuario.email||`#${h.created_by_usuario.id}`})]}),h.target_user&&e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Usuário alvo"}),e.jsx("p",{className:"text-xs font-medium",children:h.target_user.nome||h.target_user.email||`#${h.target_user.id}`})]})]}),h.pedidosSummary&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Pedidos vinculados"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"rounded-lg bg-muted/50 p-2 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total"}),e.jsx("p",{className:"text-lg font-bold",children:h.pedidosSummary.total})]}),e.jsxs("div",{className:"rounded-lg bg-green-50 p-2 text-center",children:[e.jsx("p",{className:"text-xs text-green-700",children:"Pagos"}),e.jsx("p",{className:"text-lg font-bold text-green-700",children:h.pedidosSummary.pago})]}),e.jsxs("div",{className:"rounded-lg bg-yellow-50 p-2 text-center",children:[e.jsx("p",{className:"text-xs text-yellow-700",children:"Pendentes"}),e.jsx("p",{className:"text-lg font-bold text-yellow-700",children:h.pedidosSummary.pendente})]}),e.jsxs("div",{className:"rounded-lg bg-red-50 p-2 text-center",children:[e.jsx("p",{className:"text-xs text-red-700",children:"Cancelados"}),e.jsx("p",{className:"text-lg font-bold text-red-700",children:h.pedidosSummary.cancelado})]})]}),h.pedidosSummary.totalRevenue>0&&e.jsxs("div",{className:"rounded-lg border-2 border-green-200 bg-green-50 p-3 text-center",children:[e.jsx("p",{className:"text-xs text-green-700",children:"Receita confirmada"}),e.jsx("p",{className:"text-xl font-bold text-green-700",children:fd(h.pedidosSummary.totalRevenue)})]})]}),Array.isArray(h.pedidos)&&h.pedidos.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Histórico de pedidos"}),e.jsx("div",{className:"max-h-48 overflow-y-auto rounded-lg border",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"text-xs",children:"#"}),e.jsx(ue,{className:"text-xs",children:"Status"}),e.jsx(ue,{className:"text-xs",children:"Método"}),e.jsx(ue,{className:"text-xs text-right",children:"Total"}),e.jsx(ue,{className:"text-xs",children:"Data"})]})}),e.jsx(Ct,{children:h.pedidos.map(N=>e.jsxs($s,{children:[e.jsx(ye,{className:"text-xs font-mono",children:N.id}),e.jsx(ye,{children:e.jsx(je,{variant:N.status==="pago"?"default":N.status==="pendente"?"secondary":"destructive",className:"text-xs",children:N.status})}),e.jsx(ye,{className:"text-xs",children:N.pagamento_metodo||"—"}),e.jsx(ye,{className:"text-xs text-right",children:fd(N.total)}),e.jsx(ye,{className:"text-xs",children:Ni(N.createdAt)})]},N.id))})]})})]}),h.pedidosSummary?.total===0&&e.jsx("p",{className:"text-center text-xs text-muted-foreground py-4",children:"Nenhum pedido vinculado a este link ainda."})]}):null}),n==="logs"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center rounded-lg border bg-muted/30 p-0.5 mr-2",children:[e.jsxs("button",{type:"button",className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-medium transition-colors ${l==="simple"?" text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,onClick:()=>c("simple"),children:[e.jsx(Vt,{className:"h-3 w-3"})," Resumo"]}),e.jsxs("button",{type:"button",className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-medium transition-colors ${l==="technical"?" text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,onClick:()=>c("technical"),children:[e.jsx(vm,{className:"h-3 w-3"})," Técnico"]})]}),Object.entries(jd).map(([N,b])=>{const C=b.icon,q=I[N]??0,L=i===N;return e.jsxs("button",{type:"button",className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium transition-colors border ${L?"border-primary bg-primary/10 text-primary":"border-transparent bg-muted/50 text-muted-foreground hover:bg-muted"}`,onClick:()=>u(N),children:[e.jsx(C,{className:"h-3 w-3"}),b.label,q>0&&e.jsxs("span",{className:"text-[10px] opacity-70",children:["(",q,")"]})]},N)})]}),x.isLoading?e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[e.jsx(Cs,{className:"mr-2 h-5 w-5 animate-spin"})," Carregando logs…"]}):x.isError?e.jsx(ui,{variant:"destructive",children:e.jsx(mi,{children:"Erro ao carregar logs do CloudWatch."})}):f.length===0?e.jsxs("p",{className:"py-8 text-center text-sm text-muted-foreground",children:["Nenhum log encontrado",i!=="all"?` na categoria "${jd[i]?.label}"`:"","."]}):l==="simple"?e.jsx("div",{className:"space-y-2 max-h-[55vh] overflow-y-auto pr-1",children:f.map((N,b)=>e.jsx(ff,{event:N},N.id||N.timestamp||b))}):e.jsx("div",{className:"space-y-1.5 max-h-[55vh] overflow-y-auto pr-1",children:f.map((N,b)=>e.jsx(jf,{event:N},N.id||N.timestamp||b))}),p?.timeRange&&e.jsxs("p",{className:"text-[10px] text-muted-foreground text-center pt-1",children:["Período: ",yi(new Date(p.timeRange.from).getTime())," — ",yi(new Date(p.timeRange.to).getTime()),p.totalEvents>0&&` · ${p.totalEvents} evento(s)`]})]}),e.jsxs(Ut,{children:[n==="logs"&&e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>x.refetch(),disabled:x.isFetching,className:"mr-auto",children:[x.isFetching?e.jsx(Cs,{className:"mr-1 h-3 w-3 animate-spin"}):e.jsx(ta,{className:"mr-1 h-3 w-3"}),"Atualizar"]}),e.jsx(w,{onClick:g,children:"Fechar"})]})]})})},bf=({eventos:s=[]})=>{const{toast:t}=mt(),a=na(),[n,o]=r.useState(!1),[i,u]=r.useState(null),l=Rt({queryKey:["link-checkouts"],queryFn:uf,staleTime:3e4}),c=r.useMemo(()=>{const p=l.data?.data||[];return Array.isArray(p)?p:[]},[l.data]),m=fa({mutationFn:({id:p,active:f})=>$e.put(`/link-checkouts/${p}`,{data:{active:f}}),onSuccess:()=>a.invalidateQueries({queryKey:["link-checkouts"]}),onError:p=>{t({title:"Erro ao atualizar link",description:p?.response?.data?.error?.message||p.message,variant:"destructive"})}}),x=fa({mutationFn:p=>$e.delete(`/link-checkouts/${p}`),onSuccess:()=>{a.invalidateQueries({queryKey:["link-checkouts"]}),t({title:"Link removido."})},onError:p=>{t({title:"Erro ao remover link",description:p?.response?.data?.error?.message||p.message,variant:"destructive"})}}),h=r.useCallback(p=>{const f=xu(p);navigator.clipboard?.writeText(f).then(()=>{t({title:"Link copiado!"})})},[t]);return e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-row items-center justify-between gap-4",children:[e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(zo,{className:"h-5 w-5"})," Links de Compra"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>l.refetch(),disabled:l.isFetching,"aria-label":"Atualizar",children:l.isFetching?e.jsx(Cs,{className:"h-4 w-4 animate-spin"}):e.jsx(ta,{className:"h-4 w-4"})}),e.jsxs(w,{size:"sm",onClick:()=>o(!0),children:[e.jsx(et,{className:"mr-2 h-4 w-4"})," Novo link"]})]})]}),e.jsx(ge,{children:l.isLoading?e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[e.jsx(Cs,{className:"mr-2 h-5 w-5 animate-spin"})," Carregando links…"]}):l.isError?e.jsx(ui,{variant:"destructive",children:e.jsx(mi,{children:"Erro ao carregar links. Tente atualizar."})}):c.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"Nenhum link criado ainda."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Código"}),e.jsx(ue,{children:"Motivo"}),e.jsx(ue,{children:"Evento"}),e.jsx(ue,{children:"Itens"}),e.jsx(ue,{children:"Cupom"}),e.jsx(ue,{children:"Usos"}),e.jsx(ue,{children:"Expira"}),e.jsx(ue,{children:"Status"}),e.jsx(ue,{className:"text-right",children:"Ações"})]
91})}),e.jsx(Ct,{children:c.map(p=>{const f=p.attributes||p,I=f.evento?.data?.attributes?.titulo||f.evento?.titulo||"—",g=(f.items||[]).length,N=f.max_uses?`${f.used_count}/${f.max_uses}`:String(f.used_count||0);return e.jsxs($s,{children:[e.jsx(ye,{className:"font-mono text-xs",children:f.code}),e.jsx(ye,{className:"text-xs",children:f.label||"—"}),e.jsx(ye,{className:"text-xs max-w-[140px] truncate",children:I}),e.jsxs(ye,{className:"text-xs",children:[g," tipo(s)"]}),e.jsx(ye,{className:"text-xs",children:hd(f)}),e.jsx(ye,{className:"text-xs",children:N}),e.jsx(ye,{className:"text-xs",children:Ni(f.expires_at)}),e.jsx(ye,{children:e.jsx(je,{variant:f.active?"default":"secondary",children:f.active?"Ativo":"Inativo"})}),e.jsx(ye,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(w,{variant:"ghost",size:"icon",title:"Estatísticas",onClick:()=>u(p.id),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(w,{variant:"ghost",size:"icon",title:"Copiar URL",onClick:()=>h(f.code),children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(w,{variant:"ghost",size:"icon",title:f.active?"Desativar":"Ativar",onClick:()=>m.mutate({id:p.id,active:!f.active}),disabled:m.isPending,children:f.active?e.jsx(ll,{className:"h-4 w-4 text-destructive"}):e.jsx(dl,{className:"h-4 w-4 text-primary"})}),e.jsx(w,{variant:"ghost",size:"icon",title:"Excluir",onClick:()=>{window.confirm(`Excluir link "${f.code}"?`)&&x.mutate(p.id)},disabled:x.isPending,children:e.jsx(Xt,{className:"h-4 w-4 text-muted-foreground"})})]})})]},p.id)})})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:c.map(p=>{const f=p.attributes||p,I=f.evento?.data?.attributes?.titulo||f.evento?.titulo||"—";return e.jsxs("div",{className:"rounded-lg border bg-card p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-semibold",children:f.code}),e.jsx(je,{variant:f.active?"default":"secondary",className:"text-xs",children:f.active?"Ativo":"Inativo"})]}),f.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.label}),e.jsxs("p",{className:"text-xs",children:["Evento: ",I]}),e.jsxs("p",{className:"text-xs",children:["Cupom: ",hd(f)]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Usos: ",f.max_uses?`${f.used_count}/${f.max_uses}`:f.used_count||0,f.expires_at?` · Expira: ${Ni(f.expires_at)}`:""]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>u(p.id),className:"text-xs",children:[e.jsx(ri,{className:"mr-1 h-3 w-3"})," Stats"]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>h(f.code),className:"flex-1 text-xs",children:[e.jsx(Pa,{className:"mr-1 h-3 w-3"})," Copiar"]}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>m.mutate({id:p.id,active:!f.active}),disabled:m.isPending,className:"flex-1 text-xs",children:f.active?e.jsxs(e.Fragment,{children:[e.jsx(ll,{className:"mr-1 h-3 w-3"})," Desativar"]}):e.jsxs(e.Fragment,{children:[e.jsx(dl,{className:"mr-1 h-3 w-3"})," Ativar"]})}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>{window.confirm(`Excluir link "${f.code}"?`)&&x.mutate(p.id)},disabled:x.isPending,children:e.jsx(Xt,{className:"h-4 w-4 text-muted-foreground"})})]})]},p.id)})})]})}),e.jsx(hf,{open:n,onClose:()=>o(!1),eventos:s,queryClient:a}),e.jsx(vf,{open:!!i,onClose:()=>u(null),linkId:i})]})},to=["checkout-config-fees"],Jo=[{key:"pagarme",label:"Pagar.me"},{key:"pagbank",label:"PagBank"}],Yo=["Mastercard","Visa","Elo","American_Express"],wi=[2,3,4,5,6,7,8,9,10,11,12],Nf=s=>{if(s==null||s==="")return"";if(typeof s=="number")return(s>1?s:s*100).toFixed(2).replace(".",",");const t=String(s).replace("%","").replace(",",".").trim(),a=Number(t);return Number.isFinite(a)?a.toFixed(2).replace(".",","):""},yf=s=>{if(s==null||s==="")return null;const t=String(s).replace("%","").replace(",",".").trim(),a=Number(t);return!Number.isFinite(a)||a<0?null:`${a.toFixed(2)}%`},wf=s=>{const t={};for(const{key:a}of Jo){const n=s?.[a]||{};t[a]={};for(const o of Yo){const i=n[o]||{};t[a][o]={};for(const u of wi){const l=`parcelado_em_${u}x`;t[a][o][l]=Nf(i[l])}}}return t},bd=s=>{const t={};for(const{key:a}of Jo){t[a]={};for(const n of Yo){const o={};for(const i of wi){const u=`parcelado_em_${i}x`,l=yf(s?.[a]?.[n]?.[u]);l&&(o[u]=l)}Object.keys(o).length>0&&(t[a][n]=o)}Object.keys(t[a]).length===0&&delete t[a]}return t};function _f(){const{toast:s}=mt(),t=na(),[a,n]=r.useState(null),{data:o,isLoading:i,isError:u}=Rt({queryKey:to,queryFn:async()=>{const g=await $e.get("/config");return g?.data?.data?.attributes||g?.data?.data||g?.data||null},refetchOnWindowFocus:!1}),l=o?.parcelamento_tabelas||{},c=(o?.active_gateway||"pagarme").toLowerCase();r.useEffect(()=>{o&&n(wf(l))},[o]);const m=fa({mutationFn:async g=>$e.put("/config",{data:{parcelamento_tabelas:g}}),onSuccess:async()=>{await t.invalidateQueries({queryKey:to}),await t.invalidateQueries({queryKey:["checkout-config"]}),s({title:"Taxas salvas",description:"A configuração de parcelamento foi atualizada."})},onError:g=>{const N=g?.response?.data?.error?.message||"Não foi possível salvar as taxas.";s({variant:"destructive",title:"Erro ao salvar",description:N})}}),x=fa({mutationFn:async()=>$e.put("/config",{data:{parcelamento_tabelas:null}}),onSuccess:async()=>{await t.invalidateQueries({queryKey:to}),await t.invalidateQueries({queryKey:["checkout-config"]}),s({title:"Padrões restaurados",description:"Taxas voltaram aos valores padrão do código."})},onError:()=>{s({variant:"destructive",title:"Erro",description:"Não foi possível restaurar os padrões."})}}),h=(g,N,b,C)=>{n(q=>({...q,[g]:{...q[g],[N]:{...q[g][N],[b]:C}}}))},p=g=>{const N=bd(a);delete N[g],m.mutate(N)},f=g=>{g.preventDefault(),m.mutate(bd(a))},I=r.useMemo(()=>
91{if(!o?.updatedAt)return null;try{return new Date(o.updatedAt).toLocaleString("pt-BR")}catch{return null}},[o?.updatedAt]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Taxas de Parcelamento"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Defina o percentual cobrado do cliente em cada parcela, por gateway e bandeira. Valores em branco usam o padrão do código."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1 text-xs",children:[e.jsxs(je,{variant:"secondary",children:["Gateway ativo: ",c]}),I?e.jsxs("span",{className:"text-muted-foreground",children:["Última alteração: ",I]}):null]})]}),i||!a?e.jsx("div",{className:"flex h-32 items-center justify-center",children:e.jsx(It,{})}):u?e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 p-4 text-sm text-destructive",children:"Não foi possível carregar as taxas."}):e.jsxs("form",{onSubmit:f,className:"space-y-6",children:[Jo.map(({key:g,label:N})=>e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-row items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx(ze,{className:"text-base",children:N}),e.jsx(Jt,{children:"Percentual aplicado sobre subtotal + taxa de serviço quando o cliente parcela no crédito."})]}),e.jsxs(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>p(g),disabled:m.isPending,title:"Limpar override deste gateway e voltar aos padrões do código",children:[e.jsx(xr,{className:"mr-1 h-4 w-4"}),"Restaurar padrão"]})]}),e.jsx(ge,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-xs text-muted-foreground",children:[e.jsx("th",{className:"text-left py-2 pr-3 font-medium",children:"Bandeira"}),wi.map(b=>e.jsxs("th",{className:"px-1 py-2 font-medium text-center",children:[b,"x"]},b))]})}),e.jsx("tbody",{children:Yo.map(b=>e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"py-2 pr-3 font-medium whitespace-nowrap",children:b.replace("_"," ")}),wi.map(C=>{const q=`parcelado_em_${C}x`;return e.jsx("td",{className:"px-1 py-1",children:e.jsxs("div",{className:"relative",children:[e.jsx(Te,{type:"text",inputMode:"decimal",value:a[g][b][q]||"",onChange:L=>h(g,b,q,L.target.value),placeholder:"—",className:"h-8 w-20 text-right pr-5"}),e.jsx("span",{className:"pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:"%"})]})},C)})]},b))})]})})})]},g)),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(w,{type:"submit",disabled:m.isPending,children:[m.isPending?e.jsx(Cs,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(Da,{className:"mr-1 h-4 w-4"}),"Salvar taxas"]}),e.jsxs(w,{type:"button",variant:"outline",disabled:x.isPending,onClick:()=>x.mutate(),title:"Apaga o override completo no Strapi e volta para os padrões definidos no código",children:[x.isPending?e.jsx(Cs,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(xr,{className:"mr-1 h-4 w-4"}),"Restaurar todos os padrões"]})]})]})]})}function ka({open:s,onOpenChange:t,title:a,description:n,actionLabel:o,variant:i="default",onConfirm:u,loading:l}){return e.jsx(qu,{open:s,onOpenChange:t,children:e.jsxs(zu,{children:[e.jsxs(Uu,{children:[e.jsx(Bu,{children:a}),e.jsx(Vu,{children:n})]}),e.jsxs(Gu,{children:[e.jsx(Hu,{disabled:l,children:"Cancelar"}),e.jsx(Ku,{onClick:u,disabled:l,className:i==="destructive"?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"",children:l?"Processando...":o})]})]})})}function Cf(s){if(s==null||s==="")return 0;if(typeof s=="number")return Number.isFinite(s)&&s>=0?s:0;const t=String(s).trim(),a=Number(t);if(Number.isFinite(a)&&a>=0)return a;const n=Number(t.replace(/\./g,"").replace(",","."));return Number.isFinite(n)&&n>=0?n:0}function kf(s){if(!s)return 0;const t=String(s).replace(/\s/g,"").replace(/[^\d,.-]/g,"").replace(/\.(?=\d{3}(\D|$))/g,"").replace(",","."),a=Number(t);return Number.isFinite(a)&&a>=0?a:0}
91function Nd(s){return Number(s||0).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})}function Sf(){const{user:s}=Zt(),a=(v=>String(v||"").toLowerCase().replace(/[^a-z]/g,""))(s?.role?.name||s?.role?.type||s?.role?.code),n=a.includes("superadmin"),o=a.includes("supersuporte")&&!n,{data:i,refetch:u}=$o({refetchInterval:3e4,refetchOnWindowFocus:!1}),{toast:l}=mt(),{data:c,refetch:m}=Ks(["super-dashboard-pedido-config"],"/pedido-dashboard-config",{enabled:n,refetchOnWindowFocus:!1}),{data:x}=Ks("super-dashboard-eventos","/eventos?fields[0]=id&fields[1]=documentId&fields[2]=titulo&fields[3]=data_evento&populate[datas_passadas][fields][0]=data&populate[datas_futuras][fields][0]=data&pagination[pageSize]=200&sort=data_evento:desc"),h=r.useMemo(()=>(x?.data||[]).map(ne=>{const ds=new Set;return ne.data_evento&&ds.add(ne.data_evento),(ne.datas_futuras||[]).forEach(Ds=>{Ds.data&&ds.add(Ds.data)}),(ne.datas_passadas||[]).forEach(Ds=>{Ds.data&&ds.add(Ds.data)}),{id:ne.id,documentId:ne.documentId,titulo:ne.titulo||`Evento #${ne.id}`,dataEvento:ne.data_evento||"",datas:[...ds].sort((Ds,Zs)=>Zs.localeCompare(Ds))}}),[x]),{data:p}=Ks("trocas-pedidos-list","/pedidos?filters[status_pedido][$eq]=pago&sort=data_pedido:desc&pagination[pageSize]=300&fields[0]=id&fields[1]=total&fields[2]=data_pedido&fields[3]=metodo_pagamento&fields[4]=status_pedido&populate[usuario][fields][0]=nome&populate[usuario][fields][1]=telefone&populate[usuario][populate][user][fields][0]=username&populate[usuario][populate][user][fields][1]=email"),f=r.useMemo(()=>(Array.isArray(p?.data)?p.data:Array.isArray(p)?p:[]).filter(ne=>!ne?.gateway?.merged_into_documentId).map(ne=>{const ds=ne.usuario||{},Ds=ds.user||{},Zs=ds.nome||Ds.username||Ds.email||`#${ne.id}`,Nt=ds.telefone||"",kt=ne.data_pedido?String(ne.data_pedido).slice(0,10):"";return{id:ne.id,documentId:ne.documentId,nome:Zs,telefone:Nt,date:kt,total:ne?.gateway?.merged_totals?.total??ne.total,metodo:ne.metodo_pagamento}}),[p]),[I,g]=r.useState("operations"),[N,b]=r.useState("0,00"),[C,q]=r.useState(!0),[L,M]=r.useState(!1),[z,D]=r.useState(!1),[E,A]=r.useState(!1),[S,P]=r.useState(!1),[F,ee]=r.useState(!1),[re,te]=r.useState(!1),[G,y]=r.useState(!1),[$,W]=r.useState(null),[ie,ke]=r.useState(null),[Ae,be]=r.useState(!1),[Fe,ae]=r.useState(!1),[K,O]=r.useState(""),[oe,ve]=r.useState(""),[me,fe]=r.useState(!1),[le,_e]=r.useState(!1),[U,J]=r.useState(null),[T,Ee]=r.useState(null),[Se,Ze]=r.useState(!1),[qe,Qe]=r.useState(!1),[we,Me]=r.useState(!1),[ks,xs]=r.useState("__all__"),[k,De]=r.useState(!1),[Ne,es]=r.useState(!1),[ss,We]=r.useState("__all__"),[hs,Is]=r.useState(""),[Y,Q]=r.useState(!1),[X,V]=r.useState(!1),[pe,Ce]=r.useState(null),[Ue,Xe]=r.useState("__all__"),[Ve,bs]=r.useState(""),[ts,R]=r.useState(!0),[Le,as]=r.useState(null),[ms,Ke]=r.useState(!1),[gs,fs]=r.useState(!1),[Ms,Fs]=r.useState(!1),As=r.useCallback(v=>v==="__all__"?"Todos os eventos":h.find(ds=>ds.documentId===v||String(ds.id)===v)?.titulo||v,[h]),ws=r.useMemo(()=>As(ks),[ks,As]),Rs=r.useMemo(()=>As(ss),[ss,As]),us=r.useMemo(()=>As(Ue),[Ue,As]),Gs=r.useMemo(()=>Array.isArray($?.candidates)?$.candidates.filter(v=>v.fixable):[],[$]),Ss=r.useCallback(v=>{switch(v){case"already-merged":return"Já corrigido";case"original-not-found":return"Pedido original não encontrado";case"original-not-detected":return"Sem vínculo legado detectável";case"self-reference":return"Vínculo inconsistente";default:return v||"Pulado"}},[]),ys=r.useCallback(v=>{if(v==="__all__")return{};const ne=h.find(ds=>ds.documentId===v||String(ds.id)===v);return ne?.documentId?{eventoDocumentId:ne.documentId}:ne?.id?{eventoId:ne.id}:/^\d+$/.test(v)?{eventoId:Number(v)}:{eventoDocumentId:v}},[h]),Ps=r.useCallback(()=>ys(ks),[ks,ys]),Bs=r.useCallback(v=>v==="__all__"?[]:h.find(ds=>ds.documentId===v||String(ds.id)===v)?.datas||[],[h]),dt=r.useMemo(()=>{if(!i)return 0;if(globalThis?.window===void 0)return i?.summary?.transfers||0;const v="alerts:ack";let ne=[];try{ne=JSON.parse(localStorage.getItem(v)||"[]")}catch{ne=[]}const ds=new Set(ne),Zs=(Array.isArray(i.transferAlerts)?i.transferAlerts:[]).filter(kt=>!ds.has(kt.id)).length,Nt=i?.summary?.transfers;return Number.isFinite(Nt)&&Nt>Zs?Nt:Zs},[i]),{unreadTransfers:Ts}=r.useMemo(()=>
91{if(!i)return{unreadTransfers:[]};const v="alerts:ack";let ne=[];try{ne=JSON.parse(localStorage.getItem(v)||"[]")}catch{ne=[]}const ds=new Set(ne);return{unreadTransfers:(Array.isArray(i.transferAlerts)?i.transferAlerts:[]).filter(Nt=>!ds.has(Nt.id))}},[i]),Mt=v=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format((Number(v)||0)/100),Ys=v=>Number(v||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),ht=r.useMemo(()=>{const v=c?.data||c||null;if(!v)return{id:null,attributes:{}};if(v?.attributes)return{id:v.id??null,attributes:v.attributes||{}};const ne=v?.data;return ne?.attributes?{id:ne.id??null,attributes:ne.attributes||{}}:{id:v.id??null,attributes:v||{}}},[c]),ea=r.useMemo(()=>Cf(ht?.attributes?.total_reembolsado_taxa_antecipacao_brl),[ht?.attributes?.total_reembolsado_taxa_antecipacao_brl]),Xs=r.useMemo(()=>ht?.attributes?.exibir_texto_total_reembolsado_taxa_antecipacao!==!1,[ht?.attributes?.exibir_texto_total_reembolsado_taxa_antecipacao]),xt=r.useMemo(()=>ht?.attributes?.ocultar_valores_vendedores_externos===!0,[ht?.attributes?.ocultar_valores_vendedores_externos]);r.useEffect(()=>{n&&(b(Nd(ea)),q(Xs))},[n,ea,Xs]),r.useEffect(()=>{n&&D(xt)},[n,xt]);const ia=r.useCallback(async v=>{if(!n||E)return;const ne=z;D(v),A(!0);try{const ds={data:{ocultar_valores_vendedores_externos:v}};ht?.id?await $e.put("/pedido-dashboard-config",ds):await $e.post("/pedido-dashboard-config",ds),await m?.(),l({title:"Configuração atualizada",description:v?"Vendedores externos não verão mais valores (receita e preços de pedido).":"Vendedores externos voltarão a ver os valores normalmente."})}catch(ds){D(ne),l({title:"Erro ao salvar configuração",description:ds?.response?.data?.error?.message||ds?.message||"Tente novamente em instantes.",variant:"destructive"})}finally{A(!1)}},[n,E,z,ht?.id,m,l]),oa=r.useCallback(async()=>{if(!n||L)return;const v=Math.round(kf(N)*100)/100;M(!0);try{const ne={data:{total_reembolsado_taxa_antecipacao_brl:v,exibir_texto_total_reembolsado_taxa_antecipacao:C}};ht?.id?await $e.put("/pedido-dashboard-config",ne):await $e.post("/pedido-dashboard-config",ne),await m?.(),b(Nd(v)),l({title:"Configuração atualizada",description:"Valor e visibilidade do texto de reembolso foram salvos com sucesso."})}catch(ne){l({title:"Erro ao salvar valor",description:ne?.response?.data?.error?.message||ne?.message||"Tente novamente em instantes.",variant:"destructive"})}finally{M(!1)}},[n,L,ht?.id,m,l,N,C]),[st,wt]=r.useState(""),[va,la]=r.useState(""),[da,Tt]=r.useState(!1),[Js,Ft]=r.useState(null),[ba,Kt]=r.useState({}),[_t,ca]=r.useState(null),[Na,Qt]=r.useState(!1),[ua,pt]=r.useState(""),[ft,Wt]=r.useState([]),[ya,Dt]=r.useState(!1),[gt,d]=r.useState(!1),[_,H]=r.useState(null),[ce,Pe]=r.useState(new Set),[Ie,Ye]=r.useState(""),[Ns,_s]=r.useState(!1),[Hs,Os]=r.useState(!1),[B,de]=r.useState({holder_name:"",holder_type:"individual",holder_document:"",bank:"",branch_number:"",branch_check_digit:"",account_number:"",account_check_digit:"",type:"checking"}),[Re,He]=r.useState(!1),[ps,vs]=r.useState(null),[Es,cs]=r.useState(!1),[qs,Qs]=r.useState(null),[j,Z]=r.useState("__none__"),[Je,js]=r.useState("__all__"),[zs,Ge]=r.useState(!1),[Ws,jt]=r.useState(null),[ma,Ot]=r.useState(!1),[St,br]=r.useState("__none__"),[Ha,Xo]=r.useState(""),[Nr,Zo]=r.useState(""),[Pi,el]=r.useState(!1),[tj,_n]=r.useState(null),[fu,sl]=r.useState(!1),ju=r.useCallback(async()=>{He(!0),vs(null);try{const v=await $e.post("/eventos/dedup-lotes"),ne=v?.data?.data??v?.data??{};vs(ne);const ds=ne.totalFixed??ne.results?.length??0,Ds=ne.totalNormalized??ds;l({title:ds>0?"Lotes corrigidos":"Nenhum duplicado encontrado",description:ds>0?`${ds} evento(s) corrigido(s); ${Ds} com estoque normalizado.`:"Todos os eventos já estão limpos."})}catch(v){l({title:"Erro ao deduplicar",description:v?.response?.data?.error?.message||v.message,variant:"destructive"})}finally{He(!1)}},[l]),vu=r.useCallback(async()=>{cs(!0),Qs(null);try{const v=await $e.post("/invites/actions/migrate-items"),ne=v?.data?.data??v?.data??{};Qs(ne);const ds=ne.totalSplit??0;l({title:ds>0?"Convites migrados":"Nenhum convite precisava migrar",description:ds>0?`${ds} convite(s) tiveram itens separados em 1 por QR.`:"Todos os itens já possuem quantidade = 1."})}catch(v){l({title:"Erro ao migrar convites",description:v?.response?.data?.error?.message||v.message,variant:"destructive"})}finally{cs(!1)}},[l]),bu=r.useCallback(async()=>
91{if(!zs){if(j==="__none__"){l({title:"Evento obrigatório",description:"Selecione um evento para continuar.",variant:"destructive"});return}Ge(!0),Ot(!1),jt(null);try{const v=ys(j);Je&&Je!=="__all__"&&(v.dataEvento=Je),v.compareAndFix=!0;const ne=await $e.post("/pedidos/grupos-publicos/refresh-snapshots",v),ds=ne?.data?.data??ne?.data??{};jt(ds),l({title:"Grupos atualizados",description:`Pedidos: ${ds.updatedPedidos??0}. Convites: ${ds.updatedInvites??0}.`})}catch(v){l({title:"Falha ao atualizar grupos",description:v?.response?.data?.error?.message||v.message||"Não foi possível atualizar os itens.",variant:"destructive"})}finally{Ge(!1)}}},[ys,Je,j,zs,l]),Nu=r.useCallback(async()=>{if(!Pi){if(St==="__none__"){l({title:"Evento obrigatório",description:"Selecione um evento para continuar.",variant:"destructive"});return}if(!Ha||!Nr){l({title:"Datas obrigatórias",description:"Selecione data origem e data destino.",variant:"destructive"});return}el(!0),sl(!1),_n(null);try{const v=ys(St);v.fromDate=Ha,v.toDate=Nr;const ne=await $e.post("/pedidos/grupos-publicos/copy-date",v),ds=ne?.data?.data??ne?.data??{};_n(ds),l({title:"Grupos copiados",description:`Pedidos: ${ds.updatedPedidos??0}. Convites: ${ds.updatedInvites??0}.`})}catch(v){l({title:"Falha ao copiar grupos",description:v?.response?.data?.error?.message||v.message||"Não foi possível copiar grupos.",variant:"destructive"})}finally{el(!1)}}},[ys,St,Ha,Nr,Pi,l]),tl=async v=>{const ne=v?.id;if(!ne)return;const ds="alerts:ack";let Ds=[];try{Ds=JSON.parse(localStorage.getItem(ds)||"[]")}catch{Ds=[]}const Zs=new Set(Ds);Zs.add(ne),localStorage.setItem(ds,JSON.stringify(Array.from(Zs))),an({action:"ack",meta:{id:ne,title:v.title,message:v.message,severity:v.severity,type:"transfer"}}).catch(()=>{}),xi([ne]).catch(()=>{}),await u?.()},yu=async v=>{const ne=v?.meta?.transferId;ne&&(await Nx(ne),await tl(v))},wu=async()=>{if(Ts.length===0)return;const v=Ts.map(Zs=>Zs.id),ne="alerts:ack";let ds=[];try{ds=JSON.parse(localStorage.getItem(ne)||"[]")}catch{ds=[]}const Ds=new Set(ds);v.forEach(Zs=>Ds.add(Zs)),localStorage.setItem(ne,JSON.stringify(Array.from(Ds))),an({action:"ack",meta:{ids:v}}).catch(()=>{}),xi(v).catch(()=>{}),await u?.()},_u=()=>{Ou(),l({title:"Rastreador removido",description:"Dados de rastreamento foram apagados deste navegador."})},Cu=async()=>{if(!S){P(!0),Q(!1),Ce(null);try{const v={pageSize:50,...ys(ss)};hs&&(v.dataEvento=hs);const ne=await ef(v);Ce({sent:ne?.sent??0,skipped:ne?.skipped??0,errors:ne?.errors??0}),l({title:"Reenvio concluído",description:`Enviados: ${ne?.sent??0}. Pulados: ${ne?.skipped??0}. Erros: ${ne?.errors??0}.`})}catch(v){l({title:"Falha ao reenviar e-mails",description:v?.message||"Erro inesperado.",variant:"destructive"})}finally{P(!1)}}},ku=async()=>{if(!F){ee(!0),V(!1),Ce(null);try{const v={pageSize:50,...ys(ss)};hs&&(v.dataEvento=hs);const ne=await sf(v);Ce({sent:ne?.sent??0,skipped:ne?.skipped??0,errors:ne?.errors??0}),l({title:"Reenvio forçado concluído",description:`Enviados: ${ne?.sent??0}. Pulados: ${ne?.skipped??0}. Erros: ${ne?.errors??0}.`})}catch(v){l({title:"Falha no reenvio forçado",description:v?.message||"Erro inesperado.",variant:"destructive"})}finally{ee(!1)}}},Su=async()=>{if(!G){y(!0),De(!1);try{const v=await lf(Ps());l({title:"Carrinhos atualizados",description:`Usuários: ${v?.usersUpdated??0}. Itens atualizados: ${v?.itemsUpdated??0}. Removidos: ${v?.itemsRemoved??0}.`})}catch(v){l({title:"Falha ao atualizar carrinhos",description:v?.response?.data?.error?.message||v?.message||"Erro inesperado.",variant:"destructive"})}finally{y(!1)}}},Iu=async()=>{if(!re){te(!0),es(!1);try{const v=await df(Ps());l({title:"Carrinhos limpos",description:`Usuários: ${v?.usersUpdated??0}. Itens removidos: ${v?.itemsRemoved??0}.`})}catch(v){l({title:"Falha ao limpar carrinhos",description:v?.response?.data?.error?.message||v?.message||"Erro inesperado.",variant:"destructive"})}finally{te(!1)}}},Au=r.useCallback(async()=>{if(!Ve&&Ue==="__all__"){l({title:"Filtro obrigatório",description:"Selecione uma data ou um evento para filtrar.",variant:"destructive"});return}Ke(!0),as(null);
91try{const v={skipAlreadySent:ts,...ys(Ue)};Ve&&(v.dataEvento=Ve);const ne=await tf(v);as(ne)}catch(v){l({title:"Falha ao consultar lembretes",description:v?.response?.data?.error?.message||v?.message||"Não foi possível consultar.",variant:"destructive"})}finally{Ke(!1)}},[Ve,Ue,ts,l,ys]),Eu=r.useCallback(async()=>{if(!(!Ve&&Ue==="__all__")){fs(!0),Fs(!1);try{const v={skipAlreadySent:ts,...ys(Ue)};Ve&&(v.dataEvento=Ve);const ne=await af(v);as(null),l({title:"Lembretes enviados",description:`Enviados: ${ne?.sent??0}. Pulados: ${ne?.skipped??0}. Erros: ${ne?.errors??0}.`})}catch(v){l({title:"Falha ao enviar lembretes",description:v?.response?.data?.error?.message||v?.message||"Não foi possível enviar.",variant:"destructive"})}finally{fs(!1)}}},[Ve,Ue,ts,l,ys]),ir=r.useCallback(async()=>{if(!Ae){be(!0);try{const v=await rf({limit:50});W(v)}catch(v){l({title:"Falha ao consultar upsells legados",description:v?.response?.data?.error?.message||v?.message||"Não foi possível consultar os pedidos.",variant:"destructive"})}finally{be(!1)}}},[Ae,l]),Du=r.useCallback(async()=>{if(!(Fe||Gs.length===0)){ae(!0),fe(!1);try{const v=await pd({pedidoIds:Gs.map(ne=>ne.pedidoId).filter(Boolean)});ke(v),l({title:"Correção de upsell concluída",description:`Corrigidos: ${v?.repaired??0}. Pulados: ${v?.skipped??0}.`}),await ir()}catch(v){l({title:"Falha ao corrigir upsells detectados",description:v?.response?.data?.error?.message||v?.message||"Não foi possível executar a correção.",variant:"destructive"})}finally{ae(!1)}}},[Fe,Gs,l,ir]),Pu=r.useCallback(async()=>{if(Fe)return;const v=K.trim(),ne=oe.trim();if(!v||!ne){l({title:"Campos obrigatórios",description:"Informe o pedido filho e o documentId do pedido original.",variant:"destructive"});return}ae(!0),_e(!1);try{const ds=await pd({childReference:v,originalDocumentId:ne});ke(ds),l({title:"Reparo manual concluído",description:`Corrigidos: ${ds?.repaired??0}. Pulados: ${ds?.skipped??0}.`}),O(""),ve(""),await ir()}catch(ds){l({title:"Falha no reparo manual",description:ds?.response?.data?.error?.message||ds?.message||"Não foi possível corrigir o pedido informado.",variant:"destructive"})}finally{ae(!1)}},[Fe,K,oe,l,ir]),Ri=r.useCallback(async()=>{if(!Se){Ze(!0);try{const v=await nf({limit:1e3});J(v),Ee(null)}catch(v){l({title:"Falha ao consultar status inconsistentes",description:v?.response?.data?.error?.message||v?.message||"Não foi possível consultar.",variant:"destructive"})}finally{Ze(!1)}}},[Se,l]),Ru=r.useCallback(async()=>{if(!qe){Qe(!0),Me(!1);try{const v=await of({limit:1e3});Ee(v),l({title:"Reconciliação concluída",description:`${v?.updated??0} pedido(s) corrigido(s).`}),await Ri()}catch(v){l({title:"Falha ao reconciliar status",description:v?.response?.data?.error?.message||v?.message||"Não foi possível reconciliar.",variant:"destructive"})}finally{Qe(!1)}}},[qe,l,Ri]);r.useEffect(()=>{if(Ue==="__all__")return;const v=Bs(Ue);bs(v.length>0?v[0]:""),as(null)},[Ue,Bs]),r.useEffect(()=>{if(ss==="__all__"){Is("");return}const v=Bs(ss);Is(v.length>0?v[0]:""),Ce(null)},[ss,Bs]),r.useEffect(()=>{if(j==="__none__"){js("__all__"),jt(null);return}const v=Bs(j);(v.length===0||Je!=="__all__"&&!v.includes(Je))&&js("__all__"),jt(null)},[Je,j,Bs]),r.useEffect(()=>{if(St==="__none__"){Xo(""),Zo(""),_n(null);return}const v=Bs(St);v.length!==0&&(v.includes(Ha)||Xo(v[0]||""),v.includes(Nr)||Zo(v[0]||""),_n(null))},[St,Ha,Nr,Bs]),r.useEffect(()=>{I!=="upsell"||$||Ae||ir()},[I,$,Ae,ir]);const al=r.useMemo(()=>{const v=st.trim().toLowerCase();return v?f.filter(ne=>String(ne.id).includes(v)||ne.nome?.toLowerCase().includes(v)||ne.telefone?.includes(v)||ne.date?.includes(v)):f},[f,st]),Ti=r.useCallback(async v=>{if(v){la(v),Tt(!0),Ft(null),Kt({});try{const ne=new URLSearchParams;ne.append("populate[items][populate][evento][populate][datas_futuras]","*"),ne.append("populate[items][populate][tipo_ingresso][fields][0]","nome");const ds=await $e.get(`/pedidos/${v}?${ne}`),Ds=ds?.data?.data??ds?.data??null;if(!Ds?.id)throw new Error("Pedido não encontrado");Ft(Ds);const Zs={};
91(Array.isArray(Ds.items)?Ds.items:[]).forEach((Nt,kt)=>{if((Nt.item_tipo||"ingresso")!=="ingresso")return;const La=Array.isArray(Nt.evento?.datas_futuras)?Nt.evento.datas_futuras:[],qr=Nt.metadata?.data_evento||"",$i=La.find(zr=>zr.data&&zr.data!==qr);Zs[kt]=$i?.data||""}),Kt(Zs)}catch(ne){l({title:"Erro ao carregar pedido",description:ne?.response?.data?.error?.message||ne.message,variant:"destructive"})}finally{Tt(!1)}}},[l]),Tu=r.useCallback(async()=>{if(!(!_t||!Js)){Qt(!0);try{await $e.put(`/pedidos/${Js.id}/troca-data`,{data:{itemIndex:_t.itemIndex,novaData:_t.novaData}}),l({title:"Data trocada com sucesso",description:`Item ${_t.itemIndex+1}: ${_t.oldDate} → ${_t.novaData}`}),ca(null),await Ti(Js.documentId||String(Js.id))}catch(v){l({title:"Falha na troca",description:v?.response?.data?.error?.message||v.message,variant:"destructive"})}finally{Qt(!1)}}},[_t,Js,Ti,l]),rl=r.useCallback(async()=>{const v=ua.trim();if(v){Dt(!0),Wt([]),H(null);try{const ne=new URLSearchParams;/^\d+$/.test(v)?(ne.append("filters[$or][0][id][$eq]",v),ne.append("filters[$or][1][usuario][user][username][$containsi]",v),ne.append("filters[$or][2][usuario][nome][$containsi]",v),ne.append("filters[$or][3][usuario][telefone][$containsi]",v)):(ne.append("filters[$or][0][usuario][user][username][$containsi]",v),ne.append("filters[$or][1][usuario][user][email][$containsi]",v),ne.append("filters[$or][2][usuario][nome][$containsi]",v),ne.append("filters[$or][3][usuario][telefone][$containsi]",v),ne.append("filters[$or][4][usuario][cpf][$containsi]",v)),ne.append("sort","data_pedido:desc"),ne.append("pagination[pageSize]","20"),ne.append("fields[0]","id"),ne.append("fields[1]","total"),ne.append("fields[2]","data_pedido"),ne.append("fields[3]","metodo_pagamento"),ne.append("fields[4]","status_pedido"),ne.append("populate[usuario][fields][0]","nome"),ne.append("populate[usuario][fields][1]","telefone"),ne.append("populate[usuario][populate][user][fields][0]","username"),ne.append("populate[usuario][populate][user][fields][1]","email");const Ds=await $e.get(`/pedidos?${ne}`),Zs=Array.isArray(Ds?.data?.data)?Ds.data.data:Array.isArray(Ds?.data)?Ds.data:[];Wt(Zs),Zs.length===0&&l({title:"Nenhum pedido encontrado",description:`Sem resultados para "${v}".`,variant:"destructive"})}catch(ne){l({title:"Erro na busca",description:ne?.response?.data?.error?.message||ne.message,variant:"destructive"})}finally{Dt(!1)}}},[ua,l]),$u=r.useCallback(async v=>{d(!0),H(null),Pe(new Set),Ye("");try{const ne=new URLSearchParams;ne.append("populate[items][populate][tipo_ingresso][fields][0]","nome");const ds=await $e.get(`/pedidos/${v}?${ne}`),Ds=ds?.data?.data??ds?.data??null;if(!Ds?.id)throw new Error("Pedido não encontrado");H(Ds),Wt([]);const Zs=new Set;(Array.isArray(Ds.items)?Ds.items:[]).forEach((Nt,kt)=>{(Nt.item_tipo||"ingresso")==="ingresso"&&Zs.add(kt)}),Pe(Zs)}catch(ne){l({title:"Erro ao carregar pedido",description:ne?.response?.data?.error?.message||ne.message,variant:"destructive"})}finally{d(!1)}},[l]),$t=r.useMemo(()=>{if(!_)return null;const ds=(Array.isArray(_.items)?_.items:[]).filter((zr,Cn)=>ce.has(Cn)).reduce((zr,Cn)=>zr+Number(Cn.preco_unitario||0)*Number(Cn.quantidade||1),0),Ds=Number(_.subtotal||0),Zs=Ds>0?ds/Ds:0,Nt=Math.round(Number(_.taxa_servico||0)*Zs*100)/100,kt=Math.round(Number(_.taxa_parcelamento||0)*Zs*100)/100,La=ds+Nt+kt,qr=Ie?parseFloat(Ie.replace(",",".")):NaN,$i=!isNaN(qr)&&qr>0?Math.round(qr*100):Math.round(La*100);return{selectedSubtotal:ds,taxaServico:Nt,taxaParcelamento:kt,total:La,amountCents:$i}},[_,ce,Ie]),Lu=r.useCallback(async()=>{if(!(!_||!$t||$t.amountCents<=0)){Os(!0),_s(!1);try{const v=(_.metodo_pagamento||"")==="boleto",ne={amount_cents:$t.amountCents};v&&(ne.bank_account=B);const ds=await $e.post(`/pedidos/${_.id}/reembolso`,{data:ne});l({title:"Estorno realizado",description:`Pedido #${_.id} cancelado. Status: ${ds?.data?.charge_status||"—"}`}),H(Ds=>Ds?{...Ds,status_pedido:"cancelado"}:null)}catch(v){l({title:"Falha no estorno",description:v?.response?.data?.error?.message||v.message,variant:"destructive"})}finally{Os(!1)}}},[_,$t,B,l]);return e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Super Dashboard"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gestão centralizada de carrinhos, e-mails, lembretes e alertas."})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mt-2 sm:mt-0",children:[e.jsx(Hn,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{children:"Transferências"}),e.jsx(je,{variant:dt>0?"destructive":"outline",children:dt})]})]}),e.jsxs(Lr,{value:I,onValueChange:g,className:"space-y-6",children:[e.jsxs(Mr,{className:`grid w-full ${n?"grid-cols-4":"grid-cols-3"} sm:inline-flex`,children:[e.jsx(Gt,{value:"operations",children:"Operações"}),e.jsx(Gt,{value:"upsell",children:"Correção de upsell"}),e.jsx(Gt,{value:"link-checkout",children:"Links de Compra"}),n&&e.jsx(Gt,{value:"taxas",children:"Taxas"})]}),e.jsxs(Ht,{value:"operations",className:"space-y-6",children:[!
91o&&e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(bn,{className:"h-5 w-5 shrink-0"})," Extratos Consolidados"]}),dt>0&&e.jsxs(je,{variant:"secondary",className:"flex items-center gap-1 self-start sm:self-auto",children:[e.jsx(Hn,{className:"h-3 w-3"})," ",dt," novos"]})]}),e.jsxs(ge,{className:"space-y-6",children:[n&&e.jsxs(he,{className:"border-border/60 bg-muted/20",children:[e.jsx(Be,{className:"pb-3",children:e.jsx(ze,{className:"text-sm sm:text-base",children:"Configuração de reembolso por taxa de antecipação"})}),e.jsxs(ge,{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Valor em BRL exibido no Extratos, abaixo de Disponível, Processando e Transferido no bloco Pagar.me."}),e.jsx("div",{className:"rounded-md border border-border/50 bg-background/60 p-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Exibir texto no Extrato"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Controla a exibição de "Total reembolsado por taxa de antecipação".'})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ls,{id:"toggle-exibir-texto-total-reembolsado",checked:C,onCheckedChange:q}),e.jsx(je,{variant:C?"outline":"secondary",children:C?"Ativo":"Oculto"})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-end",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("label",{htmlFor:"total-reembolsado-taxa",className:"mb-1 block text-xs font-medium text-muted-foreground",children:"Total reembolsado por taxa de antecipação (BRL)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-xs font-semibold text-muted-foreground",children:"R$"}),e.jsx(Te,{id:"total-reembolsado-taxa",type:"text",inputMode:"decimal",className:"pl-9",value:N,onChange:v=>b(v.target.value.replace(/[^\d.,]/g,"")),placeholder:"0,00"})]})]}),e.jsx(w,{type:"button",onClick:oa,disabled:L,className:"sm:min-w-[152px]",children:L?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Cs,{className:"h-4 w-4 animate-spin"})," Salvando..."]}):"Salvar valor"})]})]})]}),e.jsx(mu,{})]})]}),n&&e.jsxs(he,{children:[e.jsx(Be,{children:e.jsx(ze,{className:"text-sm sm:text-base",children:"Privacidade dos vendedores externos"})}),e.jsx(ge,{className:"space-y-3",children:e.jsx("div",{className:"rounded-md border border-border/50 bg-background/60 p-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Ocultar valores para vendedores externos"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Quando ativado, os vendedores externos não verão nenhum valor monetário no painel de Atividade do link (visão geral, receita atribuída, aba de comportamento, receita registrada e valor dos pedidos). Os valores também são removidos das exportações em Excel de /dashboard/link-convites. As demais funções (acessos, pedidos, datas) continuam visíveis. Esta restrição afeta somente o perfil de vendedores externos."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ls,{id:"toggle-ocultar-valores-externos",checked:z,onCheckedChange:ia,disabled:E}),e.jsx(je,{variant:z?"secondary":"outline",children:z?"Valores ocultos":"Valores visíveis"})]})]})})})]}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(Cr,{className:"h-5 w-5"})," Gerenciamento de Carrinhos"]})}),e.jsxs(ge,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Atualize preços/lotes ou limpe carrinhos dos usuários. Selecione um evento específico ou aplique a todos."}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end",children:[e.jsxs("div",{className:"flex flex-col gap-1 flex-1 min-w-0",children:[e.jsx("label",{htmlFor:"cart-event-select",className:"text-xs font-medium text-muted-foreground",children:"Evento"}),e.jsxs(rs,{value:ks,onValueChange:xs,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Selecione um evento"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"__all__",children:"Todos os eventos"}),h.map(v=>e.jsxs(xe,{value:v.documentId||String(v.id),children:[v.titulo,v.dataEvento?` — ${v.dataEvento}`:""]},v.documentId||v.id))]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"secondary",size:"sm",className:"flex-1 sm:flex-none text-xs sm:text-sm gap-1.5",disabled:G,onClick:()=>De(!0),children:[e.jsx(ta,{className:`h-3.5 w-3.5 ${G?"animate-spin":""}`}),G?"Atualizando...":"Atualizar preços"]}),e.jsxs(w,{variant:"destructive",size:"sm",className:"flex-1 sm:flex-none text-xs sm:text-sm gap-1.5",disabled:re,onClick:()=>es(!0),children:[e.jsx(Xt,{className:"h-3.5 w-3.5"}),re?"Limpando...":"Limpar carrinhos"]})]})]}),e.jsxs("div",{className:"rounded-lg border border-dashed p-3 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Escopo atual:"})," ",ws,ks!=="__all__"&&e.jsxs(w,{variant:"ghost",size:"sm",className:"ml-2 h-5 px-1.5 text-xs",onClick:()=>xs("__all__"),children:[e.jsx(yt,{className:"h-3 w-3 mr-0.5"})," Limpar filtro"]})]})]})]}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"})," Ações de E-mail"]})}),e.jsxs(ge,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Reenvie e-mails de confirmação de pagamento para pedidos que não receberam ou force reenvio para todos. Todos os pedidos pagos serão processados gradualmente (sem limite)."}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{htmlFor:"email-event-select",className:"text-xs font-medium text-muted-foreground",children:"Filtrar por evento"}),e.jsxs(rs,{value:ss,onValueChange:v=>{We(v),Ce(null)},children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Selecione um evento"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"__all__",children:"Todos os eventos"}),h.map(v=>e.jsxs(xe,{value:v.documentId||String(v.id),children:[v.titulo,v.dataEvento?` — ${v.dataEvento}`:""]},v.documentId||v.id))]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{htmlFor:"email-date-select",className:"text-xs font-medium text-muted-foreground",children:"Data do evento (opcional)"}),ss!=="__all__"&&Bs(ss).length>0?e.jsxs(rs,{value:hs||"__none__",onValueChange:v=>{Is(v==="__none__"?"":v),Ce(null)},children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Todas as datas"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"__none__",children:"Todas as datas"}),Bs(ss).map(v=>e.jsx(xe,{value:v,children:v},v))]})]}):e.jsx("input",{type:"date",value:hs,onChange:v=>{Is(v.target.value),Ce(null)},disabled:ss==="__all__",className:"h-10 w-full rounded-md border border-input bg-background px-3 text-sm shadow-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-40 disabled:cursor-not-allowed"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"secondary",size:"sm",className:"flex-1 sm:flex-none gap-1.5 text-xs sm:text-sm",disabled:S,onClick:()=>Q(!0),children:[e.jsx(pr,{className:"h-3.5 w-3.5 shrink-0"}),S?"Reenviando...":"Reenviar pendentes"]}),e.jsxs(w,{variant:"secondary",size:"sm",className:"flex-1 sm:flex-none gap-1.5 text-xs sm:text-sm",disabled:F,onClick:()=>V(!0),children:[e.jsx(ym,{className:"h-3.5 w-3.5 shrink-0"}),F?"Reenviando...":"Forçar reenvio (todos)"]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"rounded-lg border border-dashed p-3 text-xs text-muted-foreground flex-1",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Escopo:"})," ",Rs,ss!=="__all__"&&e.jsxs(w,{variant:"ghost",size:"sm",className:"ml-2 h-5 px-1.5 text-xs",onClick:()=>{We("__all__"),Ce(null)},children:[e.jsx(yt,{className:"h-3 w-3 mr-0.5"})," Limpar"]})]}),e.jsxs(w,{variant:"outline",size:"sm",className:"self-start sm:self-auto gap-1.5 text-xs",onClick:_u,children:[e.jsx(yt,{className:"h-3.5 w-3.5"}),"Remover rastreador"]})]}),pe&&e.jsx("div",{className:"rounded-lg border p-3 text-sm space-y-1",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(je,{variant:"default",children:[pe.sent," enviados"]}),e.jsxs(je,{variant:"outline",children:[pe.skipped," pulados"]}),pe.errors>0&&e.jsxs(je,{variant:"destructive",children:[pe.errors," erros"]})]})})]})]}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(wm,{className:"h-5 w-5"})," Lembretes de Evento"]})}),e.jsxs(ge,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Envie e-mails de lembrete para clientes com pedidos pagos. Filtre por evento e/ou data."}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{htmlFor:"reminder-event-select",className:"text-xs font-medium text-muted-foreground",children:"Evento"}),e.jsxs(rs,{value:Ue,onValueChange:v=>{Xe(v),as(null)},children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Selecione um evento"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"__all__",children:"Todos os eventos"}),h.map(v=>e.jsxs(xe,{value:v.documentId||String(v.id),children:[v.titulo,v.dataEvento?` — ${v.dataEvento}`:""]},v.documentId||v.id))]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{htmlFor:"reminder-date",className:"text-xs font-medium text-muted-foreground",children:"Data do evento (opcional)"}),Ue!=="__all__"&&Bs(Ue).length>0?e.jsxs(rs,{value:Ve||"__none__",onValueChange:v=>{bs(v==="__none__"?"":v),as(null)},children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Todas as datas"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"__none__",children:"Todas as datas"}),Bs(Ue).map(v=>e.jsx(xe,{value:v,children:v},v))]})]}):e.jsx("input",{id:"reminder-date",type:"date",value:Ve,onChange:v=>{bs(v.target.value),as(null)},className:"h-10 w-full rounded-md border border-input bg-background px-3 text-sm shadow-sm focus:outline-none focus:ring-2 focus:ring-ring"})]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ja,{id:"reminder-skip-sent",checked:ts,onCheckedChange:v=>{R(!!v),as(null)}}),e.jsx("label",{htmlFor:"reminder-skip-sent",className:"text-sm whitespace-nowrap cursor-pointer select-none",children:"Pular já enviados"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"outline",size:"sm",className:"gap-1.5",onClick:Au,disabled:ms||!Ve&&Ue==="__all__",children:[e.jsx(At,{className:"h-3.5 w-3.5"}),ms?"Consultando...":"Consultar"]}),e.jsxs(w,{variant:"default",size:"sm",className:"gap-1.5",onClick:()=>
91{if(!Ve&&Ue==="__all__"){l({title:"Filtro obrigatório",description:"Selecione um evento ou data.",variant:"destructive"});return}Fs(!0)},disabled:gs||!Ve&&Ue==="__all__"||Le?.count===0,children:[e.jsx(qa,{className:"h-3.5 w-3.5"}),gs?"Enviando...":"Enviar"]})]})]}),Le&&e.jsxs("div",{className:"rounded-lg border p-3 text-sm space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(je,{variant:Le.count>0?"default":"outline",children:[Le.count," pedido",Le.count===1?"":"s"]}),Le.dataEvento&&e.jsxs("span",{className:"text-muted-foreground",children:["para ",Le.dataEvento]})]}),Le.eventTitles?.length>0&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Eventos: ",Le.eventTitles.join(", ")]}),Le.count===0&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Nenhum pedido pago encontrado",Le.skipAlreadySent?" (que ainda não recebeu lembrete)":"","."]})]})]})]}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(Ia,{className:"h-5 w-5"})," Corrigir Lotes Duplicados"]})}),e.jsxs(ge,{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Remove lotes duplicados e recalcula o estoque dos lotes afetados. Execução única e segura de rodar múltiplas vezes."}),e.jsxs(w,{size:"sm",variant:"outline",disabled:Re,onClick:ju,className:"gap-1.5",children:[Re?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ia,{className:"h-3.5 w-3.5"}),Re?"Processando...":"Corrigir todos os eventos"]}),ps&&ps.results?.length>0&&e.jsx("div",{className:"rounded-lg border divide-y text-xs",children:ps.results.map(v=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5",children:[e.jsx("span",{className:"truncate",children:v.titulo||`Evento #${v.eventoId}`}),e.jsxs("span",{className:"text-muted-foreground shrink-0 ml-2",children:[v.before," → ",v.after," (",v.removed," removidos",v.normalizationError?", sem recontagem":", recontado",")"]})]},v.eventoId))})]})]}),(n||o)&&e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"h-5 w-5"})," Atualizar grupos públicos vendidos"]})}),e.jsxs(ge,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Reescreve os snapshots de grupo (indice, capacidade e imagem) nos itens de pedidos e convites já vendidos, usando os grupos atuais do evento."}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{htmlFor:"group-sync-event",className:"text-xs font-medium text-muted-foreground",children:"Evento"}),e.jsxs(rs,{value:j,onValueChange:v=>{Z(v)},children:[e.jsx(ns,{className:"w-full",id:"group-sync-event",children:e.jsx(is,{placeholder:"Selecione um evento"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"__none__",children:"Selecione um evento"}),h.map(v=>e.jsxs(xe,{value:v.documentId||String(v.id),children:[v.titulo,v.dataEvento?` — ${v.dataEvento}`:""]},v.documentId||v.id))]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{htmlFor:"group-sync-date",className:"text-xs font-medium text-muted-foreground",children:"Data (opcional)"}),j!=="__none__"&&Bs(j).length>0?e.jsxs(rs,{value:Je,onValueChange:v=>js(v),children:[e.jsx(ns,{className:"w-full",id:"group-sync-date",children:e.jsx(is,{placeholder:"Todas as datas"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"__all__",children:"Todas as datas"}),Bs(j).map(v=>e.jsx(xe,{value:v,children:v},v))]})]}):e.jsx("input",{type:"date",value:Je==="__all__"?"":Je,onChange:v=>js(v.target.value||"__all__"),disabled:j==="__none__",className:"h-10 w-full rounded-md border border-input bg-background px-3 text-sm shadow-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-40 disabled:cursor-not-allowed"})]})]}),e.jsxs(w,{size:"sm",variant:"outline",disabled:zs||j==="__none__",onClick:()=>Ot(!0),className:"gap-1.5",children:[zs?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(xr,{className:"h-3.5 w-3.5"}),zs?"Atualizando...":"Atualizar itens vendidos"]}),Ws&&e.jsxs("div",{className:"rounded-lg border p-3 text-xs text-muted-foreground space-y-1",children:[e.jsxs("div",{children:["Pedidos atualizados: ",e.jsx("span",{className:"text-foreground font-medium",children:Ws.updatedPedidos??0})]}),e.jsxs("div",{children:["Convites atualizados: ",e.jsx("span",{className:"text-foreground font-medium",children:Ws.updatedInvites??0})]}),Array.isArray(Ws.dates)&&Ws.dates.length>
910&&e.jsxs("div",{children:["Datas: ",Ws.dates.join(", ")]})]})]})]}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(Ia,{className:"h-5 w-5"})," Migrar Itens de Convite (1 QR por item)"]})}),e.jsxs(ge,{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Converte itens de convite com quantidade > 1 em itens individuais, cada um com seu próprio QR code. Seguro de rodar múltiplas vezes."}),e.jsxs(w,{size:"sm",variant:"outline",disabled:Es,onClick:vu,className:"gap-1.5",children:[Es?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ia,{className:"h-3.5 w-3.5"}),Es?"Migrando...":"Migrar convites"]}),qs&&qs.details?.length>0&&e.jsx("div",{className:"rounded-lg border divide-y text-xs",children:qs.details.map(v=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5",children:[e.jsxs("span",{className:"truncate",children:["Convite #",v.inviteId]}),e.jsxs("span",{className:"text-muted-foreground shrink-0 ml-2",children:[v.before," → ",v.after," itens"]})]},v.inviteId))})]})]}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5"})," Trocas de Data"]})}),e.jsxs(ge,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Troque a data de um ingresso em um pedido pago. O estoque das datas envolvidas é reajustado automaticamente."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Te,{value:st,onChange:v=>wt(v.target.value),placeholder:"Filtrar por ID, nome, telefone ou data...",className:"w-full"}),e.jsxs(rs,{value:va,onValueChange:Ti,disabled:f.length===0,children:[e.jsx(ns,{className:"w-full",children:da?e.jsxs("span",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"})," Carregando..."]}):e.jsx(is,{placeholder:f.length===0?"Nenhum pedido pago encontrado":`${al.length} pedido(s) — selecione`})}),e.jsx(os,{className:"max-h-72",children:al.map(v=>e.jsxs(xe,{value:v.documentId||String(v.id),className:"text-xs",children:[e.jsxs("span",{className:"font-mono font-semibold",children:["#",v.id]})," — ",v.nome,v.telefone?` · ${v.telefone}`:""," — ",v.date," — ",Ys(v.total)]},v.id))})]})]}),Js&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border bg-muted/30 px-3 py-2 text-sm",children:[e.jsxs("span",{className:"font-semibold",children:["Pedido #",Js.id]}),e.jsx(je,{variant:Js.status_pedido==="pago"?"default":"secondary",children:Js.status_pedido}),e.jsxs("span",{className:"text-muted-foreground",children:[Ys(Js.total)," · ",Js.metodo_pagamento||"—"]})]}),Js.status_pedido!=="pago"&&e.jsxs("div",{className:"rounded border border-yellow-200 bg-yellow-50 px-3 py-2 text-xs text-yellow-800 dark:border-yellow-800 dark:bg-yellow-950 dark:text-yellow-300",children:["Somente pedidos com status ",e.jsx("strong",{children:"pago"})," permitem troca de data."]}),e.jsx("div",{className:"divide-y divide-border/50 rounded-lg border",children:(Array.isArray(Js.items)?Js.items:[]).map((v,ne)=>{if((v.item_tipo||"ingresso")!=="ingresso")return null;const ds=Array.isArray(v.evento?.datas_futuras)?v.evento.datas_futuras:[],Ds=v.metadata?.data_evento||"—",Zs=ds.filter(kt=>kt.data&&kt.data!==v.metadata?.data_evento),Nt=ba[ne]||"";return e.jsxs("div",{className:"flex flex-col gap-2 px-3 py-2.5 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:v.nome_item||`Item ${ne+1}`}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Qty ",v.quantidade," · Atual: ",e.jsx("span",{className:"font-mono font-semibold text-foreground",children:Ds})]})]}),e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:Zs.length===0?e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sem outras datas disponíveis"}):e.jsxs(e.Fragment,{children:[e.jsxs(rs,{value:Nt,onValueChange:kt=>Kt(La=>({...La,[ne]:kt})),children:[e.jsx(ns,{className:"h-8 w-40 text-xs",children:e.jsx(is,{placeholder:"Nova data"})}),e.jsx(os,{children:Zs.map(kt=>e.jsxs(xe,{value:kt.data,className:"text-xs",children:[kt.data,kt.ativo===!1?" (inativo)":""]},kt.data))})]}),e.jsxs(w,{size:"sm",variant:"outline",className:"h-8 gap-1.5 text-xs",disabled:!Nt||Js.status_pedido!=="pago",onClick:()=>ca({itemIndex:ne,oldDate:Ds,novaData:Nt}),children:[e.jsx(kn,{className:"h-3 w-3"}),"Trocar"]})]})})]},ne)})})]})]})]}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"h-5 w-5"})," Estornos"]})}),e.jsxs(ge,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Cancele uma cobrança Pagar.me e restaure o estoque. O valor é calculado proporcionalmente à taxa de serviço e parcelamento."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Te,{value:ua,onChange:v=>pt(v.target.value),placeholder:"Nome, e-mail, CPF, telefone ou ID do pedido...",className:"flex-1",onKeyDown:v=>v.key==="Enter"&&rl()}),e.jsxs(w,{size:"sm",onClick:rl,disabled:ya||!ua.trim(),children:[ya?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(At,{className:"h-3.5 w-3.5"}),"Buscar"]})]}),ft.length>0&&!_&&e.jsxs("div",{className:"rounded-lg border divide-y divide-border/50",children:[e.jsxs("div",{className:"px-3 py-1.5 text-[11px] text-muted-foreground uppercase tracking-wide font-medium",children:[ft.length," resultado",ft.length!==1?"s":""," — clique para selecionar"]}),ft.map(v=>{const ne=v.usuario||{},ds=ne.user||{},Ds=ne.nome||ds.username||ds.email||"—",Zs=ne.telefone||"",Nt=v.data_pedido?String(v.data_pedido).slice(0,10):"—";return e.jsxs("button",{className:"w-full flex items-center justify-between gap-3 px-3 py-2.5 text-left hover:bg-muted/40 transition-colors",onClick:()=>$u(v.documentId||v.id),disabled:gt,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-mono text-xs font-semibold",children:["#",v.id]}),e.jsx(je,{variant:v.status_pedido==="pago"?"default":v.status_pedido==="cancelado"?"destructive":"secondary",className:"text-[10px] px-1.5 py-0",children:v.status_pedido}),e.jsx("span",{className:"text-xs text-muted-foreground capitalize",children:v.metodo_pagamento||"—"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-0.5",children:[Ds,Zs?` · ${Zs}`:""," · ",Nt]})]}),e.jsx("div",{className:"text-sm font-semibold shrink-0",children:Ys(v.total)})]},v.id)})]}),gt&&e.jsxs("div",{className:"flex items-center justify-center py-6 text-muted-foreground gap-2 text-sm",children:[e.jsx(Cs,{className:"h-4 w-4 animate-spin"})," Carregando pedido..."]}),_&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 px-3 py-2 text-sm space-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"font-semibold",children:["Pedido #",_.id]}),e.jsx(je,{variant:_.status_pedido==="pago"?"default":_.status_pedido==="cancelado"?"destructive":"secondary",children:_.status_pedido}),e.jsx("span",{className:"text-muted-foreground capitalize",children:_.metodo_pagamento||"—"}),Number(_.parcelas)>1&&e.jsxs(je,{variant:"outline",children:[_.parcelas,"x"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-0.5 text-xs text-muted-foreground sm:grid-cols-4",children:[e.jsxs("div",{children:["Subtotal: ",e.jsx("span",{className:"text-foreground",children:Ys(_.subtotal)})]}),e.jsxs("div",{children:["Taxa serviço: ",e.jsx("span",{className:"text-foreground",children:Ys(_.taxa_servico)})]}),e.jsxs("div",{children:["Taxa parcel.: ",e.jsx("span",{className:"text-foreground",children:Ys(_.taxa_parcelamento)})]}),e.jsxs("div",{children:["Total: ",e.jsx("span",{className:"font-semibold text-foreground",children:Ys(_.total)})]})]}),_.dados_gateway?.charge?.id&&e.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:["Charge: ",_.dados_gateway.charge.id]}),!_.dados_gateway?.charge?.id&&e.jsx("div",{className:"rounded border border-yellow-200 bg-yellow-50 px-2 py-1 text-xs text-yellow-800 dark:border-yellow-800 dark:bg-yellow-950 dark:text-yellow-300",children:"Sem charge_id Pagar.me — pedido Cielo ou POS não pode ser estornado aqui."})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-2 uppercase tracking-wide",children:"Itens do pedido"}),e.jsx("div",{className:"divide-y divide-border/50 rounded-lg border",children:(Array.isArray(_.items)?_.items:[]).map((v,ne)=>{const ds=ce.has(ne),Ds=v.tipo_ingresso?.nome||v.tipo_ingresso?.attributes?.nome||"",Zs=Number(v.preco_unitario||0)*Number(v.quantidade||1);return e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5 hover:bg-muted/40",children:[e.jsx(Ja,{id:`estorno-item-${ne}`,checked:ds,onCheckedChange:Nt=>{Pe(kt=>{const La=new Set(kt);return Nt?La.add(ne):La.delete(ne),La})}}),e.jsxs("label",{htmlFor:`estorno-item-${ne}`,className:"flex-1 min-w-0 cursor-pointer select-none",children:[e.jsx("div",{className:"text-sm truncate",children:v.nome_item||"Item"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ds&&e.jsxs("span",{children:[Ds," · "]}),"Qty ",v.quantidade," · ",v.metadata?.data_evento||"—"]}
91)]}),e.jsx("div",{className:"text-sm font-semibold shrink-0",children:Ys(Zs)})]},ne)})})]}),$t&&e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-3 space-y-1.5 text-sm",children:[e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Itens selecionados"}),e.jsx("span",{children:Ys($t.selectedSubtotal)})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Taxa de serviço proporcional"}),e.jsx("span",{children:Ys($t.taxaServico)})]}),$t.taxaParcelamento>0&&e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Taxa de parcelamento proporcional"}),e.jsx("span",{children:Ys($t.taxaParcelamento)})]}),e.jsxs("div",{className:"flex justify-between border-t pt-1.5 font-semibold",children:[e.jsx("span",{children:"Total a estornar"}),e.jsx("span",{children:Ys($t.total)})]}),e.jsxs("div",{className:"pt-1.5 space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Sobrescrever valor (R$) — deixe em branco para usar o calculado"}),e.jsx(Te,{value:Ie,onChange:v=>Ye(v.target.value),placeholder:String($t.total.toFixed(2)).replace(".",","),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground pt-0.5",children:["Enviando para Pagar.me: ",e.jsx("span",{className:"font-semibold text-foreground",children:Ys($t.amountCents/100)})," ","(",$t.amountCents," centavos)"]})]}),(_.metodo_pagamento||"")==="boleto"&&e.jsxs("div",{className:"rounded-lg border px-3 py-3 space-y-3",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Dados bancários (obrigatório para boleto)"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[[{key:"holder_name",label:"Nome do titular"},{key:"holder_document",label:"CPF/CNPJ do titular"},{key:"bank",label:"Código do banco"},{key:"branch_number",label:"Nº da agência"},{key:"branch_check_digit",label:"Dígito da agência"},{key:"account_number",label:"Nº da conta"},{key:"account_check_digit",label:"Dígito da conta"}].map(({key:v,label:ne})=>e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[11px] text-muted-foreground",children:ne}),e.jsx(Te,{value:B[v],onChange:ds=>de(Ds=>({...Ds,[v]:ds.target.value})),className:"h-8 text-xs"})]},v)),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[11px] text-muted-foreground",children:"Tipo de conta"}),e.jsxs(rs,{value:B.type,onValueChange:v=>de(ne=>({...ne,type:v})),children:[e.jsx(ns,{className:"h-8 text-xs",children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"checking",className:"text-xs",children:"Corrente"}),e.jsx(xe,{value:"savings",className:"text-xs",children:"Poupança"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[11px] text-muted-foreground",children:"Tipo de titular"}),e.jsxs(rs,{value:B.holder_type,onValueChange:v=>de(ne=>({...ne,holder_type:v})),children:[e.jsx(ns,{className:"h-8 text-xs",children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"individual",className:"text-xs",children:"Pessoa física"}),e.jsx(xe,{value:"company",className:"text-xs",children:"Pessoa jurídica"})]})]})]})]})]}),e.jsxs(w,{variant:"destructive",size:"sm",className:"w-full gap-1.5",disabled:Hs||!$t||$t.amountCents<=0||ce.size===0||!_.dados_gateway?.charge?.id||_.status_pedido==="cancelado",onClick:()=>_s(!0),children:[Hs?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(xr,{className:"h-3.5 w-3.5"}),Hs?"Processando...":`Confirmar Estorno — ${$t?Ys($t.amountCents/100):"—"}`]})]})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(Hn,{className:"h-5 w-5 shrink-0"})," Alertas de transferências"]}),e.jsxs("div",{className:"flex items-center gap-2 self-start sm:self-auto",children:[e.jsx(je,{variant:Ts.length>0?"destructive":"outline",children:Ts.length}),e.jsx(w,{variant:"outline",size:"sm",disabled:Ts.length===0,onClick:wu,children:"Marcar tudo como lido"})]})]}),e.jsx(ge,{className:"space-y-3",children:Ts.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Nenhuma transferência pendente de leitura."}):Ts.map(v=>{const ne=v?.meta||{},ds=ne.amount_cents??ne.amount,Ds=v.createdAt||v.updatedAt||ne.requested_at||ne.created_at;return e.jsxs("div",{className:"flex flex-col gap-2 rounded-lg border p-3 min-w-0",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold truncate",children:v.title||"Transferência"}),e.jsx("div",{className:"text-xs text-muted-foreground break-words",children:v.message||"Transferência registrada."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 shrink-0",children:[v?.meta?.transferId&&e.jsx(w,{variant:"default",size:"sm",onClick:()=>yu(v),children:"Marcar pago"}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>tl(v),children:"Marcar como lido"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 text-xs text-muted-foreground sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"uppercase tracking-wide",children:"Valor"}),e.jsx("div",{className:"text-foreground",children:ds?Mt(ds):"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"uppercase tracking-wide",children:"Solicitante"}),e.jsx("div",{className:"text-foreground",children:ne.requested_by_email||"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"uppercase tracking-wide",children:"Transferência"}),e.jsx("div",{className:"text-foreground",children:ne.transferId||"—"})]})]}),Ds&&e.jsx("div",{className:"text-xs text-muted-foreground",children:new Date(Ds).toLocaleStr
91ing("pt-BR")})]},v.id)})})]})]}),e.jsxs(Ht,{value:"upsell",className:"space-y-6",children:[e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5"})," Correção de Upsell Legado"]})}),e.jsxs(ge,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"Corrige pedidos-filho de upsell criados antes da nova lógica. A consulta automática encontra casos em que o vínculo com o pedido original foi salvo."}),e.jsx("p",{children:"Para os pedidos mais antigos, use o reparo manual com o ID ou documentId do pedido filho e o documentId do pedido original."})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(je,{variant:"outline",children:[$?.count??0," encontrados"]}),e.jsxs(je,{variant:Gs.length>0?"default":"outline",children:[Gs.length," corrigíveis"]}),e.jsxs(je,{variant:"secondary",children:[$?.skipped??0," pulados"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"outline",size:"sm",className:"gap-1.5",onClick:ir,disabled:Ae,children:[Ae?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(At,{className:"h-3.5 w-3.5"}),Ae?"Consultando...":"Consultar detectáveis"]}),e.jsxs(w,{size:"sm",className:"gap-1.5",onClick:()=>fe(!0),disabled:Fe||Gs.length===0,children:[Fe?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ta,{className:"h-3.5 w-3.5"}),"Corrigir detectados"]})]})]}),ie&&e.jsxs("div",{className:"rounded-lg border p-3 text-sm space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(je,{variant:"default",children:[ie.repaired??0," corrigidos"]}),e.jsxs(je,{variant:"outline",children:[ie.skipped??0," pulados"]})]}),Array.isArray(ie.results)&&ie.results.length>0&&e.jsx("div",{className:"space-y-1 text-xs text-muted-foreground",children:ie.results.slice(0,8).map(v=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"font-mono text-foreground",children:["#",v.pedidoId]}),e.jsx("span",{children:v.documentId||"sem documentId"}),e.jsx(je,{variant:v.merged?"default":"secondary",children:v.merged?"Corrigido":Ss(v.reason)})]},`${v.pedidoId}-${v.documentId||"na"}`))})]}),e.jsxs("div",{className:"rounded-lg border",children:[e.jsx("div",{className:"border-b px-3 py-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Detectados automaticamente"}),!$&&!Ae&&e.jsx("div",{className:"px-3 py-4 text-sm text-muted-foreground",children:"Consulte os pedidos com vínculo legado salvo para listar os reparos automáticos."}),Ae&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-sm text-muted-foreground",children:[e.jsx(Cs,{className:"h-4 w-4 animate-spin"})," Carregando pedidos..."]}),$&&$.count===0&&!Ae&&e.jsx("div",{className:"px-3 py-4 text-sm text-muted-foreground",children:"Nenhum pedido legado detectável foi encontrado."}),Array.isArray($?.candidates)&&$.candidates.length>0&&e.jsx("div",{className:"divide-y",children:$.candidates.map(v=>e.jsx("div",{className:"space-y-2 px-3 py-3 text-sm",children:e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"font-semibold",children:["Pedido #",v.pedidoId]}),e.jsx(je,{variant:v.fixable?"default":"secondary",children:v.fixable?"Corrigível":Ss(v.reason)}),v.source&&e.jsx(je,{variant:"outline",children:v.source==="dados_gateway"?"dados_gateway":"item metadata"})]}),e.jsxs("div",{className:"mt-1 break-all text-xs text-muted-foreground",children:["Filho: ",v.documentId||"sem documentId"]}),e.jsxs("div",{className:"break-all text-xs text-muted-foreground",children:["Original: ",v.originalDocumentId||"não detectado"]}),v.usuario&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Cliente: ",v.usuario]}),v.eventos?.length>0&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Eventos: ",v.eventos.join(", ")
91]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground sm:text-right",children:[e.jsxs("div",{children:["Total: ",Ys(v.total)]}),e.jsxs("div",{children:["Itens: ",v.itemCountOriginal," → ",v.itemCountExpandido]}),e.jsxs("div",{children:["Quantidade: ",v.quantidadeOriginal," → ",v.quantidadeExpandida]})]})]})},`${v.pedidoId}-${v.documentId||"na"}`))})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Reparo manual"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Use esta opção quando o legado não salvou o vínculo de upsell no pedido filho ou quando um pedido-filho já mesclado precisa ser reconsolidado no primeiro pedido."})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Pedido filho (#ID ou documentId)"}),e.jsx(Te,{value:K,onChange:v=>O(v.target.value),placeholder:"Ex.: 12345 ou abcdef..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"documentId do pedido original"}),e.jsx(Te,{value:oe,onChange:v=>ve(v.target.value),placeholder:"documentId do pedido correto"})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{size:"sm",className:"gap-1.5",onClick:()=>_e(!0),disabled:Fe||!K.trim()||!oe.trim(),children:[Fe?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(kn,{className:"h-3.5 w-3.5"}),"Corrigir manualmente"]})})]})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"h-5 w-5"})," Reconciliar status do gateway"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Corrige pedidos pagos/cancelados cujo ",e.jsx("code",{children:"dados_gateway"}),' ainda mostra o status antigo (ex.: um pedido pago que continua exibindo "pendente" na trilha de status). Reescreve ',e.jsx("code",{children:"statuses"})," e ",e.jsx("code",{children:"order_status"})," para refletir o status real do pedido. Vale para Pagar.me e PagBank."]})]}),e.jsxs(ge,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(je,{variant:(U?.stale??0)>0?"destructive":"outline",children:[U?.stale??0," inconsistente(s)"]}),e.jsxs(je,{variant:"secondary",children:[U?.scanned??0," verificado(s)"]}),T&&e.jsxs(je,{variant:"default",children:[T.updated??0," corrigido(s)"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(w,{size:"sm",variant:"outline",onClick:Ri,disabled:Se||qe,children:[Se?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(At,{className:"h-3.5 w-3.5"}),Se?"Consultando...":"Consultar inconsistentes"]}),e.jsxs(w,{size:"sm",onClick:()=>Me(!0),disabled:qe||Se||(U?.stale??0)===0,children:[qe?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ta,{className:"h-3.5 w-3.5"}),"Corrigir inconsistentes"]})]}),!U&&!Se&&e.jsx("p",{className:"text-sm text-muted-foreground",children:'Clique em "Consultar inconsistentes" para verificar os pedidos.'}),U&&U.stale===0&&!Se&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma inconsistência encontrada — todos os status do gateway estão coerentes."}),Array.isArray(U?.samples)&&U.samples.length>0&&e.jsxs("div",{className:"space-y-2",children:[U.samples.map(v=>e.jsxs("div",{className:"rounded-md border p-2 text-xs",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:["Pedido #",v.pedidoId]}),e.jsx(je,{variant:"outline",children:v.status_pedido})]}),e.jsxs("div",{className:"mt-1 text-muted-foreground",children:[e.jsx("span",{className:"line-through",children:(v.before?.statuses||[]).map(ne=>ne?.normalized).filter(Boolean).join(", ")||"—"})," → ",e.jsx("span",{className:"text-foreground",children:(v.after?.statuses||[]).map(ne=>ne?.normalized).filter(Boolean).join(", ")||"—"})]})]},v.pedidoId)),U.stale>U.samples.length&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["…e mais ",U.stale-U.samples.length," pedido(s)."]})]})]})]})]}),e.jsx(Ht,{value:"link-checkout",className:"space-y-6",children:e.jsx(bf,{eventos:h})}),n&&e.jsx(Ht,{value:"taxas",className:"space-y-6",children:e.jsx(_f,{})})]}),e.jsx(ka,{open:me,onOpenChange:fe,title:"Corrigir upsells detectados",description:`Corrigir ${Gs.length} pedido(s)-filho detectado(s) automaticamente? Os itens serão movidos para o pedido original e expandidos em unidades individuais quando necessário.`,actionLabel:"Corrigir detectados",onConfirm:Du,loading:Fe}),e.jsx(ka,{open:le,onOpenChange:_e,title:"Corrigir upsell manualmente",description:`Vincular o pedido filho "${K||"—"}" ao pedido original "${oe||"—"}"?`,actionLabel:"Corrigir manualmente",onConfirm:Pu,loading:Fe}),e.jsx(ka,{open:we,onOpenChange:Me,title:"Reconciliar status do gateway",description:`Reescrever a trilha de status (statuses) e order_status de ${U?.stale??0} pedido(s) para refletir o status real? Esta ação altera apenas dados_gateway; o status do pedido não é modificado.`,actionLabel:"Corrigir inconsistentes",onConfirm:Ru,loading:qe}),e.jsx(ka,{open:k,onOpenChange:De,title:"Atualizar preços dos carrinhos",description:`Confirma atualizar preços e lotes dos carrinhos de "${ws}"? Itens com lotes inválidos serão removidos automaticamente.`,actionLabel:"Atualizar",onConfirm:Su,loading:G}),e.jsx(ka,{open:Ne,onOpenChange:es,title:"Limpar carrinhos",description:`Confirma limpar todos os carrinhos de "${ws}"? Esta ação não pode ser desfeita.`,actionLabel:"Limpar",variant:"destructive",onConfirm:Iu,loading:re}),e.jsx(ka,{open:Y,onOpenChange:Q,title:"Reenviar e-mails pendentes",description:`Reenvia e-mails de confirmação de pagamento para pedidos que ainda não receberam — "${Rs}"${hs?" (data: "+hs+")":""}. Todos os pedidos serão processados gradualmente.`,actionLabel:"Reenviar",onConfirm:Cu,loading:S}),e.jsx(ka,{open:X,onOpenChange:V,title:"Forçar reenvio de todos os e-mails",description:`ATENÇÃO: Isso reenviará e-mails de confirmação para TODOS os pedidos pagos de "${Rs}"${hs?" (data: "+hs+")":""}, mesmo que já tenham recebido.`,actionLabel:"Forçar reenvio",variant:"destructive",onConfirm:ku,loading:F}),e.jsx(ka,{open:Ms,onOpenChange:Fs,title:"Enviar lembretes de evento",description:`Enviar lembrete para ${Le?.count??"?"} pedido(s) — "${us}"${Ve?" (data: "+Ve+")":""}?`,actionLabel:"Enviar lembretes",onConfirm:Eu,loading:gs}),e.jsx(ka,{open:ma,onOpenChange:Ot,title:"Atualizar grupos públicos",description:`Atualizar snapshots de grupos para "${As(j)}"${Je&&Je!=="__all__"?" (data: "+Je+")":""}?`,actionLabel:"Atualizar grupos",onConfirm:bu,loading:zs}),e.jsx(ka,{open:fu,onOpenChange:sl,title:"Copiar grupos entre datas",description:`Copiar grupos de "${As(St)}" da data ${Ha||"—"} para ${Nr||"—"} e redistribuir itens?`,actionLabel:"Copiar e redistribuir",onConfirm:Nu,loading:Pi}),e.jsx(ka,{open:!!_t,onOpenChange:v=>{v||ca(null)},title:"Confirmar troca de data",description:_t?`Trocar item ${_t.itemIndex+1} do pedido #${Js?.id} de ${_t.oldDate} para ${_t.novaData}
91? O estoque será reajustado automaticamente.`:"",actionLabel:"Trocar data",onConfirm:Tu,loading:Na}),e.jsx(ka,{open:Ns,onOpenChange:_s,title:"Confirmar estorno",description:_&&$t?`Estornar ${Ys($t.amountCents/100)} do pedido #${_.id}? Esta ação cancela a cobrança no Pagar.me e restaura o estoque. Não pode ser desfeita.`:"",actionLabel:"Confirmar Estorno",variant:"destructive",onConfirm:Lu,loading:Hs})]})}function ut({className:s,...t}){return e.jsx("div",{className:ls("animate-pulse rounded-md bg-muted",s),...t})}const To=(s="")=>String(s||"").replace(/[\\/:*?"<>|]+/g,"-").trim(),yd=(s=6)=>{const t=new Date;return Array.from({length:s}).map((a,n)=>{const o=new Date(t.getFullYear(),t.getMonth()-n,1),i=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`,u=o.toLocaleDateString("pt-BR",{month:"long",year:"numeric"});return{value:i,label:u.charAt(0).toUpperCase()+u.slice(1)}})},If=s=>{const[t,a]=String(s||"").split("-"),n=Number(t),o=Number(a);if(!Number.isFinite(n)||!Number.isFinite(o)||o<1||o>12)return null;const i=new Date(n,o-1,1,0,0,0,0),u=new Date(n,o,0,23,59,59,999);return{start:i,end:u}},Af=async({sheets:s,hideCurrency:t=!1})=>{const a=await $r(()=>import("./vendor-exceljs-AsZnDCZx.js").then(i=>i.e),__vite__mapDeps([0,1,2])),n=a.default||a,o=new n.Workbook;return(Array.isArray(s)?s:[]).forEach(i=>{const u=o.addWorksheet(i.name),l=t?(i.columns||[]).filter(m=>!/R\$/.test(m.header||"")):i.columns;u.columns=l,u.addRows(Array.isArray(i.rows)?i.rows:[]),u.getRow(1).font={bold:!0};const c=t?[]:Array.isArray(i.currencyColumns)?i.currencyColumns:[];c.length&&c.forEach(m=>{const x=u.columns.findIndex(p=>p?.key===m);if(x<0)return;const h=u.getColumn(x+1);h.numFmt='"R$" #,##0.00',h.alignment={horizontal:"right"}})}),o.xlsx.writeBuffer()},Ef=({sheets:s,hideCurrency:t=!1})=>new Promise((a,n)=>{let o;try{o=new Worker(new URL("/assets/excelExport.worker-GEpezlOv.js",import.meta.url),{type:"module"})}catch(u){n(u);return}const i=()=>{try{o.terminate()}catch{}};o.onmessage=u=>{i(),u.data?.ok?a(u.data.buffer):n(new Error(u.data?.error||"excel_worker_failed"))},o.onerror=u=>{i(),n(u?.error||new Error("excel_worker_error"))},o.postMessage({sheets:s,hideCurrency:t})}),Xn=async({fileName:s,sheets:t,hideCurrency:a=!1})=>{let n;try{n=await Ef({sheets:t,hideCurrency:a})}catch{n=await Af({sheets:t,hideCurrency:a})}const o=new Blob([n],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),i=URL.createObjectURL(o),u=document.createElement("a");u.href=i,u.download=s,document.body.appendChild(u),u.click(),u.remove(),URL.revokeObjectURL(i)};function Df(){const s=nr(),{user:t}=Zt(),{toast:a}=mt(),n=Tr(),o=globalThis?.location?.origin||"",[i,u]=r.useState(!1),[l,c]=r.useState(!1),[m,x]=r.useState(!1),[h,p]=r.useState(!1),[f,I]=r.useState(""),[g,N]=r.useState(!1),[b,C]=r.useState([]),q=r.useMemo(()=>yd(6),[]),[L,M]=r.useState(()=>yd(6)[0]?.value||""),z=(t?.role?.name||t?.role?.type||t?.role?.code||"").toLowerCase(),D=z.includes("superadmin"),E=z.includes("supersuporte")&&!D,A=z.includes("admin")||D||E,S=z.includes("gerente")&&z.includes("vendedor"),P=A||D||E||S,F=A||D||E,ee=z.includes("externo"),re=F||ee,te=!!t?.id,[G,y]=r.useState(""),[$,W]=r.useState(!1),[ie,ke]=r.useState(null),[Ae,be]=r.useState(""),[Fe,ae]=r.useState(!1),{data:K,isLoading:O,refetch:oe}=Ks("link-convites-insights","/link-convites/insights",{staleTime:60*1e3,refetchOnWindowFocus:!1}),{data:ve}=Ks("link-convites-dash-config","/pedido-dashboard-config",{staleTime:5*60*1e3,refetchOnWindowFocus:!1}),me=r.useMemo(()=>(ve?.data?.attributes||ve?.attributes||ve||{})?.ocultar_valores_vendedores_externos===!0,[ve]),fe=ee&&me,le=r.useMemo(()=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",maximumFractionDigits:2}),[]);r.useEffect(()=>{let Y=!1;return(async()=>{const X=Array.isArray(K?.rankedLinks)&&K.rankedLinks.length>0;if(O||X){!Y&&X&&b.length&&C([]);return}const V=localStorage.getItem("token"),pe=new URLSearchParams;pe.set("pagination[pageSize]","300"),pe.set("sort","createdAt:desc"),pe.set("fields[0]","id"),pe.set("fields[1]","documentId"),pe.set("fields[2]","referral"),pe.set("fields[3]","active"),pe.set("populate[evento][fields][0]","titulo"),pe.set("populate[created_by_usuario][fields][0]","nome"),pe.set("populate[created_by_usuario][fields][1]","email");const Ce=await Yt.get(`${n}
91/link-convites?${pe.toString()}`,{headers:{Authorization:`Bearer ${V}`}});if(Y)return;const Xe=(Array.isArray(Ce?.data?.data)?Ce.data.data:[]).map(Ve=>{const bs=Ve?.attributes||Ve||{},ts=bs?.evento?.data?.attributes||bs?.evento||null,R=bs?.created_by_usuario?.data?.attributes||bs?.created_by_usuario||null;return{id:Ve?.id||bs?.id,documentId:bs?.documentId||Ve?.documentId||null,attrs:{referral:bs?.referral||"",active:bs?.active!==!1,evento:ts?{titulo:ts?.titulo||"—"}:null,created_by_usuario:R?{id:R?.id||null,documentId:R?.documentId||null,nome:R?.nome||null,email:R?.email||null}:null},referral:bs?.referral||"",quantityPedidos:0,paidOrders:0,pendingOrders:0,cancelledFailedOrders:0,attributedRevenue:0,monitoredAccesses:0}});C(Xe)})().catch(X=>{Y||(console.error("Erro ao carregar fallback de links no SellersManager",X),C([]))}),()=>{Y=!0}},[n,K,O,b.length]);const _e=r.useMemo(()=>{const Y=Array.isArray(K?.rankedLinks)?K.rankedLinks:[];return(Y.length>0?Y:b).map(X=>{const V=X?.metrics||X||{};return{id:X?.id,documentId:X?.documentId||X?.attrs?.documentId||null,attrs:{referral:X?.referral||X?.attrs?.referral,active:X?.active??X?.attrs?.active,evento:X?.evento||X?.attrs?.evento||null,created_by_usuario:X?.created_by_usuario||X?.attrs?.created_by_usuario||null},referral:X?.referral||X?.attrs?.referral||"",quantityPedidos:Number(V.quantity_pedidos??0)||0,paidOrders:Number(V.pedidos_pagos??0)||0,pendingOrders:Number(V.pedidos_pendentes??0)||0,cancelledFailedOrders:Number(V.pedidos_cancelados_falhos??0)||0,attributedRevenue:Number(V.receita_atribuida_subtotal??0)||0,monitoredAccesses:Number(V.acessos_monitorados??0)||0}})},[K,b]),U=r.useMemo(()=>{const Y=Array.isArray(K?.groupedByUser)?K.groupedByUser:[];if(Y.length>0)return Y.map(X=>({key:String(X?.user?.id||X?.user?.documentId||X?.user?.nome||"sem-usuario"),ownerName:X?.user?.nome||X?.user?.email||"Sem usuário",linksCount:Number(X?.links_count??0)||0,quantityPedidos:Number(X?.quantity_pedidos??0)||0,paidOrders:Number(X?.pedidos_pagos??0)||0,pendingOrders:Number(X?.pedidos_pendentes??0)||0,cancelledFailedOrders:Number(X?.pedidos_cancelados_falhos??0)||0,attributedRevenue:Number(X?.receita_atribuida_subtotal??0)||0,monitoredAccesses:Number(X?.acessos_monitorados??0)||0}));const Q=_e.reduce((X,V)=>{const pe=V?.attrs?.created_by_usuario||{},Ce=String(pe?.id||pe?.documentId||pe?.nome||pe?.email||"sem-usuario");return X[Ce]||(X[Ce]={key:Ce,ownerName:pe?.nome||pe?.email||"Sem usuário",linksCount:0,quantityPedidos:0,paidOrders:0,pendingOrders:0,cancelledFailedOrders:0,attributedRevenue:0,monitoredAccesses:0}),X[Ce].linksCount+=1,X[Ce].quantityPedidos+=Number(V.quantityPedidos||0),X[Ce].paidOrders+=Number(V.paidOrders||0),X[Ce].pendingOrders+=Number(V.pendingOrders||0),X[Ce].cancelledFailedOrders+=Number(V.cancelledFailedOrders||0),X[Ce].attributedRevenue+=Number(V.attributedRevenue||0),X[Ce].monitoredAccesses+=Number(V.monitoredAccesses||0),X},{});return Object.values(Q)},[K,_e]),J=r.useMemo(()=>{const Y=K?.totals||{},Q=Number(Y.links),X=Number(Y.quantity_pedidos),V=Number(Y.paid_orders),pe=Number(Y.receita_atribuida_subtotal);return Number.isFinite(Q)&&Number.isFinite(X)&&Number.isFinite(V)&&Number.isFinite(pe)?{links:Q,quantityPedidos:X,paidOrders:V,attributedRevenue:pe}:_e.reduce((Ce,Ue)=>(Ce.links+=1,Ce.quantityPedidos+=Number(Ue.quantityPedidos||0),Ce.paidOrders+=Number(Ue.paidOrders||0),Ce.attributedRevenue+=Number(Ue.attributedRevenue||0),Ce),{links:0,quantityPedidos:0,paidOrders:0,attributedRevenue:0})},[K,_e]),T=r.useMemo(()=>[{title:"Links monitorados",value:J.links.toLocaleString("pt-BR"),hint:"Total de links no painel"},{title:"Total pedidos",value:J.quantityPedidos.toLocaleString("pt-BR"),hint:"Pedidos totais atribuídos"},{title:"Pedidos pagos",value:J.paidOrders.toLocaleString("pt-BR"),hint:"Somente status pago"},...fe?[]:[{title:"Receita atribuída",value:le.format(J.attributedRevenue||0),hint:"Baseado no total de pedidos pagos"}]],[J,le,fe]),[Ee,Se]=r.useState({referral:"",evento:"",usuarioId:"",description:""}),{data:Ze}=Ks("events-simple","/eventos?fields[0]=titulo&fields[1]=id"),qe=Ze?.data||[],[Qe,we]=r.useState([]),Me=r.useMemo(()=>{const Y=Array.isArray(Qe)?Qe:[],Q=["authenticated","public","superadmin","admin","afiliado"];return Y.filter(X=>{if(!X?.user?.id)return!1;const V=X?.user?.role?.data?.attributes||X?.user?.role||{},pe=(V?.name||V?.type||"").toLowerCase();return pe?!Q.some(Ce=>pe===Ce||pe.includes(Ce)):!1})},[Qe]);r.useEffect(()=>{(i&&P||$&&F)&&(async()=>{try{const Q=await Yt.get(`${n}/usuarios/sellers?pagination[pageSize]=200&sort=createdAt:desc`,{headers:{Authorization:`Bearer ${localStorage.getItem("token")}`}}),X=Q?.data?.data||Q?.data||[],pe=(Array.isArray(X)?X:[]).map(Ce=>{const Xe=(Ce?.attributes??Ce)||{},Ve=Xe.user?.data,bs=Ve?.attributes||{},ts=bs?.role?.data,R=ts?.attributes||ts||null,Le=Ve?{id:Ve.id,...bs,role:R}:Xe.user||null;return{id:Ce?.id||Xe.id,...Xe,user:Le}});we(pe)}catch(Q){console.error("Failed to fetch users",Q)}})()},[i,$,n,P,F]);const ks=async()=>
91{if(!P){a({title:"Acesso restrito",description:"Apenas administradores podem criar novos links.",variant:"destructive"});return}try{c(!0);const Y=(Ee.referral??"").trim().toUpperCase(),Q=Y.replace(/[^A-Z0-9_-]/g,""),X=(Ee.description??"").trim();if(Y&&!Q){a({title:"Código inválido",description:"Use apenas letras, números, _ ou - no código personalizado.",variant:"destructive"});return}const V=Ee.evento?Number(Ee.evento):null,pe=Ee.usuarioId?Number(Ee.usuarioId):null,Ce=Ee.usuarioId&&Me.find(Ve=>String(Ve.id)===String(Ee.usuarioId))?.documentId||null,Ue={quantityPedidos:null,quantityIngressosPerPedido:1,...X?{description:X}:{},...Q?{referral:Q}:{},...Number.isFinite(V)?{eventoId:V}:{},...Number.isFinite(pe)?{usuarioId:pe}:{},...Ce?{usuarioDocumentId:Ce}:{}};console.log("[SellersManager] Generate payload:",Ue),console.log("[SellersManager] Selected usuario:",Me.find(Xe=>String(Xe.id)===String(Ee.usuarioId))),await $e.post("/link-convites/generate",Ue),a({title:"Sucesso",description:"Link criado com sucesso."}),u(!1),oe()}catch(Y){a({title:"Erro",description:Y.response?.data?.error?.message||"Falha ao criar link.",variant:"destructive"})}finally{c(!1)}},xs=Y=>{const Q=`${o}/?ref=${Y}`;navigator.clipboard.writeText(Q),a({title:"Copiado!",description:"Link copiado para a área de transferência."})},k=r.useCallback((Y={})=>{const Q=Y?.attrs||Y?.attributes||{};return{id:Y?.id||Q?.id||null,documentId:Y?.documentId||Q?.documentId||null,referral:Q?.referral||Y?.referral||"",ownerId:Q?.created_by_usuario?.id||Y?.created_by_usuario?.id||null}},[]),De=r.useCallback(async Y=>{if(!F){a({title:"Acesso restrito",description:"Somente admin e superAdmin podem despublicar links.",variant:"destructive"});return}const{id:Q,documentId:X,referral:V}=k(Y),pe=V||`#${Q}`;if(!window.confirm(`Despublicar o link ${pe}? O link ficará inativo.`))return;const Ue=`unpublish-${Q||X||V}`;try{if(y(Ue),X)await $e.put(`/link-convites/doc/${encodeURIComponent(X)}`,{data:{active:!1}});else if(Q)await $e.put(`/link-convites/${Q}`,{data:{active:!1}});else throw new Error("Link sem identificador válido.");a({title:"Link despublicado",description:"O link foi marcado como inativo."}),oe()}catch(Xe){a({title:"Erro ao despublicar",description:Xe?.response?.data?.error?.message||"Não foi possível despublicar o link.",variant:"destructive"})}finally{y("")}},[F,k,a,oe]),Ne=r.useCallback(Y=>{if(!F){a({title:"Acesso restrito",description:"Somente admin e superAdmin podem trocar o usuário do link.",variant:"destructive"});return}const{ownerId:Q}=k(Y);ke(Y),be(Q?String(Q):"0"),W(!0)},[F,k,a]),es=r.useCallback(async()=>{if(!ie)return;const{id:Y,documentId:Q,referral:X}=k(ie),V=`reassign-${Y||Q||X}`,pe=Ae&&Ae!=="0"?Number(Ae):null;if(Ae!=="0"&&!Number.isFinite(pe)){a({title:"Usuário inválido",description:"Selecione um usuário válido para reatribuição.",variant:"destructive"});return}try{ae(!0),y(V);const Ce={data:{created_by_usuario:pe}};if(Q)await $e.put(`/link-convites/doc/${encodeURIComponent(Q)}`,Ce);else if(Y)await $e.put(`/link-convites/${Y}`,Ce);else throw new Error("Link sem identificador válido.");a({title:"Usuário atualizado",description:"O link foi reatribuído com sucesso."}),W(!1),ke(null),be(""),oe()}catch(Ce){a({title:"Erro ao reatribuir",description:Ce?.response?.data?.error?.message||"Não foi possível atualizar o usuário do link.",variant:"destructive"})}finally{ae(!1),y("")}},[ie,Ae,k,a,oe]),ss=r.useCallback(Y=>Y?.key?_e.filter(Q=>{const X=Q?.attrs?.created_by_usuario||{};return String(X?.id||X?.documentId||X?.nome||"sem-usuario")===Y.key}):[],[_e]),We=r.useCallback(async()=>{try{x(!0);const Y=U.map(V=>({Usuario:V.ownerName,Links:V.linksCount,"Acessos monitorados":V.monitoredAccesses,"Total de pedidos":V.quantityPedidos,"Pedidos pagos":V.paidOrders,"Pedidos pendentes":V.pendingOrders,"Pedidos cancelados/falhos":V.cancelledFailedOrders,"Receita atribuída (R$)":Number(V.attributedRevenue||0)})),Q=_e.map(V=>{const pe=V?.attrs?.created_by_usuario||{},Ce=V?.attrs?.evento?.titulo||"—";return{Usuario:pe?.nome||pe?.email||"Sem usuário",Codigo:V.referral||"—",Evento:Ce,"Acessos monitorados":V.monitoredAccesses||0,"Total de pedidos":V.quantityPedidos,"Pedidos pagos":V.paidOrders,"Pedidos pendentes":V.pendingOrders,"Pedidos cancelados/falhos":V.cancelledFailedOrders,"Receita atribuída (R$)":Number(V.attributedRevenue||0)}}),X=Us(new Date,"yyyy-MM-dd");await Xn({fileName:`usuarios_links_${X}.xlsx`,hideCurrency:fe,sheets:[{name:"Usuários",columns:[{header:"Usuário",key:"Usuario",width:28},{header:"Links",key:"Links",width:10},{header:"Acessos monitorados",key:"Acessos monitorados",width:18},{header:"Total de pedidos",key:"Total de pedidos",width:16},{header:"Pedidos pagos",key:"Pedidos pagos",width:14},{header:"Pedidos pendentes",key:"Pedidos pendentes",width:16},{header:"Pedidos cancelados/falhos",key:"Pedidos cancelados/falhos",width:22},{header:"Receita atribuída (R$)",key:"Receita atribuída (R$)",width:22}],rows:Y,currencyColumns:["Receita atribuída (R$)"]},{name:"Detalhes por link",columns:[{header:"Usuário",key:"Usuario",width:28},{header:"Código",key:"Codigo",width:16},{header:"Evento",key:"Evento",width:26},{header:"Acessos monitorados",key:"Acessos monitorados",width:18},{header:"Total de pedidos",key:"Total de pedidos",width:16},{header:"Pedidos pagos",key:"Pedidos pagos",width:14},{header:"Pedidos pendentes",key:"Pedidos pendentes",width:16},{header:"Pedidos cancelados/falhos",key:"Pedidos cancelados/falhos",width:22},{header:"Receita atribuída (R$)",key:"Receita atribuída (R$)",width:22}],rows:Q,currencyColumns:["Receita atribuída (R$)"]}]}),a({title:"Exportação concluída",description:`${Y.length} usuários exportados.`})}catch(Y){console.error("Falha ao exportar usuários",Y),a({title:"Falha ao exportar",description:"Não foi possível gerar o Excel de usuários.",variant:"destructive"})}finally{x(!1)}},[U,_e,a,fe]),hs=r.useCallback(async Y=>{try{I(Y.key);const Q=ss(Y),X=[{Usuario:Y.ownerName,Links:Y.linksCount,"Acessos monitorados":Y.monitoredAccesses,"Total de pedidos":Y.quantityPedidos,"Pedidos pagos":Y.paidOrders,"Pedidos pendentes":Y.pendingOrders,"Pedidos cancelados/falhos":Y.cancelledFailedOrders,"Receita atribuída (R$)":Number(Y.attributedRevenue||0)}],V=Q.map(Ue=>({Codigo:Ue.referral||"—",Evento:Ue?.attrs?.evento?.titulo||"—",Status:Ue?.attrs?.active?"Ativo":"Inativo","Acessos monitorados":Ue.monitoredAccesses||0,"Total de pedidos":Ue.quantityPedidos,"Pedidos pagos":Ue.paidOrders,"Pedidos pendentes":Ue.pendingOrders,"Pedidos cancelados/falhos":Ue.cancelledFailedOrders,"Receita atribuída (R$)":Number(Ue.attributedRevenue||0)})),pe=To(Y.ownerName||"usuario"),Ce=Us(new Date,"yyyy-MM-dd");await Xn({fileName:`usuario_${pe}_${Ce}.xlsx`,hideCurrency:fe,sheets:[{name:"Resumo",columns:[{header:"Usuário",key:"Usuario",width:28},{header:"Links",key:"Links",width:10},{header:"Acessos monitorados",key:"Acessos monitorados",width:18},{header:"Total de pedidos",key:"Total de pedidos",width:16},{header:"Pedidos pagos",key:"Pedidos pagos",width:14},{header:"Pedidos pendentes",key:"Pedidos pendentes",width:16},{header:"Pedidos cancelados/falhos",key:"Pedidos cancelados/falhos",width:22},{header:"Receita atribuída (R$)",key:"Receita atribuída (R$)",width:22}],rows:X,currencyColumns:["Receita atribuída (R$)"]},{name:"Links",columns:[{header:"Código",key:"Codigo",width:16},{header:"Evento",key:"Evento",width:26},{header:"Status",key:"Status",width:10},{header:"Acessos monitorados",key:"Acessos monitorados",width:18},{header:"Total de pedidos",key:"Total de pedidos",width:16},{header:"Pedidos pagos",key:"Pedidos pagos",width:14},{header:"Pedidos pendentes",key:"Pedidos pendentes",width:16},{header:"Pedidos cancelados/falhos",key:"Pedidos cancelados/falhos",width:22},{header:"Receita atribuída (R$)",key:"Receita atribuída (R$)",width:22}],rows:V,currencyColumns:["Receita atribuída (R$)"]}]}),a({title:"Exportação concluída",description:`Relatório do usuário ${Y.ownerName} gerado.`})}catch(Q){console.error("Falha ao exportar usuário",Q),a({title:"Falha ao exportar",description:"Não foi possível gerar o Excel do usuário.",variant:"destructive"})}finally{I("")}},[ss,a,fe]),Is=r.useCallback(async()=>{try{p(!0);const Y=If(L);
91if(!Y){a({title:"Mês inválido",description:"Selecione um mês válido para exportação.",variant:"destructive"});return}const Q=localStorage.getItem("token"),X=[];let V=1;const pe=200;for(;;){const ts=new URLSearchParams;ts.set("filters[referral_code][$notNull]","true"),ts.set("filters[createdAt][$gte]",Y.start.toISOString()),ts.set("filters[createdAt][$lte]",Y.end.toISOString()),ts.set("sort","createdAt:desc"),ts.set("pagination[pageSize]",String(pe)),ts.set("pagination[page]",String(V)),ts.set("fields[0]","referral_code"),ts.set("fields[1]","status_pedido"),ts.set("fields[2]","subtotal"),ts.set("fields[3]","desconto_cupom"),ts.set("fields[4]","total");const R=await Yt.get(`${n}/pedidos?${ts.toString()}`,{headers:{Authorization:`Bearer ${Q}`}}),Le=Array.isArray(R?.data?.data)?R.data.data:[];X.push(...Le);const as=Number(R?.data?.meta?.pagination?.pageCount||1);if(V>=as||Le.length<pe)break;V+=1}const Ce=X.reduce((ts,R)=>{const Le=R?.attributes||R||{},as=String(Le.referral_code||"").trim().toUpperCase();if(!as)return ts;const ms=String(Le.status_pedido||Le.status||"").toLowerCase();if(ts[as]||(ts[as]={pedidos:0,pagos:0,pendentes:0,canceladosFalhos:0,receita:0}),ts[as].pedidos+=1,ms==="pago"){ts[as].pagos+=1;const Ke=Number(Le.subtotal||0),gs=Number(Le.desconto_cupom||0);ts[as].receita+=Number(Math.max(0,Ke-gs).toFixed(2))}else ms==="cancelado"||ms==="falha"||ms==="failed"?ts[as].canceladosFalhos+=1:ts[as].pendentes+=1;return ts},{}),Ue=_e.reduce((ts,R)=>(ts[String(R.referral||"").toUpperCase()]=R,ts),{}),Xe=Object.entries(Ce).map(([ts,R])=>{const Le=Ue[ts],as=Le?.attrs?.created_by_usuario||{},ms=Le?.attrs?.evento?.titulo||"—";return{Ranking:0,Código:ts,Usuário:as?.nome||as?.email||"Sem usuário",Evento:ms,"Acessos monitorados":Number(Le?.monitoredAccesses||0),"Total de pedidos":R.pedidos,"Pedidos pagos":R.pagos,"Pedidos pendentes":R.pendentes,"Pedidos cancelados/falhos":R.canceladosFalhos,"Receita atribuída (R$)":Number(R.receita||0)}}).sort((ts,R)=>R["Total de pedidos"]!==ts["Total de pedidos"]?R["Total de pedidos"]-ts["Total de pedidos"]:R["Pedidos pagos"]!==ts["Pedidos pagos"]?R["Pedidos pagos"]-ts["Pedidos pagos"]:R["Receita atribuída (R$)"]-ts["Receita atribuída (R$)"]).map((ts,R)=>({...ts,Ranking:R+1})),Ve=q.find(ts=>ts.value===L)?.label||L,bs=To(Ve);await Xn({fileName:`ranking_mensal_${bs}.xlsx`,hideCurrency:fe,sheets:[{name:"Ranking mensal",columns:[{header:"Ranking",key:"Ranking",width:10},{header:"Código",key:"Código",width:16},{header:"Usuário",key:"Usuário",width:28},{header:"Evento",key:"Evento",width:24},{header:"Acessos monitorados",key:"Acessos monitorados",width:18},{header:"Total de pedidos",key:"Total de pedidos",width:16},{header:"Pedidos pagos",key:"Pedidos pagos",width:14},{header:"Pedidos pendentes",key:"Pedidos pendentes",width:16},{header:"Pedidos cancelados/falhos",key:"Pedidos cancelados/falhos",width:22},{header:"Receita atribuída (R$)",key:"Receita atribuída (R$)",width:22}],rows:Xe,currencyColumns:["Receita atribuída (R$)"]}]}),N(!1),a({title:"Exportação concluída",description:`Ranking de ${Ve} exportado com sucesso.`})}catch(Y){console.error("Falha ao exportar ranking mensal",Y),a({title:"Falha ao exportar",description:"Não foi possível gerar o ranking mensal.",variant:"destructive"})}finally{p(!1)}},[n,L,_e,q,a,fe]);return e.jsxs("div",{className:"space-y-6 pb-24 sm:pb-6 overflow-x-hidden",children:[e.jsx(at,{open:$,onOpenChange:Y=>{W(Y),Y||(ke(null),be(""))},children:e.jsxs(rt,{className:"max-w-[95vw] sm:max-w-lg",children:[e.jsx(nt,{children:e.jsx(it,{children:"Trocar usuário do link"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Link: ",e.jsx("span",{className:"font-mono",children:ie?.referral||ie?.attrs?.referral||"—"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Novo usuário relacionado"}),e.jsxs(rs,{value:Ae||"0",onValueChange:be,children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione um usuário"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"0",children:"Sem usuário"}),Me.map(Y=>e.jsx(xe,{value:String(Y.id),children:Y.nome||Y.user?.username||Y.user?.email||Y.email||"Usuário"},Y.id))]})]})]})]}),e.jsxs(Ut,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(w,{variant:"outline",className:"w-full sm:w-auto",onClick:()=>W(!1),disabled:Fe,children:"Cancelar"}),e.jsx(w,{className:"w-full sm:w-auto",onClick:es,disabled:Fe||!ie,children:Fe?"Salvando...":"Salvar usuário"})]})]})}),e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:justify-between sm:items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Gerenciar Vendedores (Links)"}),e.jsx("p",{className:"text-muted-foreground",children:"Crie e monitore links de convite e parceiros."})]}),P&&e.jsxs(at,{open:i,onOpenChange:u,children:[e.jsx(vn,{asChild:!0,children:e.jsxs(w,{className:"w-full sm:w-auto",children:[e.jsx(et,{className:"mr-2 h-4 w-4"})," Novo Link"]})}),e.jsxs(rt,{className:"max-w-[95vw] sm:max-w-lg",children:[e.jsx(nt,{children:e.jsx(it,{children:"Gerar Novo Link"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Atribuir a Usuário (Opcional)"}),e.jsxs(rs,{onValueChange:Y=>Se({...Ee,usuarioId:Y==="0"?"":Y}),children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione um usuário"})}),e.jsxs(os,{children:[te&&e.jsx(xe,{value:"0",children:"Eu mesmo (Atual)"}),Me.map(Y=>e.jsx(xe,{value:String(Y.id),children:Y.nome||Y.user?.username||Y.user?.email||Y.email||"Usuário"},Y.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Evento (Opcional)"}),e.jsxs(rs,{value:Ee.evento||"0",onValueChange:Y=>Se({...Ee,evento:Y==="0"?"":Y}),children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Geral (Sem evento específico)"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"0",children:"Geral (Todos)"}),qe.map(Y=>e.jsx(xe,{value:String(Y.id),children:Y.titulo},Y.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Código Personalizado (Opcional)"}),e.jsx(Te,{placeholder:"Ex: CASA-DOS-BICHOS (Deixe vazio para aleatório)",value:Ee.referral,onChange:Y=>Se({...Ee,referral:Y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Descrição / Notas"}),e.jsx(Te,{placeholder:"Insira informações adicionais sobre o vendedor (Opcional)",value:Ee.description,onChange:Y=>Se({...Ee,description:Y.target.value})})]})]}),e.jsxs(Ut,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(w,{variant:"outline",onClick:()=>u(!1),disabled:l,className:"w-full sm:w-auto",children:"Cancelar"}),e.jsx(w,{onClick:ks,disabled:l,className:"w-full sm:w-auto",children:l?"Gerando...":"Gerar link"})]})]})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Resumo Geral"}),e.jsx(Jt,{children:"Visão geral dos links monitorados e suas métricas."})]}),e.jsx(ge,{children:e.jsx("div",{className:"grid gap-4 grid-cols-1 sm:grid-cols-2 xl:grid-cols-4",children:T.map(Y=>e.jsxs(he,{children:[e.jsxs(Be,{className:"pb-2",children:[e.jsx(ze,{className:"text-sm text-muted-foreground break-words",children:O?e.jsx("span",{className:"inline-block h-4 w-24 animate-pulse rounded bg-muted"}):Y.title}),e.jsx(Jt,{className:"break-words",children:O?e.jsx("span",{className:"inline-block h-4 w-32 animate-pulse rounded bg-muted"}):Y.hint})]}),e.jsx(ge,{children:O?e.jsx(ut,{className:"h-8 w-32"}):e.jsx("p",{className:"text-xl sm:text-2xl font-semibold break-words",children:Y.value})})]},Y.title))})})]}),e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Links Ativos"}),e.jsx(Jt,{children:"Ranking por quantidade de pedidos ou por usuário."})]}),e.jsx(ge,{children:e.jsxs(Lr,{defaultValue:"urls",className:"space-y-4",children:[e.jsxs(Mr,{className:"grid h-auto 
91sm:h-10 w-full grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(Gt,{value:"urls",children:"Ranking por URL"}),e.jsx(Gt,{value:"users",children:"Agrupar por usuário"})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-end",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:We,disabled:m||O,children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),m?"Exportando usuários...":"Exportar usuários (todos)"]}),e.jsxs(fr,{open:g,onOpenChange:N,children:[e.jsx(jr,{asChild:!0,children:e.jsxs(w,{variant:"outline",size:"sm",disabled:h||O,children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),h?"Exportando ranking...":"Exportar ranking mensal"]})}),e.jsxs(ar,{className:"w-[320px] space-y-3",align:"end",children:[e.jsx("p",{className:"text-sm font-medium",children:"Selecione o mês para o ranking"}),e.jsxs(rs,{value:L,onValueChange:M,children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Selecione o mês"})}),e.jsx(os,{children:q.map(Y=>e.jsx(xe,{value:Y.value,children:Y.label},Y.value))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>N(!1),disabled:h,children:"Cancelar"}),e.jsx(w,{size:"sm",onClick:Is,disabled:h||O,children:"Exportar"})]})]})]})]}),e.jsx(Ht,{value:"urls",className:"space-y-4",children:O?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Carregando links..."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"#"}),e.jsx(ue,{children:"URL"}),e.jsx(ue,{children:"Evento"}),e.jsx(ue,{children:"Criado para"}),e.jsx(ue,{children:"Pedidos"}),e.jsx(ue,{children:"Pedidos pagos"}),!fe&&e.jsx(ue,{children:"Receita atribuída"}),e.jsx(ue,{children:"Status"}),re&&e.jsx(ue,{className:"text-right",children:"Ações"})]})}),e.jsx(Ct,{children:_e.map((Y,Q)=>{const X=Y.attrs,V=X.referral||Y.referral,pe=X.evento?.titulo||X.evento?.data?.attributes?.titulo||"—",Ce=X.created_by_usuario?.nome||X.created_by_usuario?.username||X.created_by_usuario?.email||X.created_by_usuario?.data?.attributes?.nome||X.created_by_usuario?.data?.attributes?.username||"—",Ue=X.active,Xe=`${o}/?ref=${encodeURIComponent(V||"")}`,Ve=String(Y.id||Y.documentId||V||Q),bs=G.includes(Ve);return e.jsxs($s,{children:[e.jsx(ye,{children:Q+1}),e.jsx(ye,{className:"font-mono text-xs break-all",children:Xe}),e.jsx(ye,{children:pe}),e.jsx(ye,{children:Ce}),e.jsx(ye,{children:Y.quantityPedidos}),e.jsx(ye,{children:Y.paidOrders}),!fe&&e.jsx(ye,{children:le.format(Y.attributedRevenue||0)}),e.jsx(ye,{children:e.jsx(je,{variant:Ue?"default":"secondary",children:Ue?"Ativo":"Inativo"})}),re&&e.jsx(ye,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsxs(w,{variant:"ghost",size:"sm",onClick:()=>s(`/dashboard/link-convites/${encodeURIComponent(V)}`),children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Atividade"]}),F&&e.jsxs(e.Fragment,{children:[e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>xs(V),title:"Copiar link",children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>Ne(Y),disabled:bs,title:"Trocar usuário",children:e.jsx(cl,{className:"h-4 w-4"})}),e.jsx(w,{variant:"ghost",size:"icon",onClick:()=>De(Y),disabled:!Ue||bs,title:Ue?"Despublicar link":"Link já inativo",children:e.jsx(Xt,{className:"h-4 w-4"})})]})]})})]},Y.id||`${V}-${Q}`)})})]})}),e.jsx("div",{className:"block md:hidden space-y-3",children:_e.map((Y,Q)=>{const X=Y.attrs,V=X.referral||Y.referral,pe=X.evento?.titulo||"—",Ce=X.created_by_usuario?.nome||X.created_by_usuario?.username||X.created_by_usuario?.email||"—",Ue=X.active,Xe=String(Y.id||Y.documentId||V||Q),Ve=G.includes(Xe);return e.jsxs("div",{className:"border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["#",Q+1]}),e.jsx("div",{className:"font-mono font-bold text-sm break-all",children:`${o}/?ref=${encodeURIComponent(V||"")}`}),e.jsx("div",{className:"text-sm text-muted-foreground",children:pe})]}),e.jsx(je,{variant:Ue?"default":"secondary",className:"shrink-0",children:Ue?"Ativo":"Inativo"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Criado para"}),e.jsx("div",{className:"font-medium truncate",children:Ce})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total de Pedidos"}),e.jsx("div",{className:"font-medium",children:Y.quantityPedidos})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Pedidos pagos"}),e.jsx("div",{className:"font-medium",children:Y.paidOrders})]}),!fe&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Receita atribuída"}),e.jsx("div",{className:"font-medium",children:le.format(Y.attributedRevenue||0)})]})]}),re&&e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>
91s(`/dashboard/link-convites/${encodeURIComponent(V)}`),className:"flex-1",children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Atividade"]}),F&&e.jsxs(e.Fragment,{children:[e.jsx(w,{variant:"outline",size:"sm",onClick:()=>xs(V),children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>Ne(Y),disabled:Ve,title:"Trocar usuário",children:e.jsx(cl,{className:"h-4 w-4"})}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>De(Y),disabled:!Ue||Ve,title:Ue?"Despublicar link":"Link já inativo",children:e.jsx(Xt,{className:"h-4 w-4"})})]})]})]},Y.id||`${V}-${Q}`)})})]})}),e.jsxs(Ht,{value:"users",className:"space-y-4",children:[O?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Carregando agrupamento..."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Usuário"}),e.jsx(ue,{children:"Links"}),e.jsx(ue,{children:"Total de Pedidos"}),e.jsx(ue,{children:"Pedidos pagos"}),!fe&&e.jsx(ue,{children:"Receita atribuída"}),e.jsx(ue,{className:"text-right",children:"Ações"})]})}),e.jsx(Ct,{children:U.map(Y=>e.jsxs($s,{children:[e.jsx(ye,{children:Y.ownerName}),e.jsx(ye,{children:Y.linksCount}),e.jsx(ye,{children:Y.quantityPedidos}),e.jsx(ye,{children:Y.paidOrders}),!fe&&e.jsx(ye,{children:le.format(Y.attributedRevenue||0)}),e.jsx(ye,{className:"text-right",children:e.jsxs(w,{variant:"ghost",size:"sm",onClick:()=>hs(Y),disabled:f===Y.key,children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),f===Y.key?"Exportando...":"Exportar"]})})]},Y.key))})]})}),e.jsx("div",{className:"block md:hidden space-y-3",children:U.map(Y=>e.jsxs("div",{className:"border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium break-words",children:Y.ownerName}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Y.linksCount," links associados"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total de Pedidos"}),e.jsx("div",{className:"font-medium",children:Y.quantityPedidos})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Pedidos pagos"}),e.jsx("div",{className:"font-medium",children:Y.paidOrders})]}),!fe&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Receita atribuída"}),e.jsx("div",{className:"font-medium",children:le.format(Y.attributedRevenue||0)})]})]}),e.jsx("div",{className:"pt-2 border-t",children:e.jsxs(w,{variant:"outline",size:"sm",className:"w-full",onClick:()=>hs(Y),disabled:f===Y.key,children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"}),f===Y.key?"Exportando usuário...":"Exportar usuário"]})})]},Y.key))})]}),O&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Atualizando pedidos pagos e receita atribuída..."})]})]})})]})]})}function hu({link:s,initialDateRange:t="7",onDateRangeChange:a}){const n=Tr(),o=nr(),{toast:i}=mt(),{user:u}=Zt(),c=(u?.role?.name||u?.role?.type||u?.role?.code||"").toLowerCase().includes("externo"),m=r.useCallback(d=>{const _=String(d??"");return!c||!_||_.length<=4?_:`${_.slice(0,4)}${"*".repeat(_.length-4)}`},[c]),{data:x}=Ks("link-convites-dash-config","/pedido-dashboard-config",{staleTime:5*60*1e3,refetchOnWindowFocus:!1}),h=r.useMemo(()=>c?(x?.data?.attributes||x?.attributes||x||{})?.ocultar_valores_vendedores_externos===!0:!1,[c,x]),[p,f]=r.useState([]),[I,g]=r.useState(!0),[N,b]=r.useState(null),[C,q]=r.useState([]),[L,M]=r.useState(!1),[z,D]=r.useState(null),[E,A]=r.useState(null),[S,P]=r.useState(t||"7"),[F,ee]=r.useState("all"),[re,te]=r.useState("all"),[G,y]=r.useState("all"),[$,W]=r.useState(""),[ie,ke]=r.useState(""),[Ae,be]=r.useState("all"),[Fe,ae]=r.useState(0),[K,O]=r.useState(Date.now()),[oe,ve]=r.useState(0),me=r.useRef(null),[fe,le]=r.useState({}),[_e,U]=r.useState(""),[J,T]=r.useState(""),[Ee,Se]=r.useState(!1),[Ze,qe]=r.useState("overview"),[Qe,we]=r.useState(1),[Me,ks]=r.useState({total:null,pageCount:null,pageSize:null,loading:!1}),[xs,k]=r.useState(!1),De=5*60*1e3,Ne=!1,es=s?.id||s?.attributes?.id||null,ss=s?.documentId||s?.attributes?.documentId||null,We=s?.referral||s?.attributes?.referral||null,hs=s?.evento?.titulo||s?.attributes?.evento?.titulo||null;s?.used_count||s?.attributes?.used_count;const Is=r.useMemo(()=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",maximumFractionDigits:2}),[]),Y=[{value:"1",label:"Últimas 24h"},{value:"7",label:"Últimos 7 dias"},{value:"30",label:"Últimos 30 dias"},{value:"90",label:"Últimos 90 dias"},{value:"all",label:"Todo o período"}],Q=[{value:"all",label:"Todas as ações"},{value:"view",label:"Visualizações de página"},{value:"cta",label:"Cliques e CTAs"},{value:"checkout",label:"Etapas de checkout"},{value:"order",label:"Eventos de pedido"}],X=[{value:"all",label:"Todos os pedidos"},{value:"pago",label:"Pagos"},{value:"pendente",label:"Pendentes"},{value:"cancelado",label:"Cancelados / falhos"}],V=r.useMemo(()=>{const d=new Set;return p.forEach(_=>{_?.viewerName&&d.add(_.viewerName)}),Array.from(d).sort((_,H)=>_.localeCompare(H,"pt-BR"))},[p]);r.useEffect(()=>{if(!G.startsWith("name:"))return;const d=G.slice(5);V.includes(d)||y("all")},[G,V]),r.useEffect(()=>{Ee&&me.current&&me.current.focus(),Ee||W("")},[Ee]),r.useEffect(()=>{const d=setTimeout(()=>ke($),250);return()=>clearTimeout(d)},[$]),r.useEffect(()=>{typeof a=="function"&&a(S)},[S,a]),r.useEffect(()=>{const d=setInterval(()=>{const _=Math.max(0,K+7e3-Date.now());ve(_)},1e3);return()=>clearInterval(d)},[K]);const pe=()=>{P("7"),ee("all"),y("all"),W(""),te("all")},Ce=r.useCallback(d=>{const _=d?.id?String(d.id):"";_&&o(`/dashboard/pedidos?search=${encodeURIComponent(_)}`)},[o]),Ue=async()=>{try{k(!0);const d=us.map(Pe=>({ID:Pe.id||"—",Status:ft(Pe.status),"Valor (R$)":Number(Pe.subtotal||0),Data:Pe.createdAt?Us(Pe.createdAt,"dd/MM/yyyy",{locale:Vs}):"—",Hora:Pe.createdAt?Us(Pe.createdAt,"HH:mm",{locale:Vs}):"—"})),_=fs.map(Pe=>({"Data e hora":Pe.createdAt?Us(Pe.createdAt,"dd/MM/yyyy HH:mm",{locale:Vs}):"—",Visitante:Pe.viewerName||"Anônimo",Ação:Ve(Pe.action),Página:ts(Pe.page),Sessão:Pe.sessionId||"—",Componente:Le(Pe.metadata,Pe.action,Pe.page,Pe.eventLabel)})),H=To(We||"link"),ce=Us(new Date,"yyyy-MM-dd");await Xn({fileName:`link_${H}_${ce}.xlsx`,hideCurrency:h,sheets:[{name:"Resumo do link",columns:[{header:"Código",key:"Código",width:18},{header:"Evento",key:"Evento",width:24}
91,{header:"Período",key:"Período",width:18},{header:"Acessos monitorados",key:"Acessos monitorados",width:18},{header:"Pedidos no período",key:"Pedidos no período",width:18},{header:"Pedidos pendentes",key:"Pedidos pendentes",width:16},{header:"Pedidos cancelados/falhos",key:"Pedidos cancelados/falhos",width:22},{header:"Receita (R$)",key:"Receita (R$)",width:18}],rows:[{Código:We||"—",Evento:hs||"Evento geral",Período:Y.find(Pe=>Pe.value===S)?.label||"Período atual","Acessos monitorados":fs.length,"Pedidos no período":us.length,"Pedidos pendentes":us.filter(Pe=>!["pago","cancelado","falha","failed"].includes(String(Pe.status||"").toLowerCase())).length,"Pedidos cancelados/falhos":us.filter(Pe=>["cancelado","falha","failed"].includes(String(Pe.status||"").toLowerCase())).length,"Receita (R$)":Number((us||[]).reduce((Pe,Ie)=>String(Ie?.status||"").toLowerCase()!=="pago"?Pe:Pe+Number(Ie?.subtotal||0),0))}],currencyColumns:["Receita (R$)"]},{name:"Pedidos",columns:[{header:"ID",key:"ID",width:12},{header:"Status",key:"Status",width:14},{header:"Valor (R$)",key:"Valor (R$)",width:16},{header:"Data",key:"Data",width:12},{header:"Hora",key:"Hora",width:10}],rows:d,currencyColumns:["Valor (R$)"]},{name:"Atividades",columns:[{header:"Data e hora",key:"Data e hora",width:20},{header:"Visitante",key:"Visitante",width:24},{header:"Ação",key:"Ação",width:18},{header:"Página",key:"Página",width:28},{header:"Sessão",key:"Sessão",width:20},{header:"Componente",key:"Componente",width:32}],rows:_}]}),i({title:"Exportação concluída",description:`Relatório do link ${We||""} exportado.`})}catch(d){console.error("Falha ao exportar link",d),i({title:"Falha ao exportar",description:"Não foi possível gerar o Excel deste link.",variant:"destructive"})}finally{k(!1)}};r.useEffect(()=>{let d=!1;return(async()=>{try{const H=new URLSearchParams;H.set("pagination[pageSize]","100"),H.set("fields[0]","documentId"),H.set("fields[1]","titulo");const ce=await Yt.get(`${n}/eventos?${H.toString()}`,{headers:{Authorization:`Bearer ${localStorage.getItem("token")}`}});if(d)return;const Pe=Array.isArray(ce.data?.data)?ce.data.data:[],Ie={};Pe.forEach(Ye=>{const Ns=Ye?.attributes||Ye||{},_s=Ye?.id||Ns.id,Hs=Ns.documentId||Ns.document_id,Os=Ns.slug,B=Ns.titulo||Ns.title||"Evento";[_s,Hs,Os].filter(Boolean).map(de=>
91String(de)).forEach(de=>{Ie[de]=B})}),le(Ie)}catch(H){console.error("Erro ao carregar eventos para mapeamento",H)}})(),()=>{d=!0}},[n]);const Xe={view:d=>["view","page_view","landing"].includes(d),cta:d=>["cta","cta_click","cta_view","button_click","link_click"].includes(d),checkout:d=>["cart_add","add_to_cart","cart","cart_view","cart_open","cart_update","cart_remove","cart_clear","checkout_start","checkout_step","checkout_completed","payment_start","payment_attempt","payment_completed","payment_failed"].includes(d),order:d=>["order_created","order_paid","order_failed","pedido_criado"].includes(d)},Ve=(d="")=>{const _=d.toLowerCase();return["view","page_view","landing"].includes(_)?"Visualização":["cta","cta_click","cta_view","button_click","link_click"].includes(_)?"Clique / CTA":["cart_add","add_to_cart","cart","cart_view","cart_open"].includes(_)?"Itens adicionados":["cart_update"].includes(_)?"Atualização de carrinho":["cart_remove","cart_clear"].includes(_)?"Remoção do carrinho":["checkout_start","checkout_step","checkout_completed","payment_start","payment_attempt","payment_completed"].includes(_)?"Fluxo de checkout":["payment_failed"].includes(_)?"Falha no pagamento":["order_created","pedido_criado"].includes(_)?"Pedido criado":["order_paid","pedido_pago"].includes(_)?"Pedido pago":["order_failed","order.payment_failed"].includes(_)?"Falha no pagamento":_==="identify"?"Identificação de usuário":_==="identify_skip"?"Identificação ignorada":d||"Ação"},bs=(d="/")=>{const H=String(d||"").split("?")[0].split("/").filter(Boolean);if(H[0]==="eventos"&&H[1]){const ce=H[1];return fe[String(ce)]||null}return null},ts=(d="/")=>{if(!d)return"Página (indefinida)";const _=String(d).split("?")[0];if(_==="/"||_==="")return"Página inicial";if(_.startsWith("/eventos/")&&_.split("/").length>2){const H=bs(_);return H?`Evento: ${H}`:"Detalhe do evento"}return _==="/eventos"?"Lista de eventos":_==="/checkout"?"Checkout":_==="/cart"?"Carrinho":_==="/login"?"Login":_==="/signup"?"Cadastro":_.startsWith("/convite/")?"Landing do convite":_==="/perfil"?"Perfil do usuário":_.split("-").map(H=>H.charAt(0).toUpperCase()+H.slice(1)).join(" ")},R=(d={})=>{if(!d||typeof d!="object"||Object.keys(d).length===0)return["Sem detalhes"];const _={viewerName:"Nome do visitante",viewerEmail:"E-mail",viewerType:"Tipo do visitante",viewerUserId:"ID do usuário",viewerProfileId:"ID do perfil",componentId:"ID do componente",componentLabel:"Componente",viewerAutoLinked:"Perfil vinculado automaticamente",referral:"Código de indicação",referral_code:"Código de indicação",session_id:"Sessão",sessionId:"Sessão",page:"Página",action:"Ação",component:"Componente",evento:"Evento",eventoTitulo:"Evento",eventTitle:"Evento",eventDocumentId:"Evento",itemName:"Item",itemTitle:"Item",productName:"Produto",amount:"Valor",total:"Total",paymentMethod:"Método de pagamento",interactionType:"Tipo de interação",relX:"Posição X (relativa)",relY:"Posição Y (relativa)",elementWidth:"Largura do elemento (px)",elementHeight:"Altura do elemento (px)"},H=(Pe,Ie)=>{if(Ie===!0)return"Sim";if(Ie===!1)return"Não";if(Ie instanceof Date)return Us(Ie,"dd/MM/yyyy HH:mm",{locale:Vs});if(Array.isArray(Ie))return Ie.map(Ye=>H(Pe,Ye)).join(", ");if(typeof Ie=="object")return JSON.stringify(Ie);if((Pe==="relX"||Pe==="relY")&&typeof Ie=="number")return`${Math.round(Ie*100)}%`;if(Pe==="viewerType"){if(Ie==="logged_in")return"Logado";if(Ie==="anonymous")return"Anônimo"}return typeof Ie=="string"&&Pe==="page"?ts(Ie):typeof Ie=="string"&&(Pe==="evento"||Pe==="eventoTitulo"||Pe==="eventTitle"||Pe==="eventDocumentId")?fe[Ie]||null||Ie:String(Ie)},ce=new Set(["viewerName","viewer_name","viewerEmail","viewer_email","viewerUserId","viewerProfileId","name","nome","email","telefone","phone","whatsapp","cpf","documento"]);return Object.entries(d).filter(([Pe,Ie])=>Ie!=null&&Ie!=="").map(([Pe,Ie])=>{const Ye=_[Pe]||Pe.replace(/[_-]/g," ").replace(/\b\w/g,Hs=>Hs.toUpperCase()),Ns=H(Pe,Ie),_s=ce.has(Pe)?m(Ns):Ns;return`${Ye}: ${_s}`})},Le=(d={},_="",H="/",ce="")=>{if(!d||typeof d!="object")return"Seção não identificada";const Ie=[d.component,d.componentLabel,d.componentId,d.section,d.sectionName,d.pageSection,d.block,d.blockName,d.widget,d.modal,d.popup,d.banner,d.hero,d.cta,d.ctaLabel,d.cta_text,d.button,d.buttonLabel,d.itemName,d.itemTitle,d.productName,d.label,d.title,d.text,d.trackedId,d.trackingId,d.element,d.elementId,d.id,d.anch
91or,d.source,d.slot,d.evento,d.eventTitle,d.eventoTitulo].find(Ye=>typeof Ye=="string"&&Ye.trim().length);return Ie?ce&&!Ie.toLowerCase().includes(ce.toLowerCase())?`${Ie} · ${ce}`:Ie:d.page?ts(d.page):["page_view","view","landing"].includes(_)?`Página: ${ts(H)}`:"Seção não identificada"},as=(d,_={})=>{const H=d?.attributes||d||{},ce=(H.metadata&&typeof H.metadata=="object"?H.metadata:{})||{},Pe=H.createdAt||H.timestamp||H.updatedAt||null,Ie=H.viewer_name||H.viewerName||ce.viewerName||ce.viewer_name||ce.name||null,Ye=H.viewer_type||H.viewerType||ce.viewerType||(ce.viewerUserId?"logged_in":null),Ns=H.viewer_user_id||H.viewerUserId||ce.viewerUserId||null,_s=H.viewer_profile_id||H.viewerProfileId||ce.viewerProfileId||null;return{id:d?.id||H.id||`${H.session_id||"session"}-${H.action||"view"}-${Pe||Math.random()}`,action:(H.action||"view").toLowerCase(),page:H.page||ce.page||"/",sessionId:H.session_id||H.sessionId||null,metadata:ce,viewerName:Ie?m(Ie):null,viewerType:Ye||null,viewerUserId:Ns,viewerProfileId:_s,timeToConversion:H.time_to_conversion||H.timeToConversion||null,createdAt:Pe?new Date(Pe):null,eventLabel:_.eventoTitulo||_.eventTitle||null}},ms=d=>{const _=d?.attributes||d||{},H=_.data_pagamento||null,ce=H||_.createdAt||_.updatedAt||null,Pe=Number(_.subtotal)||0,Ie=Number(_.desconto_cupom)||0;let Ye=ce?new Date(ce):null;return Ye&&H&&(Ye=new Date(Ye.getTime()-3*60*60*1e3)),{id:d?.id||_.id,status:(_.status_pedido||_.status||"").toLowerCase(),total:Number(_.total)||0,subtotal:Number(Math.max(0,Pe-Ie).toFixed(2)),createdAt:Ye,usuarioId:_.usuario?.data?.id||_.usuario?.id||_.usuario?.data?.attributes?.id||null}},Ke=r.useCallback(async(d,_)=>{const H=localStorage.getItem("token"),ce=[],Pe=new Set;let Ie=1,Ye=null;const Ns=100,_s=(()=>{const Hs=Number(_.get("pagination[pageSize]"));return Number.isFinite(Hs)&&Hs>0?Hs:100})();for(;Ie<=Ns;){const Hs=new URLSearchParams(_.toString());Hs.set("pagination[page]",String(Ie));const Os=await Yt.get(`${n}/${d}?${Hs.toString()}`,{headers:{Authorization:`Bearer ${H}`}}),B=Array.isArray(Os.data?.data)?Os.data.data:Array.isArray(Os.data)?Os.data:[],de=Number(Os.data?.meta?.pagination?.pageCount);Number.isFinite(de)&&de>0&&(Ye=de);const Re=Number(Os.data?.meta?.pagination?.pageSize),He=Number.isFinite(Re)&&Re>0?Re:_s;let ps=0;if(B.forEach(vs=>{const Es=vs?.id??vs?.documentId??JSON.stringify(vs),cs=String(Es);Pe.has(cs)||(Pe.add(cs),ce.push(vs),ps+=1)}),Ye!=null&&Ie>=Ye||B.length===0||ps===0||Ye==null&&B.length<He)break;Ie+=1}return ce},[n]);r.useEffect(()=>{let d=!1;return(async()=>{if(!es&&!ss){f([]),q([]),g(!1),M(!1),b("Link inválido para consulta."),D(null);return}try{g(!0),M(!0),b(null),D(null);const H=new URLSearchParams;ss?H.set("filters[link_convite][documentId][$eq]",ss):es&&H.set("filters[link_convite][id][$eq]",es),H.set("sort","createdAt:desc"),H.set("pagination[pageSize]","200"),H.set("excludeSuperAdmin","true"),H.set("fields[0]","action"),H.set("fields[1]","page"),H.set("fields[2]","session_id"),H.set("fields[3]","timestamp"),H.set("fields[4]","time_to_conversion"),H.set("fields[5]","createdAt"),H.set("fields[6]","updatedAt"),H.set("fields[7]","metadata");const ce=new URLSearchParams;We&&(ce.set("excludeSuperAdmin","true"),ce.set("filters[referral_code][$eqi]",We),ce.set("sort","createdAt:desc"),ce.set("pagination[pageSize]","200"),ce.set("fields[0]","status_pedido"),ce.set("fields[1]","total"),ce.set("fields[2]","referral_code"),ce.set("fields[3]","createdAt"),ce.set("fields[4]","data_pagamento"),ce.set("fields[5]","subtotal"),ce.set("fields[6]","desconto_cupom"),ce.set("populate[usuario][fields][0]","id"));const[Pe,Ie]=await Promise.all([Ke("link-convite-activities",H),We?Ke("pedidos",ce):Promise.resolve([])]);if(d)return;f((Pe||[]).map(Ye=>as(Ye,{eventoTitulo:hs}))),q((Ie||[]).map(Ye=>ms(Ye)))}catch(H){if(d)return;console.error("Error fetching activity/orders",H),b("Não foi possível carregar as atividades deste link."),D("Não foi possível carregar os pedidos associados ao link."),f([]),q([])}finally{d||(g(!1),M(!1))}})(),()=>{d=!0}},[es,ss,We,Fe,Ke,hs]),r.useEffect(()=>{let d=!1;return(async()=>
91{if(!We){A(null);return}try{const H=localStorage.getItem("token"),ce=await Yt.get(`${n}/link-convites/activity-report`,{headers:{Authorization:`Bearer ${H}`},params:{referral:We,dateRange:S}});d||A(ce.data||null)}catch{d||A(null)}})(),()=>{d=!0}},[We,S,Fe,n]),r.useEffect(()=>{let d=!1;return(async()=>{if(Ze==="activity"&&!(!es&&!ss))try{ks(Ye=>({...Ye,loading:!0}));const H=localStorage.getItem("token"),ce=new URLSearchParams;ss?ce.set("filters[link_convite][documentId][$eq]",ss):es&&ce.set("filters[link_convite][id][$eq]",es),ce.set("sort","createdAt:desc"),ce.set("pagination[page]","1"),ce.set("pagination[pageSize]","1"),ce.set("excludeSuperAdmin","true"),ce.set("fields[0]","id");const Pe=await Yt.get(`${n}/link-convite-activities?${ce.toString()}`,{headers:{Authorization:`Bearer ${H}`}});if(d)return;const Ie=Pe?.data?.meta?.pagination||{};ks({total:Number.isFinite(Number(Ie.total))?Number(Ie.total):null,pageCount:Number.isFinite(Number(Ie.pageCount))?Number(Ie.pageCount):null,pageSize:Number.isFinite(Number(Ie.pageSize))?Number(Ie.pageSize):null,loading:!1})}catch(H){if(d)return;console.error("Erro ao carregar metadados de paginação das atividades",H),ks(ce=>({...ce,loading:!1}))}})(),()=>{d=!0}},[Ze,es,ss,n,Fe]);const gs=r.useMemo(()=>{if(S==="all")return null;const d=Number(S);if(!Number.isFinite(d)||d<=0)return null;const _=new Date;return _.setDate(_.getDate()-d),_},[S]),fs=r.useMemo(()=>{const d=ie.trim().toLowerCase();return p.filter(_=>{if(gs&&_.createdAt&&_.createdAt.getTime()<gs.getTime())return!1;if(F!=="all"){const H=Xe[F];if(H&&!H(_.action))return!1}if(G==="named"&&!_.viewerName||G==="anonymous"&&_.viewerName)return!1;if(G.startsWith("name:")){const H=G.slice(5).toLowerCase();if((_.viewerName||"").toLowerCase()!==H)return!1}return!(d&&!(_.viewerName||"").toLowerCase().includes(d)||Ae!=="all"&&(_.sessionId||`session-${_.id}`)!==Ae)})},[p,gs,F,G,ie,Ae]),Ms=50,Fs=Math.max(1,Math.ceil(fs.length/Ms));r.useEffect(()=>{we(1)},[S,F,G,ie,Ae]),r.useEffect(()=>{Qe>Fs&&we(Fs)},[Qe,Fs]);const As=r.useMemo(()=>{const d=(Qe-1)*Ms;return fs.slice(d,d+Ms)},[fs,Qe]),ws=r.useMemo(()=>[],[p,gs,G,ie,Ae,Ne]),Rs=r.useMemo(()=>{const d=Date.now(),_=new Map;return p.forEach(H=>{if(!H.createdAt||d-H.createdAt.getTime()>De)return;const ce=H.sessionId||`anon-${H.id}`,Pe=_.get(ce)||{sessionId:ce,viewerName:H.viewerName||null,lastSeen:H.createdAt,action:H.action};!Pe.viewerName&&H.viewerName&&(Pe.viewerName=H.viewerName),H.createdAt&&H.createdAt>Pe.lastSeen&&(Pe.lastSeen=H.createdAt,Pe.action=H.action),_.set(ce,Pe)}),Array.from(_.values()).sort((H,ce)=>ce.lastSeen-H.lastSeen)},[p]),us=r.useMemo(()=>C.filter(d=>gs&&d.createdAt&&d.createdAt.getTime()<gs.getTime()?!1:re==="all"?!0:re==="cancelado"?["cancelado","canceled","cancelled","failed","payment_failed"].includes(d.status):re==="pendente"?["pendente","pending","awaiting","aguardando"].includes(d.status||""):d.status===re),[C,gs,re]),Gs=Rs.length,Ss=r.useMemo(()=>{const d=new Set,_=new Set;fs.forEach(_s=>{d.add(_s.sessionId||`session-${_s.id}`),_s.viewerName&&_.add(_s.viewerName.trim().toLowerCase())});const H=fs.filter(_s=>["view","page_view","landing"].includes(_s.action)).length,ce=us.filter(_s=>_s.status==="pago"),Pe=us.filter(_s=>["pendente","pending","aguardando"].includes(_s.status)),Ie=us.filter(_s=>["cancelado","canceled","cancelled","failed","payment_failed"].includes(_s.status)),Ye=new Set(us.map(_s=>_s.usuarioId||_s.id)).size,Ns=us.reduce((_s,Hs)=>_s+(Hs.status==="pago"&&(Hs.subtotal||Hs.total)||0),0);return{activeUsers:d.size,identifiedVisitors:_.size,totalActions:fs.length,pageViews:H,totalOrders:us.length,paidOrders:ce.length,pendingOrders:Pe.length,canceledOrders:Ie.length,buyers:Ye,totalRevenue:Ns}},[fs,us]),ys=r.useMemo(()=>{const d=new Map;return fs.forEach(_=>{const H=_.page||"/",ce=d.get(H)||{page:H,count:0,sessions:new Set,lastSeen:null};ce.count+=1,_.sessionId&&ce.sessions.add(_.sessionId),_.createdAt&&(!ce.lastSeen||_.createdAt>ce.lastSeen)&&(ce.lastSeen=_.createdAt),d.set(H,ce)}),Array.from(d.values()).map(_=>({..._,sessions:_.sessions.size,label:ts(_.page)})).sort((_,H)=>H.count-_.count)},[fs,fe]),Ps=r.useMemo(()=>{const d=new Map;
91return fs.forEach(_=>{const H=Le(_.metadata,_.action,_.page,_.eventLabel),ce=d.get(H)||{component:H,count:0};ce.count+=1,d.set(H,ce)}),Array.from(d.values()).sort((_,H)=>H.count-_.count)},[fs]),Bs=r.useMemo(()=>{const d=new Map;return p.forEach(_=>{const H=Le(_.metadata,_.action,_.page,_.eventLabel);if(!H)return;const ce=d.get(H)||new Set;_.viewerName&&ce.add(_.viewerName),d.set(H,ce)}),d},[p]);r.useMemo(()=>{const d=Array.from({length:24},(_,H)=>`${String(H).padStart(2,"0")}h`);return{byComponent:{},hours:d}},[p]);const dt=r.useMemo(()=>{const d=Ie=>typeof Ie!="number"||Number.isNaN(Ie)?null:Math.min(1,Math.max(0,Ie)),_=Ie=>{if(typeof Ie=="number")return Ie;if(typeof Ie=="string"&&Ie.trim()!==""){const Ye=Number.parseFloat(Ie);return Number.isFinite(Ye)?Ye:null}return null},H=(Ie,Ye)=>{for(const Ns of Ye){const _s=_(Ie[Ns]);if(_s!==null)return d(_s)}return null},ce=Ie=>{const Ye=String(Ie||"").toLowerCase();return Ye.includes("hover")||Ye.includes("move")?"hover":"click"},Pe=new Map;return ws.forEach(Ie=>{const Ye=Ie.metadata||{},Ns=H(Ye,["relX","rel_x","pointerRelX","pointer_x","relativeX"]),_s=H(Ye,["relY","rel_y","pointerRelY","pointer_y","relativeY"]);if(Ns===null||_s===null)return;const Hs=Le(Ye,Ie.action,Ie.page,Ie.eventLabel);if(!Hs)return;const Os=`Página: ${ts(Ie.page||"/")}`,B={relX:Ns,relY:_s,interactionType:ce(Ye.interactionType||Ie.action),elementWidth:_(Ye.elementWidth),elementHeight:_(Ye.elementHeight),createdAt:Ie.createdAt,viewerName:Ie.viewerName||null,page:Ie.page||"/",metadata:Ye},de=Re=>{if(!Re)return;const He=Pe.get(Re)||[];He.push(B),Pe.set(Re,He)};Hs===Os?de(Hs):(de(Hs),de(Os))}),Pe},[ws]),Ts=r.useMemo(()=>{const d=new Map;return ws.forEach(_=>{const H=`Página: ${ts(_.page||"/")}`,ce=_.page||"/";d.has(H)||d.set(H,ce)}),d},[ws]),Mt=r.useMemo(()=>Array.from(dt.keys()).filter(d=>d.startsWith("Página: ")).sort(),[dt]),Ys=r.useMemo(()=>{const d=new Map;return dt.forEach((_,H)=>{if(!Array.isArray(_)||_.length===0)return;const ce=_.find(Pe=>Pe.page)||_[0];ce?.page&&d.set(H,ce.page)}),d},[dt]);r.useEffect(()=>{Ps.length?Ps.find(d=>d.component===_e)||U(Ps[0].component):U("")},[Ps,_e]),r.useEffect(()=>{if(!Mt.length){T("");return}Mt.includes(J)||T(Mt[0])},[Mt,J]);const ht=r.useMemo(()=>{const d=new Map,_=(H,ce)=>(d.has(H)||d.set(H,{date:H,label:Us(ce,"dd/MM",{locale:Vs}),actions:0,pageViews:0,orders:0,paidOrders:0,revenue:0,sessions:new Set}),d.get(H));return fs.forEach(H=>{if(!H.createdAt)return;const ce=H.createdAt.toISOString().slice(0,10),Pe=_(ce,H.createdAt);Pe.actions+=1,["view","page_view","landing"].includes(H.action)&&(Pe.pageViews+=1),H.sessionId&&Pe.sessions.add(H.sessionId)}),us.forEach(H=>{if(!H.createdAt)return;const ce=H.createdAt.toISOString().slice(0,10),Pe=_(ce,H.createdAt);Pe.orders+=1,H.status==="pago"&&(Pe.paidOrders+=1,Pe.revenue+=H.subtotal||H.total||0)}),Array.from(d.values()).map(H=>({...H,sessions:H.sessions.size})).sort((H,ce)=>ce.date.localeCompare(H.date))},[fs,us]);if(!es&&!ss||!We)return e.jsx("div",{className:"p-4 text-center text-muted-foreground",children:"Link inválido para consulta."});const ea=Y.find(d=>d.value===S)?.label||"período atual",Xs=r.useMemo(()=>_e?dt.get(_e)||[]:[],[dt,_e]);r.useMemo(()=>J?dt.get(J)||[]:[],[dt,J]),r.useMemo(()=>J&&Ts.get(J)||"/",[Ts,J]),r.useMemo(()=>_e&&Ys.get(_e)||"/",[Ys,_e]),r.useMemo(()=>{if(!_e)return{summary:{total:0,hover:0,click:0},points:[]};const d=Xs;if(!Array.isArray(d)||d.length===0)return{summary:{total:0,hover:0,click:0},points:[]};const _=(Ns="")=>{const _s=String(Ns).toLowerCase();return _s.includes("hover")||_s.includes("move")?"hover":"click"},H=Ns=>typeof Ns!="number"||Number.isNaN(Ns)?null:Math.min(1,Math.max(0,Ns)),ce={total:0,hover:0,click:0},Pe=new Map;d.forEach(Ns=>{const _s=_(Ns.interactionType||Ns.action),Hs=H(Number(Ns.relX??Ns.x)),Os=H(Number(Ns.relY??Ns.y));if(Hs===null||Os===null)return;ce.total+=1,ce[_s]+=1;const B=`${_s}:${Math.round(Hs*100)}:${Math.round(Os*100)}`,de=Pe.get(B)||{x:Hs,y:Os,count:0,type:_s};de.count+=1,Pe.set(B,de)});const Ie=Array.from(Pe.values()).reduce((Ns,_s)=>Math.max(Ns,_s.count),0)||1,Ye=Array.from(Pe.values()).map(Ns=>({...Ns,intensity:Ns.count/Ie}));return{summary:ce,points:Ye}},[_e,Xs]);const xt=r.useCallback((d,_)=>e.jsx(Ct,{children:Array.from({length:d}).map((H,ce)=>e.jsx($s,{className:"opacity-80",children:Array.from({length:_}).map((Pe,Ie)=>e.jsx(ye,{children:e.jsx(ut,{className:"h-4 w-full"})},`skeleton-cell-${ce}-${Ie}`))},`skeleton-row-${ce}`))}),[]),ia=p.length>0,st=!!E&&!ia&&!(F!=="all"||G!=="all"||!!ie||Ae!=="all"||re!=="all"),wt=st&&E.stats?E.stats:Ss,va=st&&Array.isArray(E.pageBreakdown)?E.pageBreakdown.map(d=>({...d,label:ts(d.page)})):ys,la=[{title:"Usuários ativos",value:wt.activeUsers.toLocaleStr
91ing("pt-BR"),hint:`${ea.toLowerCase()}`},{title:"Visitantes identificados",value:wt.identifiedVisitors.toLocaleString("pt-BR"),hint:"Nomes informados no período"},{title:"Acessos monitorados",value:wt.totalActions.toLocaleString("pt-BR"),hint:`${wt.pageViews} visualizações de página`},{title:"Pedidos criados",value:wt.totalOrders.toLocaleString("pt-BR"),hint:`${wt.buyers} compradores únicos`},...h?[]:[{title:"Receita atribuída",value:Is.format(wt.totalRevenue||0),hint:`${wt.paidOrders} pedidos pagos`}],{title:"Pedidos pendentes",value:wt.pendingOrders.toLocaleString("pt-BR"),hint:"Inclui aguardando pagamento"},{title:"Pedidos cancelados/falhos",value:wt.canceledOrders.toLocaleString("pt-BR"),hint:"Falhas ou cancelamentos do gateway"}],da=la.slice(0,3),Tt=la.slice(3),Js=I&&p.length===0&&!st,Ft=L&&C.length===0,ba=I&&p.length===0;let Kt="";Me.loading?Kt=" • conferindo paginação...":Number.isFinite(Me.total)&&(Kt=` • total backend: ${Me.total.toLocaleString("pt-BR")}`);const _t=(Js||Ft)&&ht.length===0,ca=Js&&ys.length===0,Na=Ft&&us.length===0,Qt=r.useMemo(()=>S!=="7"||F!=="all"||G!=="all"||!!$.trim()||re!=="all",[S,F,G,$,re]),ua=r.useMemo(()=>{const d=[];return S!=="7"&&d.push(Y.find(_=>_.value===S)?.label||"Período customizado"),F!=="all"&&d.push(Q.find(_=>_.value===F)?.label||"Ações filtradas"),G!=="all"?G.startsWith("name:")?d.push(`Visitante: ${G.slice(5)}`):d.push(G==="named"?"Somente identificados":"Somente anônimos"):$.trim()&&d.push(`Busca: ${$.trim()}`),re!=="all"&&d.push(X.find(_=>_.value===re)?.label||"Status filtrado"),d.join(" · ")||"Sem filtros adicionais"},[S,F,G,$,re,Y,Q,X]),pt=r.useMemo(()=>{const d={total:us.length,paid:0,pending:0,canceled:0,revenue:0};return us.forEach(_=>{if(!_)return;const H=_.status||"";["pago","paid","completed","success"].includes(H)?(d.paid+=1,d.revenue+=_.subtotal||_.total):["pendente","pending","awaiting","aguardando"].includes(H)?d.pending+=1:["cancelado","canceled","failed","cancelled","payment_failed"].includes(H)&&(d.canceled+=1)}),d},[us]),ft=(d="")=>{const _=d.toLowerCase();return["pago","paid","completed","success"].includes(_)?"Pago":["pendente","pending","awaiting","aguardando"].includes(_)?"Pendente":["cancelado","canceled","failed","cancelled","payment_failed"].includes(_)?"Cancelado":_||"—"},Wt=(d="")=>{const _=d.toLowerCase();return["pago","paid","completed","success"].includes(_)?"default":["pendente","pending","awaiting","aguardando"].includes(_)?"secondary":["cancelado","canceled","failed","cancelled","payment_failed"].includes(_)?"destructive":"outline"},ya=va[0],Dt=Ps[0],gt=us[0];return e.jsxs("div",{className:"space-y-6 pb-24 sm:pb-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Resumo do link"}),e.jsx("p",{className:"text-lg font-semibold break-all",children:We}),e.jsx("p",{className:"text-sm text-muted-foreground break-words",children:hs&&`Evento: ${hs}  `||""})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row flex-wrap items-stretch sm:items-center gap-2",children:[e.jsxs(w,{variant:"outline",size:"sm",className:"gap-2 w-full sm:w-auto",onClick:Ue,disabled:xs,children:[e.jsx(Oa,{className:"h-4 w-4"}),xs?"Exportando Excel...":"Exportar Excel"," "]}),e.jsxs(je,{variant:Gs>0?"default":"secondary",className:"text-center",children:["Online agora: ",Gs]}),e.jsxs(Sr,{children:[e.jsx(Ir,{asChild:!0,children:e.jsxs(w,{variant:"default",size:"sm",className:"gap-2 w-full sm:w-auto",children:[e.jsx(_m,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate",children:Ae==="all"?"Sessões (todas)":"Sessão em foco"})]})}),e.jsxs(Ar,{className:"w-[min(320px,90vw)]",children:[e.jsx(Vn,{children:"Sessões ao vivo"}),e.jsx(tt,{onSelect:()=>be("all"),children:"Todas as sessões"}),e.jsx(Gn,{}),Rs.length===0&&e.jsx(tt,{disabled:!0,children:"Sem visitantes online"}),Rs.map(d=>e.jsx(tt,{onSelect:()=>be(d.sessionId),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:d.viewerName||"Visitante"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[d.sessionId.slice(0,8)," · ",Ve(d.action||"view")]})]})},d.sessionId))]})]}),e.jsxs(fr,{open:Ee,onOpenChange:Se,children:[e.jsx(jr,{asChild:!0,children:e.jsxs(w,{variant:"default",size:"sm",className:"gap-2 w-full sm:w-auto",children:[e.jsx(Hd,{className:"h-4 w-4"}),"Filtros",e.jsx("span",{className:"hidden sm:inline text-xs text-muted-foreground truncate max-w-[140px]",children:ua})]})}),e.jsxs(ar,{className:"w-[min(360px,90vw)] space-y-4",align:"end",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Período"}),e.jsxs(rs,{value:S,onValueChange:P,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Selecione"})}),e.jsx(os,{children:Y.map(d=>e.jsx(xe,{value:d.value,children:d.label},d.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Ações observadas"}),e.jsxs(rs,{value:F,onValueChange:ee,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Todas as ações"})}),e.jsx(os,{children:Q.map(d=>e.jsx(xe,{value:d.value,children:d.label},d.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Visitantes"}),e.jsxs(rs,{value:G,onValueChange:y,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Visitantes"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),e.jsx(xe,{value:"named",children:"Identificados"}),e.jsx(xe,{value:"anonymous",children:"Anônimos"}),V.map(d=>e.jsx(xe,{value:`name:${d}`,children:d},d))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Buscar visitante"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Te,{ref:me,placeholder:"Nome ou parte do nome",value:$,onChange:d=>W(d.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{children:"Status de pedidos"}),e.jsxs(rs,{value:re,onValueChange:te,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Status"})}),e.jsx(os,{children:X.map(d=>e.jsx(xe,{value:d.value,children:d.label},d.value))})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[e.jsx(w,{variant:"ghost",size:"sm",onClick:pe,children:"Limpar filtros"}),e.jsx(w,{size:"sm",onClick:()=>Se(!1),children:"Fechar"})]})]})]})]})]}),e.jsxs(Lr,{value:Ze,onValueChange:qe,className:"space-y-4",children:[e.jsxs(Mr,{className:"grid h-auto 
91sm:h-10 w-full grid-cols-2 sm:grid-cols-4 gap-2",children:[e.jsx(Gt,{value:"overview",children:"Visão Geral"}),e.jsx(Gt,{value:"behavior",children:"Comportamento"}),e.jsx(Gt,{value:"orders",children:"Pedidos"}),e.jsx(Gt,{value:"activity",children:"Atividades"})]}),e.jsxs(Ht,{value:"overview",className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-4 grid-cols-1 sm:grid-cols-2 xl:grid-cols-3",children:da.map(d=>e.jsxs(he,{children:[e.jsxs(Be,{className:"pb-2",children:[e.jsx(ze,{className:"text-sm text-muted-foreground break-words",children:Js?e.jsx("span",{className:"inline-block h-4 w-24 animate-pulse rounded bg-muted"}):d.title}),e.jsx(Jt,{className:"break-words",children:Js?e.jsx("span",{className:"inline-block h-4 w-32 animate-pulse rounded bg-muted"}):d.hint})]}),e.jsx(ge,{children:Js?e.jsx(ut,{className:"h-8 w-32"}):e.jsx("p",{className:"text-xl sm:text-2xl font-semibold break-words",children:d.value})})]},d.title))}),e.jsx("div",{className:"grid gap-4 grid-cols-2 xl:grid-cols-4",children:Tt.map(d=>e.jsxs(he,{children:[e.jsxs(Be,{className:"pb-2",children:[e.jsx(ze,{className:"text-sm text-muted-foreground break-words",children:Js?e.jsx("span",{className:"inline-block h-4 w-24 animate-pulse rounded bg-muted"}):d.title}),e.jsx(Jt,{className:"break-words",children:Js?e.jsx("span",{className:"inline-block h-4 w-32 animate-pulse rounded bg-muted"}):d.hint})]}),e.jsx(ge,{children:Js?e.jsx(ut,{className:"h-8 w-32"}):e.jsx("p",{className:"text-xl sm:text-2xl font-semibold break-words",children:d.value})})]},d.title))})]}),e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Insights rápidos"}),e.jsx(Jt,{children:"Principais destaques do período"})]}),e.jsx(ge,{children:e.jsxs("dl",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Página mais acessada"}),e.jsx("dd",{className:"font-medium break-words",children:Js?e.jsx(ut,{className:"h-4 w-48"}):ya?`${ya.label} · ${ya.count} visitas`:"Sem dados no período"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Componente em alta"}),e.jsx("dd",{className:"font-medium break-words",children:Js?e.jsx(ut,{className:"h-4 w-48"}):Dt?`${Dt.component} · ${Dt.count} interações`:"Sem componentes monitorados"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Último pedido"}),e.jsx("dd",{className:"font-medium break-words",children:Ft?e.jsx(ut,{className:"h-4 w-48"}):gt?`${ft(gt.status)}${h?"":` · ${Is.format(gt.subtotal)}`} · ${gt.createdAt?Us(gt.createdAt,"dd/MM HH:mm",{locale:Vs}):"—"}`:"Nenhum pedido registrado"})]})]})})]})]}),e.jsxs(Ht,{value:"behavior",className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(he,{className:"min-w-0",children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Desempenho diário"}),e.jsx(Jt,{children:"Visitas, pedidos e receita por dia"})]}),e.jsx(ge,{className:"space-y-2",children:_t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Dia"}),e.jsx(ue,{children:"Sessões"}),e.jsx(ue,{children:"Ações"}),e.jsx(ue,{children:"Pedidos"}),e.jsx(ue,{children:"Pagos"}),!h&&e.jsx(ue,{children:"Receita"})]})}),xt(4,h?5:6)]})}),e.jsx("div",{className:"md:hidden space-y-3",children:Array.from({length:4}).map((d,_)=>e.jsxs("div",{className:"rounded-lg border p-3 space-y-2",children:[e.jsx(ut,{className:"h-4 w-32"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ut,{className:"h-4 w-full"}),e.jsx(ut,{className:"h-4 w-full"}),e.jsx(ut,{className:"h-4 w-full"}),e.jsx(ut,{className:"h-4 w-full"})]}),e.jsx(ut,{className:"h-4 w-28"})]},`daily-skel-${_}`))})]}):ht.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"whitespace-nowrap",children:"Dia"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Sessões"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Ações"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Pedidos"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Pagos"}),!h&&e.jsx(ue,{className:"whitespace-nowrap",children:"Receita"})]})}),e.jsx(Ct,{children:ht.map(d=>e.jsxs($s,{children:[e.jsx(ye,{className:"whitespace-nowrap",children:d.label}),e.jsx(ye,{children:d.sessions}),e.jsx(ye,{children:d.actions}),e.jsx(ye,{children:d.orders}),e.jsx(ye,{children:d.paidOrders}),!h&&e.jsx(ye,{className:"whitespace-nowrap",children:Is.format(d.revenue||0)})]},d.date))})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:ht.map(d=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium break-words",children:d.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Resumo do dia"})]}),!h&&e.jsx("div",{className:"text-sm font-semibold whitespace-nowrap",children:Is.format(d.revenue||0)})]}),e.jsxs("dl",{className:"mt-3 grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Sessões"}),e.jsx("dd",{className:"font-medium",children:d.sessions})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Ações"}),e.jsx("dd",{className:"font-medium",children:d.actions})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Pedidos"}),e.jsx("dd",{className:"font-medium",children:d.orders})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Pagos"}),e.jsx("dd",{className:"font-medium",children:d.paidOrders})]})]})]},d.date))})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:L?"Carregando pedidos...":"Sem dados para o período selecionado."})})]}),e.jsxs(he,{className:"min-w-0",children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Páginas mais visitadas"}),e.jsx(Jt,{children:"Principais rotas acessadas pelo link"})]}),e.jsx(ge,{children:ca?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Página"}),e.jsx(ue,{children:"Visitas"}),e.jsx(ue,{children:"Usuários"}),e.jsx(ue,{children:"Último acesso"})]})}),xt(4,4)]})}),e.jsx("div",{className:"md:hidden space-y-3",children:Array.from({length:4}).map((d,_)=>e.jsxs("div",{className:"rounded-lg border p-3 space-y-2",children:[e.jsx(ut,{className:"h-4 w-48"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ut,{className:"h-4 w-full"}),e.jsx(ut,{className:"h-4 w-full"})]}),e.jsx(ut,{className:"h-3 w-28"})]},`pages-skel-${_}`))})]}):ys.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Nenhum acesso registrado."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"whitespace-nowrap",children:"Página"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Visitas"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Usuários"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Último acesso"})]})}),e.jsx(Ct,{children:ys.slice(0,6).map(d=>e.jsxs($s,{children:[e.jsx(ye,{className:"min-w-[200px]",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"break-words",children:d.label}),e.jsx("span",{className:"text-xs text-muted-foreground break-all",children:d.page})]})}),e.jsx(ye,{className:"whitespace-nowrap",children:d.count}),e.jsx(ye,{className:"whitespace-nowrap",children:d.sessions}),e.jsx(ye,{className:"whitespace-nowrap",children:d.lastSeen?Us(d.lastSeen,"dd/MM HH:mm",{locale:Vs}):"—"})]},d.page))})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:ys.slice(0,6).map(d=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium break-words",children:d.label}),e.jsx("p",{className:"text-xs text-muted-foreground break-all",children:d.page})]}),e.jsxs("dl",{className:"mt-3 grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Visitas"}),e.jsx("dd",{className:"font-medium",children:d.count})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Usuários"}),e.jsx("dd",{className:"font-medium",children:d.sessions})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Último acesso"}),e.jsx("dd",{className:"font-medium",children:d.lastSeen?Us(d.lastSeen,"dd/MM HH:mm",{locale:Vs}):"—"})]})]})]},d.page))})]})})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Componentes monitorados"}),e.jsx(Jt,{children:"Interações agrupadas por componente rastreado"})]}),e.jsx(ge,{className:"space-y-4 overflow-hidden",children:Ps.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sem componentes identificados no período."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2 min-w-0",children:Ps.slice(0,3).map(d=>{const _=Bs.get(d.component)?.size||0;return e.jsxs("div",{className:"flex items-center justify-between rounded-md border px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium",children:d.component}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[_," visitantes · ",d.count," interações"]})]}),e.jsx(je,{variant:"secondary",children:"Top"})]},d.component)})}),Ps.length>3&&e.jsxs(fr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx(w,{variant:"outline",size:"sm",children:"Ver lista completa"})}),e.jsxs(ar,{className:"w-[min(360px,90vw)] space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Demais componentes monitorados"}),e.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:Ps.slice(3).map(d=>{const _=Bs.get(d.component)?.size||0;return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{children:d.component}),e.jsxs("span",{className:"text-muted-foreground",children:[_," vis. · ",d.count," eventos"]})]},`${d.component}-extra`)})})]})]})]})})]})]}),e.jsxs(Ht,{value:"orders",className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 grid-cols-1 md:grid-cols-2",children:[e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Resumo de pedidos"}),e.jsx(Jt,{children:"Totais filtrados pelo período atual"})]}),e.jsx(ge,{children:e.jsxs("dl",{className:"grid gap-3 text-sm grid-cols-2 sm:grid-cols-3",style:{gridTemplateColumns:"repeat(auto-fit, minmax(100px, 1fr))"},children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Pedidos totais"}),e.jsx("dd",{className:"text-lg font-semibold",children:pt.total})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Pagos"}),e.jsx("dd",{className:"text-lg font-semibold",children:pt.paid})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Pendentes"}
91),e.jsx("dd",{className:"text-lg font-semibold",children:pt.pending})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Cancelados"}),e.jsx("dd",{className:"text-lg font-semibold",children:pt.canceled})]}),!h&&e.jsxs("div",{children:[e.jsx("dt",{children:"Receita registrada"}),e.jsx("dd",{className:"text-lg font-semibold",children:Is.format(pt.revenue)})]})]})})]}),e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Último pedido"}),e.jsx(Jt,{className:"break-words",children:gt?gt.createdAt?Us(gt.createdAt,"dd/MM HH:mm",{locale:Vs}):"Registro sem data":"Nenhum pedido associado"})]}),e.jsx(ge,{children:gt?e.jsxs("dl",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Status"}),e.jsx("dd",{children:e.jsx(je,{variant:Wt(gt.status),children:ft(gt.status)})})]}),!h&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Valor"}),e.jsx("dd",{className:"font-medium break-words",children:Is.format(gt.subtotal)})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1",children:[e.jsx("dt",{className:"text-muted-foreground",children:"ID"}),e.jsx("dd",{className:"font-mono text-xs break-all",children:gt.id||"—"})]})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Ainda não há pedidos registrados para este link."})})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Pedidos associados"}),e.jsx(Jt,{children:"Lista de pedidos vinculados ao código"})]}),e.jsxs(ge,{children:[z&&e.jsx("div",{className:"text-sm text-destructive",children:z}),Na?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Data"}),e.jsx(ue,{children:"Status"}),!h&&e.jsx(ue,{children:"Valor"}),e.jsx(ue,{children:"ID"}),e.jsx(ue,{children:"Ações"})]})}),xt(5,h?3:4)]})}),e.jsx("div",{className:"md:hidden space-y-3",children:Array.from({length:5}).map((d,_)=>e.jsxs("div",{className:"rounded-lg border p-3 space-y-2",children:[e.jsx(ut,{className:"h-4 w-36"}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(ut,{className:"h-5 w-20"}),e.jsx(ut,{className:"h-4 w-24"})]}),e.jsx(ut,{className:"h-3 w-40"})]},`orders-skel-${_}`))})]}):us.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:L?"Carregando pedidos...":"Nenhum pedido no período."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"whitespace-nowrap",children:"Data"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Status"}),!h&&e.jsx(ue,{className:"whitespace-nowrap",children:"Valor"}),e.jsx(ue,{className:"whitespace-nowrap",children:"ID"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Ações"})]})}),e.jsx(Ct,{children:us.slice(0,50).map(d=>e.jsxs($s,{children:[e.jsx(ye,{className:"whitespace-nowrap",children:d.createdAt?Us(d.createdAt,"dd/MM HH:mm",{locale:Vs}):"—"}),e.jsx(ye,{children:e.jsx(je,{variant:Wt(d.status),children:ft(d.status)})}),!h&&e.jsx(ye,{className:"whitespace-nowrap",children:Is.format(d.subtotal)}),e.jsx(ye,{className:"font-mono text-xs whitespace-nowrap",children:d.id||"—"}),e.jsx(ye,{children:e.jsx(w,{variant:"link",size:"sm",className:"h-auto p-0 text-secondary-foreground",onClick:()=>Ce(d),children:"Ir até o pedido"})})]},d.id))})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:us.slice(0,50).map(d=>e.jsxs(w,{type:"button",variant:"ghost",className:"h-auto w-full rounded-lg border p-3 text-left",onClick:()=>Ce(d),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium whitespace-nowrap",children:d.createdAt?Us(d.createdAt,"dd/MM HH:mm",{locale:Vs}):"—"}),e.jsx("p",{className:"text-xs text-muted-foreground break-words",children:"Pedido"})]}),!h&&e.jsx("div",{className:"text-sm font-semibold whitespace-nowrap",children:Is.format(d.total)})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsx(je,{variant:Wt(d.status),children:ft(d.status)}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground break-all",children:d.id||"—"})]})]},d.id))})]})]})]})]}),e.jsx(Ht,{value:"activity",className:"space-y-4",children:e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsx(ze,{children:"Atividades recentes"}),e.jsxs(Jt,{children:["Últimas interações vinculadas ao link",Kt]})]}),e.jsxs(ge,{children:[ba&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Data/Hora"}),e.jsx(ue,{children:"Visitante"}),e.jsx(ue,{children:"Ação"}),e.jsx(ue,{children:"Página"}),e.jsx(ue,{children:"Componente"}),e.jsx(ue,{children:"Sessão"}),e.jsx(ue,{children:"Detalhes"})]})}),xt(6,7)]})}),e.jsx("div",{className:"md:hidden space-y-3",children:Array.from({length:6}).map((d,_)=>e.jsxs("div",{className:"rounded-lg border p-3 space-y-2",children:[e.jsx(ut,{className:"h-4 w-36"}),e.jsx(ut,{className:"h-4 w-48"}),e.jsx(ut,{className:"h-4 w-28"}),e.jsx(ut,{className:"h-3 w-full"})]},`act-skel-${_}`))})]}),!ba&&N&&e.jsx("div",{className:"text-center text-sm text-destructive",children:N}),!ba&&!N&&fs.length===0&&e.jsx("div",{className:"text-center text-sm text-muted-foreground",children:I?"Atualizando atividades...":"Nenhuma atividade registrada no período."}),!ba&&!N&&fs.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"whitespace-nowrap",children:"Data/Hora"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Visitante"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Ação"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Página"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Componente"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Sessão"}),e.jsx(ue,{className:"whitespace-nowrap",children:"Detalhes"})]})}),e.jsx(Ct,{children:As.map(d=>{const _=d.sessionId||`session-${d.id}`,H=Ae!=="all"&&_===Ae;return e.jsxs($s,{className:H?"bg-primary/5":"",children:[e.jsx(ye,{className:"whitespace-nowrap",children:d.createdAt?Us(d.createdAt,"dd/MM HH:mm",{locale:Vs}):"—"}),e.jsx(ye,{className:"min-w-[120px]",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"break-words",children:d.viewerName||"Anônimo"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d.viewerType==="logged_in"?"Logado":d.viewerName?"Identificado":"Visitante"})]})}),e.jsx(ye,{className:"whitespace-nowrap",children:Ve(d.action)}),e.jsx(ye,{className:"min-w-[180px]",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"break-words",children:ts(d.page)}),e.jsx("span",{className:"text-xs text-muted-foreground break-all",children:d.page})]})}),e.jsx(ye,{className:"min-w-[150px] break-words",children:Le(d.metadata,d.action,d.page,d.eventLabel)}),e.jsx(ye,{className:"font-mono text-xs whitespace-nowrap",children:_||"—"}),e.jsx(ye,{className:"text-xs text-muted-foreground max-w-[240px]",children:e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer text-primary",children:"Ver detalhes"}),e.jsx("div",{className:"mt-1 space-y-1",children:R(d.metadata).map((ce,Pe)=>e.jsx("div",{className:"leading-tight break-words",children:ce},Pe))})]})})]},d.id)})})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:As.map(d=>{const _=d.sessionId||`session-${d.id}`,H=Ae!=="all"&&_===Ae;return e.jsxs("div",{className:`rounded-lg border p-3 ${H?"bg-primary/5":""}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium whitespace-nowrap",children:d.createdAt?Us(d.createdAt,"dd/MM HH:mm",{locale:Vs}):"—"}),e.jsxs("p",{className:"text-xs text-muted-foreground break-words",children:[d.viewerName||"Anônimo"," · ",Ve(d.action)]})]}),e.jsx("span",{className:"font-mono text-[10px] text-muted-foreground break-all text-right max-w-[50%]",children:_||"—"})]}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Página"}),e.jsx("p",{className:"font-medium break-words",children:ts(d.page)}),e.jsx("p",{className:"text-xs text-muted-foreground break-all",children:d.page})]}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Componente"}),e.jsx("p",{className:"font-medium break-words",children:Le(d.metadata,d.action,d.page,d.eventLabel)})]}),e.jsxs("details",{className:"text-sm",children:[e.jsx("summary",{className:"cursor-pointer text-primary",children:"Ver detalhes"}),e.jsx("div",{className:"mt-2 space-y-1 text-xs text-muted-foreground",children:R(d.metadata).map((ce,Pe)=>e.jsx("div",{className:"leading-tight break-words",children:ce},Pe))})]})]})]},d.id)})}),fs.length>Ms&&e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Página ",Qe," de ",Fs," · ",fs.length.toLocaleStr
91ing("pt-BR")," atividades"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{variant:"outline",size:"sm",onClick:()=>we(d=>Math.max(1,d-1)),disabled:Qe===1,children:"Anterior"}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>we(d=>Math.min(Fs,d+1)),disabled:Qe===Fs,children:"Próxima"})]})]})]})]})]})})]}),Ne,Ne]})}hu.propTypes={link:se.object,initialDateRange:se.string,onDateRangeChange:se.func};function Pf(){const{codigo:s}=_i(),t=nr(),a=Tr(),[n,o]=r.useState(null),[i,u]=r.useState(!0),[l,c]=r.useState(null),[m,x]=r.useState("7");r.useEffect(()=>{let I=!1;return(async()=>{if(!s){c("Código de link inválido."),u(!1);return}try{u(!0),c(null);const N=new URLSearchParams;N.set("filters[referral][$eqi]",s),N.set("fields[0]","id"),N.set("fields[1]","documentId"),N.set("fields[2]","referral"),N.set("populate[evento][fields][0]","titulo"),N.set("populate[evento][fields][1]","documentId"),N.set("pagination[pageSize]","1");const b=await Yt.get(`${a}/link-convites?${N.toString()}`,{headers:{Authorization:`Bearer ${localStorage.getItem("token")}`}});if(I)return;const C=Array.isArray(b.data?.data)?b.data.data:[];C.length?o(C[0]):(c("Nenhum link encontrado para este código."),o(null))}catch(N){if(I)return;console.error("Erro ao carregar link de convite",N),c("Não foi possível carregar os dados deste link."),o(null)}finally{I||u(!1)}})(),()=>{I=!0}},[s,a]);const h=s||n?.referral||n?.attributes?.referral||"—",p=(()=>{try{return new URLSearchParams(globalThis?.location?.search||"").get("dateRange")||"7"}catch{return"7"}})();r.useEffect(()=>{x(p)},[p]);const f={1:"Últimas 24h",7:"Últimos 7 dias",30:"Últimos 30 dias",90:"Últimos 90 dias",all:"Todo o período"}[m]||"Últimos 7 dias";return n?.evento?.titulo||n?.attributes?.evento?.titulo,e.jsxs("div",{className:"space-y-4",children:[e.jsx(w,{variant:"outline",size:"sm",onClick:()=>t("/dashboard/link-convites"),children:"Voltar para links"}),e.jsxs(he,{className:"border-primary/20 shadow-sm",children:[e.jsx(Be,{className:"flex flex-col gap-2 md:flex-row md:items-center md:justify-between",children:e.jsxs("div",{children:[e.jsx(ze,{className:"text-lg",children:"Atividade do Link"}),e.jsx(Jt,{children:h}),e.jsxs("span",{className:"text-sm text-foreground flex flex-row items-center justify-start",children:[e.jsx("span",{className:"text-destructive text-2xl",children:"•"}),f]})]})}),e.jsxs(ge,{children:[i&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Carregando link..."}),l&&!i&&e.jsx("div",{className:"text-sm text-destructive",children:l}),!i&&!l&&n&&e.jsx(hu,{link:n,initialDateRange:p,onDateRangeChange:x})]})]})]})}const Ka=Tr(),Qa=()=>localStorage.getItem("token"),Rf="/eventos?pagination[pageSize]=200&sort=titulo:asc&populate[datas_futuras]=true&populate[datas_passadas]=true&populate[lotes][populate][tipo_ingresso]=true&populate[tipos_ingresso][populate][tipo_ingresso]=true",Tf="/usuarios/sellers?pagination[pageSize]=200",$f="/link-pedidos?sort=createdAt:desc&populate[installments]=true&populate[evento]=true&populate[tipo_ingresso]=true&populate[target_usuario]=true&populate[created_by_usuario]=true",Mn=s=>{if(s==null)return null;const t=String(s).trim();if(!t||t==="null"||t==="undefined")return null;const a=Number(t);return Number.isInteger(a)&&a>0?a:null},Lt=s=>{const t=Number(String(s||"").replace(",","."));return Number.isFinite(t)?t:0},ct=s=>Number(s||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),Lf=(s,t)=>{const a=String(s||"").replace(/\D/g,"");return a?`https://wa.me/${a}?text=${encodeURIComponent(t)}`:null},wd={pix:"PIX",credit:"Crédito",credito:"Crédito",pix_credit:"PIX ou Crédito"},Fn=s=>{if(!s)return"pending";if(s.status==="pago")return"paid";if(s.status==="falha"||s.refund_status==="requested")return"late";if(s.expires_at){const t=new Date(`${String(s.expires_at).slice(0,10)}T23:59:59`);if(!Number.isNaN(t.getTime())&&t.getTime()<Date.now())return"late"}return"pending"},_d={paid:"Pago",late:"Vencida",current:"Atual",pending:"Pendente"},Mf={requested:"Reembolso solicitado",refunded:"Reembolsado",rejected:"Recusado"},Qr=s=>{if(!s)return null;const t=String(s).slice(0,10),[a,n,o]=t.split("-");return!a||!n||!o?null:new Date(parseInt(a),parseInt(n)-1,parseInt(o)).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})};function Cd(){const{toast:s}=mt(),{user:t}
91=Zt(),a=Fd(),n=nr(),[o]=Od(),i=a.pathname.endsWith("/criar"),u=()=>n("/dashboard/link-vendas"),l=d=>n(`/dashboard/link-vendas/criar${d?`?edit=${d}`:""}`),c=r.useMemo(()=>{const d=String(t?.role?.type||t?.role?.name||t?.role?.code||"").toLowerCase().replace(/[\s_-]+/g,"");return d.includes("admin")||d.includes("super")},[t]),[m,x]=r.useState(""),[h,p]=r.useState(""),[f,I]=r.useState(null),[g,N]=r.useState(""),[b,C]=r.useState(1),[q,L]=r.useState(!1),[M,z]=r.useState(""),[D,E]=r.useState(2),[A,S]=r.useState([]),[P,F]=r.useState(null),[ee,re]=r.useState(""),[te,G]=r.useState(""),[y,$]=r.useState(""),[W,ie]=r.useState(""),[ke,Ae]=r.useState(""),[be,Fe]=r.useState("relative"),[ae,K]=r.useState(!1),[O,oe]=r.useState(""),[ve,me]=r.useState(3),[fe,le]=r.useState("sem"),[_e,U]=r.useState(""),[J,T]=r.useState("percent"),[Ee,Se]=r.useState({}),[Ze,qe]=r.useState({}),[Qe,we]=r.useState(null),[Me,ks]=r.useState(null),[xs,k]=r.useState(""),[De,Ne]=r.useState(""),[es,ss]=r.useState(!1),[We,hs]=r.useState("todos"),[Is,Y]=r.useState(""),[Q,X]=r.useState("todos"),{data:V}=Ks(["eventos-link-vendas"],Rf),{data:pe,refetch:Ce}=Ks(["link-pedidos"],$f),{data:Ue}=Ks(["link-vendas-sellers"],Tf),{data:Xe}=Ks(["checkout-config"],"/config"),Ve=r.useMemo(()=>{const d=Xe?.data?.attributes||Xe?.data||Xe||{};return Qu(d)},[Xe]),bs=r.useMemo(()=>`${(Ve*100).toFixed(Ve*100%1===0?0:2).replace(".",",")}%`,[Ve]),ts=Array.isArray(V?.data)?V.data:[],R=Array.isArray(pe?.data)?pe.data:[],Le=(Array.isArray(Ue?.data)?Ue.data:[]).map(d=>({id:d.id,nome:d?.attributes?.nome||d?.nome||`Usuário ${d.id}`,email:d?.attributes?.email||d?.attributes?.user?.data?.attributes?.email||""})),as=d=>{const _=d?.attributes||d,H=Array.isArray(_?.installments)?_.installments:[],ce=_?.evento?.data||_?.evento||{},Pe=ce?.attributes||ce||{},Ie=ce?.documentId||Pe?.documentId||null,Ye=ce?.id??Pe?.id??null,Ns=Ie&&ts.find(Os=>(Os?.documentId||Os?.attributes?.documentId)===Ie)||Ye!=null&&ts.find(Os=>String(Os?.id)===String(Ye))||null;x(Ns?String(Ns.id):Ye!=null?String(Ye):""),p(String(_?.tipo_ingresso?.id||_?.tipo_ingresso?.data?.id||""));const _s=_?.lote_ref||{},Hs=_s?.data_evento||_?.data_evento;I(Hs?String(Hs).slice(0,10):null),N(_s?.id!=null?String(_s.id):""),C(_?.quantidade||1),L(!!_?.custom_price_enabled),z(_?.custom_price||""),S(H.map(Os=>({amount_base:Os.amount_base,payment_method:Os.payment_method||"pix",expires_at:Os.expires_at||"",payment_link_url:Os.payment_link_url||""}))),E(H.length||1),Ae(String(_?.target_usuario?.id||_?.target_usuario?.data?.id||"")),ie(_?.target_nome||""),$(_?.target_whatsapp||""),G(_?.target_email||""),re(_?.descricao||""),F(d.id)},ms=r.useRef(null);r.useEffect(()=>{if(!i){ms.current=null;return}const d=o.get("edit");if(!d){ms.current=null;return}if(ms.current===d)return;const _=R.find(H=>String(H.id)===String(d));_&&ts.length&&(as(_),ms.current=d)},[i,o,R,ts]);const Ke=r.useMemo(()=>{const d=Is.trim().toLowerCase();return R.filter(_=>{const H=_?.attributes||_,ce=Array.isArray(H?.installments)?H.installments:[];if(We!=="todos"&&String(H?.target_usuario?.id??H?.target_usuario?.data?.id??"")!==String(We))return!1;if(Q!=="todos"){const Pe=ce.length>0&&ce.every(Ie=>Ie?.status==="pago");if(Q==="quitado"&&!Pe||Q==="aberto"&&Pe)return!1}return!(d&&![H?.codigo,H?.evento?.titulo||H?.evento?.attributes?.titulo,H?.target_nome,H?.target_email,H?.target_whatsapp,H?.target_usuario?.username||H?.target_usuario?.nome].filter(Boolean).join(" ").toLowerCase().includes(d))})},[R,We,Q,Is]),gs=r.useMemo(()=>{let d=0,_=0,H=0,ce=0;return Ke.forEach(Pe=>{const Ie=Pe?.attributes||Pe,Ye=Array.isArray(Ie?.installments)?Ie.installments:[],Ns=Ye.filter(Os=>Os?.status==="pago"),_s=Ns.reduce((Os,B)=>Os+Lt(B?.amount_total),0),Hs=Lt(Ie?.total)||Ye.reduce((Os,B)=>Os+Lt(B?.amount_total),0);_+=_s,d+=Math.max(0,Hs-_s),(Ye.length===0||Ns.length<Ye.length)&&(ce+=1),H+=Ye.filter(Os=>Fn(Os)==="late"&&Os?.status!=="pago").length}),{aReceber:d,recebido:_,vencidas:H,ativos:ce}},[Ke]),fs=ts.find(d=>String(d?.id)===String(m))||null,Ms=r.useMemo(()=>fs?(Array.isArray(fs?.lotes?.data)?fs.lotes.data:Array.isArray(fs?.lotes)?fs.lotes:[]).map(yx):[],[fs]),Fs=r.useMemo(()=>
91{if(!fs)return[];const d=ce=>Ms.some(Pe=>Pe.ativo!==!1&&Pe.is_upsell!==!0&&(Pe.data_evento?String(Pe.data_evento).slice(0,10)===ce:!0)),_=Array.isArray(fs?.datas_futuras?.data)?fs.datas_futuras.data:Array.isArray(fs?.datas_futuras)?fs.datas_futuras:[],H=[];for(const ce of _){const Pe=ce?.attributes||ce||{};if(Pe.ativo===!1)continue;const Ie=Pe.data;if(!Ie)continue;const Ye=String(Ie).slice(0,10);d(Ye)&&H.push(Ye)}return[...new Set(H)].sort()},[fs,Ms]);r.useEffect(()=>{I(d=>d&&Fs.includes(String(d).slice(0,10))?d:Fs.length>0?Fs[0]:null)},[Fs]);const As=r.useMemo(()=>wx(Ms,f).filter(_=>_.ativo!==!1&&_.is_upsell!==!0),[Ms,f]);r.useEffect(()=>{N(d=>d&&As.some(_=>String(_.id)===String(d))?d:As.length>0?String(As[0].id):"")},[As]);const ws=r.useMemo(()=>g&&As.find(d=>String(d.id)===String(g))||null,[As,g]),Rs=r.useMemo(()=>ws?Mn(ws?.tipo_ingresso?.id??ws?.tipo_ingresso):null,[ws]),us=r.useMemo(()=>{if(!ws)return Lt(fs?.preco||0);const d=ws.preco_lote!=null?Number(ws.preco_lote):ws.tipo_ingresso?.preco_especifico??fs?.preco??0,_=Number(ws.desconto_percentual!=null?ws.desconto_percentual:ws.tipo_ingresso?.desconto_percentual??0);return Number(d)*(1-_/100)},[ws,fs]),Gs=r.useMemo(()=>us>0?Number((us*.25).toFixed(2)):0,[us]),Ss=r.useMemo(()=>{if(!q)return us;const d=Lt(M);return Gs>0?Math.max(d,Gs):d},[q,M,us,Gs]),ys=ws?.tipo_ingresso?.progressivo===!0,Ps=ys?Math.max(1,Number(ws?.tipo_ingresso?.quantidade_itens||1)):0,Bs=r.useMemo(()=>{const d=[],_=new Set;return As.forEach(H=>{if(H?.tipo_ingresso?.progressivo!==!0)return;const ce=Math.max(1,Number(H?.tipo_ingresso?.quantidade_itens||1));_.has(ce)||(_.add(ce),d.push({size:ce,lote:H}))}),d.sort((H,ce)=>H.size-ce.size)},[As]),dt=d=>{if(!Bs.length)return;const _=Math.max(1,Math.round(Number(d)||0));let H=Bs[0],ce=Math.abs(_-H.size);Bs.forEach(Pe=>{const Ie=Math.abs(_-Pe.size);(Ie<ce||Ie===ce&&Pe.size<H.size)&&(H=Pe,ce=Ie)}),N(String(H.lote.id)),C(H.size)},Ts=Bs.findIndex(d=>d.size===Ps),Mt=Bs[0]?.size??1,Ys=Bs[Bs.length-1]?.size??Mt,ht=d=>{if(!Bs.length)return;const _=Ts<0?0:Ts,H=Math.min(Bs.length-1,Math.max(0,_+d)),ce=Bs[H];N(String(ce.lote.id)),C(ce.size)};r.useEffect(()=>{ys&&C(Ps)},[g]);const ea=ys?1:Math.max(1,Number(b||1)),Xs=r.useMemo(()=>Ss*ea,[Ss,ea]),xt=r.useMemo(()=>{const d=Lt(_e);return!(d>0)||fe==="sem"?0:J==="percent"?Xs*(d/100):d},[_e,J,fe,Xs]),ia=r.useMemo(()=>fe==="desconto"?Math.max(0,Xs-xt):fe==="acrescimo_item"?Xs+xt:Xs,[fe,Xs,xt]),oa=r.useMemo(()=>fe==="acrescimo_taxa"?xt:0,[fe,xt]),st=r.useMemo(()=>Number((ia+oa).toFixed(2)),[ia,oa]),wt=r.useMemo(()=>Number((st*Ve).toFixed(2)),[st,Ve]),va=r.useMemo(()=>Number((st+wt).toFixed(2)),[st,wt]),la=d=>{const _=Math.max(1,Number(d||1)),H=st/_,ce=Array.from({length:_},(Pe,Ie)=>({amount_base:Number(H.toFixed(2)),payment_method:Ie===0?"pix":"credit",expires_at:null,payment_link_url:""}));S(ce)},da=(d,_,H)=>{S(ce=>ce.map((Pe,Ie)=>Ie===d?{...Pe,[_]:H}:Pe))},Tt=async()=>{if(!m){s({title:"Selecione um evento",variant:"destructive"});return}if(!Mn(g)){s({title:"Selecione a data e o lote",variant:"destructive"});return}if(!A.length){s({title:"Informe as parcelas",variant:"destructive"});return}try{const d={eventoId:m,loteId:Mn(g),data_evento:f||null,tipoIngressoId:Rs||null,quantidade:Number(b||1),custom_price_enabled:!0,custom_price:st,taxa_adicional:oa,installments:A.map(_=>({amount_base:Lt(_.amount_base),payment_method:_.payment_method,expires_at:_.expires_at||null,payment_link_url:_.payment_link_url||null})),expires_config:ae?{enabled:!0,mode:be,fixedDate:O||null,relativeDays:Number(ve||0)||null}:{enabled:!1},descricao:ee,target_email:te||null,target_whatsapp:y||null,target_nome:W||null,target_usuario:Mn(ke)};if(P)await Yt.put(`${Ka}/link-pedidos/${P}/installments`,d,{headers:{Authorization:`Bearer ${Qa()}`}}),s({title:"Parcelas atualizadas com sucesso"});else{const H=(await Yt.post(`${Ka}/link-pedidos/generate`,d,{headers:{Authorization:`Bearer ${Qa()}`}}))?.data?.matchedUsuario;s(H?{title:"Link criado e vinculado a um usuário",description:`Usuário encontrado: ${H.nome||`#${H.id}`}. O link ficará restrito a ele e aos gestores/vendedores.`}:{title:"Link criado com sucesso"})}Ce(),F(null),u()}catch(d){s({title:"Falha ao salvar link",description:d?.response?.data?.error?.message||d?.message,variant:"destructive"})}},Js=async(d,_)=>{const H=_||te;if(!H){s({title:"Informe o e-mail para envio",variant:"destructive"});return}try{await Yt.post(`${Ka}/link-pedidos/${encodeURIComponent(d)}/send`,{email:H},{headers:{Authorization:`Bearer ${Qa()}`}}),s({title:"E-mail enviado"})}catch(ce){s({title:"Falha ao enviar e-mail",description:ce?.response?.data?.error?.message||ce?.message,variant:"destructive"})}},[Ft,ba]=r.useState(null),Kt=async d=>{const ce=!((d?.attributes||d)?.disabled===!0);ba(d.id);try{await Yt.put(`${Ka}/link-pedidos/${d.id}/disabled`,{disabled:ce},{headers:{Authorization:`Bearer ${Qa()}`}}),await Ce(),s({title:ce?"Link desativado":"Link reativado"})}catch(Pe){s({title:ce?"Falha ao desativar link":"Falha ao reativar link",description:Pe?.response?.data?.error?.message||Pe?.message,variant:"destructive"})}finally{ba(null)}},[_t,ca]=r.useState(null),Na=async d=>{ca(d.id);try{const{data:_}=await Yt.put(`${Ka}/link-pedidos/${d.id}/sync-status`,{},{headers:{Authorization:`Bearer ${Qa()}`}});await Ce(),_?.changed?s({title:"Pagamento confirmado",description:_?.status_pedido==="pago"?"Todas as parcelas foram quitadas.":"Status das parcelas atualizado a partir do gateway."}):s({title:"Nenhuma mudança",description:_?.checked?"O gateway ainda não confirmou o pagamento das parcelas em aberto.":"Não há parcelas em aberto com cobrança gerada para consultar."})}catch(_){s({title:"Falha ao verificar pagamento",description:_?.response?.data?.error?.message||_?.message,variant:"destructive"})}finally{ca(null)}},Qt=(d,_)=>{d&&(navigator.clipboard?.writeText(d),s({title:_||"Copiado"}))},ua=(d,_,H)=>{qe(ce=>({...ce,[`${d}:${_}`]:H}))},pt=async d=>{const _=d?.attributes||d,H=Array.isArray(_?.installments)?_.installments:[],ce={Authorization:`Bearer ${Qa()}`},Pe=H.filter(Ie=>
91{if(!(Ie.status!=="pago"&&Ie.status!=="cancelado"))return!1;const Ns=`${d.id}:${Ie.installment_index}`;return Ns in Ze&&Ze[Ns]!==Ie.payment_method});if(Pe.length){we(d.id);try{for(const Ie of Pe){const Ye=`${d.id}:${Ie.installment_index}`;await Yt.put(`${Ka}/link-pedidos/${d.id}/installments/${Ie.installment_index}/method`,{payment_method:Ze[Ye]},{headers:ce})}await Ce(),qe(Ie=>{const Ye={...Ie};return Object.keys(Ye).forEach(Ns=>{Ns.startsWith(`${d.id}:`)&&delete Ye[Ns]}),Ye}),s({title:"Formas de pagamento atualizadas"})}catch(Ie){s({title:"Falha ao salvar formas",description:Ie?.response?.data?.error?.message||Ie?.message,variant:"destructive"})}finally{we(null)}}},ft=(d,_)=>{ks({linkId:d,inst:_}),k(""),Ne("")},Wt=async()=>{if(!Me)return;const{linkId:d,inst:_}=Me,H={Authorization:`Bearer ${Qa()}`};ss(!0);try{await Yt.put(`${Ka}/link-pedidos/${d}/installments/${_.installment_index}/refund`,{amount:xs?Lt(xs):null,note:De||null},{headers:H}),await Ce(),s({title:"Reembolso processado"}),ks(null)}catch(ce){s({title:"Falha ao reembolsar",description:ce?.response?.data?.error?.message||ce?.message,variant:"destructive"})}finally{ss(!1)}},ya=async(d,_)=>{const H={Authorization:`Bearer ${Qa()}`};try{await Yt.put(`${Ka}/link-pedidos/${d}/installments/${_}/refund/reject`,{note:null},{headers:H}),await Ce(),s({title:"Reembolso recusado"})}catch(ce){s({title:"Falha ao recusar reembolso",description:ce?.response?.data?.error?.message||ce?.message,variant:"destructive"})}},Dt=A.length||Math.max(1,Number(D||1)),gt=Math.min(Dt,6);return e.jsxs("div",{className:"space-y-7 lvp-fade-in",children:[i&&e.jsxs("section",{children:[e.jsxs("div",{className:"mb-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-1",children:[e.jsx("button",{type:"button",className:"hover:text-foreground transition-colors",onClick:u,children:"Link de Pagamento"}),e.jsx(er,{className:"h-3 w-3"}),e.jsx("span",{className:"text-foreground/80",children:P?"Editar parcelas":"Criar novo"})]}),e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold leading-tight flex items-center gap-2",children:[e.jsx("span",{className:"h-9 w-9 rounded-xl bg-primary/15 text-primary flex items-center justify-center",children:e.jsx(hr,{className:"h-5 w-5"})}),P?"Editar Link de Pagamento":"Criar Link de Pagamento"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Monte o parcelamento, defina a forma de pagamento de cada parcela e gere o link para o vendedor enviar ao cliente."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-12 gap-5",children:[e.jsxs("div",{className:"md:col-span-7 lg:col-span-8 space-y-5",children:[e.jsxs("div",{className:"bg-card border border-border/50 rounded-2xl shadow-card p-5 sm:p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx("span",{className:"h-7 w-7 rounded-lg bg-primary/15 text-primary flex items-center justify-center text-sm font-bold",children:"1"}),e.jsx("h2",{className:"text-base font-bold",children:"Origem da venda"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"field-label",children:["Vendedor responsável ",e.jsx("span",{className:"text-primary",children:"*"})]}),e.jsxs(rs,{value:String(ke),onValueChange:Ae,children:[e.jsx(ns,{className:"input h-[2.6rem]",children:e.jsx(is,{placeholder:"Selecione o vendedor…"})}),e.jsx(os,{children:Le.map(d=>e.jsxs(xe,{value:String(d.id),children:[d.nome,d.email?` · ${d.email}`:""]},d.id))})]}),e.jsx("span",{className:"field-hint",children:"O gestor define o dono desta venda."})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"field-label",children:["Evento ",e.jsx("span",{className:"text-primary",children:"*"})]}),e.jsxs(rs,{value:String(m),onValueChange:x,children:[e.jsx(ns,{className:"input h-[2.6rem]",children:e.jsx(is,{placeholder:"Selecione o evento"})}),e.jsx(os,{children:ts.map(d=>e.jsx(xe,{value:String(d.id),children:d?.titulo||d?.attributes?.titulo||`Evento ${d.id}`},d.id))})]}),e.jsx("span",{className:"field-hint",children:"A data e o valor são puxados do sistema."})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"field-label",children:["Data do evento ",e.jsx("span",{className:"text-primary",children:"*"})]}),e.jsxs(rs,{value:f||"",onValueChange:d=>I(d||null),disabled:!fs||Fs.length===0,children:[e.jsx(ns,{className:"input h-[2.6rem]",children:e.jsx(is,{placeholder:fs?"Selecione a data":"Escolha o evento primeiro"})}),e.jsx(os,{children:Fs.map(d=>e.jsx(xe,{value:d,children:Qr(d)},d))})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"field-label",children:["Lote ",e.jsx("span",{className:"text-primary",children:"*"})]}),e.jsxs(rs,{value:String(g),onValueChange:N,disabled:As.length===0,children:[e.jsx(ns,{className:"input h-[2.6rem]",children:e.jsx(is,{placeholder:As.length?"Selecione o lote":"Sem lotes para a data"})}),e.jsx(os,{children:As.map(d=>e.jsxs(xe,{value:String(d.id),children:[d.nome||`Lote ${d.id}`,d.preco_lote!=null?` · ${ct(d.preco_lote)}`:""]},d.id))})]}),e.jsx("span",{className:"field-hint",children:"O valor é puxado do lote selecionado."})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"field-label",children:["Número de ingressos ",e.jsx("span",{className:"text-primary",children:"*"})]}),ys?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-ghost h-[2.6rem] w-10 shrink-0 text-lg leading-none",disabled:Ts<=0,onClick:()=>ht(-1),"aria-label":"Menos ingressos",children:"−"}),e.jsx("input",{className:"input tabular text-center",type:"number",min:Mt,max:Ys,inputMode:"numeric",value:b,onChange:d=>{const _=d.target.value;if(_===""){C("");return}C(Math.min(Ys,Math.max(0,Math.round(Number(_)||0))))},onBlur:()=>dt(b)}),e.jsx("button",{type:"button",className:"btn btn-ghost h-[2.6rem] w-10 shrink-0 text-lg leading-none",disabled:Ts>=Bs.length-1,onClick:()=>ht(1),"aria-label":"Mais ingressos",children:"+"})]}):e.jsx("input",{className:"input tabular",type:"number",min:"1",step:"1",inputMode:"numeric",value:b,onChange:d=>C(d.target.value)})]})]})]}),e.jsxs("div",{className:"bg-card border border-border/50 rounded-2xl shadow-card p-5 sm:p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx("span",{className:"h-7 w-7 rounded-lg bg-primary/15 text-primary flex items-center justify-center text-sm font-bold",children:"2"}),e.jsx("h2",{className:"text-base font-bold",children:"Valores e desconto"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:ys?"Valor por pacote":"Valor unitário"}),e.jsx("input",{className:"input tabular",value:ct(Ss),readOnly:!0}),ys&&e.jsxs("span",{className:"field-hint",children:["Pacote de ",Ps," ingressos."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Preç
91o customizado (admin)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ja,{className:"h-5 w-5 shrink-0",checked:q,onCheckedChange:d=>L(d===!0)}),e.jsx("input",{className:"input tabular flex-1",type:"number",placeholder:"Valor",min:Gs||void 0,value:M,onChange:d=>z(d.target.value),onBlur:()=>{const d=Lt(M);Gs>0&&d>0&&d<Gs&&z(String(Gs))},disabled:!q})]}),e.jsx("span",{className:"field-hint",children:"Sobrepõe o valor do sistema."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Valor original"}),e.jsx("input",{className:"input tabular",value:ct(Xs),readOnly:!0})]})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("label",{className:"field-label",children:"Ajuste de valor (opcional)"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{key:"desconto",label:"Desconto",hint:"abater do valor"},{key:"acrescimo_item",label:"Acréscimo no produto",hint:"somar ao valor do item"},{key:"acrescimo_taxa",label:"Taxa de parcelamento",hint:"somar como taxa"}].map(d=>{const _=fe===d.key;return e.jsxs("button",{type:"button",onClick:()=>le(_?"sem":d.key),className:["rounded-xl border p-3 text-left transition-colors",_?"border-primary bg-primary/15 text-foreground":"border-border/60 bg-muted/30 text-muted-foreground hover:text-foreground hover:border-border"].join(" "),children:[e.jsx("div",{className:"text-sm font-semibold",children:d.label}),e.jsx("div",{className:"text-[11px] opacity-80",children:d.hint})]},d.key)})}),fe!=="sem"&&e.jsxs("div",{className:"flex items-end gap-2 mt-3 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-[140px]",children:[e.jsxs("label",{className:"field-label",children:["Valor do ",fe==="desconto"?"desconto":"acréscimo"]}),e.jsx("input",{className:"input tabular",type:"number",min:"0",inputMode:"decimal",placeholder:"0",value:_e,onChange:d=>U(d.target.value)})]}),e.jsxs("div",{className:"flex gap-1 rounded-xl p-1 bg-muted/40 border border-border/60 h-[2.6rem] items-center",children:[e.jsx("button",{type:"button",onClick:()=>T("percent"),className:["px-3 h-8 rounded-lg text-xs font-semibold transition-colors",J==="percent"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"].join(" "),children:"%"}),e.jsx("button",{type:"button",onClick:()=>T("abs"),className:["px-3 h-8 rounded-lg text-xs font-semibold transition-colors",J==="abs"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"].join(" "),children:"R$"})]})]})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-border/50 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Valor original"}),e.jsx("span",{className:"tabular",children:ct(Xs)})]}),fe==="desconto"&&xt>0&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Desconto"}),e.jsxs("span",{className:"tabular text-[hsl(var(--late-h)_84%_62%)]",children:["− ",ct(xt)]})]}),fe==="acrescimo_item"&&xt>0&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Acréscimo no produto"}),e.jsxs("span",{className:"tabular text-secondary",children:["+ ",ct(xt)]})]}),fe==="acrescimo_taxa"&&xt>0&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Taxa de parcelamento"}),e.jsxs("span",{className:"tabular text-secondary",children:["+ ",ct(xt)]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx("span",{className:"text-sm font-semibold",children:fe==="acrescimo_taxa"?"Total a parcelar":"Subtotal"}),e.jsx("span",{className:"text-base font-bold tabular",children:ct(st)})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Taxa de serviço (",bs,")"]}),e.jsxs("span",{className:"tabular text-secondary",children:["+ ",ct(wt)]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx("span",{className:"text-sm font-semibold",children:"Total com taxa (cliente paga)"}),e.jsx("span",{className:"text-lg font-extrabold tabular text-gradient-brand",children:ct(va)})]})]})]}),e.jsxs("div",{className:"bg-card border border-border/50 rounded-2xl shadow-card p-5 sm:p-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-5 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-7 w-7 rounded-lg bg-primary/15 text-primary flex items-center justify-center text-sm font-bold",children:"3"}),e.jsx("h2",{className:"text-base font-bold",children:"Parcelamento"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Nº de parcelas"}),e.jsx("input",{className:"input tabular !h-9 !w-20",type:"number",min:"1",value:D,onChange:d=>E(d.target.value)}),e.jsx("button",{type:"button",className:"btn btn-ghost h-9 px-3 text-sm",onClick:()=>la(D),children:"Gerar"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-md mb-3",children:"Defina o método de cada parcela. O cliente verá exatamente o que for marcado aqui."}),e.jsxs("div",{className:"space-y-2.5",children:[A.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground italic",children:'Clique em "Gerar" para montar as parcelas.'}),A.map((d,_)=>{const H=Lt(d.amount_base),ce=Number((H*Ve).toFixed(2)),Pe=Number((H+ce).toFixed(2));return e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3 rounded-xl border border-border/60 bg-background/40 p-3 lvp-fade-in",children:[e.jsx("span",{className:"h-8 w-8 shrink-0 rounded-lg bg-muted/50 flex items-center justify-center text-xs font-bold tabular",children:String(_+1).padStart(2,"0")}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-muted-foreground",children:"Valor base"}),e.jsx("input",{className:"input tabular !h-9",type:"number",value:d.amount_base,onChange:Ie=>da(_,"amount_base",Ie.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-muted-foreground",children:"Método"}),e.jsxs(rs,{value:d.payment_method,onValueChange:Ie=>da(_,"payment_method",Ie),children:[e.jsx(ns,{className:"input !h-9",children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"pix",children:"PIX"}),e.jsx(xe,{value:"credit",children:"Crédito"}),e.jsx(xe,{value:"pix_credit",children:"PIX ou Crédito"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-muted-foreground",children:"Expira em"}),e.jsx("input",{className:"input !h-9",type:"date",value:d.expires_at||"",onChange:Ie=>da(_,"expires_at",Ie.target.value)})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px] rounded-lg bg-muted/30 px-2.5 py-1.5",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Taxa de serviço (",bs,")",e.
91jsxs("span",{className:"tabular text-foreground/80",children:[" + ",ct(ce)]})]}),e.jsxs("span",{className:"text-muted-foreground",children:["Cliente paga"," ",e.jsx("span",{className:"tabular font-semibold text-foreground",children:ct(Pe)})]})]})]})]},_)})]})]}),e.jsxs("div",{className:"bg-card border border-border/50 rounded-2xl shadow-card p-5 sm:p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("span",{className:"h-7 w-7 rounded-lg bg-primary/15 text-primary flex items-center justify-center text-sm font-bold",children:"4"}),e.jsxs("h2",{className:"text-base font-bold",children:["Observações & envio ",e.jsx("span",{className:"font-normal text-muted-foreground text-sm",children:"(opcional)"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Nome do cliente"}),e.jsx("input",{className:"input",value:W,onChange:d=>ie(d.target.value),placeholder:"Opcional"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"WhatsApp"}),e.jsx("input",{className:"input",value:y,onChange:d=>$(d.target.value),placeholder:"(11) 99999-9999"})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("label",{className:"field-label",children:"Enviar para e-mail"}),e.jsx("input",{className:"input",value:te,onChange:d=>G(d.target.value),placeholder:"[email protected]"})]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"field-label",children:"Descrição"}),e.jsx("textarea",{className:"input !h-24 py-2.5 resize-none",value:ee,onChange:d=>re(d.target.value),placeholder:"Ex.: cliente pediu para enviar a 2ª parcela só após o dia 10."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Expiração do link"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ja,{className:"h-5 w-5 shrink-0",checked:ae,onCheckedChange:d=>K(d===!0)}),e.jsxs(rs,{value:be,onValueChange:Fe,children:[e.jsx(ns,{className:"input !h-10 max-w-[220px]",children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"fixed",children:"Data fixa"}),e.jsx(xe,{value:"per_installment",children:"Por parcela"}),e.jsx(xe,{value:"relative",children:"Duração relativa"})]})]}),be==="fixed"&&e.jsx("input",{className:"input !h-10 max-w-[180px]",type:"date",value:O,onChange:d=>oe(d.target.value)}),be==="relative"&&e.jsx("input",{className:"input tabular !h-10 max-w-[120px]",type:"number",min:"1",value:ve,onChange:d=>me(d.target.value)})]})]})]})]}),e.jsx("aside",{className:"md:col-span-5 lg:col-span-4",children:e.jsxs("div",{className:"md:sticky md:top-6 space-y-4",children:[e.jsxs("div",{className:"bg-card border border-border/60 rounded-2xl shadow-card overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-brand px-5 py-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-black/70 font-bold",children:"Resumo do link"}),e.jsx("div",{className:"text-black font-extrabold text-lg leading-tight mt-0.5",children:fs?.titulo||fs?.attributes?.titulo||"Selecione um evento"}),e.jsxs("div",{className:"text-black/70 text-xs mt-0.5",children:[Math.max(1,Number(b||1))," ingresso",Math.max(1,Number(b||1))>1?"s":""]})]}),e.jsxs("div",{className:"p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subtotal"}),e.jsx("span",{className:"tabular text-foreground/80",children:ct(st)})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Taxa de serviço (",bs,")"]}),e.jsxs("span",{className:"tabular text-foreground/80",children:["+ ",ct(wt)]})]}),e.jsxs("div",{className:"flex items-baseline justify-between pt-1 border-t border-border/50",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total (cliente paga)"}),e.jsx("span",{className:"text-2xl font-extrabold tabular text-gradient-brand",children:ct(va)})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["em ",Dt,"×"]}),e.jsxs("span",{className:"tabular",children:["≈ ",ct(va/Dt),"/parcela"]})]}),e.jsxs("div",{className:"pt-3 mt-1 border-t border-border/50",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-bold mb-3",children:"Percurso de pagamento"}),e.jsxs("div",{className:"percurso",style:{"--progress":"0%"},children:[Array.from({length:gt},(d,_)=>e.jsxs("div",{className:"percurso-step","data-state":_===0?"current":"pending",children:[e.jsx("div",{className:"percurso-node",children:_+1}),e.jsx("div",{className:"percurso-label",children:_===0?"agora":""})]},_)),Dt>gt&&e.jsxs("div",{className:"percurso-step","data-state":"pending",children:[e.jsxs("div",{className:"percurso-node",children:["+",Dt-gt]}),e.jsx("div",{className:"percurso-label",children:"parcelas"})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-3 leading-relaxed",children:"Como o cliente vai acompanhar o avanço das parcelas."})]})]})]}),e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("button",{type:"button",className:"btn btn-primary w-full h-12 text-[15px]",onClick:Tt,children:[e.jsx(hr,{className:"h-5 w-5"}),P?"Salvar alterações":"Gerar link de pagamento"]}),P&&e.jsx("button",{type:"button",className:"btn btn-ghost w-full h-11 text-sm",onClick:u,children:"Cancelar edição"}),e.jsx("p",{className:"text-[11px] text-muted-foreground text-center leading-relaxed pt-1",children:"Ao gerar, o vendedor recebe o link da 1ª parcela para enviar pelo WhatsApp."})]})]})})]})]}),!i&&e.jsxs("section",{children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-1",children:e.jsx("span",{className:"text-foreground
91/80",children:"Link de Pagamento"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold leading-tight flex items-center gap-2",children:[e.jsx("span",{className:"h-9 w-9 rounded-xl bg-primary/15 text-primary flex items-center justify-center",children:e.jsx(hr,{className:"h-5 w-5"})}),"Links de Pagamento"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Acompanhe o status das parcelas e gerencie a forma de pagamento de cada link."})]}),e.jsxs("button",{type:"button",className:"btn btn-primary h-11 px-5 text-sm self-start sm:self-auto",onClick:()=>l(),children:[e.jsx(et,{className:"h-4 w-4"}),"Criar novo link"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5",children:[e.jsxs("div",{className:"bg-card border border-border/50 rounded-2xl p-4 shadow-card",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Links ativos"}),e.jsx("div",{className:"text-2xl font-bold mt-1 tabular",children:gs.ativos})]}),e.jsxs("div",{className:"bg-card border border-border/50 rounded-2xl p-4 shadow-card",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"A receber"}),e.jsx("div",{className:"text-2xl font-bold mt-1 tabular text-secondary",children:ct(gs.aReceber)})]}),e.jsxs("div",{className:"bg-card border border-border/50 rounded-2xl p-4 shadow-card",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Recebido"}),e.jsx("div",{className:"text-2xl font-bold mt-1 tabular text-[hsl(var(--paid-h)_55%_60%)]",children:ct(gs.recebido)})]}),e.jsxs("div",{className:"bg-card border border-border/50 rounded-2xl p-4 shadow-card",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Parcelas vencidas"}),e.jsx("div",{className:"text-2xl font-bold mt-1 tabular text-[hsl(var(--late-h)_84%_62%)]",children:gs.vencidas})]})]}),e.jsx("div",{className:"bg-card border border-border/50 rounded-2xl p-4 shadow-card mb-5",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end gap-3",children:[c&&e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"field-label",children:"Vendedor"}),e.jsxs(rs,{value:String(We),onValueChange:hs,children:[e.jsx(ns,{className:"input h-[2.6rem]",children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"todos",children:"Todos os vendedores (visão gestor)"}),Le.map(d=>e.jsx(xe,{value:String(d.id),children:d.nome},d.id))]})]})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"field-label",children:"Buscar"}),e.jsx("input",{className:"input",placeholder:"Cliente, evento ou ID do link…",value:Is,onChange:d=>Y(d.target.value)})]}),e.jsx("div",{className:"flex gap-1 rounded-xl p-1 bg-muted/40 border border-border/60 h-[2.6rem] items-center self-start md:self-auto",children:[{key:"todos",label:"Todos"},{key:"aberto",label:"Em aberto"},{key:"quitado",label:"Quitados"}].map(d=>e.jsx("button",{type:"button",onClick:()=>X(d.key),className:["px-3 h-8 rounded-lg text-xs font-semibold transition-colors",Q===d.key?"bg-primary text-primary-foreground shadow-button":"text-muted-foreground hover:text-foreground"].join(" "),children:d.label},d.key))})]})}),e.jsxs("div",{className:"space-y-3",children:[Ke.length===0&&e.jsx("div",{className:"bg-card border border-border/50 rounded-2xl shadow-card p-8 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:R.length===0?"Nenhum link criado ainda.":"Nenhum link encontrado com esses filtros."})}),Ke.map(d=>{const _=d?.attributes||d,H=_?.codigo||"",ce=_?.link_url||"",Pe=`Link de pagamento: ${ce}`,Ie=Lf(_?.target_whatsapp||y,Pe),Ye=Array.isArray(_?.installments)?_.installments:[],Ns=Ye.filter(Ge=>Ge?.status==="pago"),_s=Ns.length,Hs=Ns.reduce((Ge,Ws)=>Ge+Lt(Ws?.amount_total),0),Os=Lt(_?.total)||Ye.reduce((Ge,Ws)=>Ge+Lt(Ws?.amount_total),0),B=Os>0?Math.round(Hs/Os*100):0,de=_?.data_evento,Re=_?.lote?.nome,He=_?.target_usuario?.username||_?.target_usuario?.nome||_?.target_usuario?.data?.attributes?.username||"",ps=_?.evento?.titulo||_?.evento?.attributes?.titulo||"Evento",vs=_?.target_nome||_?.target_whatsapp||"",Es=vs?`${ps} - ${vs}`:ps,cs=Ye.filter(Ge=>Fn(Ge)==="late"&&Ge.status!=="pago").length,qs=!!Ee[d.id],Qs=Qe===d.id,j=_?.disabled===!0,Z=Ft===d.id,Je=_t===d.id,js=Ye.some(Ge=>
91Ge?.status!=="pago"&&Ge?.status!=="cancelado"),zs=Ye.some(Ge=>{if(!(Ge.status!=="pago"&&Ge.status!=="cancelado"))return!1;const jt=`${d.id}:${Ge.installment_index}`;return jt in Ze&&Ze[jt]!==Ge.payment_method});return e.jsxs("div",{className:"bg-card border border-border/50 rounded-2xl shadow-card overflow-hidden",children:[e.jsxs("button",{type:"button",className:"w-full text-left p-4 sm:p-5 flex items-center gap-4 hover:bg-muted/20 transition-colors",onClick:()=>Se(Ge=>({...Ge,[d.id]:!Ge[d.id]})),children:[qs?e.jsx(ra,{className:"h-5 w-5 text-secondary shrink-0"}):e.jsx(er,{className:"h-5 w-5 text-secondary shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-bold truncate",children:Es}),H&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["#",H]}),B>=100&&Ye.length>0&&e.jsx("span",{className:"badge paid",children:"Quitado"}),cs>0&&e.jsxs("span",{className:"badge late",children:[cs," vencida",cs>1?"s":""]}),j&&e.jsx("span",{className:"badge late",children:"Desativado"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[de&&Qr(de),Re?` · ${Re}`:"",He?` · vendedor: ${He}`:"",Ye.length>0&&e.jsxs("span",{className:"text-foreground/60",children:[" · ",Ye.length," parcela",Ye.length>1?"s":""," — ver detalhes"]})]})]}),Ye.length>0&&e.jsxs("div",{className:"hidden sm:block w-40 shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] mb-1",children:[e.jsxs("span",{className:"text-muted-foreground",children:[_s,"/",Ye.length," pagas"]}),e.jsxs("span",{className:"font-semibold text-[hsl(var(--paid-h)_55%_65%)]",children:[B,"%"]})]}),e.jsx("div",{className:"progress-track",children:e.jsx("div",{className:"progress-fill",style:{width:`${Math.min(100,B)}%`}})})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total"}),e.jsx("div",{className:"font-bold tabular",children:ct(Os)})]})]}),qs&&e.jsxs("div",{className:"border-t border-border/50 p-3 sm:p-5 bg-background/30 space-y-4",children:[Ye.length>0&&e.jsxs("div",{className:"sm:hidden",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] mb-1",children:[e.jsxs("span",{className:"text-muted-foreground",children:[_s,"/",Ye.length," pagas"]}),e.jsxs("span",{className:"font-semibold text-[hsl(var(--paid-h)_55%_65%)]",children:[B,"%"]})]}),e.jsx("div",{className:"progress-track",children:e.jsx("div",{className:"progress-fill",style:{width:`${Math.min(100,B)}%`}})})]}),Ye.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sem parcelas registradas."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-[11px] uppercase tracking-wider text-muted-foreground border-b border-border/50",children:[e.jsx("th",{className:"py-2 pr-3 font-semibold",children:"#"}),e.jsx("th",{className:"py-2 pr-3 font-semibold",children:"Valor"}),e.jsx("th",{className:"py-2 pr-3 font-semibold",children:"Vencimento"}),e.jsx("th",{className:"py-2 pr-3 font-semibold",children:"Forma de pagamento"}),e.jsx("th",{className:"py-2 pr-3 font-semibold text-center",children:"Status"}),e.jsx("th",{className:"py-2 pr-0 font-semibold text-right",children:"Ações"})]})}),e.jsx("tbody",{className:"divide-y divide-border/40",children:Ye.map(Ge=>{const Ws=Fn(Ge),jt=Ge.status!=="pago"&&Ge.status!=="cancelado",ma=`${d.id}:${Ge.installment_index}`,Ot=Ze[ma]??Ge.payment_method,St=Ge.refund_status;return e.jsxs("tr",{className:Ws==="current"?"row-current":"",children:[e.jsx("td",{className:"py-2.5 pr-3 tabular font-semibold",children:String(Ge.installment_index).padStart(2,"0")}),e.jsxs("td",{className:"py-2.5 pr-3",children:[e.jsx("div",{className:"tabular font-semibold",children:ct(Ge.amount_total)}),Lt(Ge.amount_base)>0&&e.jsxs("div",{className:"text-[10px] text-muted-foreground leading-snug mt-0.5 space-y-0.5",children:[e.jsxs("div",{children:["Base ",e.jsx("span",{className:"tabular",children:ct(Ge.amount_base)})]}),Lt(Ge.taxa_servico)>0&&e.jsxs("div",{children:["+ Taxa de serviço ",e.jsx("span",{className:"tabular",children:ct(Ge.taxa_servico)})]}),Lt(Ge.taxa_parcelamento)>0&&e.jsxs("div",{children:["+ Taxa de parcelamento ",e.jsx("span",{className:"tabular",children:ct(Ge.taxa_parcelamento)})]})]})]}),e.jsx("td",{className:"py-2.5 pr-3 tabular text-muted-foreground",children:Qr(Ge.expires_at)||"—"}),e.jsx("td",{className:"py-2.5 pr-3",children:jt&&c?e.jsxs(rs,{value:Ot||"pix",onValueChange:br=>ua(d.id,Ge.installment_index,br),children:[e.jsx(ns,{className:"input forma-edit !h-8 !w-auto text-xs",children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"pix",children:"PIX"}),e.jsx(xe,{value:"credit",children:"Crédito"}),e.jsx(xe,{value:"pix_credit",children:"PIX ou Crédito"})]})]}):e.jsx("span",{className:"text-muted-foreground",children:wd[Ge.payment_method]||Ge.payment_method})}),e.jsxs("td",{className:"py-2.5 pr-3 text-center",children:[e.jsxs("span",{className:`badge ${Ws}`,children:[Ws==="paid"&&e.jsx(ti,{className:"h-3 w-3"}),_d[Ws]]}),St&&St!=="none"&&e.jsx("span",{className:"block text-[10px] text-muted-foreground mt-0.5",children:Mf[St]})]}),e.jsx("td",{className:"py-2.5 pr-0",children:e.jsxs("div",{className:"flex items-center justify-end gap-1 flex-wrap",children:[ce&&Ge.status!=="pago"&&e.jsxs("button",{type:"button",className:"btn btn-ghost h-8 px-2.5 text-xs",onClick:()=>Qt(`${ce}?parcela=${Ge.installment_index}`,`Link da parcela ${Ge.installment_index} copiado`),children:[e.jsx(Pa,{className:"h-3.5 w-3.5"}),"Copiar"]}),c&&Ge.status==="pago"&&St==="requested"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn btn-primary h-8 px-2.5 text-xs",onClick:()=>ft(d.id,Ge),children:"Aprovar"}),e.jsx("button",{type:"button",className:"btn btn-ghost h-8 px-2.5 text-xs",onClick:()=>ya(d.id,Ge.installment_index),children:"Recusar"})]}),c&&Ge.status==="pago"&&(!St||St==="none"||St==="rejected")&&e.jsxs("button",{type:"button",className:"btn btn-ghost h-8 px-2.5 text-xs text-destructive",onClick:()=>ft(d.id,Ge),children:[e.jsx(Fo,{className:"h-3.5 w-3.5"}),"Reembolsar"]})]})})]},Ge.installment_index)})})]})}),e.jsx("div",{className:"md:hidden space-y-2",children:Ye.map(Ge=>
91{const Ws=Fn(Ge),jt=Ge.status!=="pago"&&Ge.status!=="cancelado",ma=`${d.id}:${Ge.installment_index}`,Ot=Ze[ma]??Ge.payment_method,St=Ge.refund_status;return e.jsxs("div",{className:`flex items-start gap-3 rounded-xl border p-3 ${Ws==="current"?"border-accent/30 bg-accent/5":"border-border/60 bg-card/40"}`,children:[e.jsx("span",{className:"h-8 w-8 shrink-0 rounded-lg bg-muted/50 flex items-center justify-center text-xs font-bold tabular",children:String(Ge.installment_index).padStart(2,"0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-semibold tabular",children:ct(Ge.amount_total)}),Lt(Ge.amount_base)>0&&e.jsxs("div",{className:"text-[10px] text-muted-foreground leading-snug mt-0.5",children:["Base ",e.jsx("span",{className:"tabular",children:ct(Ge.amount_base)}),Lt(Ge.taxa_servico)>0&&e.jsxs(e.Fragment,{children:[" · serviço ",e.jsx("span",{className:"tabular",children:ct(Ge.taxa_servico)})]}),Lt(Ge.taxa_parcelamento)>0&&e.jsxs(e.Fragment,{children:[" · parcelamento ",e.jsx("span",{className:"tabular",children:ct(Ge.taxa_parcelamento)})]})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:Qr(Ge.expires_at)?`Vence ${Qr(Ge.expires_at)}`:"Sem vencimento"}),jt&&c?e.jsxs(rs,{value:Ot||"pix",onValueChange:br=>ua(d.id,Ge.installment_index,br),children:[e.jsx(ns,{className:"input forma-edit !h-7 !w-auto text-[11px] mt-1",children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"pix",children:"PIX"}),e.jsx(xe,{value:"credit",children:"Crédito"}),e.jsx(xe,{value:"pix_credit",children:"PIX ou Crédito"})]})]}):e.jsx("span",{className:"text-[11px] text-muted-foreground block mt-0.5",children:wd[Ge.payment_method]||Ge.payment_method})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1.5 shrink-0",children:[e.jsxs("span",{className:`badge ${Ws}`,children:[Ws==="paid"&&e.jsx(ti,{className:"h-3 w-3"}),_d[Ws]]}),ce&&Ge.status!=="pago"&&e.jsx("button",{type:"button",className:"text-[11px] text-secondary font-semibold",onClick:()=>Qt(`${ce}?parcela=${Ge.installment_index}`,`Link da parcela ${Ge.installment_index} copiado`),children:"Copiar link"}),c&&Ge.status==="pago"&&St==="requested"&&e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{type:"button",className:"text-[11px] text-primary font-semibold",onClick:()=>ft(d.id,Ge),children:"Aprovar"}),e.jsx("button",{type:"button",className:"text-[11px] text-muted-foreground",onClick:()=>ya(d.id,Ge.installment_index),children:"Recusar"})]}),c&&Ge.status==="pago"&&(!St||St==="none"||St==="rejected")&&e.jsx("button",{type:"button",className:"text-[11px] text-destructive font-semibold",onClick:()=>ft(d.id,Ge),children:"Reembolsar"})]})]},Ge.installment_index)})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3 border-t border-border/40 flex-wrap",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground max-w-md leading-relaxed",children:"Ao alterar a forma de pagamento de uma parcela, o link na mão do cliente é atualizado ao salvar."}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[ce&&e.jsxs("button",{type:"button",className:"btn btn-ghost h-9 px-3 text-sm",onClick:()=>Qt(ce,"Link copiado"),children:[e.jsx(Pa,{className:"h-4 w-4"}),"Copiar link"]}),Ie&&e.jsxs("button",{type:"button",className:"btn btn-ghost h-9 px-3 text-sm",onClick:()=>window.open(Ie,"_blank"),children:[e.jsx(si,{className:"h-4 w-4"}),"WhatsApp"]}),H&&e.jsxs("button",{type:"button",className:"btn btn-ghost h-9 px-3 text-sm",onClick:()=>Js(H,_?.target_email),children:[e.jsx(pr,{className:"h-4 w-4"}),"E-mail"]}),c&&js&&e.jsxs("button",{type:"button",className:"btn btn-ghost h-9 px-3 text-sm",disabled:Je,onClick:()=>Na(d),children:[e.jsx(ta,{className:`h-4 w-4 ${Je?"animate-spin":""}`}),Je?"Verificando…":"Verificar pagamento"]}),c&&e.jsxs("button",{type:"button",className:"btn btn-ghost h-9 px-3 text-sm",onClick:()=>l(d.id),children:[e.jsx(ln,{className:"h-4 w-4"}),"Editar parcelas"]}),c&&e.jsxs("button",{type:"button",className:`btn btn-ghost h-9 px-3 text-sm ${j?"":"text-destructive"}`,disabled:Z,onClick:()=>Kt(d),children:[j?e.jsx(xr,{className:"h-4 w-4"}):e.jsx(Qd,{className:"h-4 w-4"}),Z?"Aguarde…":j?"Reativar":"Desativar"]}),c&&zs&&e.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm",disabled:Qs,onClick:()=>pt(d),children:[e.jsx(Da,{className:"h-4 w-4"}),Qs?"Salvando…":"Salvar"]})]})]})]})]},d.id)})]})]}),e.jsx(at,{open:!!Me,onOpenChange:d=>!d&&ks(null),children:e.jsxs(rt,{children:[e.jsxs(nt,{children:[e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"h-5 w-5 text-destructive"}),"Confirmar reembolso"]}),e.jsx(Ba,{children:Me?`Parcela ${Me.inst?.installment_index} — ${ct(Me.inst?.amount_total)}. Informe um valor parcial (opcional) ou deixe em branco para reembolso total.`:""})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Valor a reembolsar (opcional)"}),e.jsx("input",{className:"input tabular",type:"number",placeholder:Me?ct(Me.inst?.amount_total):"Valor total",value:xs,onChange:d=>k(d.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Observação (opcional)"}),e.jsx("textarea",{className:"input !h-20 py-2.5 resize-none",placeholder:"Motivo do reembolso…",value:De,onChange:d=>Ne(d.target.value)})]})]}),e.jsxs(Ut,{children:[e.jsx("button",{type:"button",className:"btn btn-ghost h-10 px-4 text-sm",onClick:()=>ks(null),children:"Cancelar"}),e.jsx("button",{type:"button",className:"btn btn-primary h-10 px-4 text-sm",disabled:es,onClick:Wt,children:es?"Processando…":"Confirmar reembolso"})]})]})})]})}const kd=s=>{if(!s)return"";const t=new Date(s);if(Number.isNaN(t.valueOf()))return"";const a=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0");return`${a}-${n}-${o}`},On=s=>{if(!s)return"—";const t=new Date(s);
91return Number.isNaN(t.valueOf())?"—":t.toLocaleString("pt-BR")},qn=s=>{if(!s)return"—";let t=String(s).replace(/\D/g,"");if(!t)return"—";t.startsWith("55")&&(t=t.slice(2)),t.startsWith("0")&&t.length>=10&&(t=t.slice(1));let a="",n=t;if((t.length===10||t.length===11)&&(a=t.slice(0,2),n=t.slice(2)),a){if(n.length===9)return`(${a}) ${n.slice(0,5)}-${n.slice(5)}`;if(n.length===8)return`(${a}) ${n.slice(0,4)}-${n.slice(4)}`}return n.length===9?`${n.slice(0,5)}-${n.slice(5)}`:n.length===8?`${n.slice(0,4)}-${n.slice(4)}`:s},sn=s=>s?.evento?.data?.attributes?.titulo||s?.evento?.data?.attributes?.nome||s?.evento?.titulo||s?.evento?.nome||"—",Ff=s=>{const t=s?.evento?.data?.id||s?.evento?.id||null,a=Number(t);return Number.isFinite(a)&&a>0?a:null},gu=s=>String(s||"").toLowerCase().includes("palestra"),Of=s=>gu(sn(s)),qf=(s,t,a)=>{if(a.excludePalestra&&gu(t))return!1;if(!Array.isArray(a.allowedEventoIds))return!0;if(!a.allowedEventoIds.length)return!1;const n=Number(s);return Number.isFinite(n)&&a.allowedEventoIds.includes(n)},ao=(s,t)=>{if(!s||t.excludePalestra&&Of(s))return!1;if(!Array.isArray(t.allowedEventoIds))return!0;if(!t.allowedEventoIds.length)return!1;const a=Ff(s);return Number.isFinite(a)&&t.allowedEventoIds.includes(a)},zf=s=>{const t=new Map,a=new Map;s.forEach(u=>{const l=u?.createdAt||u?.updatedAt;if(!l)return;const c=new Date(l);if(Number.isNaN(c.valueOf()))return;const m=`${String(c.getDate()).padStart(2,"0")}/${String(c.getMonth()+1).padStart(2,"0")}`;t.set(m,(t.get(m)||0)+1);const x=`${String(c.getHours()).padStart(2,"0")}h`;a.set(x,(a.get(x)||0)+1)});const n=Array.from(t.entries()).map(([u,l])=>({label:u,total:l})).sort((u,l)=>{const[c,m]=u.label.split("/").map(Number),[x,h]=l.label.split("/").map(Number);return m===h?c-x:m-h}),o=Array.from(a.entries()).map(([u,l])=>({label:u,total:l})).sort((u,l)=>Number(u.label.replace("h",""))-Number(l.label.replace("h",""))),i=[...o].sort((u,l)=>l.total-u.total).slice(0,5);return{byDay:n,byHour:o,hotHours:i}},zn=s=>s?s.attributes?{id:s.id,...s.attributes}:s:null;function Sd(){const{toast:s}=mt(),{user:t,profile:a}=Zt(),{id:n}=_i(),o=String(t?.role?.name||"").toLowerCase(),i=String(t?.role?.type||"").toLowerCase(),u=String(t?.role?.code||"").toLowerCase(),l=r.useMemo(()=>["admin","superadmin","supersuporte"].some(V=>o.includes(V)||i.includes(V)||u.includes(V))?!0:o==="authenticated"||i==="authenticated"||u==="authenticated",[u,o,i]),c=r.useMemo(()=>[o,i,u].some(V=>V.includes("vendedor")),[u,o,i]),m=r.useMemo(()=>!(!a?.restringirFormularios||l),[l,a]),x=r.useMemo(()=>l||c?!1:a?.podeVerFormularios!==!0,[l,c,a]),h=r.useMemo(()=>m?Array.isArray(a?.eventosSelecionados)?a.eventosSelecionados.map(Number).filter(V=>Number.isFinite(V)&&V>0):[]:null,[m,a]),p=r.useMemo(()=>({excludePalestra:c,allowedEventoIds:m?h:null}),[h,m,c]),[f,I]=Od(),g=Number(f.get("page")||"1"),N=Number.isFinite(g)&&g>0?g:1,b=Number(f.get("pageSize")||"25"),C=Number.isFinite(b)&&b>0?b:25,q=!!n,[L,M]=r.useState(""),[z,D]=r.useState("all"),[E,A]=r.useState("all"),[S,P]=r.useState("all"),[F,ee]=r.useState(""),[re,te]=r.useState(""),G=r.useMemo(()=>{if(q)return"";const V=new URLSearchParams;return V.set("sort","createdAt:desc"),V.set("pagination[page]",String(N)),V.set("pagination[pageSize]",String(C)),V.set("publicationState","preview"),["nomeCompleto","email","telefone","segmento","mensagem","origem","perguntasExtras","createdAt"].forEach((Ce,Ue)=>{V.append(`fields[${Ue}]`,Ce)}),V.append("populate[0]","evento"),V.append("populate[evento][fields][0]","titulo"),`/formularios-palestras?${V.toString()}`},[q,N,C]),y=r.useMemo(()=>{if(q)return"";const V=new URLSearchParams;return V.set("sort","createdAt:desc"),V.set("pagination[pageSize]","200"),V.set("publicationState","preview"),["nomeCompleto","email","telefone","segmento","mensagem","origem","createdAt"].forEach((Ce,Ue)=>{V.append(`fields[${Ue}]`,Ce)}),V.append("populate[0]","evento"),V.append("populate[evento][fields][0]","titulo"),`/formularios-palestras?${V.toString()}`},[q]),$=r.useMemo(()=>{if(q)return"";const V=new URLSearchParams;return L&&V.set("search",L),z!=="all"&&V.set("segmento",z),E!=="all"&&V.set("origem",E),S!=="all"&&V.set("eventoId",S),F&&V.set("from",F),re&&V.set("to",re),V.set("clean","1"),V.set("pageSize","1000"),`/formularios-palestras/analytics?${V.toString()}`},[q,L,z,E,S,F,re]),W=c||m,{data:ie,isLoading:ke,error:Ae,refetch:be}=Ks("formularios-palestra-dashboard",G),{data:Fe,fetchNextPage:ae,hasNextPage:K,isFetchingNextPage:O,isLoading:oe}=Wu(["formularios-palestra-metrics"],y,{enabled:!!y}),{data:ve,isLoading:me}=Ks(["formularios-palestra-analytics",$],$,{enabled:!!$&&!W}),fe=r.useMemo(()=>
91{if(!q)return"";const V=new URLSearchParams;return V.set("publicationState","preview"),V.append("populate[0]","evento"),V.append("populate[evento][fields][0]","titulo"),`/formularios-palestras/${n}?${V.toString()}`},[n,q]),{data:le,isLoading:_e}=Ks(["formularios-palestra-detail",n],fe,{enabled:!!fe}),U=r.useMemo(()=>{const V=ie?.data||ie||[];return(Array.isArray(V)?V:[]).map(zn).filter(Boolean)},[ie]),J=r.useMemo(()=>{if(!le)return null;const V=le?.data||le;return zn(V)},[le]);r.useEffect(()=>{!K||O||ae()},[K,O,ae]);const T=r.useMemo(()=>U.filter(pe=>(pe?.id||pe?.documentId)&&!pe?.evento).map(pe=>pe.id).filter(pe=>Number.isFinite(Number(pe))).slice(0,80),[U]),Ee=r.useMemo(()=>{if(!T.length)return"";const V=new URLSearchParams;return V.set("pagination[pageSize]",String(Math.max(1,T.length))),V.set("publicationState","preview"),T.forEach((pe,Ce)=>{V.append(`filters[id][$in][${Ce}]`,String(pe))}),V.append("populate[0]","evento"),V.append("populate[evento][fields][0]","titulo"),V.set("sort","createdAt:desc"),`/formularios-palestras?${V.toString()}`},[T]),{data:Se}=Ks(["formularios-palestra-dashboard-fallback",{ids:T}],Ee,{enabled:!!Ee}),Ze=r.useMemo(()=>{const V=Se?.data||Se||[],Ce=(Array.isArray(V)?V:[]).map(zn).filter(Boolean);if(!Ce.length)return U;const Ue=new Map(Ce.map(Xe=>[String(Xe.id),Xe]));return U.map(Xe=>{const Ve=Ue.get(String(Xe.id));return!Ve||Xe?.evento?Xe:{...Xe,evento:Ve.evento??Xe.evento}})},[U,Se]),qe=r.useMemo(()=>Ze.filter(V=>ao(V,p)),[p,Ze]),Qe=r.useMemo(()=>{const V=ve?.data||ve||{};return(Array.isArray(V.eventos)?V.eventos:[]).map(Ce=>[String(Ce?.id||Ce?.documentId||Ce?.eventoId||""),Ce?.titulo||Ce?.nome||Ce?.label||""]).filter(([Ce,Ue])=>qf(Ce,Ue,p)).filter(([Ce,Ue])=>Ce&&Ue)},[p,ve]),we=r.useMemo(()=>{const V=new Set,pe=new Set,Ce=new Map;qe.forEach(Xe=>{Xe.segmento&&V.add(Xe.segmento),Xe.origem&&pe.add(Xe.origem);const Ve=Xe?.evento?.data?.attributes?.titulo||Xe?.evento?.data?.attributes?.nome||Xe?.evento?.titulo||Xe?.evento?.nome,bs=Xe?.evento?.data?.id||Xe?.evento?.id;bs&&Ve&&Ce.set(String(bs),Ve)});const Ue=Qe.length?Qe:Array.from(Ce.entries());return{segmentos:Array.from(V).sort((Xe,Ve)=>Xe.localeCompare(Ve,"pt-BR")),origens:Array.from(pe).sort((Xe,Ve)=>Xe.localeCompare(Ve,"pt-BR")),eventos:Ue.sort((Xe,Ve)=>Xe[1].localeCompare(Ve[1],"pt-BR"))}},[qe,Qe]),Me=r.useMemo(()=>{const V=L.trim().toLowerCase();return qe.filter(pe=>{const Ce=kd(pe.createdAt||pe.updatedAt);if(F&&Ce&&Ce<F||re&&Ce&&Ce>re||z!=="all"&&(pe.segmento||"").toLowerCase()!==z.toLowerCase()||E!=="all"&&(pe.origem||"").toLowerCase()!==E.toLowerCase())return!1;const Ue=String(pe?.evento?.data?.id||pe?.evento?.id||"");if(S!=="all"&&Ue!==S)return!1;if(!V)return!0;const Xe=pe?.evento?.data?.attributes?.titulo||pe?.evento?.data?.attributes?.nome||pe?.evento?.titulo||pe?.evento?.nome||"";return[pe.nomeCompleto,pe.email,pe.telefone,pe.segmento,pe.origem,Xe].filter(Boolean).join(" ").toLowerCase().includes(V)})},[qe,L,z,E,S,F,re]),ks=r.useMemo(()=>(Fe?.pages||[]).flatMap(Ce=>{const Ue=Ce?.data||Ce||[];return Array.isArray(Ue)?Ue:[]}).map(zn).filter(Boolean).filter(Ce=>ao(Ce,p)),[p,Fe]),xs=r.useMemo(()=>{const V=L.trim().toLowerCase();return ks.filter(pe=>{const Ce=kd(pe.createdAt||pe.updatedAt);if(F&&Ce&&Ce<F||re&&Ce&&Ce>re||z!=="all"&&(pe.segmento||"").toLowerCase()!==z.toLowerCase()||E!=="all"&&(pe.origem||"").toLowerCase()!==E.toLowerCase())return!1;const Ue=String(pe?.evento?.data?.id||pe?.evento?.id||"");if(S!=="all"&&Ue!==S)return!1;if(!V)return!0;const Xe=pe?.evento?.data?.attributes?.titulo||pe?.evento?.data?.attributes?.nome||pe?.evento?.titulo||pe?.evento?.nome||"";return[pe.nomeCompleto,pe.email,pe.telefone,pe.segmento,pe.origem,Xe].filter(Boolean).join(" ").toLowerCase().includes(V)})},[ks,L,z,E,S,F,re]),k=r.useMemo(()=>Me.filter(V=>!V?.evento).length,[Me]),De=r.useMemo(()=>{const V=ie?.meta?.pagination;return V?{page:V.page||N,pageSize:V.pageSize||C,pageCount:V.pageCount||1,total:V.total||0}:null},[ie,N,C]),Ne=r.useMemo(()=>{const V=xs,pe=V.length,Ce=new Set(V.map(Ve=>(Ve.email||"").toLowerCase()).filter(Boolean)).size,Ue=new Date,Xe=V.filter(Ve=>{const bs=new Date(Ve.createdAt||Ve.updatedAt);if(Number.isNaN(bs.valueOf()))return!1;const ts=Ue-bs;return ts>=0&&ts<=7*24*60*60*1e3}).length;return{total:pe,uniqueEmails:Ce,last7:Xe}},[xs]),es=oe||O||K,ss=async()=>{try{if(!xs.length){s({title:"Nada para exportar",description:"Não há registros com os filtros atuais.",variant:"destructive"});return}const V=xs.map(Ke=>({ID:Ke.id||Ke.documentId||"",Nome:Ke.nomeCompleto||"—",Email:Ke.email||"—",Telefone:qn(Ke.telefone),Segmento:Ke.segmento||"—",Origem:Ke.origem||"—",Evento:sn(Ke),Mensagem:Ke.mensagem||"—","Criado em":On(Ke.createdAt||Ke.updatedAt)})),pe=await $r(()=>import("./vendor-exceljs-AsZnDCZx.js").then(Ke=>Ke.e),__vite__mapDeps([0,1,2])),Ce=pe.default||pe,Ue=new Ce.Workbook,Xe=Ue.addWorksheet("Formulários Palestra");Xe.columns=[{header:"ID",key:"ID",width:12},{header:"Nome",key:"Nome",width:30},{header:"Email",key:"Email",width:34},{header:"Telefone",key:"Telefone",width:18},{header:"Segmento",key:"Segmento",width:18},{header:"Origem",key:"Origem",width:16},{header:"Evento",key:"Evento",width:28},{header:"Mensagem",key:"Mensagem",width:44},{header:"Criado em",key:"Criado em",width:22}
91],V.forEach(Ke=>Xe.addRow(Ke)),Xe.getRow(1).font={bold:!0};const Ve=new Date,bs=Ke=>String(Ke).padStart(2,"0"),ts=`formularios_palestra_${Ve.getFullYear()}-${bs(Ve.getMonth()+1)}-${bs(Ve.getDate())}_${bs(Ve.getHours())}-${bs(Ve.getMinutes())}.xlsx`,R=await Ue.xlsx.writeBuffer(),Le=new Blob([R],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),as=URL.createObjectURL(Le),ms=document.createElement("a");ms.href=as,ms.download=ts,document.body.appendChild(ms),ms.click(),ms.remove(),URL.revokeObjectURL(as),s({title:"Exportação concluída",description:`${V.length} formulário(s) exportado(s) para ${ts}.`})}catch(V){console.error("Falha ao exportar Excel de formulários:",V),s({title:"Falha ao exportar",description:"Veja o console para detalhes.",variant:"destructive"})}},We=r.useMemo(()=>{if(W)return zf(xs);const V=ve?.data||ve||{},pe=Array.isArray(V.byDay)?V.byDay:[],Ce=Array.isArray(V.byHour)?V.byHour:[],Ue=Array.isArray(V.hotHours)?V.hotHours:[];return{byDay:pe,byHour:Ce,hotHours:Ue}},[ve,xs,W]),hs=ke||(W?es:me),Is=hs?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Carregando gráfico..."}):We.byDay.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sem dados para o período selecionado."}):e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(Xa,{data:We.byDay,margin:{left:8,right:8,top:12},children:[e.jsx(Ra,{strokeDasharray:"3 3"}),e.jsx(Ta,{dataKey:"label",tick:{fill:"hsl(var(--foreground))"}}),e.jsx($a,{allowDecimals:!1,tick:{fill:"hsl(var(--foreground))"}}),e.jsx(Aa,{contentStyle:{backgroundColor:"hsl(var(--popover))",color:"hsl(var(--popover-foreground))",borderColor:"hsl(var(--border))"},labelStyle:{color:"hsl(var(--foreground))"},itemStyle:{color:"hsl(var(--foreground))"},cursor:{fill:"hsl(var(--primary) / 0.12)"}}),e.jsx(ha,{dataKey:"total",fill:"hsl(var(--primary))",radius:[6,6,0,0]})]})}),Y=hs?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Carregando gráfico..."}):We.byHour.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sem dados para o período selecionado."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex-1",children:e.jsx(Ca,{width:"100%",height:"100%",children:e.jsxs(Xa,{data:We.byHour,margin:{left:8,right:8,top:12},children:[e.jsx(Ra,{strokeDasharray:"3 3"}),e.jsx(Ta,{dataKey:"label",tick:{fill:"hsl(var(--foreground))"}}),e.jsx($a,{allowDecimals:!1,tick:{fill:"hsl(var(--foreground))"}}),e.jsx(Aa,{contentStyle:{backgroundColor:"hsl(var(--popover))",color:"hsl(var(--popover-foreground))",borderColor:"hsl(var(--border))"},labelStyle:{color:"hsl(var(--foreground))"},itemStyle:{color:"hsl(var(--foreground))"},cursor:{fill:"hsl(var(--primary) / 0.12)"}}),e.jsx(ha,{dataKey:"total",fill:"hsl(var(--primary))",radius:[6,6,0,0]})]})})}),e.jsx("div",{className:"flex flex-wrap gap-2 text-sm",children:We.hotHours.map(V=>e.jsxs(je,{variant:"secondary",className:"text-primary-foreground",children:[V.label,": ",V.total]},V.label))})]}),Q=ke?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Carregando registros..."}):Me.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Nenhum formulário encontrado."}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"md:hidden space-y-3",children:Me.map(V=>{const pe=sn(V);return e.jsxs("div",{className:"rounded-lg border bg-card p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"font-medium text-sm break-words",children:V.nomeCompleto||"—"}),e.jsx(w,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(lt,{to:`/dashboard/formularios-palestra/${V.id}`,children:"Ver"})})]}),e.jsx("div",{className:"text-sm text-muted-foreground break-all",children:V.email||"—"}),e.jsx("div",{className:"text-sm",children:qn(V.telefone)}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs",children:[e.jsx(je,{variant:"secondary",className:"capitalize",children:V.segmento||"—"}),e.jsx(je,{variant:"outline",children:pe})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:On(V.createdAt||V.updatedAt)})]},V.id)})}),e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Nome"}),e.jsx(ue,{children:"Email"}),e.jsx(ue,{children:"Telefone"}),e.jsx(ue,{children:"Segmento"}),e.jsx(ue,{children:"Evento"}),e.jsx(ue,{children:"Criado em"}),e.jsx(ue,{children:"Ações"})]})}),e.jsx(Ct,{children:Me.map(V=>{const pe=sn(V);return e.jsxs($s,{children:[e.jsx(ye,{className:"font-medium",children:V.nomeCompleto||"—"}),e.jsx(ye,{children:V.email||"—"}),e.jsx(ye,{children:qn(V.telefone)}),e.jsx(ye,{className:"capitalize",children:V.segmento||"—"}),e.jsx(ye,{children:pe}),e.jsx(ye,{children:On(V.createdAt||V.updatedAt)}),e.jsx(ye,{children:e.jsx(w,{asChild:!0,variant:"outline",size:"sm",children:e.jsx(lt,{to:`/dashboard/formularios-palestra/${V.id}`,children:"Ver"})})})]},V.id)})})]})})]}),X=(()=>
91{if(_e)return e.jsx("div",{className:"text-sm text-muted-foreground",children:"Carregando formulário..."});if(!J)return e.jsx("div",{className:"text-sm text-muted-foreground",children:"Formulário não encontrado."});if(!ao(J,p))return e.jsx("div",{className:"text-sm text-muted-foreground",children:"Você não tem acesso a este formulário."});const V=sn(J);return e.jsxs(he,{children:[e.jsxs(Be,{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ze,{children:"Detalhes do formulário"}),e.jsx(w,{asChild:!0,variant:"outline",size:"sm",children:e.jsx(lt,{to:`/dashboard/formularios-palestra?page=${N}&pageSize=${C}`,children:"Voltar"})})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:On(J.createdAt||J.updatedAt)})]}),e.jsxs(ge,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Nome"}),e.jsx("div",{className:"text-sm font-medium",children:J.nomeCompleto||"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx("div",{className:"text-sm font-medium",children:J.email||"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Telefone"}),e.jsx("div",{className:"text-sm font-medium",children:qn(J.telefone)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Segmento"}),e.jsx("div",{className:"text-sm font-medium",children:J.segmento||"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Evento"}),e.jsx("div",{className:"text-sm font-medium",children:V})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Mensagem"}),e.jsx("div",{className:"text-sm font-medium",children:J.mensagem||"—"})]})]})]})})();return x?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Formulários de Eventos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Acompanhe os envios de formulários dos eventos."})]}),e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 px-4 py-5 text-sm",children:[e.jsx(oo,{className:"mt-0.5 h-5 w-5 shrink-0 text-destructive"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-destructive",children:"Acesso bloqueado"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:"Seu perfil não tem permissão para visualizar a aba de Formulários de Palestra. Contate o administrador para solicitar acesso."})]})]})]}):q?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Formulários de Palestra"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Detalhe do envio selecionado."})]}),X]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Formulários de Eventos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Acompanhe os envios, picos de horários e detalhes dos contatos."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&e.jsxs(je,{variant:"secondary",className:"cursor-help",title:"Possível causa: evento em rascunho (não publicado) ou permissão de leitura do Evento no Strapi.",children:[k," sem evento"]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:ss,disabled:ke||es,children:[e.jsx(Oa,{className:"mr-2 h-4 w-4"})," Exportar Excel"]}),e.jsx(w,{variant:"outline",size:"sm",onClick:()=>be?.(),children:"Atualizar"})]})]}),Ae&&e.jsx(he,{children:e.jsx(ge,{className:"py-6",children:e.jsx("div",{className:"text-sm text-destructive",children:"Não foi possível carregar os formulários. Tente novamente."})})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium text-muted-foreground",children:"Total filtrado"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-semibold",children:es?"—":Ne.total})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium text-muted-foreground",children:"Últimos 7 dias"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-semibold",children:es?"—":Ne.last7})})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-sm font-medium text-muted-foreground",children:"Leads únicos"})}),e.jsx(ge,{children:e.jsx("div",{className:"text-3xl font-semibold",children:es?"—":Ne.uniqueEmails})})]})]}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(Ci,{className:"h-4 w-4"})," Filtros"]})}),e.jsx(ge,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"flex flex-col lg:flex-row lg:items-end gap-3",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:flex-wrap md:items-end gap-3 flex-1 min-w-0",children:[e.jsxs("div",{className:"w-full md:flex-1 md:min-w-[240px] min-w-0",children:[e.jsx("div",{className:"block text-xs font-medium text-muted-foreground mb-2",children:"Buscar"}),e.jsxs("div",{className:"relative",children:[e.jsx(At,{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(Te,{value:L,onChange:V=>M(V.target.value),placeholder:"Buscar por nome, email, telefone...",className:"pl-10 w-full"})]})]}),e.jsxs("div",{className:"w-full md:w-[220px] min-w-0",children:[e.jsx("div",{className:"block text-xs font-medium text-muted-foreground mb-2",children:"Segmento"}),e.jsxs(rs,{value:z,onValueChange:D,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Segmento"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos segmentos"}),we.segmentos.map(V=>e.jsx(xe,{value:V,children:V},V))]})]})]}),e.jsxs("div",{className:"w-full md:w-[240px] min-w-0",children:[e.jsx("div",{className:"block text-xs font-medium text-muted-foreground mb-2",children:"Evento"}),e.jsxs(rs,{value:S,onValueChange:P,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Evento"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos eventos"}),we.eventos.map(([V,pe])=>e.jsx(xe,{value:V,children:pe},V))]})]})]}),e.jsxs("div",{className:"w-full md:w-[220px] min-w-0",children:[e.jsx("div",{className:"block text-xs font-medium text-muted-foreground mb-2",children:"Origem"}),e.jsxs(rs,{value:E,onValueChange:A,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Origem"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todas origens"}),we.origens.map(V=>e.jsx(xe,{value:V,children:V},V))]})]})]})]})}),e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-end lg:justify-between gap-3 min-w-0",children:[e.jsxs("div",{className:"w-full lg:max-w-[520px] min-w-0",children:[e.jsxs("div",{className:"block text-xs font-medium text-muted-foreground mb-2",children:["Período"," ",F&&!re||!F&&re?e.jsx("span",{className:"text-amber-600",children:"(selecione ambos)"}):""]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-lg ${F&&!re||!F&&re?"border-amber-600":"border-input"}`,children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(kr,{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Te,{type:"date",value:F,onChange:V=>ee(V.target.value),className:"pl-9 min-w-0"})]}),e.jsx("span",{className:"text-muted-foreground font-medium px-1",children:"→"}),e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(kr,{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Te,{type:"date",value:re,onChange:V=>te(V.target.value),className:"pl-9 min-w-0"})]}),(F||re)&&e.jsx("button",{onClick:()=>{ee(""),te("")},className:"p-1 text-muted-foreground hover:text-foreground hover:bg-accent rounded text-lg leading-none",type:"button",title:"Limpar período",children:"✕"})]})]}),(L||z!=="all"||E!=="all"||S!=="all"||F||re)&&e.jsx(w,{variant:"ghost",size:"sm",className:"self-start lg:self-auto",onClick:()=>{M(""),D("all"),A("all"),P("all"),ee(""),te("")},children:"Limpar filtros"})]})]})})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(kr,{className:"h-4 w-4"}
91)," Envios por dia"]}),e.jsx("span",{className:"ml-1 text-xs font-normal text-muted-foreground",children:"Volumes diários de todos os envios filtrados"})]}),e.jsx(ge,{className:"h-64",children:Is})]}),e.jsxs(he,{children:[e.jsxs(Be,{children:[e.jsxs(ze,{className:"flex  items-center gap-2",children:[e.jsx(Za,{className:"h-4 w-4"})," Picos de acesso"]}),e.jsx("span",{className:"ml-1 text-xs font-normal text-muted-foreground",children:"Volumes de acesso (por hora)"})]}),e.jsx(ge,{className:"h-64 flex flex-col gap-3",children:Y})]})]}),e.jsxs(he,{children:[e.jsx(Be,{children:e.jsx(ze,{children:"Lista de formulários"})}),e.jsxs(ge,{children:[Q,De&&De.pageCount>1&&e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm",children:[e.jsxs("div",{className:"text-muted-foreground",children:["Página ",De.page," de ",De.pageCount," • ",De.total," registros"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(w,{variant:"outline",size:"sm",disabled:De.page<=1,onClick:()=>I({page:String(De.page-1),pageSize:String(De.pageSize)}),children:"Anterior"}),e.jsx(w,{variant:"outline",size:"sm",disabled:De.page>=De.pageCount,onClick:()=>I({page:String(De.page+1),pageSize:String(De.pageSize)}),children:"Próxima"})]})]})]})]})]})}const Uf=async(s,t,a)=>{const n={pedidoId:s};return t&&(n.paymentCode=t),(await $e.post("/cielo/order/send",n)).data},Bf=async({items:s,paymentCode:t,notes:a,usuarioId:n,parcelas:o,bandeira:i})=>{const u={items:s,usuarioId:n};return t&&(u.paymentCode=t),a&&(u.notes=a),o&&(u.parcelas=o),i&&(u.bandeira=i),(await $e.post("/cielo/order/create-and-send",u)).data},Vf=async s=>(await $e.get(`/cielo/order/${s}/status`)).data,Gf=async()=>(await $e.get("/cielo/orders")).data,Hf=async s=>(await $e.put(`/cielo/order/${s}/close`)).data,Kf=async(s,t)=>(await $e.put(`/cielo/order/${s}/status`,{operation:t})).data,Qf=async(s,t)=>(await $e.get(`/cielo/extrato?de=${s}&ate=${t}`)).data,Wf=async({valor:s,de:t,ate:a,observacao:n,resumo:o,pedidoIds:i})=>{const u={valor:s,de:t,ate:a};return n&&(u.observacao=n),o&&(u.resumo=o),i&&(u.pedidoIds=i),(await $e.post("/cielo/transferencia",u)).data},Jf=async(s=1,t=25)=>(await $e.get(`/cielo/transferencias?page=${s}&pageSize=${t}`)).data,Id=[{value:"",label:"Qualquer (terminal decide)"},{value:"DEBITO_AVISTA",label:"Débito à Vista"},{value:"CREDITO_AVISTA",label:"Crédito à Vista"},{value:"CREDITO_PARCELADO_LOJA",label:"Crédito Parcelado"},{value:"PIX",label:"PIX"}],Un=s=>({DRAFT:{label:"Rascunho",className:"bg-gray-400 text-gray-900"},ENTERED:{label:"No Terminal",className:"bg-blue-400 text-blue-900"},"RE-ENTERED":{label:"Re-enviado",className:"bg-blue-400 text-blue-900"},PAID:{label:"Pago",className:"bg-green-400 text-green-900"},CLOSED:{label:"Fechado",className:"bg-purple-400 text-purple-900"},CANCELED:{label:"Cancelado",className:"bg-red-400 text-red-900"}})[s]||{label:s||"—",className:"bg-muted text-foreground"},Wa=s=>(s?.data?.attributes?s.data.attributes:s)||{},Wr=s=>s?.data?.id??s?.id??null,ro=({status:s})=>{switch(s){case"PAID":case"CLOSED":return e.jsx(wa,{className:"h-4 w-4 text-green-500"});case"ENTERED":case"RE-ENTERED":return e.jsx(Xd,{className:"h-4 w-4 text-blue-500"});case"CANCELED":return e.jsx(ni,{className:"h-4 w-4 text-red-500"});default:return e.jsx(Za,{className:"h-4 w-4 text-muted-foreground"})}};function Ad(){const s=nr(),{toast:t}=mt(),{formatPrice:a}=jn(),{user:n}=r.useContext(Ju),o=String(n?.role?.name||n?.role?.type||"").toLowerCase(),i=o.includes("superadmin"),u=o.includes("terminal"),[l,c]=r.useState(""),[m,x]=r.useState(""),[h,p]=r.useState(""),[f,I]=r.useState(null),[g,N]=r.useState(null),[b,C]=r.useState(null),[q,L]=r.useState([]),M=new Date,z=new Date(M.getTime()-30*24*60*60*1e3),D=j=>j.toISOString().slice(0,10),[E,A]=r.useState(D(z)),[S,P]=r.useState(D(M)),[F,ee]=r.useState(null),[re,te]=r.useState(!1),[G,y]=r.useState([]),[$,W]=r.useState(!1),[ie,ke]=r.useState(!1),[Ae,be]=r.useState(""),[Fe,ae]=r.useState(""),[K,O]=r.useState(!1),[oe,ve]=r.useState("venda-direta"),[me,fe]=r.useState(!1),le=r.useCallback(async(j,Z)=>{te(!0);try{const Je=await Qf(j,Z);Je?.ok&&ee(Je)}catch(Je){console.error("[CieloTerminal] fetchExtrato error",Je)}te(!1)},[]),_e=r.useCallback(async()=>{W(!0);try{const j=await Jf();j?.ok&&y(j.results||[])}catch(j){console.error("[CieloTerminal] listTransfers error",j)}W(!1)},[]);r.useEffect(()=>{oe==="extrato"&&!me&&(fe(!0),le(E,S),_e())},[oe,me,E,S,le,_e]);const{data:U,isLoading:J}=Ks("cielo-eventos","/eventos?fields[0]=id&fields[1]=documentId&fields[2]=titulo&fields[3]=data_evento&fields[4]=local&populate[imagem][fields][0]=url&sort=data_evento:desc&pagination[pageSize]=100",{staleTime:6e4}),T=r.useMemo(()=>(U?.data||[]).map(Z=>{const Je=Z?.attributes?{...Z.attributes,id:Z.id,documentId:Z.documentId}:Z,js=Wa(Je.imagem);
91return{id:Je.id,documentId:Je.documentId,titulo:Je.titulo||"(sem título)",data_evento:Je.data_evento,local:Je.local,imagem:js?.url||Je.imagem?.url||null}}).filter(Z=>!Z.titulo.toLowerCase().includes("palestra")),[U]),Ee=l?`/pedidos?filters[status_pedido][$eq]=pendente&filters[eventos][id][$eq]=${l}&populate[items][populate][estoque_item][fields][0]=nome&populate[items][populate][evento][fields][0]=titulo&populate[items][populate][tipo_ingresso][fields][0]=nome&populate[usuario][fields][0]=nome&populate[usuario][fields][1]=email&sort=createdAt:desc&pagination[pageSize]=50`:null,{data:Se,isLoading:Ze,refetch:qe}=Ks(["cielo-pedidos",l],Ee,{enabled:!!l,staleTime:15e3}),Qe=r.useMemo(()=>Se?.data?(Se.data||[]).map(j=>{const Z=j?.attributes||j,Je=Wa(Z.usuario),js=(Z.items?.data||Z.items||[]).map(zs=>{const Ge=zs?.attributes||zs;return{...Ge,id:zs?.id||Ge?.id,estoque_item:Wa(Ge.estoque_item),evento:Wa(Ge.evento),tipo_ingresso:Wa(Ge.tipo_ingresso)}});return{id:j.id,documentId:j.documentId,total:Z.total||Z.valor_total||0,moeda:Z.moeda||"BRL",status_pedido:Z.status_pedido,metodo_pagamento:Z.metodo_pagamento,dados_gateway:Z.dados_gateway||{},usuario:{id:Wr(Z.usuario)||Je?.id,nome:Je.nome||Je.username||"",email:Je.email||""},items:js,createdAt:Z.createdAt||j.createdAt}}):[],[Se]),we=r.useMemo(()=>{if(!m.trim())return Qe;const j=m.toLowerCase();return Qe.filter(Z=>String(Z.id).includes(j)||(Z.usuario?.nome||"").toLowerCase().includes(j)||(Z.usuario?.email||"").toLowerCase().includes(j))},[Qe,m]),[Me,ks]=r.useState([]),[xs,k]=r.useState(!1),De=r.useCallback(async()=>{k(!0);try{const j=await Gf(),Z=j?.data?.resultset||j?.data||[];ks(Array.isArray(Z)?Z:[])}catch(j){console.error("[CieloTerminal] listOrders error",j),ks([]),t({title:"Erro ao carregar pedidos Cielo",description:j?.response?.data?.error||j?.message||"Tente novamente.",variant:"destructive"})}k(!1)},[t]);r.useEffect(()=>{De()},[De]);const Ne=async j=>{I(j);try{const Z=await Uf(j,h||void 0);if(Z?.ok){const Je=Z.already_sent?`Pedido #${j} já estava no terminal (${Z.cielo_order_id?.slice(0,8)}…)`:`Pedido #${j} enviado ao terminal! ID: ${Z.cielo_order_id?.slice(0,8)}…`;t({title:"Pedido enviado",description:Je}),L(js=>[{pedidoId:j,cieloOrderId:Z.cielo_order_id,status:"ENTERED",sentAt:new Date},...js.filter(zs=>zs.pedidoId!==j)]),qe(),De()}else t({title:"Erro ao enviar pedido",description:Z?.error||"Falha ao enviar para o terminal.",variant:"destructive"})}catch(Z){t({title:"Erro ao enviar pedido",description:Z?.response?.data?.error||Z?.message||"Tente novamente.",variant:"destructive"})}I(null)},es=async j=>{N(j);try{const Z=await Vf(j);if(Z?.ok&&(C(Z),L(Je=>Je.map(js=>js.cieloOrderId===j?{...js,status:Z.cielo_status}:js)),Z.cielo_status==="PAID")){const Je=Z.synced?'Pedido local atualizado para "pago" automaticamente.':`Pedido ${j.slice(0,8)}… foi pago no terminal.`;t({title:"Pagamento confirmado!",description:Je}),qe(),De()}}catch(Z){t({title:"Falha ao consultar status",description:Z?.response?.data?.error||Z?.message||"Tente novamente.",variant:"destructive"})}N(null)},ss=async j=>{try{(await Hf(j))?.ok&&(t({title:"Pedido fechado",description:"Pedido fechado no terminal Cielo."}),De())}catch(Z){t({title:"Erro ao fechar pedido",description:Z?.response?.data?.error||Z?.message||"Tente novamente.",variant:"destructive"})}},[We,hs]=r.useState(null),Is=async(j,Z)=>{hs(j);try{(await Kf(j,Z))?.ok&&(t({title:"Status alterado",description:`Operação ${Z} executada com sucesso.`}),De())}catch(Je){t({title:"Erro ao alterar status",description:Je?.response?.data?.error||Je?.message||"Tente novamente.",variant:"destructive"})}hs(null)},[Y,Q]=r.useState(null),X=j=>!!j.dados_gateway?.cielo_order_id||q.some(Z=>Z.pedidoId===j.id),V=j=>j.dados_gateway?.cielo_order_id||q.find(Z=>Z.pedidoId===j.id)?.cieloOrderId,pe=j=>{if(!j)return"—";try{const Z=j instanceof Date?j:new Date(j);return Number.isNaN(Z?.getTime())?"—":new Intl.DateTimeFormat("pt-BR",{timeZone:"UTC"}).format(Z)}catch{return"—"}},Ce=j=>{if(!j)return"—";try{const Z=j instanceof Date?j:new Date(j);return Number.isNaN(Z?.getTime())?"—":new Intl.DateTimeFormat("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(Z)}catch{return"—"}},[Ue,Xe]=r.useState(""),[Ve,bs]=r.useState([]),[ts,R]=r.useState(""),[Le,as]=r.useState(""),[ms,Ke]=r.useState(!1),[gs,fs]=r.useState(2),[Ms,Fs]=r.useState("visa_master_diners"),[As,ws]=r.useState(null),[Rs,us]=r.useState(""),[Gs,Ss]=r.useState([]),[ys,Ps]=r.useState(!1),[Bs,dt]=r.useState(!1),[Ts,Mt]=r.useState(""),[Ys,ht]=r.useState(""),[ea,Xs]=r.useState(""),[xt,ia]=r.useState(""),[oa,st]=r.useState(""),[wt,va]=r.useState(!1),[la,da]=r.useState(!1),[Tt,Js]=r.useState(null),Ft=Tr(),ba=Ue?`/eventos/${Ue}?populate[tipos_ingresso][populate][tipo_ingresso]=*&populate[lotes][populate][tipo_ingresso]=*`:null,{data:Kt,isLoading:_t}=Ks(["cielo-ds-evento",Ue],ba,{enabled:!!Ue,staleTime:3e4}),{data:ca}=Ks(["cielo-checkout-config"],"/config",{staleTime:6e4}),Na=r.useMemo(()=>{const j=ca?.data||ca||{},Z=j.attributes||j||{};
91try{return typeof Z.cielo_parcelamento=="string"?JSON.parse(Z.cielo_parcelamento):Z.cielo_parcelamento||{}}catch{return{}}},[ca]),Qt=r.useMemo(()=>{const j=Na||{};return j[Ms]||j.visa_master_diners||{}},[Na,Ms]),ua=r.useMemo(()=>Object.keys(Na||{}).filter(Z=>typeof Na[Z]=="object"),[Na]),pt=r.useMemo(()=>{if(!Kt?.data)return null;const j=Kt.data;return j?.attributes?{...j.attributes,id:j.id,documentId:j.documentId}:j},[Kt]),ft=r.useMemo(()=>{if(!pt)return[];let j=[];return Array.isArray(pt?.tipos_ingresso?.data)?j=pt.tipos_ingresso.data:Array.isArray(pt?.tipos_ingresso)&&(j=pt.tipos_ingresso),j.map(Z=>Z?.attributes?{...Z.attributes,id:Z.id}:Z).filter(Z=>Z.ativo!==!1)},[pt]),Wt=r.useMemo(()=>{if(!pt)return[];let j=[];return Array.isArray(pt?.lotes?.data)?j=pt.lotes.data:Array.isArray(pt?.lotes)&&(j=pt.lotes),j.map(Z=>{const Je=Z?.attributes?{...Z.attributes,id:Z.id}:Z;return{...Je,tipoId:String(Je?.tipo_ingresso?.id??Je?.tipo_ingresso??"")}})},[pt]),ya=r.useCallback(j=>{const Z=Number(j?.quantidade_disponivel??-1);return Number.isFinite(Z)&&Z===0||j?.ativo===!1&&j?.manual_ativo!==!0?!1:j?.manual_ativo===!0||j?.ativo!==!1},[]),Dt=r.useMemo(()=>{const j=new Map;for(const Z of ft){const Je=String(Wr(Z.tipo_ingresso)),js=Wt.filter(zs=>zs.tipoId===Je&&ya(zs)).sort((zs,Ge)=>Number(zs.ordem||0)-Number(Ge.ordem||0));js.length&&j.set(Je,js[0])}return j},[ft,Wt,ya]),gt=r.useMemo(()=>ft.filter(j=>{const Z=String(Wr(j.tipo_ingresso));return Wt.some(js=>js.tipoId===Z)?Dt.has(Z):!0}),[ft,Wt,Dt]),d=r.useCallback((j,Z)=>{const Je=Z?.preco_lote!=null?Number(Z.preco_lote):j?.preco_especifico!=null?Number(j.preco_especifico):Number(pt?.preco||0),js=Wa(j?.tipo_ingresso),zs=Number(Z?.desconto_percentual??js?.desconto_percentual??0);return Je*(1-zs/100)},[pt]),_=r.useCallback(j=>{const Z=Wa(j.tipo_ingresso),Je=String(Wr(j.tipo_ingresso)),js=Dt.get(Je)||null,zs=d(j,js),Ge=pt?.id||T.find(Ws=>Ws.documentId===Ue)?.id||null;bs(Ws=>{const jt=`${Ue}-${Je}-${js?.id||"no-lote"}`;return Ws.find(Ot=>Ot.key===jt)?Ws.map(Ot=>Ot.key===jt?{...Ot,quantidade:Ot.quantidade+1}:Ot):[...Ws,{key:jt,eventoId:Ge,eventoDocumentId:Ue,tipoIngressoId:Je,loteId:js?.id||null,tipoNome:Z?.nome||"Ingresso",loteNome:js?.nome||null,precoUnitario:zs,quantidade:1}]})},[Ue,Dt,d,pt,T]),H=r.useCallback((j,Z)=>{bs(Je=>Je.map(js=>js.key===j?{...js,quantidade:Math.max(0,js.quantidade+Z)}:js).filter(js=>js.quantidade>0))},[]),ce=r.useCallback(j=>{bs(Z=>Z.filter(Je=>Je.key!==j))},[]),Pe=.07,Ie=r.useMemo(()=>Ve.reduce((j,Z)=>j+Z.precoUnitario*Z.quantidade,0),[Ve]),Ye=r.useMemo(()=>Math.round((Ie*Pe+Number.EPSILON)*100)/100,[Ie]),Ns=ts==="CREDITO_PARCELADO_LOJA",_s=r.useMemo(()=>{if(!Ns||!gs)return 0;const j=Qt?.[String(gs)];return typeof j=="number"?j:0},[Ns,gs,Qt]),Hs=r.useMemo(()=>{if(_s<=0)return 0;const j=Ie+Ye;return Math.round((j*(_s/100)+Number.EPSILON)*100)/100},[Ie,Ye,_s]),Os=r.useMemo(()=>Math.round((Ie+Ye+Hs+Number.EPSILON)*100)/100,[Ie,Ye,Hs]),B=r.useMemo(()=>{const j=Object.keys(Qt||{}).map(Number).filter(Boolean);return j.length>0?Math.max(...j):12},[Qt]),de=j=>(j||"").replace(/\D/g,""),Re=j=>{const Z=de(j);return Z.length<=2?Z:Z.length<=7?`(${Z.slice(0,2)}) ${Z.slice(2)}`:Z.length<=11?`(${Z.slice(0,2)}) ${Z.slice(2,7)}-${Z.slice(7)}`:`(${Z.slice(0,2)}) ${Z.slice(2,7)}-${Z.slice(7,11)}`},He=j=>{const Z=de(j);return Z.length<=3?Z:Z.length<=6?`${Z.slice(0,3)}.${Z.slice(3)}`:Z.length<=9?`${Z.slice(0,3)}.${Z.slice(3,6)}.${Z.slice(6)}`:`${Z.slice(0,3)}.${Z.slice(3,6)}.${Z.slice(6,9)}-${Z.slice(9,11)}`},ps=r.useCallback(async j=>{if(!j||j.trim().length<2){Ss([]);return}Ps(!0);try{const Z=encodeURIComponent(j.trim()),zs=(await(await fetch(`${Ft}/usuarios?filters[$or][0][email][$containsi]=${Z}&filters[$or][1][nome][$containsi]=${Z}&filters[$or][2][cpf][$containsi]=${Z}&pagination[pageSize]=10&fields[0]=id&fields[1]=nome&fields[2]=email&fields[3]=cpf&fields[4]=telefone`,{headers:{"Content-Type":"application/json"}})).json())?.data||[];Ss(zs.map(Ge=>({id:Ge.id,nome:Ge.attributes?.nome||Ge.nome||"",email:Ge.attributes?.email||Ge.email||"",cpf:Ge.attributes?.cpf||Ge.cpf||"",telefone:Ge.attributes?.telefone||Ge.telefone||""})))}catch(Z){console.error("Usuario search error",Z),Ss([])}Ps(!1)},[Ft]);r.useEffect(()=>{const j=setTimeout(()=>{ps(Rs)},300);return()=>clearTimeout(j)},[Rs,ps]);const vs=j=>{ws(j),us(""),Ss([])},Es=()=>{ws(null)},cs=()=>{Mt(""),ht(""),Xs(""),ia(""),st(""),Js(null),dt(!0)},qs=async j=>{j.preventDefault(),da(!0),Js(null);try{const Z=(Ys||"").split("@")[0].replace(/[^a-zA-Z0-9._-]/g,"").slice(0,30)||"user",Je=`${Ft}/auth/local/register`,js=await fetch(Je,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:Z,email:Ys,password:oa})}),zs=await js.json();if(!js.ok)throw new Error(zs.error?.message||"Falha ao registrar");await new Promise(ma=>setTimeout(ma,300));const jt=(await(await fetch(`${Ft}/usuarios?filters[email][$eq]=${encodeURIComponent(Ys)}&pagination[pageSize]=1&fields[0]=id&fields[1]=nome&fields[2]=email&fields[3]=cpf&fields[4]=telefone`,{headers:{"Content-Type":"application/json"}})).json())?.data?.[0];if(jt){const ma=jt.id,Ot=`${Ft}/usuarios/${ma}`;await fetch(Ot,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zs.jwt}`},body:JSON.stringify({data:{nome:Ts.trim()||Z,cpf:de(ea),telefone:de(xt)}})}),ws({id:ma,nome:Ts.trim()||Z,email:Ys,cpf:de(ea),telefone:de(xt)})}dt(!1),t({title:"Usuário criado",description:`${Ts||Ys} cadastrado com sucesso.`})}catch(Z){Js(Z.message||"Erro ao criar usuário")}da(!1)},Qs=async()=>
91{if(Ve.length!==0){if(!As?.id){t({title:"Selecione um usuário",description:"É necessário selecionar ou criar um usuário para a venda.",variant:"destructive"});return}Ke(!0);try{const j=Ve.map(Je=>({eventoId:Je.eventoId,eventoDocumentId:Je.eventoDocumentId,tipoIngressoId:Je.tipoIngressoId,loteId:Je.loteId,quantidade:Je.quantidade,precoUnitario:Je.precoUnitario})),Z=await Bf({items:j,paymentCode:ts||void 0,notes:Le||void 0,usuarioId:As.id,parcelas:Ns?gs:void 0,bandeira:Ns?Ms:void 0});Z?.ok?(t({title:"Venda enviada ao terminal!",description:`Pedido #${Z.pedidoId} criado e enviado. Cielo ID: ${Z.cielo_order_id?.slice(0,8)}…`}),bs([]),as(""),De()):t({title:"Erro ao criar venda",description:Z?.error||"Falha ao processar venda direta.",variant:"destructive"})}catch(j){t({title:"Erro ao criar venda",description:j?.response?.data?.error||j?.message||"Tente novamente.",variant:"destructive"})}Ke(!1)}};return r.useEffect(()=>{bs([])},[Ue]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(Vd,{className:"h-6 w-6"}),"Terminal Vendas Físicas"]}),e.jsx("p",{className:"text-muted-foreground",children:"Envie pedidos para o terminal de pagamento Cielo LIO"})]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:De,disabled:xs,children:[e.jsx(ta,{className:`h-4 w-4 mr-2 ${xs?"animate-spin":""}`}),"Atualizar"]})]}),e.jsxs(Lr,{value:oe,onValueChange:ve,className:"w-full",children:[e.jsxs(Mr,{className:`grid w-full ${u?"grid-cols-2":"grid-cols-3"}`,children:[e.jsxs(Gt,{value:"venda-direta",children:[e.jsx(Cr,{className:"h-4 w-4 mr-2"})," Venda Direta"]}),e.jsxs(Gt,{value:"pedidos",children:[e.jsx(Cm,{className:"h-4 w-4 mr-2"})," Pedidos no Terminal"]}),!u&&e.jsxs(Gt,{value:"extrato",children:[e.jsx(km,{className:"h-4 w-4 mr-2"})," Extrato"]})]}),e.jsxs(Ht,{value:"venda-direta",className:"space-y-4",children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsx(ze,{className:"text-base",children:"1. Selecione o Evento"})}),e.jsx(ge,{children:J?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(It,{size:28})}):T.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum evento encontrado."}):e.jsxs(rs,{value:Ue,onValueChange:Xe,children:[e.jsx(ns,{className:"w-full",children:e.jsx(is,{placeholder:"Selecione um evento..."})}),e.jsx(os,{children:T.map(j=>e.jsxs(xe,{value:j.documentId||String(j.id),children:[j.titulo," — ",pe(j.data_evento)]},j.id))})]})})]}),Ue&&e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsx(ze,{className:"text-base",children:"2. Tipos de Ingresso"})}),e.jsx(ge,{children:_t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(It,{size:28})}):gt.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum tipo de ingresso ativo para este evento."}):e.jsx("div",{className:"space-y-2",children:gt.map(j=>{const Z=Wa(j.tipo_ingresso),Je=String(Wr(j.tipo_ingresso)),js=Dt.get(Je)||null,zs=d(j,js),Ge=js?.quantidade_disponivel??j?.quantidade_disponivel??null,Ws=Ve.find(jt=>jt.tipoIngressoId===Je&&jt.loteId===(js?.id||null));return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium text-sm",children:Z?.nome||"Ingresso"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[js&&e.jsx(je,{variant:"outline",className:"text-xs",children:js.nome}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:a(zs)}),Ge!=null&&Number.isFinite(Number(Ge))&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",Ge," disp.)"]})]})]}),e.jsx("div",{className:"flex items-center gap-1",children:Ws?e.jsxs(e.Fragment,{children:[e.jsx(w,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>H(Ws.key,-1),children:e.jsx(Sm,{className:"h-3 w-3"})}),e.jsx("span",{className:"w-8 text-center text-sm font-medium",children:Ws.quantidade}),e.jsx(w,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>H(Ws.key,1),children:e.jsx(et,{className:"h-3 w-3"})})]}):e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>_(j),children:[e.jsx(et,{className:"h-3.5 w-3.5 mr-1"}),"Adicionar"]})})]},j.id||Je)})})})]}),Ue&&e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsxs(ze,{className:"text-base flex items-center gap-2",children:[e.jsx(Er,{className:"h-4 w-4"}),"3. Cliente"]})}),e.jsx(ge,{className:"space-y-3",children:As?e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium text-sm",children:As.nome||As.email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[As.email,As.cpf?` — CPF: ${He(As.cpf)}`:""]}),As.telefone&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Tel: ",Re(As.telefone)]})]}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:Es,children:e.jsx(yt,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(At,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Te,{placeholder:"Buscar por nome, email ou CPF...",value:Rs,onChange:j=>us(j.target.value),className:"pl-9"}),ys&&e.jsx(Cs,{className:"absolute right-2.5 top-2.5 h-4 w-4 animate-spin text-muted-foreground"})]}),e.jsx(w,{variant:"outline",size:"icon",onClick:cs,title:"Criar novo usuário",children:e.jsx(Kn,{className:"h-4 w-4"})})]}),Gs.length>0&&e.jsx("div",{className:"border rounded-lg divide-y max-h-48 overflow-y-auto",children:Gs.map(j=>e.jsxs("div",{role:"button",tabIndex:0,className:"flex items-center justify-between p-2.5 hover:bg-muted/50 cursor-pointer transition-colors focus:outline-none focus:bg-muted/50",onClick:()=>vs(j),onKeyDown:Z=>{(Z.key==="Enter"||Z.key===" ")&&vs(j)},children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:j.nome||j.email}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[j.email,j.cpf?` — CPF: ${He(j.cpf)}`:""]})]}),e.jsx(wa,{className:"h-4 w-4 text-primary opacity-0 group-hover:opacity-100"})]},j.id))}),Rs.length>=2&&!ys&&Gs.length===0&&e.jsxs("div",{className:"text-center py-3 text-sm text-muted-foreground",children:["Nenhum usuário encontrado."," ",e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:cs,children:"Criar novo"})]})]})})]}),Ve.length>0&&e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsx(ze,{className:"text-base",children:"4. Resumo & Enviar"})}),e.jsxs(ge,{className:"space-y-4",children:[e.jsx("div",{className:"space-y-2",children:Ve.map(j=>e.jsxs("div",{className:"flex items-center justify-between py-1.5 border-b border-dashed last:border-0",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm font-medium",children:[j.tipoNome,j.loteNome?` — ${j.loteNome}`:""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[j.quantidade,"x ",a(j.precoUnitario)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:a(j.prec
91oUnitario*j.quantidade)}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>ce(j.key),children:e.jsx(Xt,{className:"h-3.5 w-3.5"})})]})]},j.key))}),e.jsxs("div",{className:"space-y-1 border-t pt-3",children:[i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsx("span",{children:"Subtotal"}),e.jsx("span",{children:a(Ie)})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsx("span",{children:"Taxa de Serviço (7%)"}),e.jsx("span",{children:a(Ye)})]}),Ns&&Hs>0&&e.jsxs("div",{className:"flex items-center justify-between text-sm text-orange-600",children:[e.jsxs("span",{children:["Parcelamento ",gs,"x (",_s,"%)"]}),e.jsxs("span",{children:["+",a(Hs)]})]})]}),e.jsxs("div",{className:"flex items-center justify-between font-bold pt-1",children:[e.jsx("span",{children:"Total"}),e.jsx("span",{className:"text-lg text-primary",children:a(Os)})]}),Ns&&gs>1&&e.jsxs("div",{className:"text-xs text-muted-foreground text-right",children:[gs,"x de ",a(Os/gs)]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Método de Pagamento"}),e.jsxs(rs,{value:ts,onValueChange:j=>{R(j),j!=="CREDITO_PARCELADO_LOJA"&&fs(2)},children:[e.jsx(ns,{className:"w-full md:w-72",children:e.jsx(is,{placeholder:"Qualquer (terminal decide)"})}),e.jsx(os,{children:Id.map(j=>e.jsx(xe,{value:j.value||"any",children:j.label},j.value||"any"))})]})]}),Ns&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Bandeira do Cartão"}),e.jsxs(rs,{value:Ms,onValueChange:Fs,children:[e.jsx(ns,{className:"w-full md:w-72",children:e.jsx(is,{})}),e.jsx(os,{children:ua.length>0?ua.map(j=>{const Z={visa_master_diners:"Visa / Master / Diners",elo:"Elo"};return e.jsx(xe,{value:j,children:Z[j]||j},j)}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{value:"visa_master_diners",children:"Visa / Master / Diners"}),e.jsx(xe,{value:"elo",children:"Elo"})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Número de Parcelas"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(rs,{value:String(gs),onValueChange:j=>fs(Number(j)),children:[e.jsx(ns,{className:"w-full md:w-72",children:e.jsx(is,{})}),e.jsx(os,{children:Array.from({length:B-1},(j,Z)=>Z+2).map(j=>{const Z=Qt?.[String(j)],Je=typeof Z=="number"?` (+${Z}%)`:"";return e.jsxs(xe,{value:String(j),children:[j,"x",Je]},j)})})]}),_s>0&&e.jsxs("span",{className:"text-sm text-orange-600 whitespace-nowrap",children:["+",_s,"% de juros"]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Observação (opcional)"}),e.jsx(Te,{placeholder:"Ex: Mesa 5, Cliente João...",value:Le,onChange:j=>as(j.target.value)})]}),e.jsxs(w,{className:"w-full",size:"lg",onClick:Qs,disabled:ms||Ve.length===0,children:[ms?e.jsx(Cs,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Enviar ao Terminal (",Ve.reduce((j,Z)=>j+Z.quantidade,0)," itens)"]})]})]})]}),e.jsxs(Ht,{value:"enviar",className:"space-y-4",children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsx(ze,{className:"text-base",children:"1. Selecione o Evento"})}),e.jsx(ge,{children:J?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(It,{size:28})}):T.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum evento encontrado."}):e.jsx("div",{className:"space-y-2",children:T.map(j=>{const Z=l===String(j.id);return e.jsx("button",{onClick:()=>{c(Z?"":String(j.id)),x("")},className:`w-full text-left rounded-lg border p-3 transition-colors ${Z?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/50"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[j.imagem?e.jsx("img",{src:j.imagem,alt:"",className:"h-10 w-10 rounded-md object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-md bg-muted flex items-center justify-center text-xs text-muted-foreground",children:"🎫"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:j.titulo}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[pe(j.data_evento)," ",j.local?`• ${j.local}`:""]})]})]}),Z?e.jsx(Zd,{className:"h-4 w-4 text-primary"}):e.jsx(ra,{className:"h-4 w-4 text-muted-foreground"})]})},j.id)})})})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsx(ze,{className:"text-base",children:"2. Método de Pagamento"})}),e.jsxs(ge,{children:[e.jsxs(rs,{value:h,onValueChange:p,children:[e.jsx(ns,{className:"w-full md:w-72",children:e.jsx(is,{placeholder:"Qualquer 
91(terminal decide)"})}),e.jsx(os,{children:Id.map(j=>e.jsx(xe,{value:j.value||"any",children:j.label},j.value||"any"))})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Se não selecionar, o operador escolhe no terminal."})]})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsxs(ze,{className:"text-base flex items-center justify-between",children:[e.jsx("span",{children:"3. Pedidos Pendentes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(At,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Te,{placeholder:"Buscar por ID, nome...",value:m,onChange:j=>x(j.target.value),className:"pl-8 h-9 w-48 text-sm"})]}),e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>qe(),children:e.jsx(ta,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(ge,{children:Ze?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(It,{size:28})}):we.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Nenhum pedido pendente para este evento."}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"w-12",children:"#"}),e.jsx(ue,{children:"Cliente"}),e.jsx(ue,{className:"hidden md:table-cell",children:"Itens"}),e.jsx(ue,{className:"text-right",children:"Total"}),e.jsx(ue,{className:"hidden sm:table-cell text-center",children:"Status"}),e.jsx(ue,{className:"text-right",children:"Ação"})]})}),e.jsx(Ct,{children:we.map(j=>{const Z=X(j),Je=V(j);return e.jsxs($s,{className:Z?"bg-muted/30":"",children:[e.jsx(ye,{className:"font-mono text-xs",children:j.id}),e.jsx(ye,{children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium truncate max-w-[120px] md:max-w-[160px]",children:j.usuario?.nome||"—"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[120px] md:max-w-[160px]",children:j.usuario?.email||""}),e.jsxs("div",{className:"md:hidden mt-0.5",children:[(j.items||[]).slice(0,2).map((js,zs)=>{const Ge=js.nome_item||js.estoque_item?.nome||js.tipo_ingresso?.nome||`Item ${zs+1}`;return e.jsxs("p",{className:"text-[10px] text-muted-foreground truncate",children:[Number(js.quantidade||1),"x ",Ge]},js.id||zs)}),(j.items||[]).length>2&&e.jsxs("p",{className:"text-[10px] text-muted-foreground italic",children:["+",(j.items||[]).length-2," mais"]})]})]})}),e.jsx(ye,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"space-y-0.5",children:[(j.items||[]).slice(0,3).map((js,zs)=>{const Ge=js.nome_item||js.estoque_item?.nome||js.tipo_ingresso?.nome||`Item ${zs+1}`,Ws=Number(js.quantidade||1);return e.jsxs("p",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:[Ws,"x ",Ge]},js.id||zs)}),(j.items||[]).length>3&&e.jsxs("p",{className:"text-xs text-muted-foreground italic",children:["+",(j.items||[]).length-3," mais"]}),(j.items||[]).length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"—"})]})}),e.jsx(ye,{className:"text-right font-medium text-xs sm:text-sm",children:a(j.total,j.moeda)}),e.jsx(ye,{className:"hidden sm:table-cell text-center",children:Z?e.jsx(je,{className:"bg-blue-400 text-blue-900 text-xs",children:"No Terminal"}
91):e.jsx(je,{className:Qn("pendente").className+" text-xs",children:"Pendente"})}),e.jsx(ye,{className:"text-right",children:Z?e.jsx("div",{className:"flex items-center justify-end gap-1",children:e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>es(Je),disabled:g===Je,title:"Consultar status",children:g===Je?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Vt,{className:"h-3.5 w-3.5"})})}):e.jsxs(w,{size:"sm",onClick:()=>Ne(j.id),disabled:f===j.id,children:[f===j.id?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin mr-1"}):e.jsx(qa,{className:"h-3.5 w-3.5 mr-1"}),"Enviar"]})})]},j.id)})})]})})})]})]})]}),e.jsx(Ht,{value:"pedidos",className:"space-y-4",children:e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsxs(ze,{className:"text-base flex items-center justify-between",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ul,{className:"h-4 w-4"})," Pedidos na maquininha"]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:De,disabled:xs,children:[e.jsx(ta,{className:`h-3.5 w-3.5 mr-1 ${xs?"animate-spin":""}`}),"Atualizar"]})]})}),e.jsx(ge,{children:xs?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(It,{size:28})}):Me.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Nenhum pedido encontrado no terminal Cielo."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-md border overflow-x-auto hidden md:block",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{children:"Cielo ID"}),e.jsx(ue,{children:"Referência"}),e.jsx(ue,{className:"text-right",children:"Valor"}),e.jsx(ue,{className:"text-center",children:"Status"}),e.jsx(ue,{children:"Criado em"}),e.jsx(ue,{className:"text-right",children:"Ações"})]})}),e.jsx(Ct,{children:Me.map(j=>{const Z=Un(j.status);return e.jsxs($s,{children:[e.jsxs(ye,{className:"font-mono text-xs max-w-[120px] truncate",title:j.id,children:[j.id?.slice(0,8),"…"]}),e.jsx(ye,{className:"text-sm",children:j.reference||j.number||"—"}),e.jsx(ye,{className:"text-right font-medium",children:a((j.price||0)/100)}),e.jsx(ye,{className:"text-center",children:e.jsxs(je,{className:`${Z.className} text-xs`,children:[e.jsx(ro,{status:j.status}),e.jsx("span",{className:"ml-1",children:Z.label})]})}),e.jsx(ye,{className:"text-xs text-muted-foreground",children:Ce(j.created_at)}),e.jsx(ye,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1 flex-wrap",children:[e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>es(j.id),disabled:g===j.id,title:"Consultar status",children:g===j.id?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Vt,{className:"h-3.5 w-3.5"})}),j.status==="DRAFT"&&e.jsx(w,{variant:"outline",size:"sm",onClick:()=>Is(j.id,"PLACE"),disabled:We===j.id,title:"Enviar ao terminal (PLACE)",children:We===j.id?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(qa,{className:"h-3.5 w-3.5"})}),j.status==="ENTERED"&&i&&e.jsx(w,{variant:"outline",size:"sm",onClick:()=>Is(j.id,"PAY"),disabled:We===j.id,title:"Marcar como pago (PAY)",className:"text-xs",children:We===j.id?e.jsx(Cs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx("span",{className:"text-green-600",children:"Marcar como Pago"})}),j.status==="PAID"&&e.jsx(w,{variant:"ghost",size:"sm",onClick:()=>ss(j.id),disabled:We===j.id,title:"Fechar pedido",children:e.jsx(wa,{className:"h-3.5 w-3.5"})})]})})]},j.id)})})]})}),e.jsx("div",{className:"md:hidden space-y-2",children:Me.map(j=>{const Z=Un(j.status);return e.jsxs("div",{className:"rounded-lg border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:j.reference||j.number||"—"}),e.jsxs("p",{className:"font-mono text-[10px] text-muted-foreground truncate",children:[j.id?.slice(0,12),"…"]})]}),e.jsxs(je,{className:`${Z.className} text-[10px] shrink-0`,children:[e.jsx(ro,{status:j.status}),e.jsx("span",{className:"ml-1",children:Z.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-lg font-bold",children:a((j.price||0)/100)}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ce(j.created_at)})]}),e.jsxs("div",{className:"flex items-center gap-1.5 pt-1 border-t",children:[e.jsxs(w,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>es(j.id),disabled:g===j.id,children:[g===j.id?e.jsx(Cs,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(Vt,{className:"h-3 w-3 mr-1"}),"Status"]}),j.status==="DRAFT"&&e.jsxs(w,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>Is(j.id,"PLACE"),disabled:We===j.id,children:[We===j.id?e.jsx(Cs,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(qa,{className:"h-3 w-3 mr-1"}),"Enviar"]}),j.status==="ENTERED"&&i&&e.jsxs(w,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>Is(j.id,"PAY"),disabled:We===j.id,children:[We===j.id?e.jsx(Cs,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(wa,{className:"h-3 w-3 mr-1 text-green-600"}),e.jsx("span",{className:"text-green-600",children:"Pago"})]}),j.status==="PAID"&&e.jsxs(w,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>ss(j.id),disabled:We===j.id,children:[e.jsx(wa,{className:"h-3 w-3 mr-1"}),"Fechar"]})]})]},j.id)})})]})})]})}),!u&&e.jsxs(Ht,{value:"extrato",className:"space-y-4",children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsxs(ze,{className:"text-base flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4"}),"Período do Extrato"]})}),e.jsx(ge,{children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-xs",children:"De"}),e.jsx(Te,{type:"date",value:E,onChange:j=>A(j.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-xs",children:"Até"}),e.jsx(Te,{type:"date",value:S,onChange:j=>P(j.target.value),className:"w-40"})]}),e.jsxs(w,{variant:"outline",onClick:()=>{fe(!1),le(E,S),_e()},disabled:re||!E||!S,children:[re?e.jsx(Cs,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Atualizar"]})]})})]}),re&&!F&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Cs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),F&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(he,{className:"border-green-500/30",children:e.jsxs(ge,{className:"pt-4 pb-3 px-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Disponível"}),e.jsx("p",{className:"text-xl font-bold text-green-500",children:a(F.disponivel||0)}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:[F.totalPedidos||0," pedido(s) n
91o período"]})]})}),e.jsx(he,{className:"border-yellow-500/30",children:e.jsxs(ge,{className:"pt-4 pb-3 px-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Transferência Pendente"}),e.jsx("p",{className:"text-xl font-bold text-yellow-500",children:a(F.totalTransferenciaPendente||0)}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Aguardando processamento"})]})}),e.jsx(he,{className:"border-blue-500/30",children:e.jsxs(ge,{className:"pt-4 pb-3 px-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Transferido"}),e.jsx("p",{className:"text-xl font-bold text-blue-500",children:a(F.totalTransferido||0)}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Total já transferido"})]})})]}),e.jsx(he,{children:e.jsx(ge,{className:"pt-4 pb-3 px-4",children:e.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-1 text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Total (período): ",e.jsx("span",{className:"font-medium text-foreground",children:a(F.totalLiquido||0)})]}),i&&e.jsxs("span",{className:"text-muted-foreground",children:["Taxa Serviço: ",e.jsx("span",{className:"font-medium text-orange-500",children:a(F.totalTaxaServico||0)})]}),(F.totalTaxaParcelamento||0)>0&&e.jsxs("span",{className:"text-muted-foreground",children:["Taxa Parcel.: ",e.jsx("span",{className:"font-medium text-orange-500",children:a(F.totalTaxaParcelamento||0)})]})]})})}),(F.disponivel||0)>0&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{onClick:()=>{ae(String(F.disponivel||0)),ke(!0)},className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Sn,{className:"h-4 w-4 mr-2"}),"Solicitar Transferência"]})}),(F.pedidos||[]).length>0&&e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsxs(ze,{className:"text-base flex items-center gap-2",children:[e.jsx(tn,{className:"h-4 w-4"}),"Pedidos no Período (",F.pedidos.length,")"]})}),e.jsx(ge,{className:"p-0",children:e.jsx("div",{className:"overflow-auto max-h-[400px]",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"w-[50px]",children:"#"}),e.jsx(ue,{className:"hidden sm:table-cell",children:"Data"}),e.jsx(ue,{children:"Cliente"}),e.jsx(ue,{className:"hidden md:table-cell",children:"Evento(s)"}),e.jsx(ue,{className:"text-right",children:"Total"}),e.jsx(ue,{className:"w-[40px]"})]})}),e.jsx(Ct,{children:F.pedidos.map(j=>e.jsxs($s,{children:[e.jsx(ye,{className:"font-mono text-xs",children:j.id}),e.jsx(ye,{className:"hidden sm:table-cell text-xs",children:j.data_pedido?new Date(j.data_pedido).toLocaleDateString("pt-BR"):"—"}),e.jsxs(ye,{className:"text-xs",children:[e.jsx("span",{className:"block truncate max-w-[100px] sm:max-w-none",children:j.usuario?.nome||j.usuario?.email||"—"}),e.jsx("span",{className:"sm:hidden block text-[10px] text-muted-foreground",children:j.data_pedido?new Date(j.data_pedido).toLocaleDateString("pt-BR"):""})]}),e.jsx(ye,{className:"hidden md:table-cell text-xs",children:(j.eventos||[]).map(Z=>Z.titulo).join(", ")||"—"}),e.jsx(ye,{className:"text-right text-xs font-medium",children:a(j.subtotal)}),e.jsx(ye,{className:"text-center",children:e.jsx(w,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Ver pedido",onClick:()=>s(`/dashboard/pedidos?search=${encodeURIComponent(j.id)}`),children:e.jsx(sr,{className:"h-3.5 w-3.5"})})})]},j.id))})]})})})]})]}),e.jsxs(he,{children:[e.jsxs(Be,{className:"pb-3 flex flex-row items-center justify-between",children:[e.jsxs(ze,{className:"text-base flex items-center gap-2",children:[e.jsx(Sn,{className:"h-4 w-4"}),"Histórico de Transferências"]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:_e,disabled:$,children:[e.jsx(ta,{className:`h-3.5 w-3.5 mr-1 ${$?"animate-spin":""}`}),"Atualizar"]})]}),e.jsx(ge,{children:G.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Nenhuma transferência solicitada ainda."}):e.jsx("div",{className:"overflow-auto",children:e.jsxs(vt,{children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"hidden sm:table-cell w-[50px]",children:"#"}),e.jsx(ue,{children:"Data"}),e.jsx(ue,{className:"hidden md:table-cell",children:"Período"}),e.jsx(ue,{className:"text-right",children:"Valor"}),e.jsx(ue,{children:"Status"})]})}),e.jsx(Ct,{children:G.map(j=>e.jsxs($s,{children:[e.jsx(ye,{className:"hidden sm:table-cell font-mono text-xs",children:j.id}),e.jsxs(ye,{className:"text-xs",children:[e.jsx("span",{className:"block",children:j.data_solicitacao?new Date(j.data_solicitacao).toLocaleDateString("pt-BR"):"—"}),e.jsxs("span",{className:"md:hidden block text-[10px] text-muted-foreground",children:[j.periodo_de?new Date(j.periodo_de+"T12:00:00").toLocaleDateString("pt-BR"):"?"," – ",j.periodo_ate?new Date(j.periodo_ate+"T12:00:00").toLocaleDateString("pt-BR"):"?"]})]}),e.jsxs(ye,{className:"hidden md:table-cell text-xs",children:[j.periodo_de?new Date(j.periodo_de+"T12:00:00").toLocaleDateString("pt-BR"):"?"," – ",j.periodo_ate?new Date(j.periodo_ate+"T12:00:00").toLocaleDateString("pt-BR"):"?"]}),e.jsx(ye,{className:"text-right text-xs font-medium",children:a(j.valor||0)}),e.jsx(ye,{children:e.jsx(je,{variant:j.status==="concluida"?"default":j.status==="cancelada"?"destructive":"outline",className:`text-[10px] ${j.status==="pendente"?"border-yellow-500 text-yellow-600":""}`,children:j.status==="pendente"?"Pendente":j.status==="concluida"?"Concluída":"Cancelada"})})]},j.id))})]})})})]})]})]}),e.jsx(at,{open:ie,onOpenChange:ke,children:e.jsxs(rt,{className:"max-w-md",children:[e.jsx(nt,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Sn,{className:"h-5 w-5"}),"Solicitar Transferência"]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-xs",children:"Valor da Transferência (R$)"}),e.jsx(Te,{type:"number",step:"0.01",min:"0.01",max:F?.disponivel||0,value:Fe,onCh
91ange:j=>ae(j.target.value),placeholder:"0,00"}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Disponível: ",a(F?.disponivel||0)]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Período"}),e.jsxs("p",{className:"font-medium",children:[E?new Date(E+"T12:00:00").toLocaleDateString("pt-BR"):"?"," – ",S?new Date(S+"T12:00:00").toLocaleDateString("pt-BR"):"?"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pedidos"}),e.jsx("p",{className:"font-medium",children:F?.totalPedidos||0})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Oe,{className:"text-xs",children:"Observação (opcional)"}),e.jsx(Te,{value:Ae,onChange:j=>be(j.target.value),placeholder:"Ex: transferência mensal, conta corrente..."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(w,{variant:"outline",onClick:()=>ke(!1),disabled:K,children:"Cancelar"}),e.jsxs(w,{className:"bg-green-600 hover:bg-green-700",disabled:K||!Fe||Number(Fe)<=0||Number(Fe)>(F?.disponivel||0),onClick:async()=>{O(!0);try{const j=await Wf({valor:Number(Fe),de:E,ate:S,observacao:Ae||void 0,resumo:{totalBruto:F?.totalBruto,totalTaxaServico:F?.totalTaxaServico,totalTaxaParcelamento:F?.totalTaxaParcelamento,totalLiquido:F?.totalLiquido,totalPedidos:F?.totalPedidos},pedidoIds:(F?.pedidos||[]).map(Z=>Z.id)});j?.ok?(t({title:"Transferência solicitada",description:`Transferência #${j.transfer?.id} criada. ${j.transfer?.email_enviado?"Email enviado para [email protected].":"Email não pôde ser enviado."}`}),ke(!1),be(""),ae(""),le(E,S),_e()):t({title:"Erro",description:j?.error||"Falha ao solicitar transferência",variant:"destructive"})}catch(j){t({title:"Erro",description:j?.response?.data?.error||j?.message||"Falha ao solicitar transferência",variant:"destructive"})}O(!1)},children:[K?e.jsx(Cs,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Sn,{className:"h-4 w-4 mr-2"}),"Confirmar Transferência"]})]})]})]})}),e.jsx(at,{open:!!b,onOpenChange:j=>!j&&C(null),children:e.jsxs(rt,{className:"max-w-lg",children:[e.jsx(nt,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(ul,{className:"h-5 w-5"}),"Detalhes do Pedido Cielo"]})}),b&&e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cielo Order ID"}),e.jsx("p",{className:"font-mono text-xs break-all",children:b.cielo_order_id})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status"}),e.jsxs(je,{className:Un(b.cielo_status).className,children:[e.jsx(ro,{status:b.cielo_status}),e.jsx("span",{className:"ml-1",children:Un(b.cielo_status).label})]})]}),b.pedidoId&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pedido Local"}),e.jsxs("p",{className:"font-medium",children:["#",b.pedidoId]})]}),b.pedido_status&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status Pedido"}),e.jsx(je,{className:Qn(b.pedido_status).className,children:Qn(b.pedido_status).label})]})]}),b.cielo_order&&e.jsxs("div",{className:"space-y-2 border-t pt-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Itens do Pedido"}),(b.cielo_order.items||[]).map(j=>e.jsxs("div",{className:"flex items-center justify-between py-1 border-b border-dashed last:border-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:j.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[j.quantity,"x · SKU: ",j.sku]})]}),e.jsx("p",{className:"text-sm font-medium",children:a((j.unit_price||0)/100)})]},j.id||j.sku)),e.jsxs("div",{className:"flex items-center justify-between pt-2 font-bold",children:[e.jsx("span",{children:"Total"}),e.jsx("span",{children:a((b.cielo_order.price||0)/100)})]})]}),b.transactions?.length>0&&e.jsxs("div",{className:"space-y-2 border-t pt-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Transações"}),b.transactions.map(j=>e.jsxs("div",{className:"rounded-lg border p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:[j.id?.slice(0,12),"…"]}),e.jsxs(je,{variant:"outline",className:"text-xs",children:[j.payment_fields?.primaryProductName||"N/A"," ",j.payment_fields?.secondaryProductName||""]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:a((j.amount||0)/100)}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Autorização: ",j.authorization_code||"—"]})]}),j.card&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[j.card.brand," ",j.card.mask]})]},j.id||j.external_id))]})]})]})}),e.jsx(at,{open:Bs,onOpenChange:dt,children:e.jsxs(rt,{className:"sm:max-w-md",children:[e.jsx(nt,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(Kn,{className:"h-5 w-5"}),"Novo Usuário"]})}),e.jsxs("form",{onSubmit:qs,className:"space-y-4",children:[Tt&&e.jsx("div",{className:"p-3 text-sm text-destructive bg-destructive/10 rounded-lg",children:Tt}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"reg-nome",children:"Nome completo"}),e.jsx(Te,{id:"reg-nome",placeholder:"Nome do cliente",value:Ts,onChange:j=>Mt(j.target.value),required:!0,className:"text-base"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"reg-email",children:"E-mail"}),e.jsx(Te,{id:"reg-email",type:"email",placeholder:"[email protected]",value:Ys,onChange:j=>ht(j.target.value),required:!0,className:"text-base"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"reg-cpf",children:"CPF"}),e.jsx(Te,{id:"reg-cpf",placeholder:"000.000.000-00",value:ea,onChange:j=>Xs(He(j.target.value)),maxLength:14,className:"text-base"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"reg-telefone",children:"WhatsApp / Telefone"}),e.jsx(Te,{id:"reg-telefone",placeholder:"(00) 00000-0000",value:xt,onChange:j=>ia(Re(j.target.value)),maxLength:15,className:"text-base"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Oe,{htmlFor:"reg-password",children:"Senha"}),e.jsxs("div",{className:"relative",children:[e.jsx(Te,{id:"reg-password",type:wt?"text":"password",placeholder:"Senha de acesso",value:oa,onChange:j=>st(j.target.value),required:!0,minLength:6,className:"pr-10 text-base"}),e.jsx("button",{type:"button",className:"absolute right-2.5 top-2.5 text-muted-foreground hover:text-foreground",onClick:()=>va(j=>
91!j),tabIndex:-1,children:wt?e.jsx(Kd,{className:"h-4 w-4"}):e.jsx(Vt,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(w,{type:"button",variant:"outline",onClick:()=>dt(!1),disabled:la,children:"Cancelar"}),e.jsxs(w,{type:"submit",disabled:la,children:[la?e.jsx(Cs,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Kn,{className:"h-4 w-4 mr-2"}),"Criar Usuário"]})]})]})]})})]})}function Ed(s){return String(s).padStart(2,"0")}function Dd(s){if(!s)return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(s);if(!t)return null;const a=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(a.valueOf())?null:a}function Pd(s){return!(s instanceof Date)||Number.isNaN(s.valueOf())?"":`${s.getFullYear()}-${Ed(s.getMonth()+1)}-${Ed(s.getDate())}`}const Rd={root:{base:"relative !w-full",input:{field:{base:"relative w-full",icon:{svg:"h-5 w-5 !text-muted-foreground"},input:{base:"block w-full border focus:outline-none focus:ring-1 disabled:cursor-not-allowed disabled:opacity-50",colors:{gray:"!border-input !bg-background !text-foreground !placeholder:text-muted-foreground focus:!border-ring focus:!ring-ring"},sizes:{md:"!px-3 !py-2 !text-sm"},withIcon:{on:"!pl-10",off:""},withAddon:{on:"!rounded-r-md",off:"!rounded-md"}}}}},popup:{root:{base:"absolute top-10 !z-50 block pt-2",inline:"relative top-0 z-auto",inner:"inline-block !rounded-xl !bg-popover !p-4 !text-popover-foreground !shadow-md"},header:{title:"!px-2 !py-3 text-center font-semibold !text-popover-foreground",selectors:{base:"!mb-2 flex justify-between",button:{base:"!rounded-lg !bg-background !px-5 !py-2.5 !text-sm font-semibold !text-foreground hover:!bg-accent focus:outline-none focus:!ring-2 focus:!ring-ring"}}},view:{base:"!p-1"},footer:{base:"!mt-2 flex !space-x-2",button:{base:"!w-full !rounded-lg !px-5 !py-2 text-center !text-sm font-medium focus:!ring-2 focus:!ring-ring",today:"!bg-primary !text-primary-foreground hover:!bg-primary/90",clear:"!border !border-input !bg-background !text-foreground hover:!bg-accent"}}},views:{days:{header:{title:"!h-6 text-center !text-sm font-medium leading-6 !text-muted-foreground"},items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}},months:{items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}},years:{items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}},decades:{items:{item:{base:"block flex-1 cursor-pointer !rounded-lg border-0 text-center !text-sm font-semibold leading-9 !text-foreground hover:!bg-accent",selected:"!bg-primary !text-primary-foreground hover:!bg-primary/90",disabled:"!text-muted-foreground"}}}}},Jr=s=>Number(s||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),Td="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",$d=(s=8)=>{let t="";for(;t.length<s;){const a=new Uint8Array(s);crypto.getRandomValues(a),a.forEach(n=>{t.length<s&&(t+=Td[n%Td.length])})}return t},Yf=s=>{if(!s.active)return e.jsx(je,{variant:"secondary",children:"Inativo"});const t=new Date;return s.data_inicio&&ec(t,zt(s.data_inicio))?e.jsx(je,{variant:"outline",className:"border-yellow-500 text-yellow-600",children:"Agendado"}):s.data_fim&&Bo(t,zt(s.data_fim))?e.jsx(je,{variant:"destructive",children:"Expirado"}):s.max_uses!=null&&(s.used_count||0)>=s.max_uses?e.jsx(je,{variant:"destructive",children:"Esgotado"}):e.jsx(je,{className:"bg-green-600 hover:bg-green-700",children:"Ativo"})},Ld={codigo:"",tipo_desconto:"percentual",valor_desconto:"",desconto_maximo:"",evento:"",aplicar_somente_evento:!1,active:!0,max_uses:"",data_inicio:"",data_fim:"",valor_minimo_pedido:"",description:""};function Xf(){const{user:s}=Zt(),{toast:t}=mt(),a=(s?.role?.name||s?.role?.type||s?.role?.code||"").toLowerCase(),n=a.includes("superadmin"),o=a.includes("admin")||n,[i,u]=r.useState(""),[l,c]=r.useState("all"),[m,x]=r.useState("all"),[h,p]=r.useState(1),f=25,[I,g]=r.useState(!1),[N,b]=r.useState(null),[C,q]=r.useState({...Ld}),[L,M]=r.useState(!1),[z,D]=r.useState(null),[E,A]=r.useState(null),S=["cupons-manager",h,f,l,m,i],P=r.useCallback(()=>
91{const O=new URLSearchParams;return O.set("pagination[page]",h),O.set("pagination[pageSize]",f),O.set("sort","createdAt:desc"),l==="active"&&O.set("filters[active][$eq]","true"),l==="inactive"&&O.set("filters[active][$eq]","false"),m&&m!=="all"&&O.set("filters[evento][id][$eq]",m),i&&O.set("filters[codigo][$containsi]",i),O.toString()},[h,f,l,m,i]),{data:F,isLoading:ee,refetch:re}=Ks(S,`/cupom-descontos?${P()}`,{enabled:o}),te=F?.data||[],G=F?.meta?.pagination||{page:1,pageCount:1,total:0},{data:y}=Ks(["cupons-events-options"],"/eventos?fields[0]=titulo&populate[datas_futuras][fields][0]=data&sort=createdAt:desc&pagination[pageSize]=200"),$=r.useMemo(()=>(y?.data||[]).map(oe=>{const ve=oe.attributes||oe;return{id:oe.documentId||oe.id,titulo:ve.titulo||"Sem título"}}),[y]),W=r.useMemo(()=>{let O=te;if(l==="expired"){const oe=new Date;O=O.filter(ve=>ve.data_fim&&Bo(oe,zt(ve.data_fim)))}return l==="depleted"&&(O=O.filter(oe=>oe.max_uses!=null&&(oe.used_count||0)>=oe.max_uses)),O},[te,l]),ie=()=>{b(null),q({...Ld,codigo:$d(8)}),g(!0)},ke=O=>{b(O),q({codigo:O.codigo||"",tipo_desconto:O.tipo_desconto||"percentual",valor_desconto:O.valor_desconto!=null?String(O.valor_desconto):"",desconto_maximo:O.desconto_maximo!=null?String(O.desconto_maximo):"",evento:O.evento?.documentId?String(O.evento.documentId):O.evento?.id?String(O.evento.id):"",aplicar_somente_evento:O.aplicar_somente_evento??!1,active:O.active!==!1,max_uses:O.max_uses!=null?String(O.max_uses):"",data_inicio:O.data_inicio?O.data_inicio.slice(0,16):"",data_fim:O.data_fim?O.data_fim.slice(0,16):"",valor_minimo_pedido:O.valor_minimo_pedido!=null?String(O.valor_minimo_pedido):"",description:O.description||""}),g(!0)},Ae=async()=>{if(!C.codigo?.trim())return t({title:"Erro",description:"Código é obrigatório.",variant:"destructive"});const O=Number(C.valor_desconto);if(!Number.isFinite(O)||O<=0)return t({title:"Erro",description:"Valor do desconto deve ser positivo.",variant:"destructive"});if(C.tipo_desconto==="percentual"&&O>100)return t({title:"Erro",description:"Percentual não pode exceder 100%.",variant:"destructive"});M(!0);try{const oe={codigo:C.codigo.trim().toUpperCase(),tipo_desconto:C.tipo_desconto,valor_desconto:O,desconto_maximo:C.desconto_maximo?Number(C.desconto_maximo):null,evento:C.evento||null,aplicar_somente_evento:C.evento?C.aplicar_somente_evento:!1,active:C.active,max_uses:C.max_uses?Number(C.max_uses):null,data_inicio:C.data_inicio||null,data_fim:C.data_fim||null,valor_minimo_pedido:C.valor_minimo_pedido?Number(C.valor_minimo_pedido):null,description:C.description||null};N?(await Nl(N.id,oe),t({title:"Cupom atualizado"})):(await _x(oe),t({title:"Cupom criado com sucesso"})),g(!1),re()}catch(oe){t({title:"Erro",description:oe?.response?.data?.error?.message||oe.message||"Falha ao salvar cupom.",variant:"destructive"})}finally{M(!1)}},be=async O=>{try{await Cx(O),t({title:"Cupom excluído"}),D(null),re()}catch(oe){t({title:"Erro",description:oe.message,variant:"destructive"})}},Fe=async O=>{try{await Nl(O.id,{active:!O.active}),t({title:O.active?"Cupom desativado":"Cupom ativado"}),re()}catch(oe){t({title:"Erro",description:oe.message,variant:"destructive"})}},ae=O=>{navigator.clipboard.writeText(O).then(()=>{t({title:"Código copiado!"})})},K=async O=>{A({cupomId:O,loading:!0,data:null});try{const oe=await kx(O);A({cupomId:O,loading:!1,data:oe.data})}catch{t({title:"Erro",description:"Falha ao carregar estatísticas.",variant:"destructive"}),A(null)}};return o?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[e.jsx(Nn,{className:"h-6 w-6"}),"Cupons de Desconto"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Crie e gerencie cupons de desconto para eventos ou para todo o site."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>re(),children:[e.jsx(ta,{className:"h-4 w-4 mr-1"}),"Atualizar"]}),e.jsxs(w,{size:"sm",onClick:ie,children:[e.jsx(et,{className:"h-4 w-4 mr-1"}),"Novo Cupom"]})]})]}),e.jsx(he,{children:e.jsx(ge,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(At,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Te,{placeholder:"Buscar por código...",value:i,onChange:O=>{u(O.target.value),p(1)},className:"pl-9"})]})}),e.jsxs(rs,{value:l,onValueChange:O=>{c(O),p(1)},children:[e.jsx(ns,{className:"w-full sm:w-[160px]",children:e.jsx(is,{placeholder:"Status"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos"}),e.jsx(xe,{value:"active",children:"Ativos"}),e.jsx(xe,{value:"inactive",children:"Inativos"}),e.jsx(xe,{value:"expired",children:"Expirados"}),e.jsx(xe,{value:"depleted",children:"Esgotados"})]})]}),e.jsxs(rs,{value:m,onValueChange:O=>{x(O),p(1)},children:[e.jsx(ns,{className:"w-full sm:w-[200px]",children:e.jsx(is,{placeholder:"Evento"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todos os eventos"}),$.map(O=>e.jsx(xe,{value:String(O.id),children:O.titulo},O.id))]})]})]})})}),e.jsx(he,{children:e.jsxs(ge,{className:"p-0",children:[ee?e.jsx("div",{className:"p-6 space-y-3",children:Array.from({length:5}).map((O,oe)=>e.jsx(ut,{className:"h-12 w-full"},oe))}):W.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"Nenhum cupom encontrado."}):e.jsx("div",{className:"w-full overflow-x-auto",children:e.jsxs(vt,{className:"min-w-[560px]",children:[e.jsx(bt,{children:e.jsxs($s,{children:[e.jsx(ue,{className:"min-w-[120px]",children:"Código"}),e.jsx(ue,{className:"min-w-[100px]",children:"Desconto"}),e.jsx(ue,{className:"hidden sm:table-cell min-w-[120px]",children:"Evento"}),e.jsx(ue,{className:"min-w-[60px]",children:"Uso"}),e.jsx(ue,{className:"hidden md:table-cell min-w-[130px]",children:"Período"}),e.jsx(ue,{className:"min-w-[80px]",children:"Status"}),e.jsx(ue,{className:"text-right min-w-[120px]",children:"Ações"})]})}),e.jsx(Ct,{children:W.map(O=>{const oe=O.evento?.attributes||O.evento||{};return e.jsxs($s,{children:[e.jsxs(ye,{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("code",{className:"font-mono font-bold text-sm",children:O.codigo}),e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>ae(O.codigo),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]}),O.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate max-w-[200px]",children:O.description})]}),e.jsxs(ye,{className:"font-medium",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[O.tipo_desconto==="percentual"?e.jsx(Im,{className:"h-3 w-3 text-muted-foreground shrink-0"}):e.jsx(Mo,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate",children:O.tipo_desconto==="percentual"?`${O.valor_desconto}%${O.desconto_maximo?` (máx ${Jr(O.desconto_maximo)})`:""}`:Jr(O.valor_desconto)})]}),O.valor_minimo_pedido?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Mín. ",Jr(O.valor_minimo_pedido)]}):null]}),e.jsx(ye,{className:"hidden sm:table-cell max-w-[160px]",children:oe.titulo?e.jsx("span",{className:"text-sm truncate block",title:oe.titulo,children:oe.titulo}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Todo o site"})}),e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Am,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"text-sm font-medium",children:[O.used_count||0,O.max_uses!=null?` / ${O.max_uses}`:""]})]})}),e.jsx(ye,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"text-xs space-y-0.5 whitespace-nowrap",children:[O.data_inicio&&e.jsxs("div",{children:["De: ",Us(zt(O.data_inicio),"dd/MM/yy HH:mm",{locale:Vs})]}),O.data_fim&&e.jsxs("div",{children:["Até: ",Us(zt(O.data_fim),"dd/MM/yy HH:mm",{locale:Vs})]}),!O.data_inicio&&!O.data_fim&&e.jsx("span",{className:"text-muted-foreground",children:"Sem limite"})]})}),e.jsx(ye,{children:Yf(O)}),e.jsx(ye,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>K(O.id),title:"Estatísticas",children:e.jsx(oi,{className:"h-4 w-4"})}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>ke(O),title:"Editar",children:e.jsx(ln,{className:"h-4 w-4"})}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Fe(O),title:O.active?"Desativar":"Ativar",children:e.jsx(Ls,{checked:O.active,className:"pointer-events-none scale-75"})}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>D(O),title:"Excluir",children:e.jsx(Xt,{className:"h-4 w-4"})})]})})]},O.id)})})]})}),G.pageCount>1&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[G.total," cupom",G.total!==1?"ns":""]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(w,{variant:"outline",size:"sm",disabled:h<=1,onClick:()=>p(O=>O-1),children:"Anterior"}),e.jsxs("span",{className:"px-3 py-1 text-sm",children:[G.page," / ",G.pageCount]}),e.jsx(w,{variant:"outline",size:"sm",disabled:h>=G.pageCount,onClick:()=>p(O=>
91O+1),children:"Próxima"})]})]})]})}),e.jsx(at,{open:I,onOpenChange:g,children:e.jsxs(rt,{className:"w-[calc(100vw-2rem)] sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(nt,{children:e.jsx(it,{children:N?"Editar Cupom":"Novo Cupom de Desconto"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Código do cupom"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Te,{value:C.codigo,onChange:O=>q(oe=>({...oe,codigo:O.target.value.toUpperCase()})),placeholder:"Ex: DESCONTO20",className:"uppercase font-mono"}),e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>q(O=>({...O,codigo:$d(8)})),children:"Gerar"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Tipo de desconto"}),e.jsxs(rs,{value:C.tipo_desconto,onValueChange:O=>q(oe=>({...oe,tipo_desconto:O})),children:[e.jsx(ns,{children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"percentual",children:"Percentual (%)"}),e.jsx(xe,{value:"valor_fixo",children:"Valor fixo (R$)"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:C.tipo_desconto==="percentual"?"Percentual (%)":"Valor (R$)"}),e.jsx(Te,{type:"number",min:"0",max:C.tipo_desconto==="percentual"?"100":void 0,step:"0.01",value:C.valor_desconto,onChange:O=>q(oe=>({...oe,valor_desconto:O.target.value})),placeholder:C.tipo_desconto==="percentual"?"Ex: 15":"Ex: 25.00"})]})]}),C.tipo_desconto==="percentual"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Desconto máximo (R$) — opcional"}),e.jsx(Te,{type:"number",min:"0",step:"0.01",value:C.desconto_maximo,onChange:O=>q(oe=>({...oe,desconto_maximo:O.target.value})),placeholder:"Ex: 50.00 (limitar o valor máximo do desconto)"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Evento (opcional — vazio = todo o site)"}),e.jsxs(rs,{value:C.evento||"all",onValueChange:O=>q(oe=>({...oe,evento:O==="all"?"":O})),children:[e.jsx(ns,{children:e.jsx(is,{placeholder:"Todo o site"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"all",children:"Todo o site"}),$.map(O=>e.jsx(xe,{value:String(O.id),children:O.titulo},O.id))]})]})]}),C.evento&&C.evento!=="all"&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ls,{id:"scope-toggle",checked:C.aplicar_somente_evento,onCheckedChange:O=>q(oe=>({...oe,aplicar_somente_evento:O})),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(Oe,{htmlFor:"scope-toggle",className:"cursor-pointer",children:"Aplicar desconto apenas aos ingressos deste evento"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:C.aplicar_somente_evento?"Ativo — o desconto incide só sobre os itens do evento selecionado. Demais itens do carrinho não são descontados.":"Inativo — o desconto é aplicado a todo o carrinho, mas o cupom exige que o evento esteja presente."})]})]}),e.jsx(io,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Limite de usos (vazio = ilimitado)"}),e.jsx(Te,{type:"number",min:"0",value:C.max_uses,onChange:O=>q(oe=>({...oe,max_uses:O.target.value})),placeholder:"Ilimitado"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Pedido mínimo (R$) — opcional"}),e.jsx(Te,{type:"number",min:"0",step:"0.01",value:C.valor_minimo_pedido,onChange:O=>q(oe=>({...oe,valor_minimo_pedido:O.target.value})),placeholder:"Sem mínimo"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Vigência"," ",C.data_inicio&&!C.data_fim||!C.data_inicio&&C.data_fim?e.jsx("span",{className:"text-amber-600",children:"(selecione ambos)"}):""]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"De"}),e.jsx(Rr,{language:"pt-BR",showClearButton:!1,showTodayButton:!1,title:"De",theme:Rd,value:Dd(C.data_inicio?.slice(0,10)),onChange:O=>{const oe=O instanceof Date&&!Number.isNaN(O.valueOf())?O:null,ve=oe?Pd(oe):"",me=C.data_inicio?.slice(11,16)||"00:00";q(fe=>({...fe,data_inicio:ve?`${ve}T${me}`:""}))}}),e.jsx("input",{type:"time",className:"block w-full border border-input bg-background text-foreground text-sm rounded-md px-3 py-2 focus:outline-none focus:ring-1 focus:border-ring focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [accent-color:hsl(var(--primary))] [color-scheme:light] dark:[color-scheme:dark]",value:C.data_inicio?.slice(11,16)||"",disabled:!C.data_inicio,onChange:O=>{const oe=C.data_inicio?.slice(0,10);oe&&q(ve=>({...ve,data_inicio:`${oe}T${O.target.value}`}))}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Até"}),e.jsx(Rr,{language:"pt-BR",showClearButton:!1,showTodayButton:!1,title:"Até",theme:Rd,value:Dd(C.data_fim?.slice(0,10)),onChange:O=>{const oe=O instanceof Date&&!Number.isNaN(O.valueOf())?O:null,ve=oe?Pd(oe):"",me=C.data_fim?.slice(11,16)||"23:59";q(fe=>({...fe,data_fim:ve?`${ve}T${me}`:""}))}}),e.jsx("input",{type:"time",className:"block w-full border border-input bg-background text-foreground text-sm rounded-md px-3 py-2 focus:outline-none focus:ring-1 focus:border-ring focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [accent-color:hsl(var(--primary))] [color-scheme:light] dark:[color-scheme:dark]",value:C.data_fim?.slice(11,16)||"",disabled:!C.data_fim,onCh
91ange:O=>{const oe=C.data_fim?.slice(0,10);oe&&q(ve=>({...ve,data_fim:`${oe}T${O.target.value}`}))}})]})]}),(C.data_inicio||C.data_fim)&&e.jsx("button",{type:"button",onClick:()=>q(O=>({...O,data_inicio:"",data_fim:""})),className:"text-xs text-muted-foreground hover:text-foreground hover:bg-accent px-2 py-1 rounded",children:"Limpar período"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ls,{checked:C.active,onCheckedChange:O=>q(oe=>({...oe,active:O}))}),e.jsx(Oe,{children:"Cupom ativo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Observações (interno)"}),e.jsx(yn,{value:C.description,onChange:O=>q(oe=>({...oe,description:O.target.value})),placeholder:"Notas internas sobre este cupom...",rows:2})]})]}),e.jsxs(Ut,{children:[e.jsx(w,{variant:"outline",onClick:()=>g(!1),children:"Cancelar"}),e.jsx(w,{onClick:Ae,disabled:L,children:L?"Salvando...":N?"Salvar Alterações":"Criar Cupom"})]})]})}),e.jsx(at,{open:!!z,onOpenChange:()=>D(null),children:e.jsxs(rt,{className:"sm:max-w-sm",children:[e.jsx(nt,{children:e.jsx(it,{children:"Excluir cupom?"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Tem certeza que deseja excluir o cupom ",e.jsx("strong",{children:z?.codigo}),"? Esta ação não pode ser desfeita."]}),e.jsxs(Ut,{children:[e.jsx(w,{variant:"outline",onClick:()=>D(null),children:"Cancelar"}),e.jsx(w,{variant:"destructive",onClick:()=>be(z?.id),children:"Excluir"})]})]})}),e.jsx(at,{open:!!E,onOpenChange:()=>A(null),children:e.jsxs(rt,{className:"sm:max-w-sm",children:[e.jsx(nt,{children:e.jsxs(it,{className:"flex items-center gap-2",children:[e.jsx(oi,{className:"h-5 w-5"}),"Estatísticas"]})}),E?.loading?e.jsxs("div",{className:"space-y-3 py-4",children:[e.jsx(ut,{className:"h-8 w-full"}),e.jsx(ut,{className:"h-8 w-full"}),e.jsx(ut,{className:"h-8 w-full"})]}):E?.data?e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Código"}),e.jsx("code",{className:"font-mono font-bold",children:E.data.codigo})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Total de usos"}),e.jsxs("span",{className:"font-medium",children:[E.data.used_count,E.data.max_uses!=null?` / ${E.data.max_uses}`:""]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Pedidos pagos"}),e.jsx("span",{className:"font-medium",children:E.data.pedidos_pagos})]}),e.jsx(io,{}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Total desconto dado"}),e.jsx("span",{className:"font-medium text-green-600",children:Jr(E.data.total_desconto_aplicado)})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Receita gerada"}),e.jsx("span",{className:"font-medium",children:Jr(E.data.total_receita_gerada)})]}),E.data.ultimo_uso&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Último uso"}),e.jsx("span",{children:Us(zt(E.data.ultimo_uso),"dd/MM/yy HH:mm",{locale:Vs})})]})]}):null]})})]}):e.jsx(he,{children:e.jsx(ge,{className:"py-12 text-center text-muted-foreground",children:"Você não tem permissão para acessar esta página."})})}tx.workerSrc=`//unpkg.com/pdfjs-dist@${sx}/build/pdf.worker.min.mjs`;const Bn=600,Md=[{value:"data_evento",label:"Data do Evento"},{value:"evento_titulo",label:"Título do Evento"},{value:"item_nome",label:"Nome do Item"}];function no(s){return(s||"").normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replaceAll(/(?:^_)|(?:_$)/g,"")}function Zf(s,t,a,n){return{x:s*n,y:(a-t)*n}}function ej(s,t,a,n){return{x:s/n,y:a-t/n}}function sj(){const s=na(),{toast:t}=mt(),{data:a,isLoading:n}=Ks(["template-certificados-editor"],"/template-certificados?populate[pdf_base]=true&populate[evento][fields][0]=titulo&sort=createdAt:desc"),o=r.useMemo(()=>(a?.data||[]).map(De=>{const Ne=De.attributes||De;return{id:De.id,documentId:De.documentId||De.id,...Ne}}),[a]),[i,u]=r.useState(null),[l,c]=r.useState([]),[m,x]=r.useState(null),[h,p]=r.useState(!1),[f,I]=r.useState(!1),[g,N]=r.useState(!1),[b,C]=r.useState(!1),[q,L]=r.useState(null),[M,z]=r.useState([]),[D,E]=r.useState(null),[A,S]=r.useState(!1),[P,F]=r.useState(null),[ee,re]=r.useState(0),[te,G]=r.useState(0),[y,$]=r.useState([]),[W,ie]=r.useState("__all__"),[ke,Ae]=r.useState(!1),[be,Fe]=r.useState(null),ae=r.useRef({x:0,y:0}),K=r.useRef(null),O={label:"",field_key:"",fontSize:16,align:"center",is_auto:!1,auto_source:""},[oe,ve]=r.useState(O),me=r.useMemo(()=>i?o.find(k=>k.id===i)||null:o[0]||null,[o,i]);r.useEffect(()=>{me&&(c(me.text_positions||[]),x(null),p(!1),G(0),F(null),L(null),z([]),$([]),ie("__all__"))},[me?.id]),r.useEffect(()=>{if(!me?.documentId)return;let k=!1;return Ae(!0),$e.get(`/template-certificados/${me.documentId}/dates`).then(De=>{k||$(De.data?.data?.dates||[])}).catch(()=>{k||$([])}).finally(()=>{k||Ae(!1)}),()=>{k=!0}},[me?.documentId]);const fe=r.useMemo(()=>
91{if(!me)return null;const k=me.documentId||me.id;return me.pdf_base?.data||me.pdf_base?`${Tr()}/template-certificados/${k}/pdf-proxy`:null},[me]),le=P?Bn/P.width:1,_e=P?P.height*le:800,U=r.useMemo(()=>{if(!fe)return null;const k=globalThis.localStorage?.getItem("token");return{url:fe,httpHeaders:k?{Authorization:`Bearer ${k}`}:{}}},[fe]),J=l.find(k=>k.field_key===m),T=me?.evento?.titulo||me?.evento?.data?.attributes?.titulo||me?.evento?.attributes?.titulo||null,Ee=k=>{h&&!confirm("Há alterações não salvas. Deseja descartar?")||u(k)},Se=()=>{const k=oe.field_key||no(oe.label);if(!k||!oe.label){t({variant:"destructive",title:"Preencha o nome e a chave do campo"});return}if(l.some(es=>es.field_key===k)){t({variant:"destructive",title:"Já existe um campo com essa chave"});return}const De=P?P.width/2:297,Ne=P?P.height/2:421;c(es=>[...es,{label:oe.label,field_key:k,x:Math.round(De),y:Math.round(Ne),page:te,fontSize:Number(oe.fontSize)||16,align:oe.align||"center",is_auto:oe.is_auto,auto_source:oe.is_auto?oe.auto_source:null}]),x(k),p(!0),S(!1),ve(O)},Ze=k=>{c(De=>De.filter(Ne=>Ne.field_key!==k)),m===k&&x(null),p(!0)},qe=(k,De)=>{c(Ne=>Ne.map(es=>es.field_key===k?{...es,...De}:es)),p(!0)},Qe=async()=>{if(me?.documentId){I(!0);try{await $e.put(`/template-certificados/${me.documentId}`,{data:{text_positions:l}}),s.invalidateQueries({queryKey:["template-certificados-editor"]}),p(!1),t({title:"Template salvo com sucesso!"})}catch(k){t({variant:"destructive",title:"Erro ao salvar",description:k.message})}finally{I(!1)}}},we=async()=>{if(me?.documentId){N(!0);try{h&&(await $e.put(`/template-certificados/${me.documentId}`,{data:{text_positions:l}}),s.invalidateQueries({queryKey:["template-certificados-editor"]}),p(!1));const k=await $e.post(`/template-certificados/${me.documentId}/sample`,{},{responseType:"blob"}),De=new Blob([k.data],{type:"application/pdf"}),Ne=URL.createObjectURL(De);globalThis.open(Ne,"_blank"),t({title:"Amostra gerada com sucesso!"})}catch(k){t({variant:"destructive",title:"Erro ao gerar amostra",description:k.message})}finally{N(!1)}}},Me=async()=>{if(!me?.documentId)return;if(!T){t({variant:"destructive",title:"Template sem evento vinculado"});return}if(confirm(`Enviar/reenviar certificados para ${W==="__all__"?"TODAS as datas":W} do evento "${T}"?
92
93Isso irá:
94• Criar certificados para itens sem certificado
95• Reenviar e-mail para certificados existentes`)){C(!0),L(null);try{const Ne=W==="__all__"?{}:{data_evento:W},es=await $e.post(`/template-certificados/${me.documentId}/resend`,null,{params:Ne}),ss=es.data?.data||es.data;L(ss),z(We=>[{timestamp:new Date().toISOString(),filterDate:W==="__all__"?null:W,...ss},...We]),t({title:`Certificados processados: ${ss.total||0}`,description:`${ss.issued||0} novos, ${ss.resent||0} reenviados, ${ss.skipped||0} pulados, ${ss.errors||0} erros`})}catch(Ne){t({variant:"destructive",title:"Erro ao reenviar",description:Ne.message})}finally{C(!1)}}},ks=r.useCallback((k,De)=>{c(Ne=>Ne.map(es=>es.field_key===k?{...es,...De}:es))},[]),xs=r.useCallback((k,De)=>{k.preventDefault(),k.stopPropagation();const Ne=k.currentTarget.getBoundingClientRect();ae.current={x:k.clientX-Ne.left-Ne.width/2,y:k.clientY-Ne.top-Ne.height/2},Fe(De),x(De)},[]);return r.useEffect(()=>{if(!be)return;const k=Ne=>{if(!K.current||!P)return;Ne.preventDefault();const es=K.current.getBoundingClientRect(),ss=Ne.clientX-es.left-ae.current.x,We=Ne.clientY-es.top-ae.current.y,hs=Math.max(0,Math.min(ss,Bn)),Is=Math.max(0,Math.min(We,_e)),Y=ej(hs,Is,P.height,le);ks(be,{x:Math.round(Y.x),y:Math.round(Y.y)})},De=()=>{Fe(null),p(!0)};return globalThis.addEventListener("pointermove",k),globalThis.addEventListener("pointerup",De),()=>{globalThis.removeEventListener("pointermove",k),globalThis.removeEventListener("pointerup",De)}},[be,P,le,_e,ks]),n?e.jsxs("div",{className:"space-y-6",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Templates de Certificado"}),e.jsx("p",{className:"text-muted-foreground",children:"Carregando templates..."})]}):o.length===0?e.jsxs("div",{className:"space-y-6",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Templates de Certificado"}),e.jsx(he,{children:e.jsxs(ge,{className:"py-8 text-center",children:[e.jsx(Lo,{className:"w-12 h-12 mx-auto mb-3 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"Nenhum template encontrado. Crie um template no Stra
95pi e faça upload do PDF base."})]})})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Templates de Certificado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Posicione os campos de texto arrastando sobre o PDF. Campos automáticos (data, título) são preenchidos pelo sistema."})]}),h&&e.jsxs(w,{onClick:Qe,disabled:f,children:[e.jsx(Da,{className:"w-4 h-4 mr-2"}),f?"Salvando...":"Salvar Alterações"]})]}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-3",children:e.jsx(ze,{className:"text-base",children:"Selecionar Template"})}),e.jsx(ge,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:o.map(k=>e.jsx(w,{variant:(me?.id||o[0]?.id)===k.id?"default":"outline",size:"sm",onClick:()=>Ee(k.id),children:k.nome||`Template #${k.id}`},k.id))})})]}),me&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-3",children:[e.jsxs(he,{children:[e.jsxs(Be,{className:"pb-2 flex flex-row items-center justify-between",children:[e.jsxs(ze,{className:"text-base flex items-center gap-2",children:[e.jsx(tn,{className:"w-4 h-4"}),"Editor de Posições"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ee>1&&e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx(w,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:te<=0,onClick:()=>G(k=>k-1),children:e.jsx(Em,{className:"w-3 h-3"})}),e.jsxs("span",{children:[te+1," / ",ee]}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:te>=ee-1,onClick:()=>G(k=>k+1),children:e.jsx(er,{className:"w-3 h-3"})})]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>S(!0),children:[e.jsx(et,{className:"w-4 h-4 mr-1"})," Adicionar Campo"]})]})]}),e.jsx(ge,{children:U?e.jsxs("div",{ref:K,className:"relative rounded-lg border bg-white overflow-hidden select-none",style:{width:Bn,height:_e||"auto"},children:[e.jsx(Zm,{file:U,onLoadSuccess:({numPages:k})=>re(k),loading:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("p",{className:"text-muted-foreground",children:"Carregando PDF..."})}),error:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("p",{className:"text-red-500",children:"Erro ao carregar o PDF."})}),children:e.jsx(ex,{pageNumber:te+1,width:Bn,renderTextLayer:!1,renderAnnotationLayer:!1,onLoadSuccess:k=>{F({width:k.originalWidth||k.width,height:k.originalHeight||k.height})}})}),P&&l.filter(k=>(k.page||0)===te).map(k=>{const De=Zf(k.x,k.y,P.height,le),Ne=k.field_key===m,es=k.field_key===be;return e.jsxs("button",{type:"button",className:["absolute flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium","cursor-grab select-none whitespace-nowrap transition-shadow",Ne?"ring-2 ring-primary shadow-lg z-20":"z-10 hover:shadow-md",k.is_auto?"bg-green-100 text-green-800 border border-green-300":"bg-blue-100 text-blue-800 border border-blue-300",es?"opacity-70 cursor-grabbing":""].join(" "),style:{left:De.x,top:De.y,transform:"translate(-50%, -100%)"},onPointerDown:ss=>xs(ss,k.field_key),onClick:ss=>{ss.stopPropagation(),x(k.field_key)},children:[e.jsx(Dm,{className:"w-3 h-3 flex-shrink-0 opacity-50"}),e.jsx("span",{children:k.label}),k.is_auto&&e.jsx(je,{variant:"outline",className:"text-[10px] px-1 py-0 ml-1 border-green-400",children:"auto"})]},k.field_key)})]}):e.jsx("div",{className:"flex items-center justify-center h-64 bg-muted rounded-lg",children:e.jsx("p",{className:"text-muted-foreground",children:"Nenhum PDF base. Faça upload no Strapi."})})})]}),l.length>0&&e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsxs(ze,{className:"text-sm",children:["Campos (",l.length,")"]})}),e.jsx(ge,{children:e.jsx("div",{className:"divide-y text-xs",children:l.map(k=>e.jsxs("button",{type:"button",className:["flex items-center justify-between py-2 px-1 rounded cursor-pointer w-full text-left",m===k.field_key?"bg-accent":"hover:bg-accent/50"].join(" "),onClick:()=>{x(k.field_key),(k.page||0)!==te&&G(k.page||0)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${k.is_auto?"bg-green-500":"bg-blue-500"}`}),e.jsx("span",{className:"font-medium",children:k.label}),e.jsxs("span",{className:"text-muted-foreground",children:["(",k.field_key,")"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsxs("span",{children:[k.fontSize,"px"]}),e.jsxs("span",{children:["x:",k.x," y:",k.y]}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-5 w-5 text-destructive hover:text-destructive",onClick:De=>{De.stopPropagation(),Ze(k.field_key)},children:e.jsx(Xt,{className:"w-3 h-3"})})]})]},k.field_key))})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsx(ze,{className:"text-base",children:"Detalhes"})}),e.jsxs(ge,{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Nome:"})," ",e.jsx("span",{className:"font-medium",children:me.nome})]}),me.descricao&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Descrição:"})," ",e.jsx("span",{children:me.descricao})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Sa,{className:"w-3.5 h-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Evento:"})," ",T?e.jsx(je,{variant:"secondary",className:"text-xs",children:T}):e.jsx("span",{className:"text-muted-foreground italic",children:"Nenhum"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(tn,{className:"w-3.5 h-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"PDF base:"})," ",fe?e.jsx(je,{variant:"default",className:"text-xs",children:"Enviado"}):e.jsx(je,{variant:"destructive",className:"text-xs",children:"Pendente"})]})]})]}),J&&e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsxs(ze,{className:"text-base flex items-center gap-2",children:[e.jsx(Pm,{className:"w-4 h-4"}),"Propriedades do Campo"]})}),e.jsxs(ge,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{className:"text-xs",children:"Nome (label)"}),e.jsx(Te,{value:J.label,onChange:k=>qe(m,{label:k.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{className:"text-xs",children:"Chave (field_key)"}),e.jsx(Te,{value:J.field_key,disabled:!0,className:"h-8 text-sm opacity-60"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{className:"text-xs",children:"Tamanho da fonte"}),e.jsx(Te,{type:"number",min:8,max:72,value:J.fontSize||16,onChange:k=>qe(m,{fontSize:Number(k.target.value)||16}),className:"h-8 text-sm"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{className:"text-xs",children:"Alinhamento"}),e.jsxs(rs,{value:J.align||"center",onValueChange:k=>qe(m,{align:k}),children:[e.jsx(ns,{className:"h-8 text-sm",children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"left",children:"Esquerda"}),e.jsx(xe,{value:"center",children:"Centro"}),e.jsx(xe,{value:"right",children:"Direita"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{className:"text-xs",children:"X (pts)"}),e.jsx(Te,{type:"number",value:J.x||0,onChange:k=>qe(m,{x:Number(k.target.value)||0}),className:"h-8 text-sm"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{className:"text-xs",children:"Y (pts)"}),e.jsx(Te,{type:"number",value:J.y||0,onChange:k=>qe(m,{y:Number(k.target.value)||0}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border px-3 py-2",children:[e.jsx(Oe,{className:"text-xs",children:"Preenchimento automático"}),e.jsx(Ls,{checked:J.is_auto||!1,onCheckedChange:k=>{qe(m,{is_auto:k,auto_source:k?J.auto_source||"data_evento":null})}})]}),J.is_auto&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{className:"text-xs",children:"Fonte automática"}),e.jsxs(rs,{value:J.auto_source||"data_evento",onValueChange:k=>qe(m,{auto_source:k}
95),children:[e.jsx(ns,{className:"h-8 text-sm",children:e.jsx(is,{})}),e.jsx(os,{children:Md.map(k=>e.jsx(xe,{value:k.value,children:k.label},k.value))})]})]}),e.jsxs(w,{variant:"destructive",size:"sm",className:"w-full",onClick:()=>Ze(m),children:[e.jsx(Xt,{className:"w-3.5 h-3.5 mr-1.5"})," Remover Campo"]})]})]}),fe&&e.jsx(he,{children:e.jsxs(ge,{className:"py-4 space-y-2",children:[e.jsxs(w,{variant:"default",size:"sm",className:"w-full",disabled:g||l.length===0,onClick:we,children:[g?e.jsx(Cs,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Vt,{className:"w-4 h-4 mr-2"}),g?"Gerando...":"Gerar Amostra (Preview)"]}),l.length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground text-center",children:"Adicione campos de texto para gerar uma amostra."}),e.jsx(w,{variant:"outline",size:"sm",asChild:!0,className:"w-full",children:e.jsxs("a",{href:fe,target:"_blank",rel:"noreferrer",children:[e.jsx(sr,{className:"w-4 h-4 mr-2"})," Abrir PDF base"]})})]})}),e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsxs(ze,{className:"text-base flex items-center gap-2",children:[e.jsx(pr,{className:"w-4 h-4"}),"Enviar Certificados"]})}),e.jsxs(ge,{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["Envia (ou reenvia) o e-mail de certificado para participantes que já tiveram o ingresso escaneado (",e.jsx("strong",{children:"status usado"}),"). Selecione uma data específica ou envie para todas."]}),T&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(Oe,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(Sa,{className:"w-3 h-3"})," Data do evento"]}),e.jsxs(rs,{value:W,onValueChange:ie,disabled:ke,children:[e.jsx(ns,{className:"h-8 text-xs",children:e.jsx(is,{placeholder:ke?"Carregando datas...":"Selecione"})}),e.jsxs(os,{children:[e.jsx(xe,{value:"__all__",children:"Todas as datas"}),y.map(k=>e.jsxs(xe,{value:k.date,children:[new Date(k.date+"T12:00:00").toLocaleDateString("pt-BR"),k.observacao?` — ${k.observacao}`:"",k.source==="principal"?" (principal)":""]},k.date))]})]})]}),e.jsxs(w,{variant:"default",size:"sm",className:"w-full",disabled:b||!T,onClick:Me,children:[b?e.jsx(Cs,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(qa,{className:"w-4 h-4 mr-2"}),b?"Enviando...":W!=="__all__"?`Enviar para ${new Date(W+"T12:00:00").toLocaleDateString("pt-BR")}`:"Enviar / Reenviar Certificados"]}),!T&&e.jsx("p",{className:"text-[11px] text-amber-600 text-center",children:"Vincule um evento a este template para habilitar o envio."}),q&&e.jsxs("div",{className:"rounded-md border p-3 text-xs space-y-1.5",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:["Resultado do envio",q.filterDate&&e.jsx(je,{variant:"outline",className:"text-[10px] ml-1",children:new Date(q.filterDate+"T12:00:00").toLocaleDateString("pt-BR")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(co,{className:"w-3 h-3 text-green-600"}),e.jsxs("span",{children:[q.issued||0," novos certificados criados"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"w-3 h-3 text-blue-600"}),e.jsxs("span",{children:[q.resent||0," e-mails reenviados"]})]}),(q.skipped||0)>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"w-3 h-3 text-amber-600"}),e.jsxs("span",{children:[q.skipped," pulados (sem e-mail/uid)"]})]}),(q.errors||0)>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tr,{className:"w-3 h-3 text-red-600"}),e.jsxs("span",{children:[q.errors," erros"]})]}),e.jsxs("div",{className:"text-muted-foreground pt-1",children:["Total processado: ",q.total||0]})]})]})]}),M.length>0&&e.jsxs(he,{children:[e.jsx(Be,{className:"pb-2",children:e.jsxs(ze,{className:"text-base flex items-center gap-2",children:[e.jsx(tn,{className:"w-4 h-4"}),"Histórico de Envios (",M.length,")"]})}),e.jsx(ge,{className:"space-y-2 max-h-80 overflow-y-auto",children:M.map((k,De)=>e.jsxs("div",{className:"rounded-md border text-xs",children:[e.jsxs("button",{type:"button",className:"w-full flex items-center justify-between px-3 py-2 hover:bg-muted/50 transition-colors",onClick:()=>E(D===De?null:De),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:new Date(k.timestamp).toLocaleTimeString("pt-BR")}),k.filterDate?e.jsx(je,{variant:"outline",className:"text-[10px]",children:new Date(k.filterDate+"T12:00:00").toLocaleDateString("pt-BR")}):e.jsx(je,{variant:"secondary",className:"text-[10px]",children:"Todas"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-green-700",children:[k.issued||0,"↑"]}),e.jsxs("span",{className:"text-blue-700",children:[k.resent||0,"↻"]}),(k.errors||0)>0&&e.jsxs("span",{className:"text-red-700",children:[k.errors,"✕"]}),D===De?e.jsx(Zd,{className:"w-3 h-3 text-muted-foreground"}):e.jsx(ra,{className:"w-3 h-3 text-muted-foreground"})]})]}),D===De&&k.details?.length>0&&e.jsx("div",{className:"border-t px-3 py-2 space-y-1 bg-muted/30 max-h-48 overflow-y-auto",children:k.details.map((Ne,es)=>e.jsxs("div",{className:"flex items-start gap-1.5 text-[11px]",children:[Ne.action==="issued"&&e.jsx(co,{className:"w-3 h-3 text-green-600 mt-0.5 shrink-0"}),Ne.action==="resent"&&e.jsx(qa,{className:"w-3 h-3 text-blue-600 mt-0.5 shrink-0"}),Ne.action==="skipped"&&e.jsx(ml,{className:"w-3 h-3 text-amber-600 mt-0.5 shrink-0"}),Ne.action==="error"&&e.jsx(tr,{className:"w-3 h-3 text-red-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"font-medium",children:Ne.userName||`Pedido #${Ne.pedidoId}`}),Ne.itemNome&&e.jsxs("span",{className:"text-muted-foreground",children:[" — ",Ne.itemNome]}),Ne.email&&e.jsx("span",{className:"text-muted-foreground block truncate",children:Ne.email}),Ne.dataEvento&&e.jsxs("span",{className:"text-muted-foreground block",children:["Data: ",new Date(Ne.dataEvento+"T12:00:00").toLocaleDateString("pt-BR")]}),Ne.reason&&e.jsxs("span",{className:"text-amber-700 block",children:["Motivo: ",Ne.reason]}),Ne.error&&e.jsxs("span",{className:"text-red-700 block",children:["Erro: ",Ne.error]})]})]},es))})]},De))})]}),e.jsx(he,{children:e.jsx(ge,{className:"py-4",children:e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:[e.jsx("strong",{children:"Dica:"})," Arraste os campos sobre o PDF para posicioná-los. Campos ",e.jsx("span",{className:"text-green-700 font-medium",children:"verdes"})," são automáticos (preenchidos pelo sistema). Campos"," ",e.jsx("span",{className:"text-blue-700 font-medium",children:"azuis"})," serão preenchidos pelo participante ao gerar o certificado."]})})})]})]}),e.jsx(at,{open:A,onOpenChange:S,children:e.jsxs(rt,{className:"sm:max-w-md",children:[e.jsx(nt,{children:e.jsx(it,{children:"Adicionar Campo de Texto"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Nome do campo"}),e.jsx(Te,{placeholder:"Ex: Nome Completo",value:oe.label,onChange:k=>{const De=k.target.value;ve(Ne=>({...Ne,label:De,field_key:Ne.field_key||no(De)}))}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Chave (field_key)"}),e.jsx(Te,{placeholder:"nome_completo",value:oe.field_key||no(oe.label),onChange:k=>ve(De=>({...De,field_key:k.target.value}))}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Identificador único usado no formulário e composição do PDF."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Tamanho da fonte"}),e.jsx(Te,{type:"number",min:8,max:72,value:oe.fontSize,onChange:k=>ve(De=>({...De,fontSize:Number(k.target.value)||16}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Alinhamento"}),e.jsxs(rs,{value:oe.align,onValueChange:k=>ve(De=>({...De,align:k})),children:[e.jsx(ns,{children:e.jsx(is,{})}),e.jsxs(os,{children:[e.jsx(xe,{value:"left",children:"Esquerda"}),e.jsx(xe,{value:"center",children:"Centro"}),e.jsx(xe,{value:"right",children:"Direita"})]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border px-3 py-2.5",children:[e.jsxs("div",{children:[e.jsx(Oe,{children:"Campo automático"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Preenchido automaticamente pelo sistema"})]}),e.jsx(Ls,{checked:oe.is_auto,onCheckedChange:k=>ve(De=>({...De,is_auto:k,auto_source:k?De.auto_source||"data_evento":""}))})]}),oe.is_auto&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Oe,{children:"Fonte dos dados"}),e.jsxs(rs,{value:oe.auto_source||"data_evento",onValueChange:k=>ve(De=>({...De,auto_source:k}
95)),children:[e.jsx(ns,{children:e.jsx(is,{})}),e.jsx(os,{children:Md.map(k=>e.jsx(xe,{value:k.value,children:k.label},k.value))})]})]})]}),e.jsxs(Ut,{children:[e.jsx(w,{variant:"outline",onClick:()=>S(!1),children:"Cancelar"}),e.jsxs(w,{onClick:Se,children:[e.jsx(et,{className:"w-4 h-4 mr-1"})," Adicionar"]})]})]})})]})}function Uv(){const{user:s,loading:t}=Zt();if(t)return null;if(!s)return e.jsx(Ga,{to:"/login",replace:!0});const a=(s?.role?.name||s?.role?.type||"").toLowerCase(),n=(s?.role?.code||"").toLowerCase(),o=a.includes("admin")||n.includes("admin"),i=a.includes("superadmin")||n.includes("superadmin"),u=(a.includes("supersuporte")||n.includes("supersuporte"))&&!i,l=o||i||u,c=i||o||u,m=a.includes("estoquista"),x=a.includes("externo")||n.includes("externo"),h=a.includes("vendedor")&&!x,p=a.includes("gerente")&&a.includes("vendedor")&&!x,f=a.includes("comissao")||a.includes("comissão")||n.includes("comissao")||n.includes("comissão"),I=a.includes("terminal"),g=a==="scan"||n==="scan"||a==="scanner"||n==="scanner"||a==="qr-scanner"||n==="qr-scanner"||a.includes("scanner");let N="vendedor";return u?N="supersuporte":l?N="admin":m?N="estoquista":g?N="scan":p?N="gerenteVendedores":I?N="terminal":f?N="comissao":x&&(N="vendedoresExternos"),!l&&!m&&!g&&!h&&!p&&!f&&!I&&!x?e.jsx(Ga,{to:"/",replace:!0}):e.jsx(Dx,{role:N,children:e.jsxs(Mu,{children:[l&&e.jsx(ot,{path:"/",element:e.jsx(ep,{})}),(l||h||p||f)&&e.jsx(ot,{path:"/pedidos",element:e.jsx(np,{})}),l&&e.jsx(ot,{path:"/eventos",element:e.jsx(lp,{})}),(l||g)&&e.jsx(ot,{path:"/eventos/:documentId/data/:dateKey",element:e.jsx(Xp,{})}),l&&e.jsx(ot,{path:"/eventos/:documentId",element:e.jsx(Ip,{})}),c&&e.jsx(ot,{path:"/convites",element:e.jsx(og,{})}),(l||h||p||f)&&e.jsx(ot,{path:"/chamados",element:e.jsx(_g,{})}),(l||h||p||f)&&e.jsx(ot,{path:"/usuarios",element:e.jsx(th,{})}),l||m||g?e.jsx(ot,{path:"/atividades",element:e.jsx(Tg,{})}):null,(l||m)&&e.jsx(ot,{path:"/bar",element:e.jsx(Ch,{})}),(l||m)&&e.jsx(ot,{path:"/combos",element:e.jsx(Ph,{})}),(l||m)&&e.jsx(ot,{path:"/estoque",element:e.jsx(hh,{})}),i||u?e.jsx(ot,{path:"/super",element:e.jsx(Sf,{})}):null,i||u?e.jsx(ot,{path:"/certificado-templates",element:e.jsx(sj,{})}):null,l&&!u?e.jsx(ot,{path:"/extratos",element:i?e.jsx(mu,{}):e.jsx(Zg,{})}):null,e.jsx(ot,{path:"/extrato",element:e.jsx(Ga,{to:l&&!u?"/dashboard/extratos":"/dashboard",replace:!0})}),l||h||p||f||m?e.jsx(ot,{path:"/formularios-palestra",element:e.jsx(Sd,{})}):null,l||h||p||f||m?e.jsx(ot,{path:"/formularios-palestra/:id",element:e.jsx(Sd,{})}):null,l&&e.jsx(ot,{path:"/ai",element:e.jsx(Ah,{})}),l&&e.jsx(ot,{path:"/cielo",element:e.jsx(Ad,{})}),I&&e.jsx(ot,{path:"/cielo",element:e.jsx(Ad,{})}),l&&e.jsx(ot,{path:"/cupons",element:e.jsx(Xf,{})}),e.jsx(ot,{path:"/link-convites",element:e.jsx(Df,{})}),e.jsx(ot,{path:"/link-convites/:codigo",element:e.jsx(Pf,{})}),l&&e.jsx(ot,{path:"/link-vendas",element:e.jsx(Cd,{})}),l&&e.jsx(ot,{path:"/link-vendas/criar",element:e.jsx(Cd,{})}),(h||p||f||x)&&e.jsx(ot,{path:"/",element:e.jsx(Ga,{to:"/dashboard/link-convites",replace:!0})}),I&&e.jsx(ot,{path:"/",element:e.jsx(Ga,{to:"/dashboard/cielo",replace:!0})}),g&&e.jsx(ot,{path:"/",element:e.jsx(Ga,{to:"/dashboard/atividades",replace:!0})}),!l&&!h&&!p&&!I&&!g&&!x&&e.jsx(ot,{path:"/",element:e.jsx(Ga,{to:"/dashboard/estoque",replace:!0})})]})})}export{Uv 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.