PageSourceSearch

https://sabhia.ai/assets/admin-panel-BXyvnxO_.js

js sabhia.ai collected 2026-10-05 12:33:32 UTC 1,262,693 bytes, 33 lines download raw bytes

1import{j as e}from"./vendor-motion-CPxq9Xvn.js";import{r as d,R as Kl}from"./vendor-i18n-CO3kK2bH.js";import{n as Wa,u as z,a7 as T,Z as He,X as Ce,U as Re,_ as nt,l as ns,a$ as Ca,T as Ie,dJ as Zl,an as N,C as be,ax as Zs,K as bh,aX as Nn,p as ya,a as jh,A as vh,ao as xe,a2 as Sa,ai as $a,a6 as W,B as b,k as Ct,b as as,d$ as G0,P as Va,f as ot,J as Ut,h as fn,a3 as st,ei as kr,eh as js,aJ as $s,a4 as J,ap as Ua,aa as ha,D as Je,ej as V0,ek as _m,q as Ye,aj as Ze,r as et,i as Bt,aG as vs,a9 as _a,bQ as Q0,N as W0,$ as ta,b0 as St,aU as ct,aY as Nh,el as H0,em as tc,en as sc,eo as ac,aF as K,ak as Ka,Y as ea,ay as Oa,al as mt,aT as Qa,aZ as jc,W as Us,a_ as Ul,aC as Gl,j as fh,aV as Ac,aI as O,at as Mt,z as yr,I as vc,S as qe,as as _t,e as wn,ep as Om,ar as X0,V as J0,E as Y0,R as Z0,aH as Bm,bP as ic,o as eu,b5 as Um}from"./index-CFAvyuXu.js";import{L as tu}from"./BookIntakeCard-VzlzK2vq.js";import{C as Xe}from"./circle-alert-CixghSwT.js";import{R as Cn,C as Sn,X as $n,Y as Wi,T as An,L as wh,B as Vl,a as Km}from"./generateCategoricalChart-BWPgo2XD.js";import{C as yh}from"./ComposedChart-DU-Zy1hn.js";import{L as hi}from"./Line-DQYoHYTA.js";import{S as Jt}from"./shopping-cart-B3r4TRKU.js";import{M as Ql}from"./minus-CYoHdJ99.js";import{A as $r}from"./arrow-up-right-DoEOWN5j.js";import{W as kh}from"./wallet-DDm104dr.js";import{S as Ks}from"./shield-alert-CdUhQ0gg.js";import{W as Pn}from"./wrench-B2BwrVia.js";import{C as dt}from"./circle-x-DhBMAj3Y.js";import{C as Ht}from"./cpu-DMvj8Nds.js";import{U as Vi}from"./user-plus-DqKPlBFM.js";import{C as je,a as ve,b as Fe,c as De,d as su}from"./card-CkkuFnhL.js";import{B as E}from"./badge-B9GAfHbC.js";import{B as jn}from"./brain-CGIDZ8Da.js";import{L as Gm}from"./lightbulb-BvSG_Icx.js";import{G as pt}from"./globe-D0MKCb1Y.js";import{S as Pc}from"./smartphone-B4uVuS8T.js";import{F as tt}from"./file-text-DjkUcFVd.js";import{C as ft}from"./chart-column-UGEAwQLz.js";import{A as jt}from"./activity-_YDrs4Vk.js";import{C as is}from"./circle-check-big-DgyOZTvd.js";import{A as Tc}from"./arrow-down-right-KrRc65tF.js";import{T as Ch}from"./trending-down-CfcKlIud.js";import{T as lt}from"./target-CjPWrUoS.js";import{S as rt}from"./switch-B7JW5zVV.js";import{M as au}from"./maximize-2-BDHmjU2g.js";import{R as Cr}from"./radio-BB5ERZxW.js";import{M as Xt}from"./megaphone-CJoAWoYP.js";import{V as iu}from"./volume-2-DLFW1Tgd.js";import{M as Ge}from"./mail-B6oT_qrq.js";import{B as Qi}from"./bot-Mywm8Ykk.js";import{P as Sh}from"./printer-Bblh7pWy.js";import{B as ru}from"./brain-circuit-BiacJsPX.js";import{W as yi}from"./wand-sparkles-BFRdHggN.js";import{A as pi,h as ui,a as gi,b as bi,c as ji,d as vi,e as Ni,f as fi,g as wi}from"./alert-dialog-C9feqA9b.js";import{F as nu}from"./file-spreadsheet-D3Z16_oB.js";import{C as Ec}from"./calendar-days-CgZcFkfV.js";import{D as Rt}from"./download-B7FtiUYJ.js";import{U as Hi}from"./user-tcFnhJKi.js";import{T as Vm,a as Qm,b as we,c as Be}from"./tabs-DIYA7-w6.js";import{S as Se,a as $e,b as Ae,c as Pe,d as U}from"./select-B26x0xAv.js";import{S as Wl}from"./share-2-BECwSfHo.js";import{E as ht}from"./eye-BcGCsLne.js";import{A as $h}from"./AreaChart-C0_m-Eju.js";import{A as Nc}from"./Area-DBDgpfe2.js";import{B as lu}from"./BarChart-CZu90rwW.js";import{E as Hl}from"./eye-off-BkxLcLQS.js";import{L as Ot}from"./layers-B-zOJ8Vr.js";import{T as As}from"./trash-2-BF2rPJAw.js";import{S as Wm}from"./settings-2-BQlcagWi.js";import{P as fc}from"./power-D5z6eW6f.js";import{F as Xl}from"./funnel-hT24ByFs.js";import{T as du}from"./timer-oipZZtMW.js";import{S as Ic}from"./save-QXxXVhhp.js";import{P as Rc}from"./pen-tool-Cta8E7eR.js";import{I as ls}from"./instagram-BJB2Fjof.js";import{S as qa}from"./settings-CwGm2sFb.js";import{F as Xi}from"./facebook-LtAHpCd1.js";import{R as Sr}from"./rotate-ccw-yv6DhBa4.js";import{H as ou}from"./hash-CYmkjj_q.js";import{U as cu}from"./user-check-BipRjh2G.js";import{L as xu}from"./log-in-BWcU6fvU.js";import{S as mu}from"./server-5xo7scxe.js";import{K as hu}from"./key-round-CBIBEIGQ.js";import{O as pu}from"./ops-dashboard-B5KMrMAV.js";import{c as uu}from"./upchunk-B4A0v5W4.js";import{F as gu}from"./film-5Ww7nMCK.js";import{F as Hm}from"./flag-6djadGIy.js";import{M as Jl}from"./mouse-pointer-click-BW1i1K1Y.js";import{C as bu}from"./cloud-upload-D4KUxAWd.js";import{P as Yl}from"./pen-DP6KqCyg.js";import{F as Il}from"./flask-conical-BNHqZQpQ.js";import{B as ju}from"./book-marked-3-KNVwiq.js";import{H as Xm}from"./heart-pulse-BACCDVWz.js";import{W as vu}from"./webhook-1iLIbvwP.js";import{T as _i}from"./trophy-Bk4C1tet.js";import{U as rc}from"./upload-BKNIN1AN.js";import{H as Ah}from"./heart-CzKl5jvQ.js";import{R as Nu}from"./repeat-sSLEIX2z.js";import{A as Jm}from"./arrow-left-DY50GvQQ.js";import{P as Ga}from"./pencil-DB7EhnQs.js";import"./vendor-react-CQmBMThG.js";import"./index-C7yKKq-w.js";import"./value-BTdN53H7.js";import"./index-BdQq_4o_.js";
1import"./scroll-area-nONWKjQR.js";import"./stamp-BZO_gJDT.js";import"./circle-pause-B5v17gJf.js";const fu=[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]],ka=Wa("arrow-right-left",fu);const wu=[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M17 14h-6",key:"bkmgh3"}],["path",{d:"M13 18H7",key:"bb0bb7"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 18h.01",key:"1bdyru"}]],yu=Wa("calendar-range",wu);const ku=[["path",{d:"M12 13v8l-4-4",key:"1f5nwf"}],["path",{d:"m12 21 4-4",key:"1lfcce"}],["path",{d:"M4.393 15.269A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.436 8.284",key:"ui1hmy"}]],Ym=Wa("cloud-download",ku);const Cu=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Su=Wa("ellipsis",Cu);const $u=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]],Oi=Wa("git-merge",$u);const Au=[["path",{d:"M9 17H7A5 5 0 0 1 7 7",key:"10o201"}],["path",{d:"M15 7h2a5 5 0 0 1 4 8",key:"1d3206"}],["line",{x1:"8",x2:"12",y1:"12",y2:"12",key:"rvw6j4"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]],Pu=Wa("link-2-off",Au);const Tu=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Eu=Wa("minimize-2",Tu);const Iu=[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]],nc=Wa("shield-off",Iu);const Ru=[["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m14.305 16.53.923-.382",key:"1itpsq"}],["path",{d:"m15.228 13.852-.923-.383",key:"eplpkm"}],["path",{d:"m16.852 12.228-.383-.923",key:"13v3q0"}],["path",{d:"m16.852 17.772-.383.924",key:"1i8mnm"}],["path",{d:"m19.148 12.228.383-.923",key:"1q8j1v"}],["path",{d:"m19.53 18.696-.382-.924",key:"vk1qj3"}],["path",{d:"m20.772 13.852.924-.383",key:"n880s0"}],["path",{d:"m20.772 16.148.924.383",key:"1g6xey"}],["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],Fu=Wa("user-cog",Ru),Du=a=>a>=1e3?`R$${(a/1e3).toFixed(1)}k`:`R$${a.toFixed(0)}`,gs=a=>`R$ ${a.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})}`,Js=a=>a.toLocaleString("pt-BR"),lc=a=>a===null?"—":`${a.toFixed(2)}x`,Mu={scale:{bg:"bg-emerald-500/10",border:"border-emerald-500/40",text:"text-emerald-400",ring:"ring-emerald-500/30",badgeBg:"bg-emerald-500/20 text-emerald-300 border-emerald-500/40",badgeText:"ESCALAR",icon:e.jsx($r,{className:"w-3 h-3"}),label:"Escalar"},keep:{bg:"bg-amber-500/10",border:"border-amber-500/40",text:"text-amber-400",ring:"ring-amber-500/30",badgeBg:"bg-amber-500/20 text-amber-300 border-amber-500/40",badgeText:"MANTER",icon:e.jsx(Ql,{className:"w-3 h-3"}),label:"Manter"},pause:{bg:"bg-red-500/10",border:"border-red-500/40",text:"text-red-400",ring:"ring-red-500/30",badgeBg:"bg-red-500/20 text-red-300 border-red-500/40",badgeText:"PAUSAR",icon:e.jsx(Ca,{className:"w-3 h-3"}),label:"Pausar"},no_data:{bg:"bg-white/5",border:"border-white/10",text:"text-white/40",ring:"ring-white/10",badgeBg:"bg-white/5 text-white/40 border-white/10",badgeText:"SEM DADOS",icon:e.jsx(Ql,{className:"w-3 h-3"}),label:"Sem dados"}},Lu={today:{bg:"bg-emerald-500/10",border:"border-emerald-500/30",text:"text-emerald-400"},recent:{bg:"bg-amber-500/10",border:"border-amber-500/30",text:"text-amber-400"},old:{bg:"bg-violet-500/10",border:"border-violet-500/30",text:"text-violet-400"},unknown:{bg:"bg-white/5",border:"border-white/10",text:"text-white/50"}},zu={today:e.jsx(ns,{className:"w-3.5 h-3.5"}),recent:e.jsx(Zl,{className:"w-3.5 h-3.5"}),old:e.jsx(Ie,{className:"w-3.5 h-3.5"}),unknown:e.jsx(Xe,{className:"w-3.5 h-3.5"})};function qu({campaignId:a,range:r=15}){const{data:l,isLoading:n,error:u}=z({queryKey:["/api/admin/campaigns/timeline",a,r],queryFn:()=>N("GET",`/api/admin/campaigns/${a}/timeline?range=${r}`).then(p=>p.json()),staleTime:6e4}),f=d.useMemo(()=>l?.dailySeries?l.dailySeries.map(p=>{const[,g,w]=p.date.split("-");return{...p,dateLabel:`${w}/${g}`}}):[],[l]);if(n)return e.jsx("div",{className:"px-4 py-6 bg-gradient-to-b from-white/[0.02] to-transparent border-t border-white/5",children:e.jsxs("div",{className:"flex items-center gap-2 text-white/50 text-xs",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}),"Carregando timeline da campanha..."]})});if(u)return e.jsx("div",{className:"px-4 py-3 bg-red-500/5 border-t border-red-500/20",children:e.jsxs("div",{className:"text-xs text-red-400",children:["Erro ao carregar timeline: ",u.message]})});if(!l)return null;const j=l.totals.visitors>0||l.totals.orders>0||l.totals.spend>0;return e.jsxs("div",{className:"px-4 py-4 bg-gradient-to-b from-white/[0.015] to-transparent border-t border-white/5 space-y-4","data-testid":`timeline-${a}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 text-emerald-400"}),e.jsx("h4",{className:"text-xs font-semibold text-white/90 uppercase tracking-wide",children:"ROI por período · investimento × receita real"})]}),e.jsxs("span",{className:"text-[10px] text-white/30",children:["escalar ≥",l.thresholds.scale,"x · manter ≥",l.thresholds.keep,"x · pausar <",l.thresholds.keep,"x"]})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-2",children:l.roiByPeriod.map(p=>{const g=Mu[p.recommendation],w=p.platformRoi;return e.jsxs("div",{className:`rounded-lg ${g.bg} ${g.border} border p-3 ring-1 ${g.ring}`,"data-testid":`roi-period-${p.period}-${a}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-[10px] font-semibold text-white/70 uppercase tracking-wide",children:p.label}),e.jsxs("span",{className:`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[8px] font-bold border ${g.badgeBg}`,"data-testid":`badge-recommendation-${p.period}-${a}`,children:[g.icon,g.badgeText]})]}),e.jsxs("div",{className:"flex items-baseline gap-1.5 mb-1",children:[e.jsx("span",{className:`text-2xl font-bold ${g.text}`,"data-testid":`roi-value-${p.period}-${a}`,children:lc(w)}),e.jsx("span",{className:"text-[9px] text-white/40",children:"ROI"})]}),e.jsxs("div",{className:"text-[10px] text-white/60 space-y-0.5 leading-tight",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-white/40",children:"Investido:"}),e.jsx("span",{className:"text-red-300 font-medium",children:gs(p.spend)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-white/40",children:"Receita Meta:"}),e.jsx("span",{className:"text-emerald-400 font-semibold",children:gs(p.platformRevenue)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-white/30",children:"Atrib. interna:"}),e.jsx("span",{className:"text-emerald-200/70",children:gs(p.internalRevenue)})]}),e.jsxs("div",{className:"flex justify-between pt-0.5 border-t border-white/5 mt-1",children:[e.jsx("span",{className:"text-white/40",children:"Conv. Meta:"}),e.jsxs("span",{className:"text-white/70",children:[Js(p.platformConversions)," / ",Js(p.internalOrders)," interno"]})]})]})]},p.period)})}),l.attributionGap&&l.attributionGap.metaRevenue>0&&e.jsxs("div",{className:"rounded-lg bg-gradient-to-r from-sky-500/5 to-violet-500/5 border border-sky-500/20 px-3 py-2 flex items-start gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-sky-400 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-[11px] text-white/80 leading-relaxed flex-1",children:[e.jsx("strong",{className:"text-sky-300",children:"Gap de atribuição:"})," a Meta reportou"," ",e.jsx("span",{className:"text-emerald-400 font-semibold",children:gs(l.attributionGap.metaRevenue)})," ","(",Js(l.attributionGap.metaConversions)," conversões) nos últimos ",l.range," dias, mas nossa atribuição interna por ",e.jsx("code",{className:"text-white/50 text-[10px]",children:"utm_campaign"})," só capturou"," ",e.jsx("span",{className:"text-emerald-200 font-semibold",children:gs(l.attributionGap.internalRevenue)})," ","(",Js(l.attributionGap.internalOrders)," pedidos) ="," ",e.jsxs("span",{className:`font-bold ${l.attributionGap.captureRatePct>=70?"text-emerald-400":l.attributionGap.captureRatePct>=40?"text-amber-400":"text-red-400"}`,children:[l.attributionGap.captureRatePct.toFixed(0),"%"]})," ","do real. Use a ",e.jsx("strong",{className:"text-emerald-400",children:"receita Meta"})," como referência principal pra decisões de scale."]})]}),l.totals.orders>0&&(()=>{const p=l.totals.ordersFromTodaysTraffic,g=l.totals.ordersFromRecentTraffic,w=l.totals.ordersFromOldTraffic,y=g+w,F=p+g+w+l.totals.ordersFromUnknownTraffic;if(F===0)return null;const c=F>0?y/F*100:0;return c>=50&&y>0?e.jsxs("div",{className:"rounded-lg bg-amber-500/5 border border-amber-500/20 px-3 py-2 flex items-start gap-2",children:[e.jsx(Xe,{className:"w-4 h-4 text-amber-400 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-[11px] text-amber-100/90 leading-relaxed",children:[e.jsx("strong",{className:"text-amber-300",children:"Lag dominante:"})," ",c.toFixed(0),"% das vendas (",Js(y),"/",Js(F),') vieram de tráfego de dias anteriores. Cliente leva 1-15 dias pra fechar a compra (lê plano, ajusta) — não pause só porque "vendeu pouco hoje".']})]}):null})(),j?e.jsxs("div",{className:"rounded-lg border border-white/10 bg-white/[0.02] backdrop-blur-md p-3",children:[e.jsx("div",{style:{width:"100%",height:300},"data-testid":`chart-timeline-${a}`,children:e.jsx(Cn,{children:e.jsxs(yh,{data:f,margin:{top:5,right:8,bottom:5,left:-8},children:[e.jsx(Sn,{stroke:"rgba(255,255,255,0.05)",strokeDasharray:"3 3"}),e.jsx($n,{dataKey:"dateLabel",tick:{fontSize:10,fill:"#9ca3af"}}),e.jsx(Wi,{yAxisId:"left",tick:{fontSize:10,fill:"#9ca3af"},width:32}),e.jsx(Wi,{yAxisId:"right",orientation:"right",tick:{fontSize:10,fill:"#10b981"},tickFormatter:Du,width:48}),e.jsx(An,{cursor:{fill:"rgba(255,255,255,0.04)"},content:({active:p,payload:g,label:w})=>{if(!p||!g?.length)return null;const y=g[0]?.payload;if(!y)return null;const F=y.spend>0?y.platformRevenue/y.spend:null,c=y.spend>0?y.revenue/y.spend:null;return e.jsxs("div",{className:"rounded-lg border border-white/10 bg-[#0a0a0a]/95 backdrop-blur-md p-2.5 text-[11px] shadow-xl min-w-[220px]",children:[e.jsx("div",{className:"text-white font-semibold mb-1.5",children:w}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-sky-500"}),e.jsx("span",{className:"text-white/60",children:"Visitantes:"}),e.jsx("span",{className:"text-white font-medium ml-auto",children:Js(y.visitors)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-amber-400"}),e.jsx("span",{className:"text-white/60",children:"Pedidos (interno):"}),e.jsx("span",{className:"text-white font-medium ml-auto",children:Js(y.orders)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-0.5 bg-red-400"}),e.jsx("span",{className:"text-white/60",children:"Investido:"}),e.jsx("span",{className:"text-red-300 font-semibold ml-auto",children:gs(y.spend)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-0.5 bg-emerald-500"}),e.jsx("span",{className:"text-white/60",children:"Receita Meta:"}),e.jsx("span",{className:"text-emerald-400 font-semibold ml-auto",children:gs(y.platformRevenue)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-0.5 bg-emerald-300 opacity-60",style:{borderTop:"1px dashed"}}),e.jsx("span",{className:"text-white/60",children:"Receita interna:"}),e.jsx("span",{className:"text-emerald-200 ml-auto",children:gs(y.revenue)})]}),F!==null&&e.jsxs("div",{className:"mt-1.5 pt-1.5 border-t border-white/10 space-y-0.5 text-[10px]",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-white/40",children:"ROI Meta:"}),e.jsx("span",{className:`font-bold ${F>=l.thresholds.scale?"text-emerald-400":F>=l.thresholds.keep?"text-amber-400":"text-red-400"}`,children:lc(F)})]}),c!==null&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-white/40",children:"ROI interno:"}),e.jsx("span",{className:"text-white/60",children:lc(c)})]})]})]}),y.orders>0&&e.jsxs("div",{className:"mt-2 pt-1.5 border-t border-white/10 space-y-0.5 text-[10px]",children:[e.jsx("div",{className:"text-white/40 mb-0.5",children:"Origem do tráfego das vendas:"}),y.ordersFromTodaysTraffic>0&&e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{className:"text-emerald-400",children:"▸ mesmo dia"}),e.jsxs("span",{className:"text-white/70",children:[y.ordersFromTodaysTraffic," • ",gs(y.revenueFromTodaysTraffic)]})]}),y.ordersFromRecentTraffic>0&&e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{className:"text-amber-400",children:"▸ últimos 7d"}),e.jsxs("span",{className:"text-white/70",children:[y.ordersFromRecentTraffic," • ",gs(y.revenueFromRecentTraffic)]})]}),y.ordersFromOldTraffic>0&&e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{className:"text-violet-400",children:"▸ 7d+"}),e.jsxs("span",{className:"text-white/70",children:[y.ordersFromOldTraffic," • ",gs(y.revenueFromOldTraffic)]})]}),y.ordersFromUnknownTraffic>0&&e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{className:"text-white/40",children:"▸ sem touchpoint"}),e.jsxs("span",{className:"text-white/60",children:[y.ordersFromUnknownTraffic," • ",gs(y.revenueFromUnknownTraffic)]})]})]})]})}}
1),e.jsx(wh,{wrapperStyle:{fontSize:10,color:"#9ca3af",paddingTop:4}}),e.jsx(Vl,{yAxisId:"left",dataKey:"visitors",name:"Visitantes",fill:"#0ea5e9",opacity:.5,radius:[3,3,0,0]}),e.jsx(hi,{yAxisId:"left",type:"monotone",dataKey:"orders",name:"Pedidos (interno)",stroke:"#fbbf24",strokeWidth:2,dot:{r:2.5},activeDot:{r:4}}),e.jsx(hi,{yAxisId:"right",type:"monotone",dataKey:"spend",name:"Investido",stroke:"#f87171",strokeWidth:2,dot:{r:2.5},activeDot:{r:4}}),e.jsx(hi,{yAxisId:"right",type:"monotone",dataKey:"platformRevenue",name:"Receita Meta",stroke:"#10b981",strokeWidth:2.5,dot:{r:3},activeDot:{r:5}}),e.jsx(hi,{yAxisId:"right",type:"monotone",dataKey:"revenue",name:"Receita interna",stroke:"#6ee7b7",strokeWidth:1.5,strokeDasharray:"4 3",dot:{r:2},activeDot:{r:3.5}})]})})}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-2 mt-3 pt-3 border-t border-white/5",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-[10px] text-white/40 uppercase tracking-wide mb-0.5",children:[e.jsx(Re,{className:"w-3 h-3"})," Visitantes"]}),e.jsx("div",{className:"text-sm font-semibold text-sky-400","data-testid":`total-visitors-${a}`,children:Js(l.totals.visitors)})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-[10px] text-white/40 uppercase tracking-wide mb-0.5",children:[e.jsx(Jt,{className:"w-3 h-3"})," Pedidos"]}),e.jsxs("div",{className:"text-sm font-semibold text-amber-400","data-testid":`total-orders-${a}`,children:[Js(l.totals.orders),e.jsxs("span",{className:"text-white/40 text-[10px]",children:[" / ",Js(l.totals.platformConversions)," Meta"]})]})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-[10px] text-white/40 uppercase tracking-wide mb-0.5",children:[e.jsx(nt,{className:"w-3 h-3"})," Investido"]}),e.jsx("div",{className:"text-sm font-semibold text-red-300","data-testid":`total-spend-${a}`,children:gs(l.totals.spend)})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-[10px] text-white/40 uppercase tracking-wide mb-0.5",children:[e.jsx(nt,{className:"w-3 h-3"})," Receita Meta"]}),e.jsx("div",{className:"text-sm font-semibold text-emerald-400","data-testid":`total-revenue-${a}`,children:gs(l.totals.platformRevenue)}),e.jsxs("div",{className:"text-[9px] text-white/30 mt-0.5",children:["Interna: ",gs(l.totals.revenue)]})]})]})]}):e.jsxs("div",{className:"rounded-lg border border-white/10 bg-white/[0.02] p-6 text-center",children:[e.jsxs("div",{className:"text-white/40 text-xs",children:["Sem dados nos últimos ",l.range," dias."]}),e.jsxs("div",{className:"text-white/25 text-[10px] mt-1",children:["Atribuição interna usa ",e.jsx("code",{className:"text-white/40",children:"utm_campaign"}),"; investimento e receita Meta vêm dos snapshots do Meta Ads (sincronize a campanha se ainda não houver dados)."]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ns,{className:"w-3.5 h-3.5 text-white/50"}),e.jsxs("h5",{className:"text-[11px] font-semibold text-white/70 uppercase tracking-wide",children:["Atribuição interna por idade do tráfego (últimos ",l.range," dias)"]})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-2",children:l.lagBreakdown.map(p=>{const g=Lu[p.bucket],w=zu[p.bucket];return e.jsxs("div",{className:`rounded-lg ${g.bg} ${g.border} border p-2.5`,"data-testid":`lag-bucket-${p.bucket}-${a}`,children:[e.jsxs("div",{className:`flex items-center gap-1.5 ${g.text} text-[10px] font-medium mb-1`,children:[w,e.jsx("span",{className:"truncate",children:p.label})]}),e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:`text-base font-bold ${g.text}`,"data-testid":`lag-orders-${p.bucket}-${a}`,children:Js(p.orders)}),e.jsx("span",{className:"text-[10px] text-white/40",children:p.orders===1?"venda":"vendas"})]}),e.jsx("div",{className:"text-[10px] text-white/60","data-testid":`lag-revenue-${p.bucket}-${a}`,children:gs(p.revenue)}),e.jsx("div",{className:"text-[9px] text-white/35 mt-0.5 leading-tight",children:p.description})]},p.bucket)})})]}),l.partialFailures.length>0&&e.jsxs("div",{className:"text-[10px] text-amber-400/70",children:["⚠ Falhas parciais: ",l.partialFailures.join(" · ")]})]})}const _u=a=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format((a||0)/100),Ou={critical:{dot:"bg-rose-400",iconWrap:"bg-rose-500/15 border-rose-500/30",icon:"text-rose-300",badge:"bg-rose-500/20 text-rose-200 border-rose-500/30",cta:"text-rose-200 hover:text-white"}
1,warn:{dot:"bg-amber-400",iconWrap:"bg-amber-500/15 border-amber-500/30",icon:"text-amber-300",badge:"bg-amber-500/20 text-amber-100 border-amber-500/30",cta:"text-amber-100 hover:text-white"},info:{dot:"bg-sky-400",iconWrap:"bg-sky-500/15 border-sky-500/30",icon:"text-sky-300",badge:"bg-sky-500/20 text-sky-100 border-sky-500/30",cta:"text-sky-100 hover:text-white"}};function Bu(){const{data:a}=z({queryKey:["/api/admin/pending-actions"],queryFn:async()=>{const u=await fetch("/api/admin/pending-actions");if(!u.ok)throw new Error("Erro ao carregar pendências");return u.json()},refetchInterval:6e4});if(!a)return null;if(a.totalCount===0)return e.jsxs("div",{className:"rounded-2xl border border-emerald-500/20 bg-emerald-500/[0.04] px-4 py-3 flex items-center gap-3","data-testid":"banner-pending-clear",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-emerald-500/15 border border-emerald-500/30 flex items-center justify-center flex-shrink-0",children:e.jsx(be,{className:"w-4.5 h-4.5 text-emerald-300"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-emerald-100",children:"Central de Pendências · tudo em dia"}),e.jsx("p",{className:"text-xs text-emerald-200/70",children:"Nenhuma entrega atrasada, saque, verificação ou disputa aguardando você agora."})]})]});const r=[];if(a.delivery.count>0){const u=a.delivery.needsAdmin>0||(a.delivery.oldestHours||0)>=6,f=[];a.delivery.oldestHours!==null&&f.push(`mais antigo há ${a.delivery.oldestHours}h`),a.delivery.needsAdmin>0&&f.push(`${a.delivery.needsAdmin} ${a.delivery.needsAdmin===1?"precisa":"precisam"} de atenção manual`),a.delivery.recoveredLast24h>0&&f.push(`${a.delivery.recoveredLast24h} recuperados em 24h`),r.push({key:"delivery",icon:Zs,title:`${a.delivery.count} ${a.delivery.count===1?"pedido pago aguardando entrega":"pedidos pagos aguardando entrega"}`,detail:f.join(" · ")||"Verifique a fila de entrega.",href:"/admin/bundle-delivery",cta:"Investigar entregas",count:a.delivery.count,severity:u?"critical":"warn"})}if(a.withdrawals.count>0){const u=a.withdrawals.count>=5||(a.withdrawals.oldestHours||0)>=24,f=[`${_u(a.withdrawals.totalNetCents)} a liberar`];a.withdrawals.oldestHours!==null&&a.withdrawals.oldestHours>0&&f.push(`mais antigo há ${a.withdrawals.oldestHours}h`),r.push({key:"withdrawals",icon:kh,title:`${a.withdrawals.count} ${a.withdrawals.count===1?"autor aguardando saque":"autores aguardando saque"}`,detail:f.join(" · "),href:"/admin/loja/saques",cta:"Processar saques",count:a.withdrawals.count,severity:u?"critical":"warn"})}a.disputes.count>0&&r.push({key:"disputes",icon:Ks,title:`${a.disputes.count} ${a.disputes.count===1?"disputa DMCA aberta":"disputas DMCA abertas"}`,detail:"Casos de remoção aguardando decisão.",href:"/admin/loja/dmca",cta:"Analisar disputas",count:a.disputes.count,severity:"critical"}),a.kyc.count>0&&r.push({key:"kyc",icon:bh,title:`${a.kyc.count} ${a.kyc.count===1?"verificação KYC pendente":"verificações 
1KYC pendentes"}`,detail:"Documentos de autores aguardando revisão para saque.",href:"/admin/loja/kyc",cta:"Revisar KYC",count:a.kyc.count,severity:"info"}),a.humanServices.count>0&&r.push({key:"humanServices",icon:Pn,title:`${a.humanServices.count} ${a.humanServices.count===1?"serviço humano aguardando revisão":"serviços humanos aguardando revisão"}`,detail:"ISBN / ficha / diagramação aguardando ação do autor ou admin.",href:"/admin/servicos-humanos",cta:"Abrir serviços",count:a.humanServices.count,severity:"info"}),a.brokenFunnels?.count>0&&r.push({key:"brokenFunnels",icon:Pu,title:`${a.brokenFunnels.count} ${a.brokenFunnels.count===1?"funil ativo sem página de venda":"funis ativos sem página de venda"}`,detail:"O link público /f/… retorna erro 503 enquanto não houver ao menos 1 página ativa.",href:"/admin/sales-funnels",cta:"Corrigir funis",count:a.brokenFunnels.count,severity:"critical"});const l=r.some(u=>u.severity==="critical"),n=l?{border:"border-rose-500/40",bg:"bg-rose-500/[0.06]",icon:"text-rose-300",iconWrap:"bg-rose-500/15 border-rose-500/30"}:{border:"border-amber-500/40",bg:"bg-amber-500/[0.06]",icon:"text-amber-300",iconWrap:"bg-amber-500/15 border-amber-500/30"};return e.jsxs("div",{className:`rounded-2xl border-2 ${n.border} ${n.bg} overflow-hidden`,"data-testid":"banner-pending-actions",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 md:px-5 pt-4 pb-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-xl border ${n.iconWrap} flex items-center justify-center flex-shrink-0`,children:l?e.jsx(Ce,{className:`w-5 h-5 ${n.icon}`}):e.jsx(Nn,{className:`w-5 h-5 ${n.icon}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"text-base md:text-lg font-bold text-white flex items-center gap-2","data-testid":"text-pending-title",children:["Central de Pendências",e.jsx("span",{className:"inline-flex items-center justify-center min-w-6 h-6 px-2 rounded-full bg-white/10 text-white text-xs font-bold",children:a.totalCount})]}),e.jsx("p",{className:"text-xs text-white/70",children:l?"Itens críticos exigem sua atenção agora.":"Itens aguardando sua ação para manter tudo em dia."})]})]}),e.jsx("div",{className:"divide-y divide-white/5 border-t border-white/10",children:r.map(u=>{const f=Ou[u.severity],j=u.icon;return e.jsxs("a",{href:u.href,className:"group flex items-center gap-3 px-4 md:px-5 py-3 hover:bg-white/[0.04] transition-colors","data-testid":`pending-row-${u.key}`,children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${f.dot} flex-shrink-0`,"aria-hidden":!0}),e.jsx("div",{className:`w-9 h-9 rounded-lg border ${f.iconWrap} flex items-center justify-center flex-shrink-0`,children:e.jsx(j,{className:`w-4.5 h-4.5 ${f.icon}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-white truncate",children:u.title}),e.jsx("p",{className:"text-xs text-white/60 truncate",children:u.detail})]}),e.jsxs("span",{className:`hidden sm:inline-flex items-center gap-1 text-xs font-semibold ${f.cta} transition-colors flex-shrink-0`,children:[u.cta,e.jsx(ya,{className:"w-4 h-4 group-hover:translate-x-0.5 transition-transform"})]}),e.jsx(ya,{className:"w-4 h-4 text-white/40 sm:hidden flex-shrink-0"})]},u.key)})}),a.partialFailures.length>0&&e.jsxs("p",{className:"px-4 md:px-5 py-2 text-[11px] text-white/40 border-t border-white/5","data-testid":"text-pending-partial",children:["Alguns dados podem estar incompletos no momento (",a.partialFailures.join(", "),")."]})]})}const Uu={ok:{wrap:"border-emerald-500/30 bg-emerald-500/5",icon:"text-emerald-400",Icon:be,chip:"bg-emerald-500/15 text-emerald-300 border-emerald-500/30"},warning:{wrap:"border-amber-500/40 bg-amber-500/10",icon:"text-amber-400",Icon:Ce,chip:"bg-amber-500/15 text-amber-300 border-amber-500/30"},critical:{wrap:"border-red-500/50 bg-red-500/10",icon:"text-red-400",Icon:dt,chip:"bg-red-500/15 text-red-300 border-red-500/30"}};function Ku(){const{data:a}=z({queryKey:["/api/admin/ai-key-health"],queryFn:async()=>(await N("GET","/api/admin/ai-key-health")).json(),refetchInterval:6e4,staleTime:3e4});if(!a)return null;const r=a.severity||"ok",l=Uu[r],n=a.chain?.tiers?.find(f=>f.active)||null,u=(a.chain?.tiers||[]).filter(f=>f.healthy&&!f.active).length;return e.jsxs("div",{className:`rounded-xl border px-4 py-3 flex items-start gap-3 ${l.wrap}`,"data-testid":"banner-ai-primary-status",children:[e.jsx("div",{className:`mt-0.5 shrink-0 ${l.icon}`,children:e.jsx(l.Icon,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Ht,{className:"w-3.5 h-3.5 text-white/50"}),e.jsx("span",{className:"text-sm font-semibold text-white truncate","data-testid":"text-ai-primary-title",children:a.title}),n&&e.jsx("span",{className:`text-[10px] font-medium px-2 py-0.5 rounded-full border ${l.chip}`,"data-testid":"chip-ai-active-tier",children:n.label})]}),e.jsxs("p",{className:"text-xs text-white/60 mt-1 leading-relaxed","data-testid":"text-ai-primary-message",children:[a.message,r==="ok"&&u>0&&e.jsxs("span",{className:"text-white/40",children:[" · ",u," reserva(s) pronta(s)."]})]})]}),e.jsxs(jh,{href:"/admin/escala",className:"shrink-0 self-center text-[11px] text-white/60 hover:text-white inline-flex items-center gap-1 whitespace-nowrap","data-testid":"link-ai-escala",children:["Detalhes ",e.jsx(vh,{className:"w-3 h-3"})]})]})}const jr=a=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(a||0),Bi=a=>new Intl.NumberFormat("pt-BR").format(a||0),Gu=a=>{try{const[,r,l]=a.split("-");return`${l}/${r}`}catch{return a}};function wc(){return new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date)}function Ui(a){return`${a.getUTCFullYear()}
1-${String(a.getUTCMonth()+1).padStart(2,"0")}-${String(a.getUTCDate()).padStart(2,"0")}`}function Vu(){const[a,r,l]=wc().split("-").map(Number);return new Date(Date.UTC(a,r-1,l,12,0,0))}function Qu(a,r,l){if(a==="custom")return{from:r,to:l};if(["7","15","30","90"].includes(a))return{range:Number(a)};const n=Vu(),u=Ui(n);if(a==="today")return{from:u,to:u};const j=(n.getUTCDay()+6)%7;if(a==="this_week"){const p=new Date(n);return p.setUTCDate(n.getUTCDate()-j),{from:Ui(p),to:u}}if(a==="last_week"){const p=new Date(n);p.setUTCDate(n.getUTCDate()-j);const g=new Date(p);g.setUTCDate(p.getUTCDate()-1);const w=new Date(g);return w.setUTCDate(g.getUTCDate()-6),{from:Ui(w),to:Ui(g)}}if(a==="this_month"){const p=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),1,12,0,0));return{from:Ui(p),to:u}}if(a==="last_month"){const p=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth()-1,1,12,0,0)),g=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),0,12,0,0));return{from:Ui(p),to:Ui(g)}}return{range:30}}const Wu={today:"Hoje",this_week:"Esta semana",last_week:"Semana passada",this_month:"Este mês",last_month:"Mês passado",7:"Últimos 7 dias",15:"Últimos 15 dias",30:"Últimos 30 dias",90:"Últimos 90 dias",custom:"Personalizado"};function cn({icon:a,label:r,value:l,sub:n,accent:u="text-white",testId:f}){return e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3","data-testid":f,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground text-[11px] uppercase tracking-wide mb-1",children:[e.jsx(a,{className:"w-3.5 h-3.5"})," ",r]}),e.jsx("div",{className:`text-lg font-semibold ${u}`,children:l}),n&&e.jsx("div",{className:"text-[11px] text-muted-foreground mt-0.5",children:n})]})}function Hu(){const[a,r]=d.useState("30"),[l,n]=d.useState(""),[u,f]=d.useState(""),j=d.useMemo(()=>Qu(a,l,u),[a,l,u]),p=d.useMemo(()=>j.range?`range=${j.range}`:j.from&&j.to?`from=${j.from}&to=${j.to}`:"range=30",[j]),g=a!=="custom"||!!l&&!!u,{data:w,isLoading:y,isFetching:F,refetch:c}=z({queryKey:["/api/admin/funil-landing","timeline-panel",p],queryFn:async()=>{const A=await fetch(`/api/admin/funil-landing?${p}`);if(!A.ok)throw new Error("Erro ao carregar funil");return A.json()},enabled:g,staleTime:6e4}),m=d.useMemo(()=>(w?.dailySeries||[]).map(A=>({...A,dateLabel:Gu(A.date)})),[w]),$=w?.funnelTotals,D=w?.kpis?.revenue?.currentNet;return e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.02] backdrop-blur-md p-5 space-y-5","data-testid":"panel-funnel-timeline",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"})," Linha do tempo · ",Wu[a],e.jsx("span",{className:"text-xs text-muted-foreground font-normal",children:"(São Paulo)"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yu,{className:"w-3.5 h-3.5 text-muted-foreground absolute left-2.5 top-1/2 -translate-y-1/2 pointer-events-none"}),e.jsxs("select",{value:a,onChange:A=>r(A.target.value),className:"appearance-none bg-white/5 border border-white/10 text-white text-xs rounded-lg pl-8 pr-7 py-2 focus:outline-none focus:border-emerald-500/50 cursor-pointer","data-testid":"select-timeline-period",children:[e.jsxs("optgroup",{label:"Atalhos",children:[e.jsx("option",{value:"today",children:"Hoje"}),e.jsx("option",{value:"this_week",children:"Esta semana"}),e.jsx("option",{value:"last_week",children:"Semana passada"}),e.jsx("option",{value:"this_month",children:"Este mês"}),e.jsx("option",{value:"last_month",children:"Mês passado"})]}),e.jsxs("optgroup",{label:"Períodos",children:[e.jsx("option",{value:"7",children:"Últimos 7 dias"}),e.jsx("option",{value:"15",children:"Últimos 15 dias"}),e.jsx("option",{value:"30",children:"Últimos 30 dias"}),e.jsx("option",{value:"90",children:"Últimos 90 dias"})]}),e.jsx("optgroup",{label:"Avançado",children:e.jsx("option",{value:"custom",children:"Personalizado…"})})]})]}),a==="custom"&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"date",value:l,max:u||wc(),onChange:A=>n(A.target.value),className:"bg-white/5 border border-white/10 text-white text-xs rounded-lg px-2 py-2 focus:outline-none focus:border-emerald-500/50","data-testid":"input-timeline-from"}),e.jsx("span",{className:"text-muted-foreground text-xs",children:"até"}),e.jsx("input",{type:"date",value:u,min:l,max:wc(),onChange:A=>f(A.target.value),className:"bg-white/5 border border-white/10 text-white text-xs rounded-lg px-2 py-2 focus:outline-none focus:border-emerald-500/50","data-testid":"input-timeline-to"})]}),e.jsx("button",{onClick:()=>c(),className:"inline-flex items-center justify-center w-9 h-9 rounded-lg bg-white/5 border border-white/10 hover:bg-white/10 transition-colors",title:"Atualizar","data-testid":"button-timeline-refresh",children:e.jsx(xe,{className:`w-3.5 h-3.5 text-white/70 ${F?"animate-spin":""}`})})]})]}),a==="custom"&&!g&&e.jsx("p",{className:"text-xs text-muted-foreground py-8 text-center","data-testid":"text-timeline-pick-range",children:"Selecione a data inicial e final para ver o gráfico."}),g&&y&&e.jsx("div",{className:"flex items-center justify-center py-16","data-testid":"timeline-loading",children:e.jsx(xe,{className:"w-6 h-6 animate-spin text-emerald-400"})}),g&&w&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 ga
1p-3",children:[e.jsx(cn,{icon:Re,label:"Visitantes",value:Bi($?.visitors||0),testId:"timeline-visitors"}),e.jsx(cn,{icon:Vi,label:"Cadastros",value:Bi($?.signups||0),sub:`${($?.visitorToSignupPct||0).toFixed(1)}% dos visitantes`,testId:"timeline-signups"}),e.jsx(cn,{icon:Jt,label:"Pedidos pagos",value:Bi($?.paidOrders||0),sub:`${Bi($?.buyers||0)} compradores`,testId:"timeline-orders"}),e.jsx(cn,{icon:nt,label:"Receita bruta",value:jr($?.revenue||0),sub:typeof D=="number"?`Líq. ~${jr(D)}`:void 0,accent:"text-emerald-400",testId:"timeline-revenue"}),e.jsx(cn,{icon:Ie,label:"R$ / visitante",value:jr($?.revenuePerVisitor||0),accent:"text-emerald-400",testId:"timeline-rpv"})]}),e.jsx("div",{style:{width:"100%",height:320},"data-testid":"chart-timeline-daily",children:e.jsx(Cn,{children:e.jsxs(yh,{data:m,margin:{top:5,right:12,bottom:5,left:0},children:[e.jsx(Sn,{stroke:"rgba(255,255,255,0.05)",strokeDasharray:"3 3"}),e.jsx($n,{dataKey:"dateLabel",tick:{fontSize:11,fill:"#9ca3af"}}),e.jsx(Wi,{yAxisId:"left",tick:{fontSize:11,fill:"#9ca3af"}}),e.jsx(Wi,{yAxisId:"right",orientation:"right",tick:{fontSize:11,fill:"#10b981"},tickFormatter:A=>`R$${A>=1e3?(A/1e3).toFixed(1)+"k":A}`}),e.jsx(An,{cursor:{fill:"rgba(255,255,255,0.04)"},content:({active:A,payload:o,label:L})=>{if(!A||!o||!o.length)return null;const v=o[0]?.payload||{},I=Number(v.revenue||0),de=Number(v.orders||0);return e.jsxs("div",{className:"rounded-lg border border-white/10 bg-[#0a0a0a] p-3 text-xs shadow-xl min-w-[220px]","data-testid":`tooltip-timeline-${v.date||L}`,children:[e.jsx("div",{className:"text-white font-semibold mb-2",children:String(L)}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"text-sky-300",children:["Visitantes: ",e.jsx("span",{className:"text-white",children:Bi(Number(v.visitors||0))})]}),e.jsxs("div",{className:"text-violet-300",children:["Cadastros: ",e.jsx("span",{className:"text-white",children:Bi(Number(v.signups||0))})]}),e.jsxs("div",{className:"text-amber-300",children:["Pedidos: ",e.jsx("span",{className:"text-white",children:Bi(de)})]}),e.jsxs("div",{className:"text-emerald-400",children:["Receita bruta: ",e.jsx("span",{className:"text-white",children:jr(I)})]}),typeof v.revenueNet=="number"&&v.revenueNet>0&&e.jsxs("div",{className:"text-emerald-300/80",children:["Líquida estimada: ",e.jsx("span",{className:"text-white",children:jr(Number(v.revenueNet))})]}),typeof v.aiCostBRL=="number"&&v.aiCostBRL>0&&e.jsxs("div",{className:"text-rose-300",children:["Custo IA: ",e.jsx("span",{className:"text-white",children:jr(Number(v.aiCostBRL))})]})]})]})}}),e.jsx(wh,{wrapperStyle:{fontSize:11,color:"#9ca3af"}}),e.jsx(Vl,{yAxisId:"left",dataKey:"visitors",name:"Visitantes",fill:"#0ea5e9",opacity:.6}),e.jsx(hi,{yAxisId:"left",type:"monotone",dataKey:"signups",name:"Cadastros",stroke:"#a78bfa",strokeWidth:2,dot:{r:3}}),e.jsx(hi,{yAxisId:"left",type:"monotone",dataKey:"orders",name:"Pedidos",stroke:"#fbbf24",strokeWidth:2,dot:{r:3}}),e.jsx(hi,{yAxisId:"right",type:"monotone",dataKey:"revenue",name:"Receita",stroke:"#10b981",strokeWidth:3,dot:{r:4}}),e.jsx(hi,{yAxisId:"right",type:"monotone",dataKey:"aiCostBRL",name:"Custo IA (R$)",stroke:"#f43f5e",strokeWidth:2,strokeDasharray:"4 3",dot:{r:3}})]})})})]})]})}function xn(a,r,l){const n=new Map;for(const u of a){const f=u.dimensions?.[r]||"unknown",j=parseFloat(u.metrics?.[l]||"0");n.set(f,(n.get(f)||0)+j)}return[...n.entries()].sort((u,f)=>f[1]-u[1]).map(([u,f])=>({name:u,value:f}))}function Bs(a){return a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${(a/1e3).toFixed(1)}K`:a.toLocaleString("pt-BR")}function dc(a){return`R$ ${a.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})}`}const Xu=[{event:"page_view",label:"Visualizações",color:"bg-blue-500"},{event:"session_start",label:"Sessões",color:"bg-indigo-500"},{event:"book_created",label:"Livro Criado",color:"bg-purple-500"},{event:"begin_checkout",label:"Checkout",color:"bg-amber-500"},{event:"add_to_cart",label:"Carrinho",color:"bg-orange-500"},{event:"purchase",label:"Compra",color:"bg-emerald-500"}];function Ju(){const{user:a}=Sa(),r=!!a&&a.role==="admin",l=$a(),[n,u]=d.useState(!1),{data:f,isLoading:j}=z({queryKey:["/api/admin/ga-intelligence/latest"],queryFn:()=>N("GET","/api/admin/ga-intelligence/latest").then(B=>B.json()),enabled:r}),{data:p,isLoading:g}=z({queryKey:["/api/admin/ga-intelligence/audience"],queryFn:()=>N("GET","/api/admin/ga-intelligence/audience").then(B=>B.json()),enabled:r}),{data:w}=z({queryKey:["/api/admin/ga-intelligence/funnel"],queryFn:()=>N("GET","/api/admin/ga-intelligence/funnel").then(B=>B.json()),enabled:r}),{data:y}=z({queryKey:["/api/admin/ga-intelligence/purchaser-profile"],queryFn:()=>N("GET","/api/admin/ga-intelligence/purchaser-profile").then(B=>B.json()),enabled:r}),{data:F}=z({queryKey:["/api/admin/ga-intelligence/traffic-sources"],queryFn:()=>N("GET","/api/admin/ga-intelligence/traffic-sources").then(B=>B.json()),enabled:r}),{data:c}=z({queryKey:["/api/admin/ga-intelligence/pages"],queryFn:()=>N("GET","/api/admin/ga-intelligence/pages").then(B=>B.json()),enabled:r}),{data:m}=z({queryKey:["/api/admin/ga-intelligence/revenue-by-source"],queryFn:()=>N("GET","/api/admin/ga-intelligence/revenue-by-source").then(B=>B.json()),enabled:r}),$=W({mutationFn:()=>N("POST","/api/admin/ga-intelligence/refresh").then(B=>B.json()),onSuccess:()=>
1{l.invalidateQueries({queryKey:["/api/admin/ga-intelligence/latest"]}),l.invalidateQueries({queryKey:["/api/admin/ga-intelligence/audience"]}),l.invalidateQueries({queryKey:["/api/admin/ga-intelligence/funnel"]}),l.invalidateQueries({queryKey:["/api/admin/ga-intelligence/purchaser-profile"]}),l.invalidateQueries({queryKey:["/api/admin/ga-intelligence/traffic-sources"]}),l.invalidateQueries({queryKey:["/api/admin/ga-intelligence/pages"]}),l.invalidateQueries({queryKey:["/api/admin/ga-intelligence/revenue-by-source"]})}}),D=j||g,A=p?.audience||[],o=p?.devices||[],L=w?.funnel||[],v=y?.purchaser||[],I=F?.traffic||[],de=c?.pages||[],me=m?.sources||[],ne=xn(A,"country","activeUsers").slice(0,10),Z=xn(o,"deviceCategory","activeUsers"),S=xn(A,"language","activeUsers").slice(0,8),re=ne.reduce((B,ge)=>B+ge.value,0),_=Z.reduce((B,ge)=>B+ge.value,0),ee=xn(v,"country","conversions").slice(0,10),h=xn(v,"deviceCategory","conversions"),te=I.slice(0,15).map(B=>({source:`${B.dimensions?.sessionSource||"?"}/${B.dimensions?.sessionMedium||"?"}`,sessions:parseInt(B.metrics?.sessions||"0"),conversions:parseInt(B.metrics?.conversions||"0"),bounceRate:parseFloat(B.metrics?.bounceRate||"0")})),M=L.map(B=>({event:B.dimensions?.eventName||"",count:parseInt(B.metrics?.eventCount||"0"),users:parseInt(B.metrics?.totalUsers||"0")})),ae=Xu.map(B=>{const ge=M.find(ut=>ut.event===B.event);return{...B,count:ge?.count||0,users:ge?.users||0}}).filter(B=>B.count>0),ye=Math.max(...ae.map(B=>B.count),1),Me=de.map(B=>({path:B.dimensions?.pagePath||B.dimensions?.pageTitle||"",title:B.dimensions?.pageTitle||B.dimensions?.pagePath||"",views:parseInt(B.metrics?.screenPageViews||"0"),bounceRate:parseFloat(B.metrics?.bounceRate||"0")})).sort((B,ge)=>ge.views-B.views).slice(0,10),se=me.reduce((B,ge)=>B+Number(ge.revenue||0),0),Ne=me.reduce((B,ge)=>B+Number(ge.orderCount||0),0),ie=f?.latest,X=A.length>0||ie;return D?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"ga-loading",children:[e.jsx(T,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("span",{className:"ml-3 text-white/60",children:"Carregando dados de inteligência..."})]}):e.jsxs("div",{className:"space-y-6","data-testid":"ga-intelligence-panel",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jn,{className:"w-6 h-6 text-primary"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white",children:"Inteligência Analytics"}),e.jsx("p",{className:"text-xs text-white/50",children:p?.lastUpdated?`Atualizado: ${new Date(p.lastUpdated).toLocaleString("pt-BR")}`:"Aguardando primeiro ciclo de dados"})]})]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>$.mutate(),disabled:$.isPending,"data-testid":"btn-refresh-ga",children:[$.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin mr-1"}):e.jsx(xe,{className:"w-4 h-4 mr-1"}),"Atualizar"]})]}),!X&&e.jsx(je,{className:"bg-amber-500/10 border-amber-500/30",children:e.jsxs(ve,{className:"p-4 flex items-start gap-3",children:[e.jsx(Ce,{className:"w-5 h-5 text-amber-400 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white font-medium text-sm",children:"Google Analytics não configurado"}),e.jsx("p",{className:"text-white/60 text-xs mt-1",children:'Configure as variáveis GA4_PROPERTY_ID e GA4_SERVICE_ACCOUNT_JSON para ativar a inteligência de analytics. Após configurar, clique em "Atualizar" para puxar os dados.'})]})]})}),ie&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-3",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Gm,{className:"w-4 h-4 text-yellow-400"}),"Briefing de Inteligência — ",ie.reportDate]})}),e.jsxs(ve,{children:[e.jsxs("div",{className:`prose prose-invert prose-sm max-w-none ${n?"":"max-h-64 overflow-hidden relative"}`,"data-testid":"text-intelligence-report",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:Yu(ie.content)}}),!n&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-16 bg-gradient-to-t from-[#1a1a2e] to-transparent"})]}),e.jsx(b,{variant:"ghost",size:"sm",className:"mt-2 text-primary hover:text-primary/80",onClick:()=>u(!n),"data-testid":"btn-toggle-report",children:n?"Mostrar menos":"Ler relatório completo"})]})]}),me.length>0&&e.jsxs(je,{className:"bg-gradient-to-br from-emerald-500/10 to-emerald-900/5 border-emerald-500/20",children:[e.jsxs(Fe,{className:"pb-2",children:[e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4 text-emerald-400"})," Receita por Fonte de Tráfego"]}),e.jsxs("p",{className:"text-xs text-white/50",children:["Total: ",dc(se)," em ",Ne," pedidos"]})]}),e.jsx(ve,{children:e.jsx("div",{className:"space-y-2",children:me.slice(0,10).map((B,ge)=>{const ut=se>0?Number(B.revenue)/se*100:0,at=Number(B.orderCount)>0?Number(B.revenue)/Number(B.orderCount):0;return e.jsxs("div",{className:"group","data-testid":`row-revenue-source-${ge}`,children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-white/80 font-medium",children:[B.source,"/",B.medium]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-white/40",children:[Number(B.orderCount)," pedidos"]}),e.jsxs("span",{className:"text-white/40",children:["ARPU: ",dc(at)]}),e.jsx("span",{className:"text-emerald-400 font-bold",children:dc(Number(B.revenue))})]})]}),e.jsx("div",{className:"w-full bg-white/5 rounded-full h-2",children:e.jsx("div",{className:"bg-gradient-to-r from-emerald-500 to-emerald-400 h-2 rounded-full transition-all",style:{width:`${Math.max(ut,1)}%`}})}),e.jsxs("div",{className:"text-right text-[10px] text-white/30 mt-0.5",children:[ut.toFixed(1),"% da receita"]})]},`${B.source}-${B.medium}`)})})})]}),ae.length>1&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ka,{className:"w-4 h-4 text-orange-400"})," Funil de Conversão"]})}),e.jsxs(ve,{children:[e.jsx("div",{className:"space-y-3",children:ae.map((B,ge)=>{const ut=B.count/ye*100,at=ge>0?ae[ge-1]:null,$t=at&&at.count>0?(at.count-B.count)/at.count*100:0;return e.jsxs("div",{"data-testid":`funnel-step-${B.event}`,children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-white/80 font-medium",children:B.label}),$t>0&&ge>0&&e.jsxs(E,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${$t>80?"border-red-500/40 text-red-400":$t>50?"border-amber-500/40 text-amber-400":"border-green-500/40 text-green-400"}`,children:[e.jsx(Ct,{className:"w-2.5 h-2.5 mr-0.5"}),$t.toFixed(0),"% perdidos"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-white/40",children:[Bs(B.users)," usuários"]}),e.jsx("span",{className:"text-white/70 font-bold",children:Bs(B.count)}
1)]})]}),e.jsx("div",{className:"w-full bg-white/5 rounded-full h-3",children:e.jsx("div",{className:`${B.color} h-3 rounded-full transition-all`,style:{width:`${Math.max(ut,2)}%`}})})]},B.event)})}),ae.length>=2&&e.jsx("div",{className:"mt-4 p-3 bg-white/5 rounded-lg",children:e.jsxs("p",{className:"text-xs text-white/50",children:["Taxa de conversão geral: ",e.jsx("span",{className:"text-emerald-400 font-bold",children:ae[ae.length-1].count>0&&ae[0].count>0?`${(ae[ae.length-1].count/ae[0].count*100).toFixed(2)}%`:"0%"})," ","(",Bs(ae[0].count)," → ",Bs(ae[ae.length-1].count),")"]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[ne.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(pt,{className:"w-4 h-4 text-blue-400"})," Audiência por País"]})}),e.jsx(ve,{className:"space-y-2",children:ne.map((B,ge)=>e.jsxs("div",{className:"flex items-center justify-between text-xs","data-testid":`row-country-${ge}`,children:[e.jsx("span",{className:"text-white/80",children:B.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-24 bg-white/10 rounded-full h-1.5",children:e.jsx("div",{className:"bg-blue-400 h-1.5 rounded-full",style:{width:`${re?B.value/re*100:0}%`}})}),e.jsx("span",{className:"text-white/60 w-12 text-right",children:Bs(B.value)})]})]},B.name))})]}),Z.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Pc,{className:"w-4 h-4 text-green-400"})," Dispositivos"]})}),e.jsx(ve,{className:"space-y-3",children:Z.map((B,ge)=>e.jsxs("div",{className:"flex items-center justify-between","data-testid":`row-device-${ge}`,children:[e.jsx("span",{className:"text-white/80 text-sm capitalize",children:B.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"secondary",className:"text-xs",children:_?`${(B.value/_*100).toFixed(0)}%`:"0%"}),e.jsx("span",{className:"text-white/60 text-xs",children:Bs(B.value)})]})]},B.name))})]}),S.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 text-purple-400"})," Idiomas"]})}),e.jsx(ve,{className:"space-y-2",children:S.map((B,ge)=>e.jsxs("div",{className:"flex items-center justify-between text-xs","data-testid":`row-language-${ge}`,children:[e.jsx("span",{className:"text-white/80",children:B.name}),e.jsx("span",{className:"text-white/60",children:Bs(B.value)})]},B.name))})]}),ee.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"})," DNA do Comprador"]})}),e.jsxs(ve,{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-white/50 mb-2",children:"Países que mais compram:"}),ee.map((B,ge)=>e.jsxs("div",{className:"flex items-center justify-between text-xs","data-testid":`row-purchaser-country-${ge}`,children:[e.jsx("span",{className:"text-white/80",children:B.name}),e.jsxs("span",{className:"text-emerald-400 font-medium",children:[Bs(B.value)," conversões"]})]},B.name)),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-white/50 mt-3 mb-2",children:"Dispositivos dos compradores:"}),h.map((B,ge)=>e.jsxs("div",{className:"flex items-center justify-between text-xs","data-testid":`row-purchaser-device-${ge}`,children:[e.jsx("span",{className:"text-white/80 capitalize",children:B.name}),e.jsx("span",{className:"text-emerald-400 font-medium",children:Bs(B.value)})]},B.name))]})]})]})]}),Me.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4 text-violet-400"})," Performance de Páginas"]})}),e.jsx(ve,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-white/50 border-b border-white/10",children:[e.jsx("th",{className:"text-left p-2",children:"Página"}),e.jsx("th",{className:"text-right p-2",children:"Visualizações"}),e.jsx("th",{className:"text-right p-2",children:"Bounce Rate"})]})}),e.jsx("tbody",{children:Me.map((B,ge)=>{const ut=B.bounceRate*100;return e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5","data-testid":`row-page-${ge}`,children:[e.jsx("td",{className:"p-2 text-white/80 font-medium max-w-[300px] truncate",title:B.title||B.path,children:B.title||B.path}),e.jsx("td",{className:"p-2 text-right text-white/60",children:Bs(B.views)}),e.jsx("td",{className:"p-2 text-right",children:e.jsxs("span",{className:ut>70?"text-red-400":ut>50?"text-amber-400":"text-green-400",children:[ut.toFixed(0),"%"]})})]},B.path+ge)})})]})})})]}),te.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-cyan-400"})," Qualidade do Tráfego por Fonte"]})}),e.jsx(ve,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-white/50 border-b border-white/10",children:[e.jsx("th",{className:"text-left p-2",children:"Fonte"}),e.jsx("th",{className:"text-right p-2",children:"Sessões"}),e.jsx("th",{className:"text-right p-2",children:"Conversões"}),e.jsx("th",{className:"text-right p-2",children:"Taxa Conv."}),e.jsx("th",{className:"text-right p-2",children:"Bounce"})]})}),e.jsx("tbody",{children:te.map((B,ge)=>{const ut=B.sessions>0?B.conversions/B.sessions*100:0,at=B.bounceRate*100;return e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5","data-testid":`row-traffic-source-${ge}`,children:[e.jsx("td",{className:"p-2 text-white/80 font-medium",children:B.source}),e.jsx("td",{className:"p-2 text-right text-white/60",children:Bs(B.sessions)}),e.jsx("td",{className:"p-2 text-right",children:e.jsx("span",{className:B.conversions>0?"text-emerald-400 font-medium":"text-white/40",children:B.conversions})}),e.jsx("td",{className:"p-2 text-right",children:e.jsxs(E,{variant:ut>5?"default":ut>1?"secondary":"outline",className:"text-xs",children:[ut.toFixed(1),"%"]})}),e.jsx("td",{className:"p-2 text-right",children:e.jsxs("span",{className:at>70?"text-red-400":at>50?"text-amber-400":"text-green-400",children:[at.toFixed(0),"%"]})})]},B.source)})})]})})})]}),M.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ka,{className:"w-4 h-4 text-orange-400"})," Todos os Eventos GA4"]})}),e.jsx(ve,{children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 ga
1p-3",children:M.sort((B,ge)=>ge.count-B.count).slice(0,15).map((B,ge)=>e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center","data-testid":`card-funnel-event-${ge}`,children:[e.jsx("p",{className:"text-xs text-white/50 truncate",children:B.event}),e.jsx("p",{className:"text-lg font-bold text-white mt-1",children:Bs(B.count)}),e.jsxs("p",{className:"text-xs text-white/40",children:[Bs(B.users)," usuários"]})]},B.event))})})]}),ie?.recommendations&&Array.isArray(ie.recommendations)&&ie.recommendations.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Gm,{className:"w-4 h-4 text-yellow-400"})," Ações Recomendadas pela IA"]})}),e.jsx(ve,{className:"space-y-2",children:ie.recommendations.map((B,ge)=>e.jsxs("div",{className:"flex items-start gap-3 p-2 bg-white/5 rounded-lg","data-testid":`card-recommendation-${ge}`,children:[e.jsxs(E,{variant:"outline",className:"text-xs shrink-0 mt-0.5",children:["#",B.priority||ge+1]}),e.jsx("p",{className:"text-sm text-white/80",children:B.action})]},ge))})]})]})}function Yu(a){return a?a.replace(/^### (.*$)/gm,'<h3 class="text-white font-semibold text-base mt-4 mb-2">$1</h3>').replace(/^## (.*$)/gm,'<h2 class="text-white font-bold text-lg mt-5 mb-2">$1</h2>').replace(/^# (.*$)/gm,'<h1 class="text-white font-bold text-xl mt-6 mb-3">$1</h1>').replace(/\*\*(.*?)\*\*/g,'<strong class="text-white">$1</strong>').replace(/\*(.*?)\*/g,"<em>$1</em>").replace(/^- (.*$)/gm,'<li class="text-white/70 ml-4">$1</li>').replace(/\n\n/g,"<br/><br/>").replace(/\n/g,"<br/>"):""}function bs(a){return`R$${(a/100).toFixed(2)}`}function Zu(){const[a,r]=d.useState("overview"),{data:l,isLoading:n}=z({queryKey:["/api/admin/traffic-manager/multiplier"]}),{data:u,isLoading:f}=z({queryKey:["/api/admin/traffic-manager/reconciliation"],enabled:a==="reconciliation"||a==="overview"}),{data:j,isLoading:p}=z({queryKey:["/api/admin/traffic-manager/forecast"],enabled:a==="forecast"||a==="overview"}),{data:g,isLoading:w}=z({queryKey:["/api/admin/traffic-manager/sync-status"]}),y=W({mutationFn:()=>N("POST","/api/admin/traffic-manager/force-sync")}),F=l,c=u,m=j,$=g,D=F?.currentRoas>=3?"text-green-400":F?.currentRoas>=2?"text-yellow-400":"text-red-400",A=F?.healthScore>=70?"text-green-400":F?.healthScore>=40?"text-yellow-400":"text-red-400";return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2 border-b border-white/10 pb-3 mb-2 overflow-x-auto",children:[{val:"overview",label:"Visão Geral",icon:e.jsx(jt,{className:"w-3.5 h-3.5"})},{val:"reconciliation",label:"Reconciliação",icon:e.jsx(is,{className:"w-3.5 h-3.5"})},{val:"forecast",label:"Previsão",icon:e.jsx(ft,{className:"w-3.5 h-3.5"})},{val:"sync",label:"Sync & Saúde",icon:e.jsx(xe,{className:"w-3.5 h-3.5"})}].map(o=>e.jsxs("button",{onClick:()=>r(o.val),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors whitespace-nowrap ${a===o.val?"bg-orange-600/20 text-orange-400 border border-orange-500/30":"text-white/50 hover:text-white/80 border border-transparent"}`,"data-testid":`multiplier-tab-${o.val}`,children:[o.icon," ",o.label]},o.val))}),F?.killSwitchActive&&e.jsxs("div",{className:"bg-red-900/30 border border-red-500/50 rounded-xl p-4 flex items-center gap-3","data-testid":"kill-switch-alert",children:[e.jsx(as,{className:"w-6 h-6 text-red-400 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-red-400",children:"KILL SWITCH ATIVADO"}),e.jsx("p",{className:"text-xs text-red-300/70",children:"CPA da conta ultrapassou 2x o ótimo por 48h+. Todas as decisões automáticas estão suspensas. O sistema desativará automaticamente quando o CPA normalizar."})]})]}),a==="overview"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"ROAS Atual"}),e.jsx("p",{className:`text-xl font-bold ${D}`,"data-testid":"text-current-roas",children:n?"...":`${F?.currentRoas?.toFixed(2)||"0"}x`}),e.jsx("p",{className:"text-[9px] text-white/30",children:"Meta: 3.0x"})]})}),e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"P&L Hoje"}),e.jsx("p",{className:`text-xl font-bold ${(F?.dailyPnL||0)>=0?"text-green-400":"text-red-400"}`,"data-testid":"text-daily-pnl",children:n?"...":bs(F?.dailyPnL||0)}),e.jsxs("p",{className:"text-[9px] text-white/30",children:["Gasto: ",bs(F?.todaySpend||0)," | Rec: ",bs(F?.todayRevenue||0)]})]})}),e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"CPA Mês"}),e.jsx("p",{className:`text-xl font-bold ${(F?.monthCpa||0)<=(F?.optimalCpa||6300)?"text-green-400":"text-orange-400"}`,"data-testid":"text-month-cpa",children:n?"...":bs(F?.monthCpa||0)}),e.jsxs("p",{className:"text-[9px] text-white/30",children:["Ótimo: ",bs(F?.optimalCpa||6300)]})]})}),e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"Score Saúde"}),e.jsx("p",{className:`text-xl font-bold ${A}`,"data-testid":"text-health-score",children:n?"...":`${F?.healthScore||0}/100`}),e.jsx("div",{className:"w-full bg-white/10 rounded-full h-1.5 mt-1",children:e.jsx("div",{className:`h-1.5 rounded-full ${F?.healthScore>=70?"bg-green-500":F?.healthScore>=40?"bg-yellow-500":"bg-red-500"}`,style:{width:`${F?.healthScore||0}%`}})})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"P&L Mês"}),e.jsx("p",{className:`text-lg font-bold ${(F?.monthPnL||0)>=0?"text-green-400":"text-red-400"}`,children:bs(F?.monthPnL||0)}),e.jsxs("p",{className:"text-[9px] text-white/30",children:[F?.monthConversions||0," conversões"]})]})}),e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"ROAS Mês"}),e.jsxs("p",{className:`text-lg font-bold ${(F?.monthRoas||0)>=3?"text-green-400":"text-yellow-400"}`,children:[F?.monthRoas?.toFixed(2)||"0","x"]}),e.jsxs("p",{className:"text-[9px] text-white/30",children:["Gasto: ",bs(F?.monthSpend||0)]})]})}),e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"Criativos Ativos"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs(E,{variant:"outline",className:"text-[9px] bg-green-900/20 text-green-400 border-green-500/30",children:[F?.activeWinners||0," winners"]}),e.jsxs(E,{variant:"outline",className:"text-[9px] bg-blue-900/20 text-blue-400 border-blue-500/30",children:[F?.activeTests||0," testando"]})]}),(F?.fatiguedCreatives||0)>0&&e.jsxs(E,{variant:"outline",className:"text-[9px] bg-red-900/20 text-red-400 border-red-500/30 mt-1",children:[F?.fatiguedCreatives," fatigados"]})]})}),e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"Sync"}),$?.isStale?e.jsxs(E,{variant:"outline",className:"text-[9px] bg-red-900/20 text-red-400 border-red-500/30 mt-1",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"})," Dados desatualizados"]}
1):$?.isPaused?e.jsxs(E,{variant:"outline",className:"text-[9px] bg-yellow-900/20 text-yellow-400 border-yellow-500/30 mt-1",children:[e.jsx(Xe,{className:"w-3 h-3 mr-1"})," Sync pausado"]}):e.jsxs(E,{variant:"outline",className:"text-[9px] bg-green-900/20 text-green-400 border-green-500/30 mt-1",children:[e.jsx(is,{className:"w-3 h-3 mr-1"})," OK"]}),$?.staleness!==null&&e.jsxs("p",{className:"text-[9px] text-white/30 mt-1",children:[$?.staleness,"min atrás"]})]})})]}),F?.cpaHistory?.length>0&&e.jsxs(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:[e.jsx(Fe,{className:"pb-2",children:e.jsx(De,{className:"text-xs text-white/60",children:"Tendência CPA & ROAS (últimos dias)"})}),e.jsxs(ve,{children:[e.jsx("div",{className:"flex gap-1 items-end h-24",children:F.cpaHistory.slice(-14).map((o,L)=>{const v=Math.max(...F.cpaHistory.slice(-14).map(me=>me.cpa||1)),I=v>0?o.cpa/v*100:0,de=o.cpa<=(F?.optimalCpa||6300);return e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-0.5",children:[e.jsx("div",{className:`w-full rounded-t ${de?"bg-green-500/60":"bg-orange-500/60"}`,style:{height:`${Math.max(I,4)}%`},title:`${o.date}: CPA ${bs(o.cpa)} | ROAS ${o.roas}x`}),e.jsx("span",{className:"text-[7px] text-white/20",children:o.date?.slice(-2)})]},L)})}),e.jsxs("div",{className:"flex justify-between mt-1",children:[e.jsx("span",{className:"text-[8px] text-white/30",children:"Verde = CPA ≤ ótimo"}),e.jsx("span",{className:"text-[8px] text-white/30",children:"Laranja = CPA acima"})]})]})]})]}),a==="reconciliation"&&e.jsx("div",{className:"space-y-3",children:f?e.jsx("p",{className:"text-xs text-white/40",children:"Carregando..."}):c?e.jsx(e.Fragment,{children:e.jsxs(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-xs text-white/60 flex items-center gap-2",children:[e.jsx(is,{className:"w-4 h-4"})," Reconciliação Meta x Plataforma (30 dias)"]})}),e.jsxs(ve,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Meta Conversões"}),e.jsx("p",{className:"text-lg font-bold text-blue-400","data-testid":"text-meta-conversions",children:c.totals?.metaConversions||0})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Vendas Plataforma"}),e.jsx("p",{className:"text-lg font-bold text-green-400","data-testid":"text-platform-sales",children:c.totals?.platformSales||0})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Discrepância"}),e.jsxs("p",{className:`text-lg font-bold ${Math.abs(c.totals?.overallDiscrepancy||0)<=15?"text-green-400":"text-red-400"}`,"data-testid":"text-discrepancy",children:[c.totals?.overallDiscrepancy||0,"%"]})]})]}),e.jsxs("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:[(c.campaigns||[]).map(o=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-white/5 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs text-white/80 truncate",children:o.campaignName}),e.jsxs("p",{className:"text-[9px] text-white/40",children:["Meta: ",o.metaConversions," conv | Plat: ",o.platformSales," vendas | Gasto: ",bs(o.metaSpend)]})]}),e.jsxs(E,{variant:"outline",className:`text-[9px] shrink-0 ml-2 ${o.status==="ok"?"bg-green-900/20 text-green-400 border-green-500/30":o.status==="warning"?"bg-yellow-900/20 text-yellow-400 border-yellow-500/30":"bg-red-900/20 text-red-400 border-red-500/30"}`,children:[o.discrepancy>0?"+":"",o.discrepancy,"%"]})]},o.campaignId)),(c.campaigns||[]).length===0&&e.jsx("p",{className:"text-xs text-white/30 text-center py-4",children:"Nenhuma campanha com dados de reconciliação"})]})]})]})}):null}),a==="forecast"&&e.jsx("div",{className:"space-y-3",children:p?e.jsx("p",{className:"text-xs text-white/40",children:"Carregando..."}):m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"Gasto Médio/Dia"}),e.jsx("p",{className:"text-lg font-bold text-white","data-testid":"text-avg-spend",children:bs(m.forecast?.avgDailySpend||0)}),e.jsxs("div",{className:"flex items-center gap-1 mt-0.5",children:[m.forecast?.spendTrend>0?e.jsx($r,{className:"w-3 h-3 text-red-400"}):e.jsx(Tc,{className:"w-3 h-3 text-green-400"}),e.jsxs("span",{className:"text-[9px] text-white/40",children:[Math.abs(m.forecast?.spendTrend||0),"% tendência"]})]})]})}),e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"Conv. Média/Dia"}),e.jsx("p",{className:"text-lg font-bold text-white",children:m.forecast?.avgDailyConversions||0})]})}),e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"ROAS Médio"}),e.jsxs("p",{className:`text-lg font-bold ${(m.forecast?.avgRoas||0)>=3?"text-green-400":"text-yellow-400"}`,children:[m.forecast?.avgRoas||0,"x"]})]})}),e.jsx(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase",children:"CPA Médio"}),e.jsx("p",{className:`text-lg font-bold ${(m.forecast?.avgCpa||0)<=6300?"text-green-400":"text-orange-400"}`,children:bs(m.forecast?.avgCpa||0)}),e.jsxs("div",{className:"flex items-center gap-1 mt-0.5",children:[m.forecast?.cpaTrend>0?e.jsx(Ie,{className:"w-3 h-3 text-red-400"}):e.jsx(Ch,{className:"w-3 h-3 text-green-400"}),e.jsxs("span",{className:"text-[9px] text-white/40",children:[Math.abs(m.forecast?.cpaTrend||0),"%"]})]})]})})]}),e.jsxs(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-xs text-white/60 flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4"})," Previsão Semanal"]})}),e.jsxs(ve,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center p-3 bg-white/5 rounded-lg",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Gasto Projetado"}),e.jsx("p",{className:"text-lg font-bold text-white",children:bs(m.forecast?.forecastWeekSpend||0)})]}),e.jsxs("div",{className:"text-center p-3 bg-white/5 rounded-lg",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Conversões Projetadas"}),e.jsx("p",{className:"text-lg font-bold text-teal-400",children:m.forecast?.forecastWeekConversions||0})]}),e.jsxs("div",{className:"text-center p-3 bg-white/5 rounded-lg",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Receita Projetada"}),e.jsx("p",{className:"text-lg font-bold text-green-400",children:bs(m.forecast?.forecastWeekRevenue||0)})]})]}),m.forecast?.recommendedDailyBudget>0&&e.jsx("div",{className:"mt-3 p-3 bg-orange-900/20 border border-orange-500/20 rounded-lg",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 text-orange-400"}),e.jsxs("p",{className:"text-xs text-orange-300",children:["Budget recomendado: ",e.jsxs("strong",{children:[bs(m.forecast.recommendedDailyBudget),"/dia"]})," para ",m.forecast.targetConversionsPerDay," conv/dia no CPA ótimo"]})]})})]})]}),m.history?.length>0&&e.jsxs(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:[e.jsx(Fe,{className:"pb-2",children:e.jsx(De,{className:"text-xs text-white/60",children:"Histórico Diário"})}),e.jsx(ve,{children:e.jsx("div",{className:"space-y-1 max-h-48 overflow-y-auto",children:(m.history||[]).slice(-14).reverse().map(o=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-white/5 rounded text-xs",children:[e.jsx("span",{className:"text-white/50 w-20",children:o.date}),e.jsxs("span",{className:"text-white/70",children:["Gasto: ",bs(o.spend)]}),e.jsxs("span",{className:"text-teal-400",children:[o.conversions," conv"]}),e.jsxs("span",{className:o.roas>=3?"text-green-400":"text-yellow-400",children:[o.roas?.toFixed(2),"x"]}),e.jsxs("span",{className:o.cpa<=6300?"text-green-400":"text-orange-400",children:["CPA ",bs(o.cpa)]})]},o.date))})})]})]}):null}),a==="sync"&&e.jsx("div",{className:"space-y-3",children:e.jsxs(je,{className:"bg-[#1a1a2e]/80 border-white/5",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-xs text-white/60 flex items-center gap-2",children:[e.jsx(xe,{className:"w-4 h-4"})," Status de Sincronização"]})}),e.jsxs(ve,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"p-3 bg-white/5 rounded-lg text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Último Sync"}),e.jsx("p",{className:"text-sm font-bold text-white","data-testid":"text-last-sync",children:$?.lastSyncAt?new Date($.lastSyncAt).toLocaleStr
1ing("pt-BR"):"Nunca"})]}),e.jsxs("div",{className:"p-3 bg-white/5 rounded-lg text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Atraso"}),e.jsx("p",{className:`text-sm font-bold ${($?.staleness||0)>360?"text-red-400":"text-green-400"}`,children:$?.staleness!==null?`${$.staleness} min`:"N/A"})]}),e.jsxs("div",{className:"p-3 bg-white/5 rounded-lg text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Falhas Consecutivas"}),e.jsx("p",{className:`text-sm font-bold ${($?.syncFailCount||0)>=3?"text-red-400":"text-green-400"}`,children:$?.syncFailCount||0})]}),e.jsxs("div",{className:"p-3 bg-white/5 rounded-lg text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Status"}),$?.isPaused?e.jsxs(E,{variant:"outline",className:"text-[9px] bg-red-900/20 text-red-400 border-red-500/30",children:[e.jsx(dt,{className:"w-3 h-3 mr-1"})," Pausado"]}):$?.isStale?e.jsxs(E,{variant:"outline",className:"text-[9px] bg-yellow-900/20 text-yellow-400 border-yellow-500/30",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"})," Desatualizado"]}):e.jsxs(E,{variant:"outline",className:"text-[9px] bg-green-900/20 text-green-400 border-green-500/30",children:[e.jsx(is,{className:"w-3 h-3 mr-1"})," Saudável"]})]})]}),($?.isStale||$?.isPaused)&&e.jsx("div",{className:"bg-yellow-900/20 border border-yellow-500/20 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-yellow-400"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-yellow-300 font-medium",children:$?.isPaused?"Sync pausado por falhas":"Dados desatualizados"}),e.jsx("p",{className:"text-[9px] text-yellow-300/60",children:$?.isPaused?"3+ falhas consecutivas. Decisões automáticas suspensas.":$?.staleWarning})]})]}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs border-yellow-500/30 text-yellow-400 hover:bg-yellow-900/20",onClick:()=>y.mutate(),disabled:y.isPending,"data-testid":"button-force-sync",children:[e.jsx(xe,{className:`w-3 h-3 mr-1 ${y.isPending?"animate-spin":""}`}),y.isPending?"Sincronizando...":"Forçar Sync"]})]})}),e.jsxs("div",{className:"p-3 bg-white/5 rounded-lg",children:[e.jsx("p",{className:"text-xs text-white/60 mb-2",children:"Proteções Ativas"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(as,{className:"w-3.5 h-3.5 text-teal-400"}),e.jsx("span",{className:"text-white/70",children:"Cool-down 24h entre ações no mesmo ad set"}),e.jsx(E,{variant:"outline",className:"text-[8px] bg-green-900/20 text-green-400 border-green-500/30 ml-auto",children:"Ativo"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(as,{className:"w-3.5 h-3.5 text-teal-400"}),e.jsx("span",{className:"text-white/70",children:"Kill-switch se CPA > 2x ótimo por 48h"}),e.jsx(E,{variant:"outline",className:`text-[8px] ml-auto ${F?.killSwitchActive?"bg-red-900/20 text-red-400 border-red-500/30":"bg-green-900/20 text-green-400 border-green-500/30"}`,children:F?.killSwitchActive?"ATIVADO":"Standby"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(as,{className:"w-3.5 h-3.5 text-teal-400"}),e.jsx("span",{className:"text-white/70",children:"Pausa automática se sync falhar 3x"}),e.jsx(E,{variant:"outline",className:`text-[8px] ml-auto ${$?.isPaused?"bg-red-900/20 text-red-400 border-red-500/30":"bg-green-900/20 text-green-400 border-green-500/30"}`,children:$?.isPaused?"ATIVADO":"Standby"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(as,{className:"w-3.5 h-3.5 text-teal-400"}),e.jsx("span",{className:"text-white/70",children:"Dados stale (>12h) suspende otimização"}),e.jsx(E,{variant:"outline",className:`text-[8px] ml-auto ${$?.isStale?"bg-yellow-900/20 text-yellow-400 border-yellow-500/30":"bg-green-900/20 text-green-400 border-green-500/30"}`,children:$?.isStale?"Alerta":"OK"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(as,{className:"w-3.5 h-3.5 text-teal-400"}),e.jsx("span",{className:"text-white/70",children:"Smart bid COST_CAP auto quando CPA alto"}),e.jsx(E,{variant:"outline",className:"text-[8px] bg-green-900/20 text-green-400 border-green-500/30 ml-auto",children:"Ativo"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(as,{className:"w-3.5 h-3.5 text-teal-400"}),e.jsx("span",{className:"text-white/70",children:"Rotação criativa (fadiga >14d ou freq >2.0)"}),e.jsx(E,{variant:"outline",className:"text-[8px] bg-green-900/20 text-green-400 border-green-500/30 ml-auto",children:"Ativo"})]})]})]})]})]})})]})}function mn(a){return a>=1e6?`${(a/1e6).toFixed(1)}
1M`:a>=1e3?`${(a/1e3).toFixed(1)}K`:a.toLocaleString("pt-BR")}function vr(a){return`R$ ${a.toFixed(2).replace(".",",")}`}function Rl(a){return a==null?"—":`${(a*100).toFixed(1)}%`}function eg(){const{user:a}=Sa(),r=!!a&&a.role==="admin",{data:l,isLoading:n}=z({queryKey:["/api/admin/growth/score-distribution"],queryFn:()=>N("GET","/api/admin/growth/score-distribution").then(Z=>Z.json()),enabled:r}),{data:u,isLoading:f}=z({queryKey:["/api/admin/growth/cohort-metrics"],queryFn:()=>N("GET","/api/admin/growth/cohort-metrics").then(Z=>Z.json()),enabled:r}),{data:j,isLoading:p}=z({queryKey:["/api/admin/growth/channel-attribution"],queryFn:()=>N("GET","/api/admin/growth/channel-attribution").then(Z=>Z.json()),enabled:r}),{data:g,isLoading:w}=z({queryKey:["/api/admin/growth/trigger-log"],queryFn:()=>N("GET","/api/admin/growth/trigger-log").then(Z=>Z.json()),enabled:r}),{data:y,isLoading:F}=z({queryKey:["/api/admin/growth/velocity"],queryFn:()=>N("GET","/api/admin/growth/velocity").then(Z=>Z.json()),enabled:r});if(n||f||p||w||F)return e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"growth-loading",children:[e.jsx(T,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("span",{className:"ml-3 text-white/60",children:"Carregando dados de crescimento..."})]});const m=l||{hot:0,warm:0,cold:0,total:0,segments:[]},$=u?.cohorts||[],D=j?.channels||[],A=g?.triggers||[],o=y||{newUsersThisWeek:0,newUsersLastWeek:0,revenueThisWeek:0,revenueLastWeek:0},L=m.hot+m.warm+m.cold,v=L>0?m.hot/L*100:0,I=L>0?m.warm/L*100:0,de=L>0?m.cold/L*100:0,me=o.newUsersLastWeek>0?(o.newUsersThisWeek-o.newUsersLastWeek)/o.newUsersLastWeek*100:0,ne=o.revenueLastWeek>0?(o.revenueThisWeek-o.revenueLastWeek)/o.revenueLastWeek*100:0;return e.jsxs("div",{className:"space-y-6","data-testid":"growth-dashboard",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ie,{className:"w-6 h-6 text-emerald-400"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white",children:"Crescimento Inteligente"}),e.jsx("p",{className:"text-xs text-white/50",children:"Visão completa de scores, cohorts, atribuição e triggers"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-total-leads",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Re,{className:"w-4 h-4"}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:"Total Leads"})]}),e.jsx("p",{className:"text-2xl font-bold text-white",children:mn(m.total)})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-hot-leads",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(He,{className:"w-4 h-4 text-red-400"}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:"Hot Leads"})]}),e.jsx("p",{className:"text-2xl font-bold text-red-400",children:mn(m.hot)}),e.jsx("p",{className:"text-xs text-white/40",children:"Score > 70"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-new-users-week",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:"Novos/Semana"})]}),e.jsx("p",{className:"text-2xl font-bold text-white",children:mn(o.newUsersThisWeek)}),e.jsxs("p",{className:`text-xs ${me>=0?"text-emerald-400":"text-red-400"}`,children:[me>=0?"+":"",me.toFixed(1),"% vs semana anterior"]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-revenue-week",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(nt,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:"Receita/Semana"})]}),e.jsx("p",{className:"text-2xl font-bold text-emerald-400",children:vr(o.revenueThisWeek)}),e.jsxs("p",{className:`text-xs ${ne>=0?"text-emerald-400":"text-red-400"}`,children:[ne>=0?"+":"",ne.toFixed(1),"% vs semana anterior"]})]})]}),e.jsxs(je,{className:"bg-white/5 border-white/10","data-testid":"card-score-distribution",children:[e.jsx(Fe,{className:"pb-3",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-primary"})," Distribuição de Scores"]})}),e.jsx(ve,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3","data-testid":"bar-hot-leads",children:[e.jsx("span",{className:"text-xs text-white/60 w-20",children:"Hot (>70)"}),e.jsx("div",{className:"flex-1 bg-white/10 rounded-full h-5 overflow-hidden",children:e.jsx("div",{className:"bg-red-500 h-5 rounded-full flex items-center justify-end pr-2 transition-all duration-500",style:{width:`${Math.max(v,2)}%`},children:v>8&&e.jsx("span",{className:"text-[10px] font-medium text-white",children:m.hot})})}),e.jsxs("span",{className:"text-xs text-white/40 w-12 text-right",children:[v.toFixed(0),"%"]})]}),e.jsxs("div",{className:"flex items-center gap-3","data-testid":"bar-warm-leads",children:[e.jsx("span",{className:"text-xs text-white/60 w-20",children:"Warm (40-70)"}),e.jsx("div",{className:"flex-1 bg-white/10 rounded-full h-5 overflow-hidden",children:e.jsx("div",{className:"bg-amber-500 h-5 rounded-full flex items-center justify-end pr-2 transition-all duration-500",style:{width:`${Math.max(I,2)}%`},children:I>8&&e.jsx("span",{className:"text-[10px] font-medium text-white",children:m.warm})})}),e.jsxs("span",{className:"text-xs text-white/40 w-12 text-right",children:[I.toFixed(0),"%"]})]}),e.jsxs("div",{className:"flex items-center gap-3","data-testid":"bar-cold-leads",children:[e.jsx("span",{className:"text-xs text-white/60 w-20",children:"Cold (<40)"}),e.jsx("div",{className:"flex-1 bg-white/10 rounded-full h-5 overflow-hidden",children:e.jsx("div",{className:"bg-blue-500 h-5 rounded-full flex items-center justify-end pr-2 transition-all duration-500",style:{width:`${Math.max(de,2)}%`},children:de>8&&e.jsx("span",{className:"text-[10px] font-medium text-white",children:m.cold})})}),e.jsxs("span",{className:"text-xs text-white/40 w-12 text-right",children:[de.toFixed(0),"%"]})]})]})})]}),m.segments&&m.segments.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10","data-testid":"card-segment-breakdown",children:[e.jsx(Fe,{className:"pb-3",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-purple-400"})," Segmentos"]})}),e.jsx(ve,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-white/50 border-b border-white/10",children:[e.jsx("th",{className:"text-left p-2",children:"Segmento"}),e.jsx("th",{className:"text-right p-2",children:"Usuários"}),e.jsx("th",{className:"text-right p-2",children:"% do Total"})]})}),e.jsx("tbody",{children:m.segments.map((Z,S)=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5","data-testid":`row-segment-${S}`,children:[e.jsx("td",{className:"p-2 text-white/80 font-medium",children:e.jsx(E,{variant:"outline",className:"text-xs",children:Z.tag})}),e.jsx("td",{className:"p-2 text-right text-white/60",children:mn(Z.count)}
1),e.jsxs("td",{className:"p-2 text-right text-white/60",children:[m.total>0?(Z.count/m.total*100).toFixed(1):"0","%"]})]},Z.tag))})]})})})]}),$.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10","data-testid":"card-cohort-retention",children:[e.jsx(Fe,{className:"pb-3",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ka,{className:"w-4 h-4 text-orange-400"})," Retenção por Cohort"]})}),e.jsx(ve,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-white/50 border-b border-white/10",children:[e.jsx("th",{className:"text-left p-2",children:"Semana"}),e.jsx("th",{className:"text-right p-2",children:"Usuários"}),e.jsx("th",{className:"text-right p-2",children:"D1"}),e.jsx("th",{className:"text-right p-2",children:"D7"}),e.jsx("th",{className:"text-right p-2",children:"D30"}),e.jsx("th",{className:"text-right p-2",children:"Conv."}),e.jsx("th",{className:"text-right p-2",children:"ARPU"}),e.jsx("th",{className:"text-right p-2",children:"Fonte Top"})]})}),e.jsx("tbody",{children:$.map((Z,S)=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5","data-testid":`row-cohort-${S}`,children:[e.jsx("td",{className:"p-2 text-white/80 font-medium",children:Z.cohortWeek}),e.jsx("td",{className:"p-2 text-right text-white/60",children:mn(Z.totalUsers)}),e.jsx("td",{className:"p-2 text-right",children:e.jsx("span",{className:Z.day1Retention>.3?"text-emerald-400":"text-white/60",children:Rl(Z.day1Retention)})}),e.jsx("td",{className:"p-2 text-right",children:e.jsx("span",{className:Z.day7Retention>.2?"text-emerald-400":"text-white/60",children:Rl(Z.day7Retention)})}),e.jsx("td",{className:"p-2 text-right",children:e.jsx("span",{className:Z.day30Retention>.1?"text-emerald-400":"text-white/60",children:Rl(Z.day30Retention)})}),e.jsx("td",{className:"p-2 text-right",children:e.jsx(E,{variant:Z.conversionRate>.05?"default":"secondary",className:"text-xs",children:Rl(Z.conversionRate)})}),e.jsx("td",{className:"p-2 text-right text-white/60",children:Z.avgRevenuePerUser!=null?vr(Z.avgRevenuePerUser):"—"}),e.jsx("td",{className:"p-2 text-right text-white/50",children:Z.topSource||"—"})]},Z.cohortWeek))})]})})})]}),D.length>0&&e.jsxs(je,{className:"bg-white/5 border-white/10","data-testid":"card-channel-attribution",children:[e.jsx(Fe,{className:"pb-3",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4 text-emerald-400"})," Atribuição por Canal"]})}),e.jsx(ve,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-white/50 border-b border-white/10",children:[e.jsx("th",{className:"text-left p-2",children:"Canal"}),e.jsx("th",{className:"text-left p-2",children:"Período"}),e.jsx("th",{className:"text-right p-2",children:"Gasto"}),e.jsx("th",{className:"text-right p-2",children:"Conv."}),e.jsx("th",{className:"text-right p-2",children:"Receita"}),e.jsx("th",{className:"text-right p-2",children:"CAC"}),e.jsx("th",{className:"text-right p-2",children:"LTV"}),e.jsx("th",{className:"text-right p-2",children:"ROAS"})]})}),e.jsx("tbody",{children:D.map((Z,S)=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5","data-testid":`row-channel-${S}`,children:[e.jsx("td",{className:"p-2 text-white/80 font-medium",children:Z.channel}),e.jsx("td",{className:"p-2 text-white/50",children:Z.period}),e.jsx("td",{className:"p-2 text-right text-white/60",children:Z.spend!=null?vr(Z.spend):"—"}),e.jsx("td",{className:"p-2 text-right text-white/60",children:Z.conversions??0}),e.jsx("td",{className:"p-2 text-right text-emerald-400 font-medium",children:Z.revenue!=null?vr(Z.revenue):"—"}),e.jsx("td",{className:"p-2 text-right text-white/60",children:Z.cac!=null?vr(Z.cac):"—"}),e.jsx("td",{className:"p-2 text-right text-white/60",children:Z.ltv!=null?vr(Z.ltv):"—"}),e.jsx("td",{className:"p-2 text-right",children:Z.roas!=null?e.jsxs(E,{variant:Z.roas>3?"default":Z.roas>
11?"secondary":"outline",className:"text-xs",children:[Z.roas.toFixed(1),"x"]}):"—"})]},`${Z.channel}-${Z.period}`))})]})})})]}),e.jsxs(je,{className:"bg-white/5 border-white/10","data-testid":"card-trigger-log",children:[e.jsx(Fe,{className:"pb-3",children:e.jsxs(De,{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 text-yellow-400"})," Behavioral Triggers Recentes"]})}),e.jsx(ve,{children:A.length===0?e.jsx("p",{className:"text-xs text-white/40 text-center py-4","data-testid":"text-no-triggers",children:"Nenhum trigger disparado ainda."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-white/50 border-b border-white/10",children:[e.jsx("th",{className:"text-left p-2",children:"Tipo"}),e.jsx("th",{className:"text-left p-2",children:"Ação"}),e.jsx("th",{className:"text-left p-2",children:"Usuário"}),e.jsx("th",{className:"text-right p-2",children:"Converteu?"}),e.jsx("th",{className:"text-right p-2",children:"Data"})]})}),e.jsx("tbody",{children:A.map((Z,S)=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5","data-testid":`row-trigger-${S}`,children:[e.jsx("td",{className:"p-2",children:e.jsx(E,{variant:"outline",className:"text-xs",children:Z.triggerType})}),e.jsx("td",{className:"p-2 text-white/80",children:Z.action}),e.jsx("td",{className:"p-2 text-white/50 truncate max-w-[120px]",children:Z.userId}),e.jsx("td",{className:"p-2 text-right",children:Z.convertedAt?e.jsx(E,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-xs",children:"Sim"}):e.jsx("span",{className:"text-white/30",children:"—"})}),e.jsx("td",{className:"p-2 text-right text-white/40",children:Z.createdAt?new Date(Z.createdAt).toLocaleDateString("pt-BR"):"—"})]},Z.id))})]})})})]})]})}const Zm=[{key:"marketing",label:"Marketing",icon:Xt,color:"#f59e0b",agents:[{name:"Traffic Manager",icon:Cr},{name:"Blog Worker",icon:tt},{name:"Meta Optimizer",icon:He},{name:"Ad Creatives",icon:Va},{name:"Behavioral Triggers",icon:lt},{name:"Meta Sync",icon:xe}]},{key:"editorial",label:"Editorial",icon:ot,color:"#8b5cf6",agents:[{name:"Writing Worker",icon:tt},{name:"Cover Generator",icon:Va},{name:"Illustration AI",icon:Va},{name:"Audiobook Gen",icon:iu}]},{key:"crm",label:"CRM",icon:Re,color:"#ec4899",agents:[{name:"Daily Email",icon:Ge},{name:"Notification",icon:Nn},{name:"Email Sequences",icon:Ge},{name:"Scoring Engine",icon:Ie},{name:"Cohort Analytics",icon:ft}]},{key:"support",label:"Suporte",icon:Ut,color:"#06b6d4",agents:[{name:"Chat AI",icon:Qi},{name:"Email AI",icon:Ge}]},{key:"operations",label:"Operações",icon:Pn,color:"#22c55e",agents:[{name:"Distribution",icon:pt},{name:"Source Cleanup",icon:Pn},{name:"Translations",icon:fn},{name:"Publishing",icon:Sh},{name:"Analytics AI",icon:ru}]}];function tg({orchStatus:a}){const[r,l]=d.useState(!1),n=d.useCallback(()=>{l(w=>!w)},[]);d.useEffect(()=>{if(!r)return;const w=G0("admin-orchestration-fullscreen"),y=F=>{F.key==="Escape"&&l(!1)};return document.addEventListener("keydown",y),()=>{w(),document.removeEventListener("keydown",y)}},[r]);const u=a?.orchestrationEnabled===!0,f=a?.agents?.ceo?.enabled&&u,j=a?.agents?.ceo,p=w=>u&&a?.agents?.[w]?.enabled===!0,g=r?"fixed inset-0 z-[9999] bg-[#060a10] overflow-auto":"bg-white/5 border border-white/10 rounded-xl overflow-hidden";return e.jsx("div",{className:g,"data-app-overlay-open":r?"true":void 0,"data-scroll-lock-owner":"admin-orchestration-fullscreen","data-testid":"orchestration-viz",children:e.jsxs("div",{className:`p-5 ${r?"pt-6 px-8":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-emerald-400"}),e.jsx("h3",{className:`font-semibold text-white ${r?"text-lg":"text-sm"}`,children:"Organograma IA"}),e.jsxs("div",{className:"flex items-center gap-1.5 ml-2 px-2.5 py-0.5 rounded-full bg-white/5 border border-white/10",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${u?"bg-emerald-400":"bg-red-400"}`}),e.jsx("span",{className:"text-[10px] text-white/50 font-medium",children:u?"ONLINE":"OFFLINE"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[a&&e.jsxs("div",{className:"flex items-center gap-3 text-xs text-white/50",children:[e.jsxs("span",{children:["Relatórios: ",e.jsx("strong",{className:"text-white",children:a?.totalReports??0})]}),e.jsxs("span",{children:["Escalações: ",e.jsx("strong",{className:"text-amber-400",children:a?.totalEscalations??0})]})]}),e.jsx("button",{onClick:n,className:"p-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-white/60 hover:text-white transition-colors","data-testid":"orchestration-fullscreen-toggle",title:r?"Sair da tela cheia (ESC)":"Tela cheia",children:r?e.jsx(Eu,{className:"w-4 h-4"}):e.jsx(au,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"flex justify-center mb-1",children:e.jsx("div",{className:"text-[9px] text-white/25 uppercase tracking-[0.2em] font-medium",children:"CEO IA"})}),e.jsx("div",{className:"flex justify-center mb-2",children:e.jsxs("div",{className:`border rounded-2xl ${r?"px-10 py-5":"px-7 py-4"} text-center`,style:{background:f?"linear-gradient(135deg, rgba(20,184,166,0.12), rgba(16,185,129,0.06))":"rgba(255,255,255,0.02)",borderColor:f?"rgba(20,184,166,0.35)":"rgba(255,255,255,0.07)"},children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-1.5",children:[e.jsx("div",{className:`p-1.5 rounded-lg ${f?"bg-teal-500/20":"bg-white/5"}`,children:e.jsx(as,{className:`${r?"w-5 h-5":"w-4 h-4"} ${f?"text-teal-400":"text-white/25"}`})}),e.jsx("span",{className:`font-bold ${f?"text-white":"text-white/40"} ${r?"text-base":"text-sm"}`,children:"CEO Agent"})]}),e.jsx(E,{className:`text-[10px] ${f?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-white/5 text-white/25 border-white/10"}`,children:f?"Ativo":"Inativo"}),j?.lastReport&&e.jsxs("p",{className:"text-[10px] text-white/30 mt-1",children:["Último: ",new Date(j.lastReport).toLocaleStr
1ing("pt-BR")]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-1 text-[10px] text-white/35",children:[e.jsxs("span",{children:[j?.reports24h??0," relatórios"]}),e.jsxs("span",{children:[j?.escalations??0," escalações"]})]})]})}),e.jsx("div",{className:"flex justify-center mb-2",children:e.jsx("div",{className:"relative w-full max-w-4xl h-12",children:e.jsx("svg",{className:"absolute inset-0 w-full h-full",preserveAspectRatio:"none",viewBox:"0 0 1000 48",children:Zm.map((w,y)=>{const F=100+y*200,c=p(w.key);return e.jsx("path",{d:`M 500,0 C 500,8 ${F},40 ${F},48`,fill:"none",stroke:c?w.color:"rgba(255,255,255,0.06)",strokeWidth:c?"1.5":"1",opacity:c?.5:.3},w.key)})})})}),e.jsx("div",{className:"flex justify-center mb-3",children:e.jsx("div",{className:"text-[9px] text-white/25 uppercase tracking-[0.2em] font-medium",children:"Gerentes de Departamento"})}),e.jsx("div",{className:`grid ${r?"grid-cols-5 gap-6 px-4":"grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3"} mb-3`,children:Zm.map(w=>{const y=a?.agents?.[w.key],F=p(w.key),c=w.icon;return e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsxs("div",{className:`w-full border rounded-2xl ${r?"p-5":"p-3"} text-center`,style:{background:F?`linear-gradient(135deg, ${w.color}12, ${w.color}05)`:"rgba(255,255,255,0.02)",borderColor:F?`${w.color}40`:"rgba(255,255,255,0.06)"},"data-testid":`orchestration-status-${w.key}`,children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 mb-1.5",children:[e.jsx("div",{className:"p-1 rounded-md",style:{background:F?`${w.color}18`:"rgba(255,255,255,0.04)"},children:e.jsx(c,{className:`${r?"w-4 h-4":"w-3.5 h-3.5"}`,style:{color:F?w.color:"rgba(255,255,255,0.25)"}})}),e.jsx("span",{className:`font-medium ${F?"text-white":"text-white/35"} ${r?"text-sm":"text-xs"}`,children:w.label})]}),e.jsx(E,{className:`text-[10px] ${F?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-white/5 text-white/25 border-white/8"}`,children:F?"Ativo":"Inativo"}),y?.lastReport&&e.jsx("p",{className:"text-[10px] text-white/25 mt-1",children:new Date(y.lastReport).toLocaleString("pt-BR")}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-1 text-[10px] text-white/30",children:[e.jsxs("span",{children:[y?.reports24h??0," rel."]}),e.jsxs("span",{children:[y?.escalations??0," esc."]})]})]}),e.jsx("div",{className:"w-px h-4",style:{background:F?`${w.color}40`:"rgba(255,255,255,0.06)"}}),e.jsx("div",{className:"w-full space-y-1",children:w.agents.map((m,$)=>{const D=m.icon;return e.jsxs("div",{className:"flex items-center gap-1.5 rounded-xl border px-2.5 py-1.5",style:{background:F?`${w.color}06`:"rgba(255,255,255,0.01)",borderColor:F?`${w.color}20`:"rgba(255,255,255,0.04)"},"data-testid":`orch-agent-${w.key}-${$}`,children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{background:F?w.color:"rgba(255,255,255,0.1)"}}),e.jsx(D,{className:"w-2.5 h-2.5 flex-shrink-0",style:{color:F?w.color:"rgba(255,255,255,0.15)"}}),e.jsx("span",{className:`text-[10px] truncate ${F?"text-white/70":"text-white/20"}`,children:m.name})]},`${w.key}-agent-${$}`)})})]},w.key)})}),e.jsx("div",{className:"flex justify-center mt-2",children:e.jsx("div",{className:"text-[9px] text-white/25 uppercase tracking-[0.2em] font-medium",children:"Agentes Operacionais"})}),e.jsxs("div",{className:"flex items-center justify-center gap-5 mt-4 pt-3 border-t border-white/5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400"}),e.jsx("span",{className:"text-[10px] text-white/25",children:"Ativo"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-white/10"}),e.jsx("span",{className:"text-[10px] text-white/25",children:"Inativo"})]}),r&&e.jsx("span",{className:"text-[10px] text-white/15 ml-2",children:"ESC para sair"})]})]})})}const eh=a=>a.toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),sg=a=>a<60?`${a} min`:a<1440?`${Math.floor(a/60)}h`:`${Math.floor(a/1440)}d`;function ag(){const{toast:a}
1=st(),r=$a(),[l,n]=d.useState(null),{data:u,isLoading:f,refetch:j,isFetching:p}=z({queryKey:["/api/admin/credits/orphaned-purchases"],refetchInterval:6e4,staleTime:3e4}),g=W({mutationFn:async m=>(n(m),(await N("POST",`/api/admin/credits/orphaned-purchases/${m}/heal`)).json()),onSuccess:(m,$)=>{n(null),m?.ok?a({title:"Créditos aplicados",description:`+${m.creditsAdded?.toLocaleString("pt-BR")} créditos (${m.pkgLabel})`}):a({title:"Não foi possível creditar",description:m?.reason||"erro desconhecido",variant:"destructive"}),r.invalidateQueries({queryKey:["/api/admin/credits/orphaned-purchases"]})},onError:m=>{n(null),a({title:"Erro ao creditar",description:m?.message||"falha de rede",variant:"destructive"})}}),w=W({mutationFn:async()=>(await N("POST","/api/admin/credits/orphaned-purchases/run-healer")).json(),onSuccess:m=>{const $=m?.report;a({title:"Auto-healer executado",description:$?`Varreu ${$.scanned} · curou ${$.healed} · alertas ${$.alertedCount} · falhas ${$.failures}`:"—"}),r.invalidateQueries({queryKey:["/api/admin/credits/orphaned-purchases"]})},onError:m=>{a({title:"Erro ao rodar healer",description:m?.message||"—",variant:"destructive"})}}),y=u?.orphans||[],F=d.useMemo(()=>y.reduce((m,$)=>m+($.amountBrl||0),0),[y]),c=u?.lastHealerReport;return f?e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/20 p-4 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"})," Verificando carteira de créditos..."]}):y.length===0?e.jsxs("div",{className:"rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-4 flex items-center justify-between gap-3","data-testid":"card-orphaned-credits-clean",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-500/15 flex items-center justify-center shrink-0",children:e.jsx(be,{className:"w-4 h-4 text-emerald-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:"Carteira de Créditos saudável"}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:["Nenhuma compra confirmada sem grant nas últimas ",u?.sinceHours||168,"h",c?` · auto-healer última varredura: ${new Date(c.ts).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:""]})]})]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"text-[11px] h-8",onClick:()=>w.mutate(),disabled:w.isPending,"data-testid":"button-run-healer-clean",children:[w.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Re-verificar"})]})]}):e.jsxs("div",{className:"rounded-xl border border-amber-500/30 bg-gradient-to-br from-amber-500/10 via-orange-500/5 to-red-500/5 p-4 md:p-5 space-y-3","data-testid":"card-orphaned-credits-alert",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-amber-500/20 flex items-center justify-center shrink-0",children:e.jsx(Ce,{className:"w-5 h-5 text-amber-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm md:text-base font-bold text-white flex items-center gap-2 flex-wrap",children:["Créditos pagos mas NÃO creditados",e.jsxs(E,{className:"bg-amber-500/20 text-amber-200 border-amber-500/30 text-[10px]",children:[y.length," ",y.length===1?"pedido":"pedidos"]}),e.jsxs(E,{className:"bg-red-500/20 text-red-200 border-red-500/30 text-[10px]",children:[eh(F)," em risco"]})]}),e.jsxs("div",{className:"text-[11px] md:text-xs text-amber-100/80 mt-0.5",children:['Auto-healer roda a cada 60s. Use "Aplicar agora" pra forçar (idempotente — não credita 2x).',c?` · última varredura: ${new Date(c.ts).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})} (curou ${c.healed}/${c.scanned})`:""]})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsxs(b,{size:"sm",variant:"outline",className:"border-amber-500/30 hover:bg-amber-500/10 text-amber-100 h-8 text-[11px]",onClick:()=>j(),disabled:p,"data-testid":"button-refresh-orphans",children:[p?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5 hidden sm:inline",children:"Atualizar"})]}),e.jsxs(b,{size:"sm",className:"bg-amber-500 hover:bg-amber-600 text-black font-semibold h-8 text-[11px]",onClick:()=>w.mutate(),disabled:w.isPending,"data-testid":"button-run-healer",children:[w.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(yi,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Rodar healer"})]})]})]}),e.jsx("div",{className:"space-y-2",children:y.map(m=>{const $=l===m.orderId&&g.isPending;return e.jsxs("div",{className:"rounded-lg border border-amber-500/20 bg-black/30 p-3 flex flex-col md:flex-row md:items-center md:justify-between gap-2 md:gap-3","data-testid":`row-orphan-${m.orderId}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm text-white font-medium truncate","data-testid":`text-orphan-user-${m.orderId}`,children:[m.userName||"—",e.jsx("span",{className:"text-muted-foreground font-normal text-[11px] ml-2",children:m.userEmail||"sem email"})]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-0.5 mt-0.5",children:[e.jsxs("span",{className:"font-mono",children:[m.orderId.slice(0,12),"…"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:m.packageId||"?"}),m.expectedCredits!=null&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{className:"text-amber-300 font-semibold",children:["+",m.expectedCredits.toLocaleStr
1ing("pt-BR")," cred"]})]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:m.paymentMethod||"?"}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[sg(m.ageMinutes)," atrás"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 md:shrink-0",children:[e.jsx("div",{className:"text-sm font-bold text-emerald-400 tabular-nums","data-testid":`text-orphan-amount-${m.orderId}`,children:eh(m.amountBrl)}),e.jsxs(b,{size:"sm",className:"bg-emerald-500 hover:bg-emerald-600 text-black font-semibold h-8 text-[11px]",onClick:()=>g.mutate(m.orderId),disabled:$||g.isPending,"data-testid":`button-heal-${m.orderId}`,children:[$?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(yi,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Aplicar agora"})]})]})]},m.orderId)})})]})}const th=a=>a.toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),ig=a=>a<60?`${a} min`:a<1440?`${Math.floor(a/60)}h`:`${Math.floor(a/1440)}d`;function rg(){const{toast:a}=st(),r=$a(),[l,n]=d.useState(null),{data:u,isLoading:f,refetch:j,isFetching:p}=z({queryKey:["/api/admin/checkouts/blocked-mismatches"],refetchInterval:6e4,staleTime:3e4}),g=W({mutationFn:async m=>(n(m),(await N("POST",`/api/admin/checkouts/blocked-mismatches/${m}/heal`)).json()),onSuccess:m=>{if(n(null),m?.ok){const $=m.reason==="already_paid"?" (já estava pago)":"";a({title:"Cobrança liberada",description:`Checkout ${(m.checkoutSessionId||"").slice(0,8)}… confirmado${$}`})}else a({title:"Não foi possível liberar",description:`${m?.reason||"erro"} ${m?.detail?`· ${m.detail}`:""}`,variant:"destructive"});r.invalidateQueries({queryKey:["/api/admin/checkouts/blocked-mismatches"]})},onError:m=>{n(null),a({title:"Erro ao liberar",description:m?.message||"falha de rede",variant:"destructive"})}}),w=W({mutationFn:async()=>(await N("POST","/api/admin/checkouts/blocked-mismatches/run-healer")).json(),onSuccess:m=>{const $=m?.report;a({title:"Auto-healer executado",description:$?`Varreu ${$.scanned} · liberou ${$.healed} · pulou ${$.skipped} · falhas ${$.failed}`:"—"}),r.invalidateQueries({queryKey:["/api/admin/checkouts/blocked-mismatches"]})},onError:m=>{a({title:"Erro ao rodar healer",description:m?.message||"—",variant:"destructive"})}}),y=u?.blocked||[],F=d.useMemo(()=>y.reduce((m,$)=>m+(typeof $.totalAmount=="number"?$.totalAmount:$.paidAmountCents?$.paidAmountCents/100:0),0),[y]),c=u?.lastHealerReport;return f?e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/20 p-4 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"})," Verificando checkouts bloqueados..."]}):y.length===0?e.jsxs("div",{className:"rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-4 flex items-center justify-between gap-3","data-testid":"card-blocked-checkouts-clean",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-500/15 flex items-center justify-center shrink-0",children:e.jsx(be,{className:"w-4 h-4 text-emerald-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:"Checkouts PIX saudáveis"}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:["Nenhum pagamento bloqueado por mismatch nas últimas ",u?.sinceHours||168,"h",c?` · auto-healer última varredura: ${new Date(c.ts).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:""]})]})]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"text-[11px] h-8",onClick:()=>w.mutate(),disabled:w.isPending,"data-testid":"button-run-checkout-healer-clean",children:[w.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Re-verificar"})]})]}):e.jsxs("div",{className:"rounded-xl border border-rose-500/30 bg-gradient-to-br from-rose-500/10 via-pink-500/5 to-red-500/5 p-4 md:p-5 space-y-3","data-testid":"card-blocked-checkouts-alert",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-rose-500/20 flex items-center justify-center shrink-0",children:e.jsx(Ce,{className:"w-5 h-5 text-rose-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm md:text-base font-bold text-white flex items-center gap-2 flex-wrap",children:["Checkouts PIX pagos mas BLOQUEADOS",e.jsxs(E,{className:"bg-rose-500/20 text-rose-200 border-rose-500/30 text-[10px]",children:[y.length," ",y.length===1?"checkout":"checkouts"]}),e.jsxs(E,{className:"bg-red-500/20 text-red-200 border-red-500/30 text-[10px]",children:[th(F)," em risco"]})]}),e.jsxs("div",{className:"text-[11px] md:text-xs text-rose-100/80 mt-0.5",children:['Cliente pagou no PIX, sistema rejeitou como mismatch falso. Auto-healer roda a cada 90s. "Liberar" valida na Woovi e entrega o livro (idempotente).',c?` · última: ${new Date(c.ts).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})} (liberou ${c.healed}/${c.scanned})`:""]})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsxs(b,{size:"sm",variant:"outline",className:"border-rose-500/30 hover:bg-rose-500/10 text-rose-100 h-8 text-[11px]",onClick:()=>j(),disabled:p,"data-testid":"button-refresh-blocked",children:[p?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5 hidden sm:inline",children:"Atualizar"})]}),e.jsxs(b,{size:"sm",className:"bg-rose-500 hover:bg-rose-600 text-white font-semibold h-8 text-[11px]",onClick:()=>w.mutate(),disabled:w.isPending,"data-testid":"button-run-checkout-healer",children:[w.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(yi,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Rodar healer"})]})]})]}),e.jsx("div",{className:"space-y-2",children:y.map(m=>{const $=l===m.eventId&&g.isPending,D=typeof m.totalAmount=="number"?m.totalAmount:m.paidAmountCents?m.paidAmountCents/100:0;return e.jsxs("div",{className:"rounded-lg border border-rose-500/20 bg-black/30 p-3 flex flex-col md:flex-row md:items-center md:justify-between gap-2 md:gap-3","data-testid":`row-blocked-${m.eventId}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm text-white font-medium truncate","data-testid":`text-blocked-email-${m.eventId}`,children:[m.userEmail||"—",m.bookTitle&&e.jsx("span",{className:"text-muted-foreground font-normal text-[11px] ml-2",children:m.bookTitle})]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-0.5 mt-0.5",children:[e.jsxs("span",{className:"font-mono",children:[m.checkoutSessionId.slice(0,12),"…"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:m.paymentMethod||"pix"}),m.eventStatus&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{className:"uppercase tracking-wide",children:m.eventStatus})]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[ig(m.ageMinutes)," atrás"]}),m.sessionStatus&&m.sessionStatus!=="pending"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{className:m.sessionStatus==="paid"?"text-emerald-400":"",children:["session ",m.sessionStatus]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 md:shrink-0",children:[e.jsx("div",{className:"text-sm font-bold text-emerald-400 tabular-nums","data-testid":`text-blocked-amount-${m.eventId}`,children:th(D)}),e.jsxs(b,{size:"sm",className:"bg-emerald-500 hover:bg-emerald-600 text-black font-semibold h-8 text-[11px]",onClick:()=>g.mutate(m.eventId),disabled:$||g.isPending,"data-testid":`button-heal-checkout-${m.eventId}`,children:[$?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(yi,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Liberar"})]})]})]},m.eventId)})})]})}const ng=["confirmed","completed","paid"];function lg(a){const{toast:r}
1=st(),l=$a(),[n,u]=d.useState(!1),[f,j]=d.useState(""),[p,g]=d.useState(!1),w=a.orderStatus==="refunded"||!!a.refundedAt,y=ng.includes(a.orderStatus)&&!w,F=z({queryKey:["/api/admin/orders",a.orderId,"refund-diagnostic"],queryFn:async()=>await(await N("GET",`/api/admin/orders/${a.orderId}/refund-diagnostic`)).json(),enabled:n,staleTime:1e4,refetchOnWindowFocus:!1}),c=W({mutationFn:async A=>await(await N("POST",`/api/admin/orders/${a.orderId}/refund`,A)).json(),onSuccess:A=>{r({title:"Reembolso processado",description:`Protocolo ${A.protocolNumber} via ${A.gateway}. Baixe o comprovante.`}),l.invalidateQueries({queryKey:["/api/admin/users"]}),l.invalidateQueries({queryKey:["/api/admin/orders",a.orderId,"refund-diagnostic"]}),u(!1),j(""),g(!1),setTimeout(()=>{window.open(`/api/admin/orders/${a.orderId}/refund-receipt.pdf`,"_blank")},500)},onError:A=>{const o=A?.status,L=o?` (HTTP ${o})`:"";r({title:"Falha no reembolso",description:(A?.message||"Erro inesperado")+L,variant:"destructive"}),g(!0),l.invalidateQueries({queryKey:["/api/admin/orders",a.orderId,"refund-diagnostic"]})}});if(w)return e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`refunded-state-${a.orderId}`,children:[e.jsxs(E,{variant:"outline",className:"border-orange-500/30 text-orange-400 text-[10px] gap-1",children:[e.jsx(be,{className:"w-2.5 h-2.5"}),"REEMBOLSADO"]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px] text-emerald-400 hover:text-emerald-300 hover:bg-emerald-500/10",onClick:()=>window.open(`/api/admin/orders/${a.orderId}/refund-receipt.pdf`,"_blank"),"data-testid":`button-download-refund-receipt-${a.orderId}`,children:[e.jsx(tt,{className:"w-3 h-3 mr-1"})," PDF"]})]});if(!y)return null;const m=F.data,$=A=>A==="ok"?{cls:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",label:"Pronto",Icon:be}:A==="warn"?{cls:"border-amber-500/30 text-amber-400 bg-amber-500/10",label:"Atenção",Icon:Ce}:{cls:"border-red-500/40 text-red-400 bg-red-500/10",label:"Bloqueado",Icon:Ks},D=A=>A==="stripe"?"bg-indigo-500/15 text-indigo-300 border-indigo-500/30":A==="woovi"?"bg-cyan-500/15 text-cyan-300 border-cyan-500/30":"bg-zinc-500/15 text-zinc-300 border-zinc-500/30";return e.jsxs(pi,{open:n,onOpenChange:A=>{u(A),A||g(!1)},children:[e.jsx(ui,{asChild:!0,children:e.jsxs(b,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px] text-orange-400 hover:text-orange-300 hover:bg-orange-500/10","data-testid":`button-refund-order-${a.orderId}`,children:[e.jsx(kr,{className:"w-3 h-3 mr-1"})," Reembolsar"]})}),e.jsxs(gi,{className:"bg-[#0a0a0a] border-white/10 text-white max-w-lg max-h-[90vh] overflow-y-auto","data-testid":`alert-confirm-refund-${a.orderId}`,children:[e.jsxs(bi,{children:[e.jsxs(ji,{className:"text-white flex items-center gap-2",children:[e.jsx(kr,{className:"w-4 h-4 text-orange-400"}),"Reembolsar este pedido?"]}),e.jsx(vi,{className:"text-muted-foreground text-xs space-y-2",asChild:!0,children:e.jsxs("div",{children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1 mt-2 border border-white/5",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Cliente:"}),e.jsx("span",{className:"text-white",children:a.customerName})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Produto:"}),e.jsx("span",{className:"text-white",children:a.orderLabel})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Valor:"}),e.jsxs("span",{className:"text-white font-bold",children:["R$ ",a.orderAmount.toFixed(2)]})]})]}),F.isLoading&&e.jsxs("div",{className:"mt-3 rounded-lg border border-white/10 bg-white/5 p-3 flex items-center gap-2 text-[11px] text-muted-foreground","data-testid":`refund-diag-loading-${a.orderId}`,children:[e.jsx(T,{className:"w-3 h-3 animate-spin"}),"Analisando elegibilidade no gateway…"]}),F.isError&&e.jsx("div",{className:"mt-3 rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 text-[11px] text-amber-300","data-testid":`refund-diag-error-${a.orderId}`,children:"Não foi possível pré-validar (você ainda pode prosseguir)."}),m&&(()=>{const A=$(m.eligibility.severity),o=A.Icon;return e.jsxs("div",{className:"mt-3 rounded-lg border border-white/10 bg-gradient-to-br from-white/[0.04] to-white/[0.02] p-3 space-y-2","data-testid":`refund-diag-${a.orderId}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Diagnóstico"}),e.jsxs(E,{variant:"outline",className:`text-[10px] gap-1 ${A.cls}`,"data-testid":`refund-diag-severity-${a.orderId}`,children:[e.jsx(o,{className:"w-2.5 h-2.5"}),A.label]})]}),e.jsx("p",{className:"text-[11px] text-white/80","data-testid":`refund-diag-reason-${a.orderId}`,children:m.eligibility.reason}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsxs(E,{variant:"outline",className:`text-[10px] ${D(m.gateway)}`,children:["Gateway: ",m.gateway]}),m.handle&&e.jsxs(E,{variant:"outline",className:"text-[10px] border-white/10 text-white/70 max-w-[180px] truncate",title:m.handle,children:[m.handle.slice(0,24),m.handle.length>24?"…":""]}),m.gatewayLive&&m.gatewayLive.ok&&m.gatewayLive.status&&e.jsxs(E,{variant:"outline",className:"text-[10px] border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:["Live: ",m.gatewayLive.status]}),m.gatewayLive&&!m.gatewayLive.ok&&e.jsx(E,{variant:"outline",className:"text-[10px] border-red-500/30 text-red-400 bg-red-500/10",title:m.gatewayLive.error||"",children:"Live: indisponível"}),m.lock.lockedAt&&e.jsxs(E,{variant:"outline",className:`text-[10px] ${m.lock.stale?"border-amber-500/30 text-amber-400 bg-amber-500/10":"border-zinc-500/30 text-zinc-400 bg-zinc-500/10"}`,children:["Lock: ",m.lock.lockAgeSec,"s ",m.lock.stale?"(órfão)":""]})]})]})})(),m?.lastRefundError&&e.jsxs("div",{className:"mt-3 rounded-lg border border-red-500/20 bg-red-500/5 p-3 space-y-1.5","data-testid":`refund-last-error-${a.orderId}`,children:[e.jsxs("button",{type:"button",onClick:()=>g(A=>!A),className:"flex items-center justify-between w-full text-left text-[11px] text-red-300 hover:text-red-200","data-testid":`button-toggle-error-details-${a.orderId}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ks,{className:"w-3 h-3"}),"Última tentativa falhou em ",new Date(m.lastRefundError.at).toLocaleStr
1ing("pt-BR")]}),e.jsx("span",{className:"text-[10px] text-red-400/70",children:p?"ocultar":"ver detalhes"})]}),p&&e.jsxs("div",{className:"space-y-1 pt-1.5 border-t border-red-500/15 text-[10.5px]",children:[e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Gateway:"}),e.jsx("span",{className:"text-white/90",children:m.lastRefundError.gateway})]}),m.lastRefundError.httpStatus!==null&&e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"HTTP:"}),e.jsx("span",{className:"text-white/90",children:m.lastRefundError.httpStatus})]}),m.lastRefundError.isTimeout&&e.jsx("div",{className:"text-amber-400",children:"Tipo: TIMEOUT — gateway demorou demais"}),m.lastRefundError.isNetwork&&e.jsx("div",{className:"text-amber-400",children:"Tipo: REDE — gateway inacessível"}),e.jsx("div",{className:"text-white/80 break-words",children:m.lastRefundError.message}),m.lastRefundError.gatewayBody&&e.jsxs("details",{className:"text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer text-[10px] hover:text-white/70",children:"Resposta bruta do gateway"}),e.jsx("pre",{className:"mt-1 max-h-32 overflow-auto rounded bg-black/40 p-2 text-[10px] text-white/70 whitespace-pre-wrap break-words",children:typeof m.lastRefundError.gatewayBody=="string"?m.lastRefundError.gatewayBody:JSON.stringify(m.lastRefundError.gatewayBody,null,2)})]})]})]}),e.jsxs("div",{className:"text-orange-400/80 text-[11px] pt-2 flex items-start gap-1.5",children:[e.jsx(js,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:"O reembolso será processado IMEDIATAMENTE no gateway (Stripe ou Woovi). O valor sairá do seu faturamento do dia."})]})]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Motivo do reembolso (obrigatório)"}),e.jsx($s,{value:f,onChange:A=>j(A.target.value),placeholder:"Ex: cliente solicitou via WhatsApp por insatisfação com a entrega",className:"bg-black/20 border-white/10 text-white text-xs min-h-[80px]",maxLength:500,"data-testid":`textarea-refund-reason-${a.orderId}`}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[f.length,"/500 — aparecerá no comprovante."]})]}),e.jsxs(Ni,{children:[e.jsx(fi,{className:"bg-white/5 border-white/10 text-white hover:bg-white/10","data-testid":`button-cancel-refund-${a.orderId}`,children:"Cancelar"}),e.jsxs(wi,{onClick:A=>{if(A.preventDefault(),f.trim().length<3){r({title:"Motivo obrigatório",description:"Mínimo 3 caracteres.",variant:"destructive"});return}if(m&&!m.eligibility.eligible&&m.eligibility.severity==="critical"){r({title:"Reembolso bloqueado",description:m.eligibility.reason,variant:"destructive"});return}c.mutate({reason:f.trim()})},disabled:c.isPending||!!m&&!m.eligibility.eligible&&m.eligibility.severity==="critical",className:"bg-orange-500 hover:bg-orange-600 text-white disabled:opacity-50","data-testid":`button-confirm-refund-${a.orderId}`,children:[c.isPending?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(kr,{className:"w-3 h-3 mr-1"}),c.isError?"Tentar novamente":"Confirmar reembolso"]})]})]})]})}const dg=new Set(["cancelled","completed"]);function og(a){const{toast:r}=st(),l=$a(),[n,u]=d.useState(!1),[f,j]=d.useState(""),p=a.orderStatus==="cancelled",g=W({mutationFn:async w=>{const y=await N("POST",`/api/admin/human-services/${a.orderId}/refund`,{reason:w.reason||void 0}),F=await y.json();if(!y.ok)throw new Error(F.message||"Erro");return F},onSuccess:w=>{r({title:w.idempotent?"Já estava cancelado":"✓ Estorno realizado",description:w.refundId?`Refund ${w.refundId} (${w.refundStatus||"ok"}) — DigiWork notificado em paralelo`:"Pedido marcado como cancelado"}),l.invalidateQueries({queryKey:["/api/admin/users"]}),l.invalidateQueries({queryKey:["/api/admin/human-services"]}),u(!1),j("")},onError:w=>r({title:"Falha no estorno",description:w.message||"Erro inesperado",variant:"destructive"})});return p?e.jsxs(E,{variant:"outline",className:"border-orange-500/30 text-orange-400 text-[10px] gap-1","data-testid":`refunded-state-hs-${a.orderId}`,children:[e.jsx(be,{className:"w-2.5 h-2.5"})," CANCELADO"]}):dg.has(a.orderStatus)?null:e.jsxs(pi,{open:n,onOpenChange:u,children:[e.jsx(ui,{asChild:!0,children:e.jsxs(b,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px] text-orange-400 hover:text-orange-300 hover:bg-orange-500/10","data-testid":`button-refund-hs-${a.orderId}`,children:[e.jsx(kr,{className:"w-3 h-3 mr-1"})," Estornar"]})}),e.jsxs(gi,{className:"bg-[#0a0a0a] border-white/10 text-white max-w-lg","data-testid":`alert-confirm-refund-hs-${a.orderId}`,children:[e.jsxs(bi,{children:[e.jsxs(ji,{className:"text-white flex items-center gap-2",children:[e.jsx(kr,{className:"w-4 h-4 text-orange-400"}),"Estornar serviço humano?"]}),e.jsx(vi,{className:"text-muted-foreground text-xs space-y-2",asChild:!0,children:e.jsxs("div",{children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1 mt-2 border border-white/5",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Cliente:"}),e.jsx("span",{className:"text-white",children:a.customerName})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Serviço:"}),e.jsx("span",{className:"text-white",children:a.serviceTitle})]}),typeof a.amountBRL=="number"&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Valor:"}),e.jsxs("span",{className:"text-white font-bold",children:["R$ ",a.amountBRL.toFixed(2)]})]})]}),e.jsxs("div",{className:"text-orange-400/80 text-[11px] pt-2 flex items-start gap-1.5",children:[e.jsx(js,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:"Estorno via Woovi (PIX) + cancelamento no DigiWork são disparados em paralelo. Se o pagamento original não foi via PIX, o estorno financeiro pode falhar — mesmo assim o status é marcado como cancelado e o DigiWork é notificado."})]})]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Motivo (opcional)"}),e.jsx($s,{value:f,onChange:w=>j(w.target.value),placeholder:"Ex: cliente solicitou via WhatsApp",className:"bg-black/20 border-white/10 text-white text-xs min-h-[60
1px]",maxLength:500,"data-testid":`textarea-refund-reason-hs-${a.orderId}`})]}),e.jsxs(Ni,{children:[e.jsx(fi,{className:"bg-white/5 border-white/10 text-white hover:bg-white/10","data-testid":`button-cancel-refund-hs-${a.orderId}`,children:"Cancelar"}),e.jsxs(wi,{onClick:w=>{w.preventDefault(),g.mutate({reason:f.trim()})},disabled:g.isPending,className:"bg-orange-500 hover:bg-orange-600 text-white disabled:opacity-50","data-testid":`button-confirm-refund-hs-${a.orderId}`,children:[g.isPending?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(kr,{className:"w-3 h-3 mr-1"}),"Confirmar estorno"]})]})]})]})}const cg={submitted:"border-blue-500/30 text-blue-300 bg-blue-500/10",in_progress:"border-amber-500/30 text-amber-300 bg-amber-500/10",awaiting_author_review:"border-violet-500/30 text-violet-300 bg-violet-500/10",awaiting_revision_info:"border-orange-500/30 text-orange-300 bg-orange-500/10",completed:"border-emerald-500/30 text-emerald-300 bg-emerald-500/10",cancelled:"border-zinc-500/30 text-zinc-400 bg-zinc-500/10"};function xg(a){if(typeof a.amountBRL=="number")return a.amountBRL;if(typeof a.amount=="number")return a.amount;if(typeof a.priceCents=="number")return a.priceCents/100}function mg({userId:a,customerName:r}){const{data:l}=z({queryKey:["/api/admin/users",a,"human-services"],queryFn:async()=>{const n=await N("GET",`/api/admin/users/${a}/human-services`);return n.ok?n.json():[]},staleTime:3e4});return!l||l.length===0?null:e.jsxs("div",{"data-testid":`section-human-services-${a}`,children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2 flex items-center gap-1.5",children:[e.jsx(Zs,{className:"w-3 h-3"})," Serviços Humanos (DigiWork)"]}),e.jsx("div",{className:"grid gap-2",children:l.map(n=>{const u=xg(n),f=cg[n.status]||"border-white/10 text-muted-foreground";return e.jsxs("div",{className:"flex items-center justify-between bg-white/5 rounded-lg px-3 py-2","data-testid":`card-hs-order-${n.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-[11px] font-mono text-muted-foreground",children:n.id.slice(0,8)}),e.jsx("span",{className:"text-xs text-white truncate",children:n.serviceTitle||n.serviceSlug}),n.externalPedidoId&&e.jsxs(E,{variant:"outline",className:"text-[10px] border-cyan-500/30 text-cyan-300",title:`DigiWork ID: ${n.externalPedidoId}`,children:["#",String(n.externalPedidoId).slice(0,8)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[typeof u=="number"&&e.jsxs("span",{className:"text-xs font-medium text-white",children:["R$ ",u.toFixed(2)]}),e.jsx(E,{variant:"outline",className:`text-[10px] ${f}`,children:n.status}),e.jsx(og,{orderId:n.id,orderStatus:n.status,serviceTitle:n.serviceTitle||n.serviceSlug,customerName:r,amountBRL:u}),n.createdAt&&e.jsx("span",{className:"text-[10px] text-muted-foreground hidden sm:inline",children:new Date(n.createdAt).toLocaleDateString("pt-BR")})]})]},n.id)})})]})}const hg=new Set(["pix","card","credit_card"]),pg=new Set(["confirmed","completed","paid"]),ug=[{key:"all",label:"Todos",color:"text-white/60 border-white/10"},{key:"paid",label:"Tráfego Pago",color:"text-teal-400 border-teal-500/30"},{key:"facebook",label:"Facebook Ads",color:"text-blue-400 border-blue-500/30"},{key:"google",label:"Google",color:"text-red-400 border-red-500/30"},{key:"blog",label:"Blog",color:"text-orange-400 border-orange-500/30"},{key:"chat",label:"Chat",color:"text-violet-400 border-violet-500/30"},{key:"create",label:"Criar Livro",color:"text-pink-400 border-pink-500/30"},{key:"organic",label:"Orgânico",color:"text-white/40 border-white/10"}],gg=[{key:"all",label:"Todos",color:"text-white/60 border-white/10"},{key:"user",label:"Usuário",color:"text-white/70 border-white/20"},{key:"support",label:"Suporte",color:"text-orange-400 border-orange-500/30"},{key:"admin",label:"Admin",color:"text-primary border-primary/30"},{key:"openclaw",label:"Publicador",color:"text-blue-400 border-blue-500/30"}],Fc=a=>a.toLocaleDateString("en-CA",{timeZone:"America/Sao_Paulo"}),wa=()=>Fc(new Date),Fl=a=>Fc(new Date(Date.now()-a*864e5)),bg=()=>wa().slice(0,8)+"01",Nr=a=>{if(!a)return null;const r=new Date(a);return isNaN(r.getTime())?null:Fc(r)},jg={user:"Usuário",support:"Suporte",admin:"Admin",openclaw:"Publicador"},vg={active:"Ativa",deletion_requested:"Exclusão solicitada",anonymized:"Anonimizada"},Dl=a=>(Number(a)||0).toFixed(2).replace(".",","),sh=a=>{let r=a==null?"":String(a);return(/^\s*[=+\-@]/.test(r)||/^[\t\r]/.test(r))&&(r="'"+r),/[",\n\r;]/.test(r)?`"${r.replace(/"/g,'""')}"`:r};function Ng({users:a,loading:r,getUserSource:l}
1){const[n,u]=d.useState(Fl(29)),[f,j]=d.useState(wa()),[p,g]=d.useState("30d"),[w,y]=d.useState("signup"),[F,c]=d.useState("all"),[m,$]=d.useState("all"),[D,A]=d.useState(!0),[o,L]=d.useState(!1),[v,I]=d.useState(!1),de=se=>{g(se),se==="today"?(u(wa()),j(wa())):se==="7d"?(u(Fl(6)),j(wa())):se==="30d"?(u(Fl(29)),j(wa())):se==="90d"?(u(Fl(89)),j(wa())):se==="month"?(u(bg()),j(wa())):se==="all"&&(u(""),j(""))},me=se=>!n&&!f?!0:!(!se||n&&se<n||f&&se>f),ne=se=>(se.orders||[]).filter(Ne=>pg.has((Ne.status||"").toLowerCase())&&hg.has((Ne.paymentMethod||"").toLowerCase())),Z=se=>{const Ne=ne(se).map(ie=>Nr(ie.createdAt)).filter(Boolean);return Ne.length?Ne.sort()[Ne.length-1]:null},S=se=>{const Ne=ne(se).filter(ie=>me(Nr(ie.createdAt)));return{count:Ne.length,total:Ne.reduce((ie,X)=>ie+(X.amount||0),0)}},re=se=>{if(F==="all")return!0;const Ne=l(se).key;return F==="paid"?Ne==="facebook"||Ne==="google":Ne===F},_=se=>{if(m==="all")return!0;const Ne=se.role||"user";return m==="user"?Ne==="user":Ne===m},ee=d.useMemo(()=>(a||[]).filter(Ne=>!re(Ne)||!_(Ne)?!1:w==="signup"?me(Nr(Ne.createdAt)):!n&&!f?ne(Ne).length>0:ne(Ne).some(ie=>me(Nr(ie.createdAt)))),[a,F,m,w,n,f]),h=d.useMemo(()=>{let se=0,Ne=0,ie=0;for(const X of ee){se+=X.totalSpent||0;const B=S(X);Ne+=B.total,Z(X)&&(ie+=1)}return{count:ee.length,lifetime:se,periodTotal:Ne,withPurchase:ie}},[ee,n,f]),te=()=>{const se=["Nome","E-mail","Telefone","Papel","Origem","Canal","País","Cidade","Estado","Cadastro (BRT)","E-mail verificado","Status da conta","Livros","Total gasto (R$)","Última compra (BRT)"];w==="purchase"&&se.push("Compras no período","Gasto no período (R$)"),D&&se.push("Planejamentos","Capas","Ilustrações","Traduções","Publicações","Mat. divulgação"),o&&se.push("Documento (CPF)","Tipo doc.","Endereço","CEP","Nascimento","Cód. indicação");const Ne=ee.map(ie=>{const X=ie.primaryChannel==="chat"?"Chat":ie.primaryChannel==="landing_page"?"Landing":"",B=[ie.name||"",ie.email,ie.phone||"",jg[ie.role]||ie.role||"",l(ie).label,X,ie.country||"",ie.city||"",ie.state||"",Nr(ie.createdAt)||"",ie.emailVerifiedAt?"Sim":"Não",vg[ie.accountStatus]||ie.accountStatus||"",ie.booksCount??0,Dl(ie.totalSpent||0),Z(ie)||""];if(w==="purchase"){const ge=S(ie);B.push(ge.count,Dl(ge.total))}if(D){const ge=ie.activity;B.push(ge?.plans??0,ge?.covers??0,ge?.illustrations??0,ge?.translations??0,ge?.publications??0,ge?.marketingMaterials??0)}return o&&B.push(ie.taxId||"",ie.taxIdType||"",[ie.addressLine1,ie.addressLine2].filter(Boolean).join(" "),ie.postalCode||"",ie.dateOfBirth||"",ie.referralCode||""),B});return{header:se,rows:Ne}},M=()=>{if(!ee.length)return;const{header:se,rows:Ne}=te(),ie=[se.map(sh).join(",")];for(const $t of Ne)ie.push($t.map(sh).join(","));const X="\uFEFF"+ie.join(`\r
2`),B=new Blob([X],{type:"text/csv;charset=utf-8;"}),ge=URL.createObjectURL(B),ut=!n&&!f?"todos":`${n||"inicio"}_a_${f||wa()}`,at=document.createElement("a");at.href=ge,at.download=`clientes-sabhia-${w==="purchase"?"compra-":""}${ut}.csv`,document.body.appendChild(at),at.click(),document.body.removeChild(at),URL.revokeObjectURL(ge)},ae=async()=>{if(!ee.length)return;const se=ee.map(Ne=>Ne.email).filter(Boolean).join(", ");try{await navigator.clipboard.writeText(se),I(!0),setTimeout(()=>I(!1),2e3)}catch{}},ye=!n&&!f?"Todo o período":`${n||"início"} → ${f||wa()}`,Me=ee.slice(0,12);return e.jsxs("div",{className:"space-y-4","data-testid":"clientes-export-panel",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/10 via-white/[0.03] to-transparent border border-primary/20 rounded-2xl p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/15 flex items-center justify-center shrink-0",children:e.jsx(nu,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-white",children:"Exportar base de clientes"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Filtre por período personalizado e baixe as informações dos clientes em CSV (abre no Excel/Sheets)."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-white/40",children:[e.jsx(Ec,{className:"w-3 h-3"})," Período"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5","data-testid":"export-preset-filters",children:[{key:"today",label:"Hoje"},{key:"7d",label:"7 dias"},{key:"30d",label:"30 dias"},{key:"90d",label:"90 dias"},{key:"month",label:"Este mês"},{key:"all",label:"Tudo"}].map(se=>e.jsx("button",{onClick:()=>de(se.key),className:`px-3 py-1 rounded-full text-[11px] font-medium border transition-all ${p===se.ke
2y?"text-primary border-primary/40 bg-primary/10":"text-white/40 border-white/10 hover:text-white/70 hover:border-white/20"}`,"data-testid":`button-preset-${se.key}`,children:se.label},se.key))}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 pt-1",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[10px] uppercase text-muted-foreground tracking-wider",children:"De"}),e.jsx(J,{type:"date",value:n,onChange:se=>{u(se.target.value),g("custom")},className:"bg-black/20 border-white/10 h-9 text-xs w-40","data-testid":"input-export-from"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[10px] uppercase text-muted-foreground tracking-wider",children:"Até"}),e.jsx(J,{type:"date",value:f,onChange:se=>{j(se.target.value),g("custom")},className:"bg-black/20 border-white/10 h-9 text-xs w-40","data-testid":"input-export-to"})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground pb-2",children:ye})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-white/40",children:"Base do período"}),e.jsx("div",{className:"inline-flex rounded-lg border border-white/10 overflow-hidden","data-testid":"export-basis-toggle",children:[{key:"signup",label:"Por cadastro",hint:"clientes cadastrados no período"},{key:"purchase",label:"Por compra",hint:"clientes que compraram no período"}].map(se=>e.jsx("button",{onClick:()=>y(se.key),title:se.hint,className:`px-4 py-1.5 text-xs font-medium transition-all ${w===se.key?"bg-primary/15 text-primary":"text-white/40 hover:text-white/70"}`,"data-testid":`button-basis-${se.key}`,children:se.label},se.key))}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:w==="signup"?"Inclui clientes cuja data de cadastro está dentro do período.":"Inclui clientes com pelo menos uma compra paga (PIX/cartão) dentro do período."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-white/40",children:"Origem"}),e.jsx("div",{className:"flex flex-wrap gap-1.5","data-testid":"export-source-filters",children:ug.map(se=>e.jsx("button",{onClick:()=>c(se.key),className:`px-2.5 py-1 rounded-full text-[10px] font-medium border transition-all ${F===se.key?`${se.color} bg-white/10`:"text-white/30 border-transparent hover:border-white/10 hover:text-white/50"}`,"data-testid":`button-export-source-${se.key}`,children:se.label},se.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-white/40",children:"Papel"}),e.jsx("div",{className:"flex flex-wrap gap-1.5","data-testid":"export-role-filters",children:gg.map(se=>e.jsx("button",{onClick:()=>$(se.key),className:`px-2.5 py-1 rounded-full text-[10px] font-medium border transition-all ${m===se.key?`${se.color} bg-white/10`:"text-white/30 border-transparent hover:border-white/10 hover:text-white/50"}`,"data-testid":`button-export-role-${se.key}`,children:se.label},se.key))})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("button",{onClick:()=>A(se=>!se),className:`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium border transition-all ${D?"border-primary/40 bg-primary/10 text-primary":"border-white/10 text-white/50 hover:text-white/70"}`,"data-testid":"button-toggle-activity",children:[e.jsx("span",{className:`w-4 h-4 rounded flex items-center justify-center border ${D?"bg-primary border-primary":"border-white/20"}`,children:D&&e.jsx(Ua,{className:"w-3 h-3 text-black"})}),"Incluir atividade (livros, capas, etc.)"]}),e.jsxs("button",{onClick:()=>L(se=>!se),className:`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium border transition-all ${o?"border-amber-500/40 bg-amber-500/10 text-amber-300":"border-white/10 text-white/50 hover:text-white/70"}`,"data-testid":"button-toggle-pii",children:[e.jsx("span",{className:`w-4 h-4 rounded flex items-center justify-center border ${o?"bg-amber-400 border-amber-400":"border-white/20"}`,children:o&&e.jsx(Ua,{className:"w-3 h-3 text-black"})}),e.jsx(Ks,{className:"w-3.5 h-3.5"}),"Incluir dados pessoais (CPF, endereço)"]})]}),o&&e.jsxs("p",{className:"text-[11px] text-amber-300/80 flex items-center gap-1.5",children:[e.jsx(Ks,{className:"w-3 h-3 shrink-0"}),"Dados sensíveis (LGPD): use apenas para fins legítimos e mantenha o arquivo em local seguro."]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-2xl p-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"bg-primary/10 border border-primary/20 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] uppercase text-primary/70 tracking-wider",children:[e.jsx(Re,{className:"w-3 h-3"})," Clientes"]}),e.jsx("div",{className:"text-2xl font-bold text-primary","data-testid":"text-export-count",children:h.count}),e.jsx("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:"no filtro atual"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] uppercase text-muted-foreground tracking-wider",children:[e.jsx(kh,{className:"w-3 h-3"})," ",w==="purchase"?"Arrecadado no período":"Total arrecadado (vida)"]}),e.jsxs("div",{className:"text-2xl font-bold text-emerald-400","data-testid":"text-export-revenue",children:["R$ ",Dl(w==="purchase"?h.periodTotal:h.lifetime)]}),e.jsx("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:"PIX/cartão"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] uppercase text-muted-foreground tracking-wider",children:[e.jsx(Vi,{className:"w-3 h-3"})," Compradores"]}),e.jsx("div",{className:"text-2xl font-bold text-white","data-testid":"text-export-buyers",children:h.withPurchase}),e.jsx("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:"com ≥ 1 compra"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(b,{onClick:M,disabled:r||h.count===0,className:"bg-primary hover:bg-primary/90 text-black font-semibold h-10 text-sm","data-testid":"button-export-csv",children:[e.jsx(Rt,{className:"w-4 h-4 mr-1.5"}),"Baixar CSV (",h.count,")"]}),e.jsxs(b,{onClick:ae,disabled:r||h.count===0,variant:"outline",className:"bg-white/5 border-white/10 text-white hover:bg-white/10 h-10 text-sm","data-testid":"button-copy-emails",children:[v?e.jsx(Ua,{className:"w-4 h-4 mr-1.5 text-emerald-400"}):e.jsx(ha,{className:"w-4 h-4 mr-1.5"}),v?"E-mails copiados!":"Copiar e-mails"]}
2),r&&e.jsx(T,{className:"w-4 h-4 animate-spin text-primary"})]}),h.count>0&&e.jsxs("div",{className:"border border-white/10 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"overflow-auto max-h-[340px]",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-white/5 sticky top-0",children:e.jsxs("tr",{className:"text-left text-[10px] uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"px-3 py-2",children:"Cliente"}),e.jsx("th",{className:"px-3 py-2",children:"Origem"}),e.jsx("th",{className:"px-3 py-2 whitespace-nowrap",children:"Cadastro"}),e.jsx("th",{className:"px-3 py-2 text-right whitespace-nowrap",children:"Gasto"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:Me.map(se=>e.jsxs("tr",{className:"hover:bg-white/5","data-testid":`row-export-${se.id}`,children:[e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"text-white truncate max-w-[220px]",children:se.name||"—"}),e.jsx("div",{className:"text-[10px] text-muted-foreground truncate max-w-[220px]",children:se.email})]}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full border ${l(se).color}`,children:l(se).label})}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",children:Nr(se.createdAt)||"—"}),e.jsxs("td",{className:"px-3 py-2 text-right font-medium text-emerald-400 whitespace-nowrap",children:["R$ ",Dl(se.totalSpent||0)]})]},se.id))})]})}),h.count>Me.length&&e.jsxs("div",{className:"px-3 py-2 text-[11px] text-muted-foreground bg-white/[0.02] border-t border-white/5 text-center",children:["Mostrando ",Me.length," de ",h.count," — o CSV inclui todos."]})]}),!r&&h.count===0&&e.jsxs("div",{className:"p-10 text-center text-muted-foreground",children:[e.jsx(Re,{className:"w-8 h-8 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum cliente no filtro atual. Ajuste o período ou os filtros."})]})]})]})}const fg=()=>new Date().toISOString().slice(0,10),wg=a=>new Date(Date.now()-a*864e5).toISOString().slice(0,10),oc=a=>a.toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),yg=a=>new Date(a).toLocaleString("pt-BR",{timeZone:"America/Sao_Paulo",dateStyle:"short",timeStyle:"short"});function kg(){const[a,r]=d.useState(!1),[l,n]=d.useState(wg(30)),[u,f]=d.useState(fg()),{data:j,isLoading:p,refetch:g}=z({queryKey:["/api/admin/refunds-report",l,u],queryFn:async()=>{const y=await fetch(`/api/admin/refunds-report?from=${l}T00:00:00.000Z&to=${u}T23:59:59.999Z`);if(!y.ok)throw new Error("Erro ao carregar relatório");return y.json()},enabled:a}),w=()=>{window.open(`/api/admin/refunds-report?from=${l}T00:00:00.000Z&to=${u}T23:59:59.999Z&format=csv`,"_blank")};return e.jsxs(Je,{open:a,onOpenChange:r,children:[e.jsx(V0,{asChild:!0,children:e.jsxs(b,{variant:"outline",size:"sm",className:"bg-orange-500/10 border-orange-500/30 text-orange-400 hover:bg-orange-500/20 hover:text-orange-300 h-9 text-xs","data-testid":"button-open-refunds-report",children:[e.jsx(_m,{className:"w-3.5 h-3.5 mr-1.5"})," Relatório de Reembolsos"]})}),e.jsxs(Ye,{className:"bg-[#0a0a0a] border-white/10 text-white max-w-5xl max-h-[85vh] overflow-hidden flex flex-col","data-testid":"dialog-refunds-report",children:[e.jsx(Ze,{children:e.jsxs(et,{className:"text-white flex items-center gap-2",children:[e.jsx(_m,{className:"w-5 h-5 text-orange-400"})," Relatório de Reembolsos"]})}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 pb-3 border-b border-white/10",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[10px] uppercase text-muted-foreground tracking-wider",children:"De"}),e.jsx(J,{type:"date",value:l,onChange:y=>n(y.target.value),className:"bg-black/20 border-white/10 h-9 text-xs w-40","data-testid":"input-refunds-from"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[10px] uppercase text-muted-foreground tracking-wider",children:"Até"}),e.jsx(J,{type:"date",value:u,onChange:y=>f(y.target.value),className:"bg-black/20 border-white/10 h-9 text-xs w-40","data-testid":"input-refunds-to"})]}),e.jsx(b,{size:"sm",onClick:()=>g(),className:"bg-primary hover:bg-primary/90 text-white h-9 text-xs","data-testid":"button-refresh-refunds",children:"Atualizar"}),e.jsxs(b,{size:"sm",variant:"outline",onClick:w,disabled:!j||j.refunds.length===0,className:"bg-white/5 border-white/10 text-white hover:bg-white/10 h-9 text-xs ml-auto","data-testid":"button-export-refunds-csv",children:[e.jsx(Rt,{className:"w-3.5 h-3.5 mr-1.5"})," Exportar CSV"]})]}),p&&e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(T,{className:"w-5 h-5 animate-spin mr-2"})," Carregando..."]}),j&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 py-3","data-testid":"refunds-summary",children:[e.jsxs("div",{className:"bg-orange-500/10 border border-orange-500/20 rounded-lg p-3",children:[e.jsx("div",{className:"text-[10px] uppercase text-orange-300/70 tracking-wider",children:"Total reembolsado"}),e.jsx("div",{className:"text-xl font-bold text-orange-400","data-testid":"text-total-refund-amount",children:oc(j.total.amount)}),e.jsxs("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:[j.total.count," ",j.total.count===1?"pedido":"pedidos"]})]}),Object.entries(j.byGateway).map(([y,F])=>e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-lg p-3","data-testid":`card-gateway-${y}`,children:[e.jsx("div",{className:"text-[10px] uppercase text-muted-foreground tracking-wider",children:y==="stripe"?"Stripe (cartão)":y==="woovi"?"Woovi (PIX)":y}),e.jsx("div",{className:"text-xl font-bold text-white",children:oc(F.amount)}),e.jsxs("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:[F.count," ",F.count===1?"reembolso":"reembolsos"]})]},y))]}),e.jsx("div",{className:"flex-1 overflow-auto border border-white/10 rounded-lg",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-white/5 sticky top-0",children:e.jsxs("tr",{className:"text-left text-[10px] uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"px-3 py-2",children:"Data"}),e.jsx("th",{className:"px-3 py-2",children:"Protocolo"}),e.jsx("th",{className:"px-3 py-2",children:"Cliente"}),e.jsx("th",{className:"px-3 py-2",children:"Produto"}),e.jsx("th",{className:"px-3 py-2",children:"Gateway"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Valor"}),e.jsx("th",{className:"px-3 py-2",children:"Motivo"}),e.jsx("th",{className:"px-3 py-2"})]})}),e.jsxs("tbody",{className:"divide-y divide-white/5",children:[j.refunds.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-3 py-8 text-center text-muted-foreground",children:"Nenhum reembolso no período."})}),j.refunds.map(y=>e.jsxs("tr",{className:"hover:bg-white/5","data-testid":`row-refund-${y.orderId}`,children:[e.jsx("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",children:yg(y.refundedAt)}),e.jsx("td",{className:"px-3 py-2 font-mono text-[10px] text-orange-400",children:y.refundProtocol}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"text-white",children:y.userName||"—"}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:y.userEmail})]}),e.jsx("td",{className:"px-3 py-2 text-white/80",children:y.orderTypeLabel}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:y.refundGateway||"manual"}),e.jsxs("td",{className:"px-3 py-2 text-right font-medium text-orange-400 whitespace-nowrap",children:["- ",oc(y.refundAmount)]}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground max-w-[200px] truncate",title:y.refundReason,children:y.refundReason}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs(b,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px] text-emerald-400 hover:bg-emerald-500/10",onClick:()=>window.open(`/api/admin/orders/${y.orderId}/refund-receipt.pdf`,"_blank"),"data-testid":`button-download-report-pdf-${y.orderId}`,children:[e.jsx(tt,{className:"w-3 h-3 mr-1"})," PDF"]})})]},y.orderId))]})]})})]})]})]})}const Ph={healthy:{ring:"border-emerald-500/30",bg:"bg-emerald-500/10",text:"text-emerald-300",icon:be},warning:{ring:"border-amber-500/30",bg:"bg-amber-500/10",text:"text-amber-300",icon:Ce},critical:{ring:"border-rose-500/40",bg:"bg-rose-500/10",text:"text-rose-300",icon:Xe},unknown:{ring:"border-white/10",bg:"bg-white/5",text:"text-muted-foreground",icon:Ql}},cc=a=>a==null?"—":a<60?`${a} min`:a<1440?`${Math.floor(a/60)}h ${a%60}min`:`${Math.floor(a/1440)}d`,ah=a=>
2a.toLocaleString("pt-BR",{style:"currency",currency:"BRL",maximumFractionDigits:0});function Ml({title:a,status:r,message:l,metric:n,Icon:u,testid:f}){const j=Ph[r],p=j.icon;return e.jsxs("div",{className:`rounded-lg border ${j.ring} ${j.bg} p-3 flex items-start gap-3`,"data-testid":f,children:[e.jsx("div",{className:`w-8 h-8 rounded-md ${j.bg} border ${j.ring} flex items-center justify-center shrink-0`,children:e.jsx(u,{className:`w-4 h-4 ${j.text}`})}),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:"text-sm font-semibold text-white",children:a}),e.jsxs("span",{className:`inline-flex items-center gap-1 text-[10px] uppercase tracking-wide ${j.text}`,children:[e.jsx(p,{className:"w-3 h-3"}),r==="healthy"?"OK":r==="warning"?"atenção":r==="critical"?"crítico":"—"]}),n&&e.jsx(E,{className:`bg-black/30 border ${j.ring} ${j.text} text-[10px] tabular-nums`,children:n})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground mt-0.5 leading-snug",children:l})]})]})}function Cg(){const{data:a,isLoading:r,refetch:l,isFetching:n}=z({queryKey:["/api/admin/funnel-health"],refetchInterval:6e4,staleTime:3e4});if(r)return e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/20 p-4 flex items-center gap-2 text-xs text-muted-foreground","data-testid":"card-funnel-health-loading",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"})," Verificando saúde do funil..."]});if(!a)return e.jsxs("div",{className:"rounded-xl border border-rose-500/20 bg-rose-500/5 p-4 text-xs text-rose-300","data-testid":"card-funnel-health-error",children:["Falha ao carregar status do funil. ",e.jsx(b,{size:"sm",variant:"ghost",className:"ml-2 h-7 text-[11px]",onClick:()=>l(),children:"Tentar de novo"})]});const u=Ph[a.overall],f=u.icon,j=a.overall==="healthy"?"Funil saudável":a.overall==="warning"?"Funil com pontos de atenção":a.overall==="critical"?"Funil em ALERTA — investigar agora":"Status do funil",p=w=>w>5?e.jsx(Ie,{className:"w-3 h-3 text-emerald-400"}):w<-5?e.jsx(Ch,{className:"w-3 h-3 text-rose-400"}):e.jsx(Ql,{className:"w-3 h-3 text-muted-foreground"}),g=w=>`${w>0?"+":""}${w.toFixed(0)}% vs 7d`;return e.jsxs("div",{className:`rounded-xl border ${u.ring} ${u.bg} p-4 md:p-5 space-y-3`,"data-testid":`card-funnel-health-${a.overall}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg ${u.bg} border ${u.ring} flex items-center justify-center shrink-0`,children:e.jsx(f,{className:`w-5 h-5 ${u.text}`})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:`text-sm md:text-base font-bold ${u.text}`,children:j}),e.jsx("div",{className:"text-[11px] md:text-xs text-muted-foreground mt-0.5",children:"Token Meta · Webhook Stripe · Conversões hoje · Receita hoje (atualiza a cada 60s)"}),a.conversion.lastPaidAgeMinutes!=null&&e.jsxs("div",{className:"text-[11px] md:text-xs mt-0.5 inline-flex items-center gap-1.5",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:`animate-ping absolute inline-flex h-full w-full rounded-full opacity-60 ${a.conversion.lastPaidAgeMinutes<=180?"bg-emerald-400":"bg-amber-400"}`}),e.jsx("span",{className:`relative inline-flex rounded-full h-1.5 w-1.5 ${a.conversion.lastPaidAgeMinutes<=180?"bg-emerald-400":"bg-amber-400"}`})]}),e.jsx("span",{className:"text-muted-foreground",children:"Última venda real:"}),e.jsxs("span",{className:"text-white font-medium tabular-nums","data-testid":"text-last-sale-age",children:["há ",cc(a.conversion.lastPaidAgeMinutes)]})]})]})]}),e.jsxs(b,{size:"sm",variant:"outline",className:"border-white/15 hover:bg-white/5 h-8 text-[11px]",onClick:()=>l(),disabled:n,"data-testid":"button-refresh-funnel-health",children:[n?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5 hidden sm:inline",children:"Atualizar"})]})]}),e.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[e.jsx(Ml,{title:"Token Meta (Pixel/CAPI)",status:a.meta.status,Icon:jt,message:a.meta.message,metric:a.meta.lastTestedAt?`validado há ${cc(a.meta.ageMinutes)}`:null,testid:"signal-meta-token"}),e.jsx(Ml,{title:"Webhook Stripe",status:a.stripe.status,Icon:Bt,message:a.stripe.message,metric:`${a.stripe.eventsLast24h} eventos/24h${a.stripe.lastReceivedAt?` · ${cc(a.stripe.ageMinutes)}`:""}`,testid:"signal-stripe-webhook"}),e.jsx(Ml,{title:"Conversões hoje",status:a.conversion.status,Icon:be,message:a.conversion.message,metric:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[a.conversion.todayCount," hoje · média 7d ",a.conversion.baseline7dDaily.toFixed(1)," ",p(a.conversion.deltaPct)," ",g(a.conversion.deltaPct)]}),testid:"signal-conversion"}),e.jsx(Ml,{title:"Receita real hoje",status:a.traffic.status,Icon:Ie,message:a.traffic.message,metric:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[ah(a.traffic.todayRevenueBrl)," · média 7d ",ah(a.traffic.baseline7dDailyBrl)," ",p(a.traffic.deltaPct)," ",g(a.traffic.deltaPct)]}),testid:"signal-revenue"})]}
2),e.jsx("div",{className:"text-[10px] text-muted-foreground/70 text-right",children:"Receita filtra apenas dinheiro real (PIX/cartão) — pedidos pagos com créditos não contam."})]})}const ih=a=>a.toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),Sg=a=>a<60?`${Math.round(a)} min`:a<1440?`${Math.floor(a/60)}h`:`${Math.floor(a/1440)}d`;function $g(){const{data:a,isLoading:r,refetch:l,isFetching:n}=z({queryKey:["/api/admin/credits/stripe-pending"],refetchInterval:12e4,staleTime:6e4}),u=a?.pending||[],f=d.useMemo(()=>u.reduce((j,p)=>j+(typeof p.amount=="number"?p.amount:0),0),[u]);return r?e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/20 p-4 flex items-center gap-2 text-xs text-muted-foreground","data-testid":"card-stripe-pending-loading",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"})," Verificando compras de crédito Stripe pendentes..."]}):u.length===0?e.jsxs("div",{className:"rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-4 flex items-center justify-between gap-3","data-testid":"card-stripe-pending-clean",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-500/15 flex items-center justify-center shrink-0",children:e.jsx(be,{className:"w-4 h-4 text-emerald-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:"Compras Stripe saudáveis"}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:["Nenhuma compra de crédito por cartão presa há mais de ",a?.minAgeMin||10,"min nas últimas ",a?.sinceHours||168,"h"]})]})]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"text-[11px] h-8",onClick:()=>l(),disabled:n,"data-testid":"button-refresh-stripe-pending-clean",children:[n?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Re-verificar"})]})]}):e.jsxs("div",{className:"rounded-xl border border-rose-500/30 bg-gradient-to-br from-rose-500/10 via-pink-500/5 to-red-500/5 p-4 md:p-5 space-y-3","data-testid":"card-stripe-pending-alert",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-rose-500/20 flex items-center justify-center shrink-0",children:e.jsx(Ce,{className:"w-5 h-5 text-rose-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm md:text-base font-bold text-white flex items-center gap-2 flex-wrap",children:["Compras de crédito por CARTÃO presas em pending",e.jsxs(E,{className:"bg-rose-500/20 text-rose-200 border-rose-500/30 text-[10px]",children:[u.length," ",u.length===1?"pedido":"pedidos"]}),e.jsxs(E,{className:"bg-red-500/20 text-red-200 border-red-500/30 text-[10px]",children:[ih(f)," em risco"]})]}),e.jsx("div",{className:"text-[11px] md:text-xs text-rose-100/80 mt-0.5",children:"Cliente pagou no cartão mas créditos não foram entregues. Investigue no Stripe Dashboard (PI id) e use fulfill manual no dossiê. Sem ação automática neste card."})]})]}),e.jsx("div",{className:"flex gap-2 shrink-0",children:e.jsxs(b,{size:"sm",variant:"outline",className:"border-rose-500/30 hover:bg-rose-500/10 text-rose-100 h-8 text-[11px]",onClick:()=>l(),disabled:n,"data-testid":"button-refresh-stripe-pending",children:[n?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5 hidden sm:inline",children:"Atualizar"})]})})]}),e.jsx("div",{className:"space-y-2",children:u.map(j=>e.jsxs("div",{className:"rounded-lg border border-rose-500/20 bg-black/30 p-3 flex flex-col md:flex-row md:items-center md:justify-between gap-2 md:gap-3","data-testid":`row-stripe-pending-${j.id}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm text-white font-medium truncate","data-testid":`text-stripe-pending-email-${j.id}`,children:[j.userEmail||"—",j.userName&&e.jsx("span",{className:"text-muted-foreground font-normal text-[11px] ml-2",children:j.userName})]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-0.5 mt-0.5",children:[e.jsxs("span",{className:"font-mono",children:[j.id.slice(0,12),"…"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:j.paymentMethod||"card"}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[Sg(j.ageMinutes)," atrás"]}),j.stripePaymentIntentId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{className:"font-mono text-rose-200/80",children:[j.stripePaymentIntentId.slice(0,14),"…"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 md:shrink-0 flex-wrap",children:[e.jsx("div",{className:"text-sm font-bold text-emerald-400 tabular-nums","data-testid":`text-stripe-pending-amount-${j.id}`,children:ih(j.amount)}),j.stripePaymentIntentId&&e.jsx("a",{href:`https://dashboard.stripe.com/payments/${j.stripePaymentIntentId}`,target:"_blank",rel:"noopener noreferrer","data-testid":`link-stripe-dashboard-${j.id}`,children:e.jsxs(b,{size:"sm",variant:"outline",className:"border-rose-500/30 hover:bg-rose-500/10 text-rose-100 h-8 text-[11px]",children:[e.jsx(vs,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Stripe"})]})}),e.jsx("a",{href:`/admin?tab=users&user=${j.userId}`,"data-testid":`link-user-dossier-${j.id}`,children:e.jsxs(b,{size:"sm",className:"bg-emerald-500 hover:bg-emerald-600 text-black font-semibold h-8 text-[11px]",children:[e.jsx(Hi,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Dossiê"})]})})]})]},j.id))})]})}const Ag={no_cover_selected:"sem capa selecionada",resolve_failed:"falha ao buscar a capa real",adjust_failed:"ajuste de capa quebrou",svg_fallback_used:"placeholder SVG entregue",sharp_failed:"renderização falhou",unexpected_error:"erro inesperado"},Pg=a=>{const r=Math.floor((Date.now()-new Date(a).getTime())/6e4);return r<60?`${Math.max(1,r)} min`:r<1440?`${Math.floor(r/60)}h`:`${Math.floor(r/1440)}d`};function Tg(){const{data:a,isLoading:r,refetch:l,isFetching:n}=z({queryKey:["/api/admin/cover-fallback/events","?sinceHours=168"],queryFn:async()=>{const y=await fetch("/api/admin/cover-fallback/events?sinceHours=168",{credentials:"include"});if(!y.ok)throw new Error("falha");return y.json()},refetchInterval:18e4,staleTime:6e4}),f=(a?.events||[]).filter(y=>y.severity==="incident"),j=(a?.stats?.incidents??f.length)>0,p=a?.stats?.incidents??f.length,g=a?.stats?.uniqueIncidentBooks??new Set(f.map(y=>y.bookId)).size,w=a?.stats?.uniqueBenignBooks??0;return r?e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/20 p-4 flex items-center gap-2 text-xs text-muted-foreground","data-testid":"card-cover-fallback-loading",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}
2)," Verificando exports com capa placeholder..."]}):j?e.jsxs("div",{className:"rounded-xl border border-amber-500/30 bg-gradient-to-br from-amber-500/10 via-yellow-500/5 to-orange-500/5 p-4 md:p-5 space-y-3","data-testid":"card-cover-fallback-alert",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-amber-500/20 flex items-center justify-center shrink-0",children:e.jsx(Xe,{className:"w-5 h-5 text-amber-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm md:text-base font-bold text-white flex items-center gap-2 flex-wrap",children:["Cliente pagou por capa e recebeu placeholder",e.jsxs(E,{className:"bg-amber-500/20 text-amber-200 border-amber-500/30 text-[10px]",children:[p," ",p===1?"evento":"eventos"]}),g>0&&e.jsxs(E,{className:"bg-yellow-500/20 text-yellow-200 border-yellow-500/30 text-[10px]",children:[g," ",g===1?"livro":"livros"]})]}),e.jsxs("div",{className:"text-[11px] md:text-xs text-amber-100/80 mt-0.5",children:["Estes livros têm capa comprada (ou capa real que falhou ao renderizar), mas o PDF/DOCX saiu com o cartão genérico. Abra o livro no editor pra re-disparar a geração.",w>0&&e.jsxs("span",{className:"text-amber-100/50",children:[" ","(",w," ",w===1?"livro":"livros"," sem capa comprada não ",w===1?"conta":"contam"," — placeholder esperado.)"]})]})]})]}),e.jsx("div",{className:"flex gap-2 shrink-0",children:e.jsxs(b,{size:"sm",variant:"outline",className:"border-amber-500/30 hover:bg-amber-500/10 text-amber-100 h-8 text-[11px]",onClick:()=>l(),disabled:n,"data-testid":"button-refresh-cover-fallback",children:[n?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5 hidden sm:inline",children:"Atualizar"})]})})]}),e.jsx("div",{className:"space-y-2",children:f.map((y,F)=>e.jsxs("div",{className:"rounded-lg border border-amber-500/20 bg-black/30 p-3 flex flex-col md:flex-row md:items-center md:justify-between gap-2 md:gap-3","data-testid":`row-cover-fallback-${y.bookId}-${F}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm text-white font-medium truncate","data-testid":`text-cover-fallback-title-${y.bookId}-${F}`,children:[y.bookTitle||"(sem título)",y.bookAuthor&&e.jsx("span",{className:"text-muted-foreground font-normal text-[11px] ml-2",children:y.bookAuthor})]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-0.5 mt-0.5",children:[e.jsxs("span",{className:"font-mono",children:[y.bookId.slice(0,12),"…"]}),e.jsx("span",{children:"·"}),e.jsx("span",{className:"uppercase tracking-wide text-amber-200/80",children:Ag[y.reason]||y.reason}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[Pg(y.occurredAt)," atrás"]}),y.detail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{className:"italic truncate max-w-[300px]",title:y.detail,children:y.detail})]})]})]}),e.jsx("div",{className:"flex items-center gap-3 md:shrink-0",children:e.jsx("a",{href:`/livro/${y.bookId}`,"data-testid":`link-cover-fallback-book-${y.bookId}-${F}`,children:e.jsxs(b,{size:"sm",className:"bg-amber-500 hover:bg-amber-600 text-black font-semibold h-8 text-[11px]",children:[e.jsx(ot,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Abrir livro"})]})})})]},`${y.bookId}-${y.occurredAt}-${F}`))})]}):e.jsxs("div",{className:"rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-4 flex items-center justify-between gap-3","data-testid":"card-cover-fallback-clean",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-500/15 flex items-center justify-center shrink-0",children:e.jsx(be,{className:"w-4 h-4 text-emerald-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:"Capas de exportação saudáveis"}),e.jsx("div",{className:"text-[11px] text-muted-foreground truncate","data-testid":"text-cover-fallback-clean-detail",children:w>0?e.jsxs(e.Fragment,{children:["Nenhum cliente que comprou capa ficou sem ela nas últimas ",a?.sinceHours||168,"h."," ",e.jsxs("span",{className:"text-emerald-300/70",children:[w," ",w===1?"livro":"livros"," sem capa comprada"]})," ","usaram o cartão genérico (esperado — capa é um serviço à parte)."]}):e.jsxs(e.Fragment,{children:["Nenhum PDF/DOCX caiu em placeholder nas últimas ",a?.sinceHours||168,"h (buffer em memória, zera no restart)"]})})]})]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"text-[11px] h-8",onClick:()=>l(),disabled:n,"data-testid":"button-refresh-cover-fallback-clean",children:[n?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5",children:"Re-verificar"})]})]})}const Eg=Q0("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),yc=d.forwardRef(({className:a,variant:r,...l},n)=>e.jsx("div",{ref:n,role:"alert",className:_a(Eg({variant:r}),a),...l}));yc.displayName="Alert";const kc=d.forwardRef(({className:a,...r},l)=>e.jsx("h5",{ref:l,className:_a("mb-1 font-medium leading-none tracking-tight",a),...r}));kc.displayName="AlertTitle";const Cc=d.forwardRef(({className:a,...r},l)=>e.jsx("div",{ref:l,className:_a("text-sm [&_p]:leading-relaxed",a),...r}));Cc.displayName="AlertDescription";function Ig(){const{data:a,isLoading:r}=z({queryKey:["/api/admin/ads-automation/status"],refetchInterval:3e4});if(r||!a)return e.jsxs(je,{"data-testid":"card-ads-automation-status",children:[e.jsx(Fe,{children:e.jsx(De,{className:"text-sm",children:"Status das Automações de Anúncios"})}),e.jsx(ve,{className:"text-sm text-muted-foreground",children:"Carregando…"})]});const l=a.summary.fullyLocked;return e.jsxs(je,{"data-testid":"card-ads-automation-status",className:l?"border-emerald-500/40 bg-emerald-500/5":"border-amber-500/40 bg-amber-500/5",children:[e.jsx(Fe,{className:"pb-3",children:e.jsxs(De,{className:"text-base flex items-center gap-2",children:[l?e.jsx(bh,{className:"w-5 h-5 text-emerald-600"}):e.jsx(Ks,{className:"w-5 h-5 text-amber-600"}),"Modo Manual de Anúncios",e.jsx(E,{variant:l?"default":"destructive",className:l?"bg-emerald-600 hover:bg-emerald-700":"","data-testid":"badge-automation-mode",children:l?"TRAVADO":"PARCIAL"})]})}),e.jsxs(ve,{className:"space-y-4",children:[l?e.jsxs(yc,{className:"border-emerald-500/40 bg-emerald-500/10",children:[e.jsx(W0,{className:"h-4 w-4 text-emerald-600"}),e.jsx(kc,{className:"text-emerald-700 dark:text-emerald-400",children:"Nenhuma criação automática de anúncios está ativa"}),e.jsx(Cc,{className:"text-xs text-muted-foreground mt-1",children:"IA, otimizador e orquestração bloqueados. Ape
2nas uploads e ajustes manuais funcionam. Tentativas de criação automática são registradas e bloqueadas no servidor."})]}):e.jsxs(yc,{variant:"destructive",children:[e.jsx(Ce,{className:"h-4 w-4"}),e.jsx(kc,{children:"Há automações ativas"}),e.jsx(Cc,{className:"text-xs mt-1",children:"Verifique os toggles abaixo. Para travar tudo, mantenha a variável ADS_AUTOMATION_HARD_DISABLED=true e desabilite todos os workers."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs",children:[e.jsx(Ll,{label:"Trava global (env)",on:a.guard.hardDisabled,invert:!0}),e.jsx(Ll,{label:"Auto-Campaign Config",on:!!a.autoCampaignConfig?.isEnabled,invert:!0}),e.jsx(Ll,{label:"Orquestração IA",on:!!a.orchestrationConfig?.enableOrchestration,invert:!0}),a.workerToggles.map(n=>e.jsx(Ll,{label:n.workerName,on:n.enabled,invert:!0},n.workerName))]}),a.recentBlockedAttempts.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs font-semibold mb-2 text-muted-foreground",children:["Últimas tentativas automáticas bloqueadas (",a.recentBlockedAttempts.length,")"]}),e.jsx("div",{className:"space-y-1 max-h-40 overflow-y-auto",children:a.recentBlockedAttempts.slice(0,8).map(n=>e.jsxs("div",{className:"text-[11px] bg-background/60 border rounded px-2 py-1","data-testid":`row-blocked-${n.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:n.title}),e.jsx("span",{className:"text-muted-foreground shrink-0",children:new Date(n.createdAt).toLocaleString("pt-BR")})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:n.message})]},n.id))})]})]})]})}function Ll({label:a,on:r,invert:l}){const n=l?!r:r;return e.jsxs("div",{className:"flex items-center justify-between bg-background/60 rounded border px-2 py-1.5",children:[e.jsx("span",{className:"truncate",children:a}),e.jsx(E,{variant:"outline",className:n?"border-emerald-500/40 text-emerald-700 dark:text-emerald-400":"border-amber-500/40 text-amber-700 dark:text-amber-400",children:r?"ON":"OFF"})]})}const Rg={Indicação:"bg-violet-500","Meta Ads":"bg-blue-500","Google Ads":"bg-amber-500","TikTok Ads":"bg-pink-500",Email:"bg-emerald-500","Outro Pago":"bg-orange-500","Orgânico (Referrer)":"bg-cyan-500","Direto / Orgânico":"bg-slate-400"},Fg={Indicação:Wl,"Meta Ads":Xt,"Google Ads":pt,"TikTok Ads":Pc,Email:Ge};function zl({label:a,value:r,sub:l,color:n,testId:u}){return e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 p-4","data-testid":u,children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1","data-testid":u?`${u}-label`:void 0,children:a}),e.jsx("p",{className:`text-2xl font-bold ${n||"text-white"}`,"data-testid":u?`${u}-value`:void 0,children:r}),l&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:l})]})}function Dg({activeAdminTab:a}){const[r,l]=d.useState("30d"),[n,u]=d.useState(""),[f,j]=d.useState(null),[p,g]=d.useState("overview"),w=()=>{if(r==="all")return{};const S=r==="7d"?7:r==="30d"?30:90,re=new Date;return re.setDate(re.getDate()-S),{startDate:re.toISOString()}},{data:y,isLoading:F}=z({queryKey:["/api/admin/origins-dashboard",r],queryFn:async()=>{const S=w(),re=new URLSearchParams(S).toString();return(await N("GET",`/api/admin/origins-dashboard${re?"?"+re:""}`)).json()},enabled:a==="origins",refetchInterval:6e4});if(F||!y)return e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full"})});const{channelBreakdown:c,topReferrers:m,campaignPerformance:$,recentUsers:D,funnelStats:A,dailySignups:o}=y,L=Number(A.total_users||0),v=Number(A.from_referral||0),I=Number(A.with_purchase||0),de=Number(A.total_revenue||0),me=L>0?(I/L*100).toFixed(1):"0",ne=c.reduce((S,re)=>S+Number(re.user_count),0),Z=D.filter(S=>!n||(S.name||"").toLowerCase().includes(n.toLowerCase())||(S.email||"").toLowerCase().includes(n.toLowerCase())||(S.origin_label||"").toLowerCase().includes(n.toLowerCase()));return 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-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-white","data-testid":"text-origins-title",children:"Origens dos Clientes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"De onde vêm seus clientes e onde investir mais"})]}),e.jsx("div",{className:"flex gap-1.5 bg-white/5 rounded-lg p-1 border border-white/10",children:["7d","30d","90d","all"].map(S=>e.jsx("button",{onClick:()=>l(S),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-all ${r===S?"bg-primary text-black":"text-muted-foreground hover:text-white"}`,"data-testid":`button-range-${S}`,children:S==="all"?"Tudo":S==="7d"?"7 dias":S==="30d"?"30 dias":"90 dias"},S))})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsx(zl,{label:"Total de Clientes",value:L,testId:"metric-origins-total"}),e.jsx(zl,{label:"Via Indicação",value:v,sub:L>0?`${(v/L*100).toFixed(0)}% do total`:"",color:"text-violet-400",testId:"metric-origins-referral"}),e.jsx(zl,{label:"Compraram",value:I,sub:`${me}% conversão`,color:"text-emerald-400",testId:"metric-origins-purchased"}),e.jsx(zl,{label:"Receita Total",value:`R$ ${de.toFixed(2)}`,color:"text-emerald-400",testId:"metric-origins-revenue"})]}),e.jsx("div",{className:"flex gap-1.5 bg-white/5 rounded-lg p-1 border border-white/10 w-fit",children:[{key:"overview",label:"Visão Geral"},{key:"referrers",label:"Indicadores"},{key:"campaigns",label:"Campanhas"},{key:"users",label:"Clientes"}].map(S=>e.jsx("button",{onClick:()=>g(S.key),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-all ${p===S.key?"bg-white/10 text-white":"text-muted-foreground hover:text-white"}`,"data-testid":`button-subtab-${S.key}`,children:S.label},S.key))}),p==="overview"&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 p-5",children:[e.jsx("h3",{className:"text-sm font-semibold text-white mb-4",children:"Canais de Aquisição"}),e.jsxs("div",{className:"space-y-3",children:[c.map(S=>{const re=Number(S.user_count),_=ne>0?re/ne*100:0,ee=Number(S.revenue||0),h=Number(S.conversions||0),te=Fg[S.channel]||lt;return e.jsxs("div",{"data-testid":`row-channel-${S.channel}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{className:"w-3.5 h-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-white font-medium",children:S.channel})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[re," clientes"]}),e.jsxs("span",{className:"text-emerald-400 font-medium",children:["R$ ",ee.toFixed(0)]}),e.jsxs(E,{variant:"outline",className:"text-[10px] h-5 px-1.5",children:[_.toFixed(0),"%"]})]})]}),e.jsx("div",{className:"w-full bg-white/5 rounded-full h-2",children:e.jsx("div",{className:`h-2 rounded-full transition-all duration-500 ${Rg[S.channel]||"bg-slate-500"}`,style:{width:`${Math.max(_,2)}%`}})}),h>0&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[h," vendas • ticket médio R$ ",(ee/h).toFixed(0)]})]},S.channel)}),c.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Nenhum dado disponível no período"})]})]}),e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 p-5",children:[e.jsx("h3",{className:"text-sm font-semibold text-white mb-4",children:"Cadastros por Dia"}),e.jsx("div",{className:"space-y-1.5",children:o.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-col gap-1",children:o.slice(-14).map(S=>{const re=Number(S.signups),_=Number(S.from_referral||0),ee=Math.max(...o.map(ae=>Number(ae.signups)),1),h=re/ee*100,te=re>0?_/re*h:0,M=new Date(S.signup_date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});return e.jsxs("div",{className:"flex items-center gap-2 group","data-testid":`row-daily-${S.signup_date}`,children:[e.jsx("span",{className:"text-[10px] text-muted-foreground w-10 shrink-0",children:M}),e.jsxs("div",{className:"flex-1 flex h-4 bg-white/5 rounded overflow-hidden",children:[e.jsx("div",{className:"bg-primary/60 h-full transition-all",style:{width:`${Math.max(h-te,0)}%`}}),e.jsx("div",{className:"bg-violet-500/80 h-full transition-all",style:{width:`${te}%`}})]}),e.jsx("span",{className:"text-[10px] text-white font-medium w-6 text-right",children:re})]},S.signup_date)})}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-[10px] text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-sm bg-primary/60"})," Outros"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-sm bg-violet-500/80"})," Indicação"]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Sem dados no período"})})]})]}),p==="referrers"&&e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 p-5",children:[e.jsx("h3",{className:"text-sm font-semibold text-white mb-4",children:"Top Indicadores"}),m.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Nenhuma indicação registrada no período"}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-2 text-[10px] font-medium text-muted-foreground uppercase tracking-wider px-3 pb-2 border-b border-white/5",children:[e.jsx("div",{className:"col-span-4",children:"Indicador"}),e.jsx("div",{className:"col-span-2 text-center",children:"Indicados"}),e.jsx("div",{className:"col-span-2 text-center",children:"Convertidos"}),e.jsx("div",{className:"col-span-2 text-center",children:"Créditos"}),e.jsx("div",{className:"col-span-2 text-right",children:"Receita Gerada"})]}),m.map((S,re)=>{const _=Number(S.total_referred),ee=Number(S.converted),h=Number(S.total_credits_awarded),te=Number(S.referred_revenue||0),M=_>0?(ee/_*100).toFixed(0):"0",ae=f===S.referrer_id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>j(ae?null:S.referrer_id),className:"w-full grid grid-cols-12 gap-2 items-center px-3 py-2.5 rounded-lg hover:bg-white/5 transition-colors text-left","data-testid":`row-referrer-${S.referrer_id}`,children:[e.jsxs("div",{className:"col-span-4 flex items-center gap-2",children:[e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold ${re<3?"bg-amber-500/20 text-amber-400":"bg-white/10 text-muted-foreground"}`,children:re+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm text-white font-medium truncate",children:S.referrer_name||"Sem nome"}),e.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:S.referral_code})]})]}),e.jsx("div",{className:"col-span-2 text-center",children:e.jsx("span",{className:"text-sm font-semibold text-white",children:_})}),e.jsxs("div",{className:"col-span-2 text-center",children:[e.jsx("span",{className:"text-sm font-semibold text-emerald-400",children:ee}),e.jsxs("span",{className:"text-[10px] text-muted-foreground ml-1",children:["(",M,"%)"]})]}),e.jsx("div",{className:"col-span-2 text-center",children:e.jsx("span",{className:"text-sm text-amber-400",children:h.toLocaleStr
2ing()})}),e.jsxs("div",{className:"col-span-2 text-right flex items-center justify-end gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-emerald-400",children:["R$ ",te.toFixed(0)]}),ae?e.jsx(ta,{className:"w-3 h-3 text-muted-foreground"}):e.jsx(Ct,{className:"w-3 h-3 text-muted-foreground"})]})]}),ae&&e.jsxs("div",{className:"ml-10 mr-3 mb-2 p-3 rounded-lg bg-white/[0.02] border border-white/5 text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:["Email: ",e.jsx("span",{className:"text-white",children:S.referrer_email})]}),e.jsxs("p",{children:["Link: ",e.jsxs("span",{className:"text-primary font-mono",children:["sabhia.ai/?ref=",S.referral_code]})]}),e.jsxs("p",{children:["Taxa de conversão: ",e.jsxs("span",{className:"text-white",children:[M,"%"]})," dos indicados compraram"]}),e.jsxs("p",{children:["Receita gerada pelos indicados: ",e.jsxs("span",{className:"text-emerald-400",children:["R$ ",te.toFixed(2)]})]})]})]},S.referrer_id)})]})]}),p==="campaigns"&&e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 p-5",children:[e.jsx("h3",{className:"text-sm font-semibold text-white mb-4",children:"Performance por Campanha UTM"}),$.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Nenhuma campanha com vendas no período"}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider border-b border-white/5",children:[e.jsx("th",{className:"text-left py-2 px-2",children:"Campanha"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Fonte"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Meio"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Conteúdo"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Vendas"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Compradores"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Receita"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Ticket Médio"})]})}),e.jsx("tbody",{children:$.map((S,re)=>e.jsxs("tr",{className:"border-b border-white/[0.03] hover:bg-white/[0.02]","data-testid":`row-campaign-${re}`,children:[e.jsx("td",{className:"py-2.5 px-2",children:e.jsx("span",{className:"text-white font-medium",children:S.campaign})}),e.jsx("td",{className:"py-2.5 px-2",children:e.jsx(E,{variant:"outline",className:"text-[10px] h-5",children:S.source})}),e.jsx("td",{className:"py-2.5 px-2 text-muted-foreground",children:S.medium}),e.jsx("td",{className:"py-2.5 px-2 text-muted-foreground text-xs truncate max-w-[120px]",children:S.content}),e.jsx("td",{className:"py-2.5 px-2 text-center text-white font-medium",children:Number(S.orders_count)}),e.jsx("td",{className:"py-2.5 px-2 text-center text-muted-foreground",children:Number(S.unique_buyers)}),e.jsxs("td",{className:"py-2.5 px-2 text-right text-emerald-400 font-semibold",children:["R$ ",Number(S.revenue).toFixed(2)]}),e.jsxs("td",{className:"py-2.5 px-2 text-right text-muted-foreground",children:["R$ ",Number(S.avg_ticket).toFixed(2)]})]},re))})]})})]}),p==="users"&&e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Clientes Recentes e suas Origens"}),e.jsxs("div",{className:"relative w-60",children:[e.jsx(St,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground"}),e.jsx(J,{placeholder:"Buscar por nome, email...",value:n,onChange:S=>u(S.target.value),className:"h-8 pl-8 text-xs bg-white/5 border-white/10","data-testid":"input-search-users"})]})]}),e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider border-b border-white/5",children:[e.jsx("th",{className:"text-left py-2 px-2",children:"Cliente"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Origem"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Campanha"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Indicado por"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Compras"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Gasto Total"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Cadastro"})]})}),e.jsx("tbody",{children:Z.map(S=>
2{const re=S.referred_by?"text-violet-400 bg-violet-500/10":S.first_utm_source?"text-blue-400 bg-blue-500/10":"text-slate-400 bg-white/5";return e.jsxs("tr",{className:"border-b border-white/[0.03] hover:bg-white/[0.02]","data-testid":`row-user-${S.id}`,children:[e.jsxs("td",{className:"py-2.5 px-2",children:[e.jsx("p",{className:"text-white font-medium text-xs",children:S.name||"Sem nome"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:S.email})]}),e.jsx("td",{className:"py-2.5 px-2",children:e.jsx(E,{className:`text-[10px] h-5 ${re} border-0`,children:S.origin_label})}),e.jsx("td",{className:"py-2.5 px-2 text-muted-foreground text-xs truncate max-w-[120px]",children:S.first_utm_campaign||"-"}),e.jsx("td",{className:"py-2.5 px-2",children:S.referred_by?e.jsx("span",{className:"text-xs text-violet-400 font-mono",children:S.referred_by}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"-"})}),e.jsx("td",{className:"py-2.5 px-2 text-center text-white",children:Number(S.order_count)}),e.jsx("td",{className:"py-2.5 px-2 text-right",children:Number(S.total_spent)>0?e.jsxs("span",{className:"text-emerald-400 font-medium",children:["R$ ",Number(S.total_spent).toFixed(2)]}):e.jsx("span",{className:"text-muted-foreground",children:"R$ 0"})}),e.jsx("td",{className:"py-2.5 px-2 text-right text-xs text-muted-foreground",children:S.created_at?new Date(S.created_at).toLocaleDateString("pt-BR"):"-"})]},S.id)})})]}),Z.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Nenhum cliente encontrado"})]})]}),e.jsx("div",{className:"glass-card rounded-xl border border-white/10 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Ie,{className:"w-4 h-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-white mb-1",children:"Insights de Investimento"}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[c.length>0&&(()=>{const S=[...c].sort((ee,h)=>{const te=Number(ee.conversions)>0?Number(ee.revenue)/Number(ee.user_count):0;return(Number(h.conversions)>0?Number(h.revenue)/Number(h.user_count):0)-te})[0],re=Number(S?.conversions)>0?Number(S.revenue)/Number(S.user_count):0,_=[...c].sort((ee,h)=>Number(h.user_count)-Number(ee.user_count))[0];return e.jsxs(e.Fragment,{children:[re>0&&e.jsxs("p",{className:"flex items-start gap-1.5",children:[e.jsx($r,{className:"w-3 h-3 text-emerald-400 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Melhor retorno por cliente: ",e.jsx("span",{className:"text-white font-medium",children:S.channel})," — R$ ",re.toFixed(2)," por cliente"]})]}),e.jsxs("p",{className:"flex items-start gap-1.5",children:[e.jsx(Re,{className:"w-3 h-3 text-blue-400 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Maior volume: ",e.jsx("span",{className:"text-white font-medium",children:_.channel})," — ",Number(_.user_count)," clientes (",(Number(_.user_count)/ne*100).toFixed(0),"%)"]})]}),v>0&&e.jsxs("p",{className:"flex items-start gap-1.5",children:[e.jsx(Wl,{className:"w-3 h-3 text-violet-400 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Indicações representam ",e.jsxs("span",{className:"text-white font-medium",children:[(v/L*100).toFixed(0),"%"]})," dos clientes — custo zero de aquisição"]})]})]})})(),c.length===0&&e.jsx("p",{children:"Dados insuficientes para gerar insights"})]})]})]})})]})}const Th={"Meta Ads":"from-blue-500/20 to-blue-600/10 border-blue-500/30","Google Ads":"from-amber-500/20 to-amber-600/10 border-amber-500/30","Google Orgânico":"from-emerald-500/20 to-emerald-600/10 border-emerald-500/30","Instagram Orgânico":"from-pink-500/20 to-pink-600/10 border-pink-500/30","Facebook Orgânico":"from-indigo-500/20 to-indigo-600/10 border-indigo-500/30","TikTok Ads":"from-rose-500/20 to-rose-600/10 border-rose-500/30",Email:"from-teal-500/20 to-teal-600/10 border-teal-500/30","Email (Webmail)":"from-teal-400/20 to-teal-500/10 border-teal-400/30","Chat IA":"from-violet-500/20 to-violet-600/10 border-violet-500/30","Landing Page":"from-cyan-500/20 to-cyan-600/10 border-cyan-500/30",Blog:"from-lime-500/20 to-lime-600/10 border-lime-500/30",Indicação:"from-purple-500/20 to-purple-600/10 border-purple-500/30","Indicação Link":"from-purple-400/20 to-purple-500/10 border-purple-400/30","Prospecção de Autores":"from-fuchsia-500/20 to-fuchsia-600/10 border-fuchsia-500/30","Outro Pago":"from-orange-500/20 to-orange-600/10 border-orange-500/30","Outro Orgânico":"from-slate-400/20 to-slate-500/10 border-slate-400/30",Bing:"from-sky-500/20 to-sky-600/10 border-sky-500/30",Yahoo:"from-violet-400/20 to-violet-500/10 border-violet-400/30",Direto:"from-zinc-500/20 to-zinc-600/10 border-zinc-500/30"},vn={"Meta Ads":"bg-blue-500","Google Ads":"bg-amber-500","Google Orgânico":"bg-emerald-500","Instagram Orgânico":"bg-pink-500","Facebook Orgânico":"bg-indigo-500","TikTok Ads":"bg-rose-500",Email:"bg-teal-500","Email (Webmail)":"bg-teal-400","Chat IA":"bg-violet-500","Landing Page":"bg-cyan-500",Blog:"bg-lime-500",Indicação:"bg-purple-500","Indicação Link":"bg-purple-400","Prospecção de Autores":"bg-fuchsia-500","Outro Pago":"bg-orange-500","Outro Orgânico":"bg-slate-400",Bing:"bg-sky-500",Yahoo:"bg-violet-400",Direto:"bg-zinc-500"},Mg={"Meta Ads":Xt,"Google Ads":pt,"Google Orgânico":St,"Instagram Orgânico":Xt,"Facebook Orgânico":pt,"TikTok Ads":Pc,Email:Ge,"Email (Webmail)":Ge,"Chat IA":lt,"Landing Page":Nh,Blog:Ka,Indicação:Wl,"Indicação Link":Wl,"Prospecção de Autores":Re,"Outro Pago":nt,"Outro Orgânico":vs,Bing:pt,Yahoo:pt,Direto:ht};
2function Ys(a){const r=typeof a=="string"?parseFloat(a):a;return isNaN(r)?"R$ 0,00":`R$ ${r.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function hn({label:a,value:r,sub:l,icon:n,color:u="text-white",testId:f}){return e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 p-4 hover:border-white/20 transition-all","data-testid":f,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n&&e.jsx(n,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]}),e.jsx("p",{className:`text-2xl font-bold ${u}`,"data-testid":f?`${f}-value`:void 0,children:r}),l&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:l})]})}function Lg({channel:a,revenue:r,totalRevenue:l,orderCount:n,uniqueBuyers:u,avgTicket:f}){const j=l>0?r/l*100:0,p=Th[a]||"from-zinc-500/20 to-zinc-600/10 border-zinc-500/30",g=vn[a]||"bg-zinc-500",w=Mg[a]||pt;return e.jsxs("div",{className:`rounded-xl border bg-gradient-to-r ${p} p-4 transition-all hover:scale-[1.01]`,"data-testid":`channel-bar-${a}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${g}`}),e.jsx(w,{className:"w-4 h-4 text-white/60"}),e.jsx("span",{className:"font-semibold text-white text-sm",children:a}),e.jsxs(E,{variant:"secondary",className:"text-[10px] px-1.5 py-0 h-4",children:[j.toFixed(1),"%"]})]}),e.jsx("span",{className:"text-lg font-bold text-white",children:Ys(r)})]}),e.jsx("div",{className:"w-full bg-white/5 rounded-full h-2 mb-2",children:e.jsx("div",{className:`h-2 rounded-full ${g} transition-all duration-700`,style:{width:`${Math.max(j,1)}%`}})}),e.jsxs("div",{className:"flex gap-4 text-xs text-white/50",children:[e.jsxs("span",{children:[e.jsx(Jt,{className:"w-3 h-3 inline mr-1"}),n," vendas"]}),e.jsxs("span",{children:[e.jsx(Re,{className:"w-3 h-3 inline mr-1"}),u," compradores"]}),e.jsxs("span",{children:[e.jsx(nt,{className:"w-3 h-3 inline mr-1"}),"Ticket: ",Ys(f)]})]})]})}function zg({activeAdminTab:a}){const[r,l]=d.useState("30d"),[n,u]=d.useState("channels"),[f,j]=d.useState(""),[p,g]=d.useState(null),[w,y]=d.useState("24"),[F,c]=d.useState(!1),{toast:m}=st(),$=Number(w),D=$===24?"24h":$===168?"7 dias":"30 dias",{data:A,isLoading:o,refetch:L}=z({queryKey:["/api/admin/sales-attribution",r],queryFn:async()=>(await N("GET",`/api/admin/sales-attribution?period=${r}`)).json(),enabled:a==="sales-attribution",refetchInterval:6e4}),{data:v,refetch:I}=z({queryKey:["/api/admin/meta-capi/health"],queryFn:async()=>(await N("GET","/api/admin/meta-capi/health")).json(),enabled:a==="sales-attribution",refetchInterval:6e4}),de=W({mutationFn:async()=>(await N("POST","/api/admin/orders/reattribute")).json(),onSuccess:h=>{m({title:"Reatribuição concluída",description:`${h.updated}/${h.total} pedidos atualizados.`}),K.invalidateQueries({queryKey:["/api/admin/sales-attribution"]})},onError:()=>{m({title:"Erro",description:"Falha ao reatribuir pedidos.",variant:"destructive"})}}),me=W({mutationFn:async({orderId:h,dryRun:te})=>(await N("POST","/api/admin/meta-capi/replay",{orderIds:[h],dryRun:!!te})).json(),onSuccess:(h,te)=>{const M=h?.results?.[0];M?.success&&!M?.skipped?m({title:te.dryRun?"Simulação OK":"Reenviado para Meta",description:`eventId: ${M.eventId}`}):M?.skipped?m({title:"Pulado",description:M.skipped}):m({title:"Falha ao reenviar",description:M?.error||"Erro desconhecido",variant:"destructive"}),I()},onError:()=>{m({title:"Erro",description:"Falha ao chamar reenvio.",variant:"destructive"})}}),ne=W({mutationFn:async({sinceHours:h,dryRun:te})=>(await N("POST","/api/admin/meta-capi/replay",{sinceHours:h,onlyMissing:!0,limit:100,dryRun:!!te})).json(),onSuccess:(h,te)=>{m({title:te.dryRun?"Simulação concluída":"Reenvio concluído",description:`${h.success||0} ok · ${h.skipped||0} pulados · ${h.failed||0} falhas (de ${h.total||0})`}),I()},onError:()=>{m({title:"Erro",description:"Falha ao reenviar pedidos sem Purchase.",variant:"destructive"})}}),Z=A?.totals||{},S=parseFloat(Z.total_revenue||"0"),re=Z.total_orders>0?(Z.attributed_orders/Z.total_orders*100).toFixed(1):"0",_=d.useMemo(()=>
2{if(!A?.recentSales)return[];if(!f)return A.recentSales;const h=f.toLowerCase();return A.recentSales.filter(te=>(te.email||"").toLowerCase().includes(h)||(te.name||"").toLowerCase().includes(h)||(te.channel||"").toLowerCase().includes(h)||(te.utm_source||"").toLowerCase().includes(h)||(te.utm_campaign||"").toLowerCase().includes(h))},[A?.recentSales,f]),ee=d.useMemo(()=>{if(!A?.dailyRevenue)return[];const h={};for(const te of A.dailyRevenue){const M=te.day?.split("T")[0]||te.day;h[M]||(h[M]={}),h[M][te.channel]=(h[M][te.channel]||0)+parseFloat(te.revenue||"0")}return Object.entries(h).sort(([te],[M])=>M.localeCompare(te)).slice(0,14).reverse()},[A?.dailyRevenue]);return o?e.jsxs("div",{className:"flex items-center justify-center py-20",children:[e.jsx(xe,{className:"w-6 h-6 animate-spin text-white/40"}),e.jsx("span",{className:"ml-3 text-white/40",children:"Carregando atribuição de vendas..."})]}):e.jsxs("div",{className:"space-y-6","data-testid":"sales-attribution-tab",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(lt,{className:"w-6 h-6 text-emerald-400"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-white","data-testid":"text-attribution-title",children:"Atribuição de Vendas"}),e.jsx("p",{className:"text-xs text-white/50",children:"De onde vem cada real — UTM, referrer e first-touch"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[["7d","30d","90d","all"].map(h=>e.jsx("button",{onClick:()=>l(h),className:`px-3 py-1.5 text-xs rounded-lg transition-all ${r===h?"bg-white/20 text-white font-semibold":"bg-white/5 text-white/50 hover:bg-white/10"}`,"data-testid":`button-period-${h}`,children:h==="all"?"Tudo":h},h)),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1",onClick:()=>de.mutate(),disabled:de.isPending,"data-testid":"button-reattribute",children:[e.jsx(xe,{className:`w-3 h-3 ${de.isPending?"animate-spin":""}`}),"Reatribuir"]}),e.jsx(b,{size:"sm",variant:"ghost",className:"text-xs gap-1",onClick:()=>L(),"data-testid":"button-refresh-attribution",children:e.jsx(xe,{className:"w-3 h-3"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(hn,{label:"Receita Total",value:Ys(S),icon:nt,color:"text-emerald-400",testId:"metric-total-revenue"}),e.jsx(hn,{label:"Pedidos",value:Z.total_orders||0,icon:Jt,testId:"metric-total-orders"}),e.jsx(hn,{label:"Compradores",value:Z.total_buyers||0,icon:Re,testId:"metric-total-buyers"}),e.jsx(hn,{label:"Ticket Médio",value:Ys(Z.avg_ticket||0),icon:Ie,color:"text-amber-400",testId:"metric-avg-ticket"}),e.jsx(hn,{label:"Atribuídos",value:`${re}%`,sub:`${Z.attributed_orders||0} de ${Z.total_orders||0}`,icon:lt,color:"text-blue-400",testId:"metric-attributed-pct"})]}),v&&e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 p-4","data-testid":"card-meta-capi-health",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-blue-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Saúde do Tracking Meta CAPI"}),v.configured?e.jsxs(E,{variant:"outline",className:"text-[10px] border-emerald-500/30 text-emerald-400 bg-emerald-500/5 gap-1",children:[e.jsx(be,{className:"w-3 h-3"})," Configurado",v.pixelIds?.length>1?` (${v.pixelIds.length} pixels)`:""]}):e.jsxs(E,{variant:"outline",className:"text-[10px] border-red-500/30 text-red-400 bg-red-500/5 gap-1",children:[e.jsx(Ce,{className:"w-3 h-3"})," Sem pixel/token configurado"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"flex items-center gap-1 bg-white/5 rounded-md p-0.5","data-testid":"capi-replay-period-group",children:[{v:"24",label:"24h"},{v:"168",label:"7d"},{v:"720",label:"30d"}].map(({v:h,label:te})=>e.jsx("button",{type:"button",onClick:()=>{y(h),c(!1)},className:`px-2 py-1 text-[11px] rounded transition-colors ${w===h?"bg-blue-500/30 text-blue-200":"text-white/60 hover:text-white"}`,"data-testid":`button-capi-replay-period-${h}`,children:te},h))}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1",onClick:()=>{c(!1),ne.mutate({sinceHours:$,dryRun:!0})},disabled:ne.isPending,"data-testid":"button-capi-replay-dry",children:[e.jsx(ht,{className:`w-3 h-3 ${ne.isPending?"animate-pulse":""}`}),"Simular (",D,")"]}
2),F?e.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 rounded-md bg-amber-500/10 border border-amber-500/30","data-testid":"capi-replay-confirm-zone",children:[e.jsx(Ce,{className:"w-3 h-3 text-amber-400"}),e.jsxs("span",{className:"text-[11px] text-amber-200",children:["Confirmar envio de ",v.missingOrders?.length||0," eventos?"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-6 px-2 text-[10px] gap-1 border-emerald-500/40 text-emerald-300 hover:bg-emerald-500/10",onClick:()=>{c(!1),ne.mutate({sinceHours:$,dryRun:!1})},disabled:ne.isPending,"data-testid":"button-capi-replay-confirm",children:[e.jsx(be,{className:"w-3 h-3"})," Confirmar"]}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px]",onClick:()=>c(!1),"data-testid":"button-capi-replay-cancel",children:"Cancelar"})]}):e.jsxs(b,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1 border-emerald-500/40 text-emerald-300 hover:bg-emerald-500/10",onClick:()=>c(!0),disabled:ne.isPending||!v.configured||!(v.missingOrders?.length>0),"data-testid":"button-capi-replay-init",children:[e.jsx(ct,{className:"w-3 h-3"}),"Reenviar Faltantes (",D,")"]}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 text-xs gap-1",onClick:()=>I(),"data-testid":"button-capi-health-refresh",children:e.jsx(xe,{className:"w-3 h-3"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.02] p-3","data-testid":"capi-coverage-1h",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40 mb-1",children:"Última hora"}),e.jsx("div",{className:"flex items-baseline gap-2",children:e.jsxs("p",{className:`text-2xl font-bold ${v.paidOrders1h===0?"text-white/40":(v.purchaseSuccessOrders1h||0)>=v.paidOrders1h?"text-emerald-400":"text-amber-400"}`,children:[v.purchaseSuccessOrders1h||0,"/",v.paidOrders1h||0]})}),e.jsx("p",{className:"text-[10px] text-white/30 mt-1",children:"eventos / vendas"})]}),e.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.02] p-3","data-testid":"capi-coverage-24h",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40 mb-1",children:"Cobertura 24h"}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("p",{className:`text-2xl font-bold ${v.coverage24h===null?"text-white/40":v.coverage24h>=95?"text-emerald-400":v.coverage24h>=70?"text-amber-400":"text-red-400"}`,children:v.coverage24h===null?"—":`${v.coverage24h.toFixed(0)}%`}),e.jsxs("span",{className:"text-[10px] text-white/40",children:[v.purchaseSuccessOrders24h," de ",v.paidOrders24h]})]}),e.jsx("p",{className:"text-[10px] text-white/30 mt-1",children:"eventos Purchase enviados / vendas pagas"})]}),e.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.02] p-3","data-testid":"capi-coverage-7d",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40 mb-1",children:"Cobertura 7 dias"}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("p",{className:`text-2xl font-bold ${v.coverage7d===null?"text-white/40":v.coverage7d>=95?"text-emerald-400":v.coverage7d>=70?"text-amber-400":"text-red-400"}`,children:v.coverage7d===null?"—":`${v.coverage7d.toFixed(0)}%`}),e.jsxs("span",{className:"text-[10px] text-white/40",children:[v.purchaseSuccessOrders7d," de ",v.paidOrders7d]})]}),e.jsxs("p",{className:"text-[10px] text-white/30 mt-1",children:[Ys(v.purchaseSuccessValue7d)," / ",Ys(v.paidRevenue7d)]})]}),e.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.02] p-3","data-testid":"capi-failed-24h",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40 mb-1",children:"Falhas 24h"}),e.jsx("p",{className:`text-2xl font-bold ${v.purchaseFailed24h>0?"text-red-400":"text-white/60"}`,children:v.purchaseFailed24h}),e.jsx("p",{className:"text-[10px] text-white/30 mt-1",children:"tentativas de envio com erro"})]}),e.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.02] p-3","data-testid":"capi-missing",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40 mb-1",children:"Sem Purchase (7d)"}),e.jsx("p",{className:`text-2xl font-bold ${v.missingOrders?.length>0?"text-amber-400":"text-emerald-400"}`,children:v.missingOrders?.length||0}),e.jsx("p",{className:"text-[10px] text-white/30 mt-1",children:"vendas pagas que não viraram evento"})]})]}),v.recentFailures?.length>0&&e.jsxs("details",{className:"mt-3","data-testid":"capi-failures-details",children:[e.jsxs("summary",{className:"text-[11px] text-white/50 cursor-pointer hover:text-white/70",children:["Ver últimas ",v.recentFailures.length," falhas"]}),e.jsx("div",{className:"mt-2 space-y-1 text-[10px] font-mono",children:v.recentFailures.map((h,te)=>e.jsx("div",{className:"rounded bg-white/[0.02] border border-white/5 p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-white/60 truncate",children:["order: ",h.order_id||"—"]}
2),e.jsx("span",{className:"text-red-400 truncate",title:h.error_message,children:h.error_message?.slice(0,60)||"erro"})]})},te))})]}),v.missingOrders?.length>0&&e.jsxs("details",{className:"mt-2","data-testid":"capi-missing-details",children:[e.jsx("summary",{className:"text-[11px] text-white/50 cursor-pointer hover:text-white/70",children:"Ver vendas sem Purchase (7d)"}),e.jsx("div",{className:"mt-2 space-y-1 text-[10px]",children:v.missingOrders.slice(0,25).map((h,te)=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded bg-white/[0.02] border border-white/5 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-white/60 truncate",children:h.email||"—"}),e.jsx(E,{variant:"secondary",className:"text-[10px] px-1 py-0 h-4 shrink-0",children:h.type})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("span",{className:"text-emerald-400 font-mono",children:Ys(h.amount)}),e.jsx("span",{className:"text-white/30",children:new Date(h.created_at).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-5 px-1.5 text-[9px] gap-1",disabled:me.isPending,onClick:()=>me.mutate({orderId:h.id,dryRun:!1}),"data-testid":`button-capi-replay-missing-${h.id}`,children:[e.jsx(ct,{className:"w-2.5 h-2.5"})," Enviar"]})]})]},te))})]})]}),e.jsx("div",{className:"flex gap-1 bg-white/5 rounded-lg p-1",children:[{key:"channels",label:"Canais",icon:ft},{key:"landings",label:"Páginas",icon:Nh}
2,{key:"referrers",label:"Referrers",icon:vs},{key:"sales",label:"Vendas",icon:Jt}].map(({key:h,label:te,icon:M})=>e.jsxs("button",{onClick:()=>u(h),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-xs rounded-md transition-all ${n===h?"bg-white/15 text-white font-semibold":"text-white/50 hover:text-white/70"}`,"data-testid":`button-subtab-${h}`,children:[e.jsx(M,{className:"w-3.5 h-3.5"}),te]},h))}),n==="channels"&&e.jsxs("div",{className:"space-y-3","data-testid":"section-channels",children:[(A?.revenueByChannel||[]).map((h,te)=>e.jsx(Lg,{channel:h.channel,revenue:parseFloat(h.revenue||"0"),totalRevenue:S,orderCount:h.order_count,uniqueBuyers:h.unique_buyers,avgTicket:parseFloat(h.avg_ticket||"0")},te)),(A?.revenueByChannel||[]).length===0&&e.jsx("p",{className:"text-center text-white/30 py-10 text-sm",children:"Nenhum dado de canal encontrado."}),ee.length>0&&e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 p-4 mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white mb-3 flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"}),"Tendência Diária (últimos 14 dias)"]}),e.jsx("div",{className:"space-y-1.5",children:ee.map(([h,te])=>{const M=Object.values(te).reduce((ye,Me)=>ye+Me,0),ae=Math.max(...ee.map(([,ye])=>Object.values(ye).reduce((Me,se)=>Me+se,0)));return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-white/40 w-16 shrink-0 font-mono",children:new Date(h+"T12:00:00").toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}),e.jsx("div",{className:"flex-1 flex h-5 rounded overflow-hidden bg-white/5",children:Object.entries(te).sort(([,ye],[,Me])=>Me-ye).map(([ye,Me])=>{const se=ae>0?Me/ae*100:0,Ne=vn[ye]||"bg-zinc-500";return e.jsx("div",{className:`${Ne} opacity-80 hover:opacity-100 transition-opacity`,style:{width:`${se}%`},title:`${ye}: ${Ys(Me)}`},ye)})}),e.jsx("span",{className:"text-[10px] text-white/50 w-20 text-right font-mono",children:Ys(M)})]},h)})}),e.jsx("div",{className:"flex flex-wrap gap-3 mt-3 pt-3 border-t border-white/5",children:Object.keys(vn).map(h=>ee.some(([,M])=>h in M)?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${vn[h]}`}),e.jsx("span",{className:"text-[10px] text-white/40",children:h})]},h):null)})]})]}),n==="landings"&&e.jsx("div",{className:"space-y-2","data-testid":"section-landings",children:e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_80px_100px_70px] gap-2 px-4 py-2 text-[10px] text-white/40 uppercase tracking-wider border-b border-white/5",children:[e.jsx("span",{children:"Página de Entrada"}),e.jsx("span",{className:"text-right",children:"Vendas"}),e.jsx("span",{className:"text-right",children:"Receita"}),e.jsx("span",{className:"text-right",children:"Compradores"})]}),(A?.revenueByLanding||[]).map((h,te)=>e.jsxs("div",{className:"grid grid-cols-[1fr_80px_100px_70px] gap-2 px-4 py-2.5 border-b border-white/5 hover:bg-white/5 transition-colors","data-testid":`landing-row-${te}`,children:[e.jsx("span",{className:"text-xs text-white/80 truncate font-mono",children:h.landing_page||"(desconhecida)"}),e.jsx("span",{className:"text-xs text-white/60 text-right",children:h.order_count}),e.jsx("span",{className:"text-xs text-emerald-400 text-right font-semibold",children:Ys(h.revenue)}),e.jsx("span",{className:"text-xs text-white/60 text-right",children:h.unique_buyers})]},te)),(A?.revenueByLanding||[]).length===0&&e.jsx("p",{className:"text-center text-white/30 py-8 text-sm",children:"Nenhuma landing page encontrada."})]})}),n==="referrers"&&e.jsx("div",{className:"space-y-2","data-testid":"section-referrers",children:e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_80px_100px_70px] gap-2 px-4 py-2 text-[10px] text-white/40 uppercase tracking-wider border-b border-white/5",children:[e.jsx("span",{children:"Referrer (Domínio)"}),e.jsx("span",{className:"text-right",children:"Vendas"}),e.jsx("span",{className:"text-right",children:"Receita"}),e.jsx("span",{className:"text-right",children:"Compradores"})]}),(A?.revenueByReferrer||[]).map((h,te)=>e.jsxs("div",{className:"grid grid-cols-[1fr_80px_100px_70px] gap-2 px-4 py-2.5 border-b border-white/5 hover:bg-white/5 transition-colors","data-testid":`referrer-row-${te}`,children:[e.jsx("span",{className:"text-xs text-white/80 truncate",children:h.referrer_domain||"(direto)"}),e.jsx("span",{className:"text-xs text-white/60 text-right",children:h.order_count}),e.jsx("span",{className:"text-xs text-emerald-400 text-right font-semibold",children:Ys(h.revenue)}),e.jsx("span",{className:"text-xs text-white/60 text-right",children:h.unique_buyers})]},te)),(A?.revenueByReferrer||[]).length===0&&e.jsx("p",{className:"text-center text-white/30 py-8 text-sm",children:"Nenhum referrer encontrado."})]})}),n==="sales"&&e.jsxs("div",{className:"space-y-3","data-testid":"section-sales",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-white/30"}),e.jsx(J,{placeholder:"Buscar por email, canal, UTM...",value:f,onChange:h=>j(h.target.value),className:"bg-white/5 border-white/10 text-sm h-9","data-testid":"input-sales-search"})]}),e.jsxs("div",{className:"glass-card rounded-xl border border-white/10 overflow-hidden",children:[e.jsxs("div",{className:"hidden md:grid grid-cols-[1fr_180px_110px_70px_120px_24px] gap-2 px-4 py-2 text-[10px] uppercase tracking-wider text-white/40 border-b border-white/5",children:[e.jsx("span",{children:"Cliente"}),e.jsx("span",{children:"Origem"}),e.jsx("span",{className:"text-right",children:"Valor"}),e.jsx("span",{className:"text-right",children:"Data"}),e.jsx("span",{className:"text-right",children:"Meta CAPI"}),e.jsx("span",{})]}),e.jsx(H0,{delayDuration:200,children:_.slice(0,50).map((h,te)=>{const M=p===h.id,ae=vn[h.channel]||"bg-zinc-500",ye=Th[h.channel]||"from-zinc-500/20 to-zinc-600/10 border-zinc-500/30",Me=[h.utm_source&&`source: ${h.utm_source}`,h.utm_medium&&`medium: ${h.utm_medium}`,h.utm_campaign&&`campaign: ${h.utm_campaign}`,h.first_referrer&&`referrer: ${h.first_referrer}`,h.first_landing&&`landing: ${h.first_landing}`,h.referred_by&&`indicado por: ${h.referred_by}
2`].filter(Boolean);return e.jsxs("div",{className:"border-b border-white/5",children:[e.jsxs("div",{className:"flex items-center gap-2 md:grid md:grid-cols-[1fr_180px_110px_70px_120px_24px] px-4 py-2.5 hover:bg-white/5 cursor-pointer transition-colors",onClick:()=>g(M?null:h.id),"data-testid":`sale-row-${h.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1 md:flex-none",children:[e.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${ae}`}),e.jsx("span",{className:"text-xs text-white/80 truncate","data-testid":`text-sale-email-${h.id}`,children:h.email||"—"})]}),e.jsxs("div",{className:"hidden md:flex items-center min-w-0 gap-1",children:[e.jsxs(tc,{children:[e.jsx(sc,{asChild:!0,children:e.jsxs("div",{className:`inline-flex items-center gap-1.5 rounded-md border bg-gradient-to-r ${ye} px-2 py-0.5 max-w-full`,"data-testid":`badge-origem-${h.id}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${ae} shrink-0`}),e.jsx("span",{className:"text-[11px] font-medium text-white/90 truncate",children:h.channel})]})}),Me.length>0&&e.jsx(ac,{className:"max-w-sm text-[11px]",children:e.jsx("div",{className:"space-y-1",children:Me.map((se,Ne)=>e.jsx("div",{className:"font-mono text-white/80",children:se},Ne))})})]}),h.metaAccountName&&e.jsxs(tc,{children:[e.jsx(sc,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-violet-500/30 bg-violet-500/10 px-1.5 py-0.5 text-[9px] font-medium text-violet-300 shrink-0 max-w-[140px]","data-testid":`badge-meta-account-${h.id}`,children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-violet-400 shrink-0"}),e.jsx("span",{className:"truncate",children:h.metaAccountName})]})}),e.jsxs(ac,{className:"text-[11px]",children:["Conta Meta: ",h.metaAccountName," (#",h.metaAccountId,")"]})]})]}),e.jsx("span",{className:"text-sm font-semibold text-emerald-400 md:text-right shrink-0",children:Ys(h.amount)}),e.jsx("span",{className:"text-[10px] text-white/30 md:text-right shrink-0 hidden md:inline",children:new Date(h.created_at).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}),e.jsx("div",{className:"hidden md:flex items-center justify-end gap-1.5",children:e.jsxs(tc,{children:[e.jsx(sc,{asChild:!0,children:e.jsxs(b,{size:"sm",variant:"outline",className:"h-6 px-2 text-[10px] gap-1",disabled:me.isPending,onClick:se=>{se.stopPropagation(),me.mutate({orderId:h.id,dryRun:!1})},"data-testid":`button-replay-capi-${h.id}`,children:[e.jsx(ct,{className:"w-3 h-3"}),"Reenviar"]})}),e.jsxs(ac,{className:"text-[11px]",children:["Reenviar evento Purchase ao Meta CAPI (R$ ",Number(h.amount||0).toFixed(2)," real, sem ajustes). Idempotente — Meta deduplica pelo eventId."]})]})}),M?e.jsx(ta,{className:"w-3 h-3 text-white/30"}):e.jsx(Ct,{className:"w-3 h-3 text-white/30"})]}),M&&e.jsxs("div",{className:"px-4 pb-3 pt-1 bg-white/[0.02] grid grid-cols-2 md:grid-cols-4 gap-2 text-[11px]",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-white/30",children:"Tipo:"})," ",e.jsx("span",{className:"text-white/70",children:h.type})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/30",children:"Pagamento:"})," ",e.jsx("span",{className:"text-white/70",children:h.payment_method})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/30",children:"UTM Source:"})," ",e.jsx("span",{className:"text-white/70",children:h.utm_source||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/30",children:"UTM Medium:"})," ",e.jsx("span",{className:"text-white/70",children:h.utm_medium||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/30",children:"UTM Campaign:"})," ",e.jsx("span",{className:"text-white/70",children:h.utm_campaign||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/30",children:"Referrer:"})," ",e.jsx("span",{className:"text-white/70 truncate",children:h.first_referrer||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/30",children:"Landing:"})," ",e.jsx("span",{className:"text-white/70 truncate",children:h.first_landing||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/30",children:"Indicado por:"})," ",e.jsx("span",{className:"text-white/70",children:h.referred_by||"—"})]})]})]},h.id||te)})}),_.length===0&&e.jsx("p",{className:"text-center text-white/30 py-8 text-sm",children:"Nenhuma venda encontrada."}),_.length>50&&e.jsxs("p",{className:"text-center text-white/30 py-3 text-xs",children:["Mostrando 50 de ",_.length," vendas"]})]})]})]})}const pn=a=>`R$ ${(a/100).toFixed(2)}`,xc=a=>
2a?.toLocaleString("pt-BR")??"0";function qg(a){const r=Date.now()-new Date(a).getTime(),l=Math.floor(r/6e4);if(l<60)return`${l}min`;const n=Math.floor(l/60);return n<24?`${n}h`:`${Math.floor(n/24)}d`}const mc={pix_expired:"PIX Expirado",card_failed:"Cartão Recusado",checkout_abandoned:"Checkout Abandonado",funnel_drop:"Saiu do Funil"},ql={pix_expired:"text-amber-400 bg-amber-500/20 border-amber-500/30",card_failed:"text-red-400 bg-red-500/20 border-red-500/30",checkout_abandoned:"text-violet-400 bg-violet-500/20 border-violet-500/30",funnel_drop:"text-zinc-400 bg-zinc-500/20 border-zinc-500/30"},_g={pix_expired:e.jsx(Oa,{className:"w-4 h-4"}),card_failed:e.jsx(Bt,{className:"w-4 h-4"}),checkout_abandoned:e.jsx(ht,{className:"w-4 h-4"}),funnel_drop:e.jsx(Hl,{className:"w-4 h-4"})},rh={standard:"Email Padrão",pix_expired:"PIX Expirado",card_failed:"Cartão Recusado",last_chance:"Última Chance"};function Og(){const{toast:a}=st(),[r,l]=d.useState(null),[n,u]=d.useState(""),[f,j]=d.useState(new Set),[p,g]=d.useState(null),[w,y]=d.useState(null),[F,c]=d.useState(null),{data:m,isLoading:$}=z({queryKey:["/api/admin/recovery-dashboard"],queryFn:()=>N("GET","/api/admin/recovery-dashboard").then(_=>_.json()),refetchInterval:6e4}),{data:D}=z({queryKey:["/api/admin/recovery-dashboard/stats"],queryFn:()=>N("GET","/api/admin/recovery-dashboard/stats").then(_=>_.json()),refetchInterval:12e4}),A=W({mutationFn:async({checkoutSessionId:_,emailType:ee})=>(await N("POST","/api/admin/recovery/send-email",{checkoutSessionId:_,emailType:ee})).json(),onSuccess:()=>{a({title:"Email enviado",description:"Email de recuperação enviado com sucesso"}),K.invalidateQueries({queryKey:["/api/admin/recovery-dashboard"]}),g(null)},onError:_=>{a({title:"Erro ao enviar",description:_.message,variant:"destructive"})}}),o=W({mutationFn:async({checkoutSessionIds:_,emailType:ee})=>(await N("POST","/api/admin/recovery/send-bulk",{checkoutSessionIds:_,emailType:ee})).json(),onSuccess:_=>{a({title:"Envio em massa concluído",description:`${_.sent} enviados, ${_.failed} falharam`}),K.invalidateQueries({queryKey:["/api/admin/recovery-dashboard"]}),j(new Set),y(null)},onError:_=>{a({title:"Erro no envio em massa",description:_.message,variant:"destructive"})}}),L=d.useMemo(()=>{if(!m?.sessions)return[];let _=m.sessions;if(r&&(_=_.filter(ee=>ee.abandonmentType===r)),n.trim()){const ee=n.toLowerCase();_=_.filter(h=>h.email?.toLowerCase().includes(ee)||h.userName?.toLowerCase().includes(ee)||h.bookTitle?.toLowerCase().includes(ee))}return _},[m?.sessions,r,n]),v=_=>{j(ee=>{const h=new Set(ee);return h.has(_)?h.delete(_):h.add(_),h})},I=()=>{f.size===L.length?j(new Set):j(new Set(L.map(_=>_.id)))},de=_=>{const ee=`${window.location.origin}/checkout/${_.id}?token=${_.magicToken}`;navigator.clipboard.writeText(ee),a({title:"Link copiado",description:"Link do checkout copiado para a área de transferência"})},me=_=>{switch(_){case"pix_expired":return"pix_expired";case"card_failed":return"card_failed";default:return"standard"}};if($)return e.jsx("div",{className:"flex justify-center items-center p-20",children:e.jsx(T,{className:"w-8 h-8 animate-spin text-teal-400"})});const ne=m?.summary||{},Z=m?.typeCounts||{},S=m?.dripFunnel||[],re=D?.timeSeries||[];return e.jsxs("div",{className:"space-y-6","data-testid":"recovery-panel",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-bold text-white flex items-center gap-2",children:[e.jsx(xe,{className:"w-5 h-5 text-teal-400"}),"Recuperação de Vendas"]}),e.jsx("p",{className:"text-xs text-white/40 mt-1",children:"Acompanhe e recupere checkouts abandonados"})]}),e.jsxs(b,{size:"sm",variant:"outline",className:"border-white/10 text-white/60 hover:text-white hover:bg-white/5",onClick:()=>K.invalidateQueries({queryKey:["/api/admin/recovery-dashboard"]}),"data-testid":"btn-refresh-recovery",children:[e.jsx(xe,{className:"w-3.5 h-3.5 mr-1.5"})," Atualizar"]})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3","data-testid":"recovery-summary",children:[e.jsxs("div",{className:"border border-white/10 rounded-xl bg-gradient-to-br from-red-500/[0.05] to-transparent p-4",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Abandonos Ativos"}),e.jsx("p",{className:"text-2xl font-bold text-white mt-1","data-testid":"text-total-abandoned",children:xc(ne.totalAbandoned||0)}),e.jsxs("p",{className:"text-[10px] text-white/30 mt-0.5",children:["Potencial: ",pn(ne.potentialRevenue||0)]})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-gradient-to-br from-emerald-500/[0.05] to-transparent p-4",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Recuperados (30d)"}),e.jsx("p",{className:"text-2xl font-bold text-emerald-400 mt-1","data-testid":"text-total-recovered",children:xc(ne.totalRecovered||0)}),e.jsxs("p",{className:"text-[10px] text-white/30 mt-0.5",children:["Receita: ",pn(ne.recoveredRevenue||0)]})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-gradient-to-br from-teal-500/[0.05] to-transparent p-4",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Taxa de Recuperação"}),e.jsxs("p",{className:"text-2xl font-bold text-teal-400 mt-1","data-testid":"text-recovery-rate",children:[(ne.recoveryRate||0).toFixed(1),"%"]})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-gradient-to-br from-violet-500/[0.05] to-transparent p-4",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Receita Potencial"}),e.jsx("p",{className:"text-2xl font-bold text-violet-400 mt-1",children:pn(ne.potentialRevenue||0)})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-gradient-to-br from-sky-500/[0.05] to-transparent p-4",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Drip Ativo"}),e.jsx("p",{className:"text-2xl font-bold text-sky-400 mt-1",children:xc(ne.dripActiveCount||0)}),e.jsx("p",{className:"text-[10px] text-white/30 mt-0.5",children:"Em sequência de emails"})]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-3","data-testid":"abandonment-types",children:["pix_expired","card_failed","checkout_abandoned","funnel_drop"].map(_=>{const ee=Z[_]||0,h=r===_;return e.jsxs("button",{onClick:()=>l(h?null:_),className:`border rounded-xl p-4 text-left transition-all ${h?`${ql[_]} border-opacity-100`:"border-white/10 bg-white/[0.02] hover:bg-white/[0.04]"}`,"data-testid":`btn-filter-${_}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:h?"":"text-white/50",children:_g[_]}),e.jsx(E,{variant:"outline",className:`text-[10px] ${ql[_]}`,children:ee})]}),e.jsx("p",{className:`text-xs font-medium ${h?"":"text-white/70"}`,children:mc[_]}),ee>0&&e.jsxs(b,{size:"sm",variant:"ghost",className:"mt-2 h-6 text-[10px] px-2 text-teal-400 hover:text-teal-300 hover:bg-teal-500/10 w-full",onClick:te=>{te.stopPropagation(),l(_);const M=(m?.sessions||[]).filter(ae=>ae.abandonmentType===_).map(ae=>ae.id);j(new Set(M)),y(me(_))}
2,"data-testid":`btn-bulk-${_}`,children:[e.jsx(ct,{className:"w-3 h-3 mr-1"})," Enviar recuperação"]})]},_)})}),re.length>0&&e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4",children:[e.jsx("p",{className:"text-xs font-medium text-white/60 mb-3",children:"Abandonos vs Recuperações (30d)"}),e.jsx(Cn,{width:"100%",height:180,children:e.jsxs($h,{data:re,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"gradAbandoned",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#ef4444",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"#ef4444",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"gradRecovered",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#10b981",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"#10b981",stopOpacity:0})]})]}),e.jsx(Sn,{strokeDasharray:"3 3",stroke:"rgba(255,255,255,0.05)"}),e.jsx($n,{dataKey:"date",tick:{fill:"rgba(255,255,255,0.3)",fontSize:10},tickFormatter:_=>_.slice(5)}),e.jsx(Wi,{tick:{fill:"rgba(255,255,255,0.3)",fontSize:10}}),e.jsx(An,{contentStyle:{background:"#1a1a2e",border:"1px solid rgba(255,255,255,0.1)",borderRadius:8,fontSize:11}}),e.jsx(Nc,{type:"monotone",dataKey:"abandoned",stroke:"#ef4444",fill:"url(#gradAbandoned)",name:"Abandonos"}),e.jsx(Nc,{type:"monotone",dataKey:"recovered",stroke:"#10b981",fill:"url(#gradRecovered)",name:"Recuperados"})]})})]}),S.length>0&&e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4",children:[e.jsx("p",{className:"text-xs font-medium text-white/60 mb-3",children:"Funil de Drip (por etapa)"}),e.jsx(Cn,{width:"100%",height:180,children:e.jsxs(lu,{data:S.filter(_=>_.step>0),children:[e.jsx(Sn,{strokeDasharray:"3 3",stroke:"rgba(255,255,255,0.05)"}),e.jsx($n,{dataKey:"step",tick:{fill:"rgba(255,255,255,0.3)",fontSize:10}}),e.jsx(Wi,{tick:{fill:"rgba(255,255,255,0.3)",fontSize:10}}),e.jsx(An,{contentStyle:{background:"#1a1a2e",border:"1px solid rgba(255,255,255,0.1)",borderRadius:8,fontSize:11},formatter:(_,ee,h)=>[_,h?.dataKey==="total"?"No drip":"Recuperados"],labelFormatter:_=>`Etapa ${_}`}),e.jsx(Vl,{dataKey:"total",name:"No drip",radius:[4,4,0,0],children:S.filter(_=>_.step>0).map((_,ee)=>e.jsx(Km,{fill:"rgba(139,92,246,0.4)"},ee))}),e.jsx(Vl,{dataKey:"recovered",name:"Recuperados",radius:[4,4,0,0],children:S.filter(_=>_.step>0).map((_,ee)=>e.jsx(Km,{fill:"#10b981"},ee))})]})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(St,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/30"}),e.jsx("input",{type:"text",placeholder:"Buscar por nome, email ou livro...",value:n,onChange:_=>u(_.target.value),className:"w-full h-9 pl-9 pr-4 bg-white/5 border border-white/10 rounded-lg text-sm text-white placeholder:text-white/30 focus:outline-none focus:border-teal-500/50","data-testid":"input-search-recovery"})]}),r&&e.jsxs(b,{size:"sm",variant:"ghost",className:"h-8 text-xs text-white/50 hover:text-white",onClick:()=>l(null),children:[e.jsx(ea,{className:"w-3 h-3 mr-1"})," Limpar filtro: ",mc[r]]}),f.size>0&&e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsxs("span",{className:"text-xs text-white/40",children:[f.size," selecionados"]}),e.jsx("div",{className:"flex gap-1",children:["standard","pix_expired","card_failed","last_chance"].map(_=>e.jsxs(b,{size:"sm",variant:"outline",className:"h-7 text-[10px] border-white/10 text-white/60 hover:text-white hover:bg-teal-500/10 hover:border-teal-500/30",disabled:o.isPending,onClick:()=>{o.mutate({checkoutSessionIds:Array.from(f),emailType:_})},"data-testid":`btn-bulk-send-${_}`,children:[o.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(ct,{className:"w-3 h-3 mr-1"}),rh[_]]},_))})]})]}),e.jsx("div",{className:"border border-white/10 rounded-xl overflow-hidden","data-testid":"recovery-table",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white/[0.03] border-b border-white/10",children:[e.jsx("th",{className:"p-3 text-left w-8",children:e.jsx("input",{type:"checkbox",checked:f.size===L.length&&L.length>0,onChange:I,className:"rounded border-white/20 bg-white/5","data-testid":"checkbox-select-all"})}),e.jsx("th",{className:"p-3 text-left text-[10px] text-white/40 uppercase tracking-wider",children:"Cliente"}),e.jsx("th",{className:"p-3 text-left text-[10px] text-white/40 uppercase tracking-wider",children:"Livro"}),e.jsx("th",{className:"p-3 text-left text-[10px] text-white/40 uppercase tracking-wider",children:"Valor"}),e.jsx("th",{className:"p-3 text-left text-[10px] text-white/40 uppercase tracking-wider",children:"Tipo"}),e.jsx("th",{className:"p-3 text-left text-[10px] text-white/40 uppercase tracking-wider",children:"Tempo"}),e.jsx("th",{className:"p-3 text-left text-[10px] text-white/40 uppercase tracking-wider",children:"Drip"}),e.jsx("th",{className:"p-3 text-left text-[10px] text-white/40 uppercase tracking-wider",children:"Ações"})]})}),e.jsx("tbody",{children:L.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"p-12 text-center text-white/30 text-sm",children:r?"Nenhum checkout abandonado nesta categoria":"Nenhum checkout abandonado encontrado"})}):L.map(_=>e.jsxs(Kl.Fragment,{children:[e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/[0.02] transition-colors cursor-pointer",onClick:()=>c(F===_.id?null:_.id),"data-testid":`row-session-${_.id}`,children:[e.jsx("td",{className:"p-3",children:e.jsx("input",{type:"checkbox",checked:f.has(_.id),onChange:ee=>{ee.stopPropagation(),v(_.id)},className:"rounded border-white/20 bg-white/5"})}),e.jsxs("td",{className:"p-3",children:[e.jsx("p",{className:"text-xs text-white font-medium truncate max-w-[140px]",children:_.userName||_.email?.split("@")[0]}),e.jsx("p",{className:"text-[10px] text-white/30 truncate max-w-[140px]",children:_.email})]}),e.jsx("td",{className:"p-3",children:e.jsx("p",{className:"text-xs text-white/80 truncate max-w-[180px]",title:_.bookTitle,children:_.bookTitle})}),e.jsx("td",{className:"p-3",children:e.jsx("p",{className:"text-xs font-semibold text-emerald-400",children:pn(_.totalAmount||0)})}),e.jsx("td",{className:"p-3",children:e.jsx(E,{variant:"outline",className:`text-[10px] ${ql[_.abandonmentType]||ql.funnel_drop}`,children:mc[_.abandonmentType]||"Desconhecido"})}),e.jsx("td",{className:"p-3",children:e.jsx("p",{className:"text-xs text-white/50",children:_.createdAt?qg(_.createdAt):"—"})}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-16 h-1.5 bg-white/10 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-teal-500 to-violet-500 rounded-full transition-all",style:{width:`${Math.min((_.abandonedEmailStep||0)/15*100,100)}%`}})}),e.jsxs("span",{className:"text-[10px] text-white/40",children:[_.abandonedEmailStep||0,"/15"]}
2)]})}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-1",onClick:ee=>ee.stopPropagation(),children:[e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-teal-400 hover:text-teal-300 hover:bg-teal-500/10",onClick:()=>g(_),title:"Enviar email de recuperação","data-testid":`btn-send-email-${_.id}`,children:e.jsx(Ge,{className:"w-3.5 h-3.5"})}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-white/40 hover:text-white hover:bg-white/10",onClick:()=>de(_),title:"Copiar link do checkout","data-testid":`btn-copy-link-${_.id}`,children:e.jsx(ha,{className:"w-3.5 h-3.5"})}),e.jsx("a",{href:`/checkout/${_.id}?token=${_.magicToken}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center justify-center h-7 w-7 text-white/40 hover:text-white hover:bg-white/10 rounded-md transition-colors",title:"Abrir checkout","data-testid":`btn-open-checkout-${_.id}`,children:e.jsx(vs,{className:"w-3.5 h-3.5"})})]})})]}),F===_.id&&e.jsx("tr",{className:"bg-white/[0.01]",children:e.jsx("td",{colSpan:8,className:"p-4",children:e.jsxs("div",{className:"grid grid-cols-4 gap-4 text-xs",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-white/30 text-[10px] mb-1",children:"Telefone"}),e.jsx("p",{className:"text-white/70",children:_.phone||"Não informado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white/30 text-[10px] mb-1",children:"Método"}),e.jsxs("p",{className:"text-white/70 flex items-center gap-1",children:[_.paymentMethod==="pix"?e.jsx(Oa,{className:"w-3 h-3"}):_.paymentMethod==="card"?e.jsx(Bt,{className:"w-3 h-3"}):null,_.paymentMethod||"Não selecionado"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white/30 text-[10px] mb-1",children:"Último contato"}),e.jsx("p",{className:"text-white/70",children:_.lastDripSentAt?new Date(_.lastDripSentAt).toLocaleDateString("pt-BR"):_.recoverySentAt?new Date(_.recoverySentAt).toLocaleDateString("pt-BR")+" (WhatsApp)":"Nunca"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white/30 text-[10px] mb-1",children:"Variante"}),e.jsx("p",{className:"text-white/70",children:_.variant||"A"})]}),_.selectedBumps&&_.selectedBumps.length>0&&e.jsxs("div",{className:"col-span-4",children:[e.jsx("p",{className:"text-white/30 text-[10px] mb-1",children:"Produtos selecionados"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:_.selectedBumps.map((ee,h)=>e.jsx(E,{variant:"outline",className:"text-[10px] border-white/10 text-white/50",children:typeof ee=="string"?ee:ee.title||ee.type||"Produto"},h))})]})]})})})]},_.id))})]})}),L.length>0&&e.jsxs("p",{className:"text-[10px] text-white/20 text-right",children:[L.length," checkout(s) abandonado(s)"]})]}),e.jsx(Je,{open:!!p,onOpenChange:_=>!_&&g(null),children:e.jsxs(Ye,{className:"bg-[#0f0f1a] border-white/10 max-w-md",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"text-white flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4 text-teal-400"}),"Enviar Email de Recuperação"]}),e.jsxs(mt,{className:"text-white/40",children:["Escolha o tipo de email para ",p?.userName||p?.email]})]}),p&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-white/[0.03] border border-white/10 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-white/70 font-medium",children:p.bookTitle}),e.jsxs("p",{className:"text-[10px] text-white/40 mt-1",children:[p.email," · ",pn(p.totalAmount||0)]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:["standard","pix_expired","card_failed","last_chance"].map(_=>{const ee=me(p.abandonmentType)===_;return e.jsxs("button",{className:`p-3 rounded-lg border text-left transition-all ${ee?"border-teal-500/50 bg-teal-500/10":"border-white/10 bg-white/[0.02] hover:bg-white/[0.04]"}`,onClick:()=>A.mutate({checkoutSessionId:p.id,emailType:_}),disabled:A.isPending,"data-testid":`btn-email-type-${_}`,children:[e.jsx("p",{className:"text-xs text-white font-medium",children:rh[_]}),ee&&e.jsx("p",{className:"text-[9px] text-teal-400 mt-0.5",children:"Recomendado"})]},_)})}),A.isPending&&e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-white/50",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Gerando e enviando..."]})]})]})})]})}function yt(a){return new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(a)}function un(a){return`${a.toFixed(1)}%`}function Bg(a){return a>=1e6?`${(a/1e6).toFixed(1)}
2M`:a>=1e3?`${(a/1e3).toFixed(1)}K`:a.toString()}function Ug(a){return a==="Chat"?e.jsx(Qa,{className:"w-5 h-5"}):e.jsx(pt,{className:"w-5 h-5"})}function Kg(a){return a==="Chat"?"from-violet-500/20 to-violet-600/10 border-violet-500/30":"from-teal-500/20 to-teal-600/10 border-teal-500/30"}function Gg(a){return a==="Chat"?"text-violet-400":"text-teal-400"}function Vg(a){return a==="pix"?e.jsx(Oa,{className:"w-4 h-4 text-emerald-400"}):a==="card"?e.jsx(Bt,{className:"w-4 h-4 text-blue-400"}):e.jsx(jc,{className:"w-4 h-4 text-amber-400"})}function Qg(){const{user:a}=Sa(),r=!!a&&a.role==="admin",{data:l,isLoading:n,error:u,refetch:f,isFetching:j}=z({queryKey:["/api/admin/bi-dashboard"],enabled:r,refetchInterval:!1,staleTime:300*1e3});if(n)return e.jsx("div",{className:"flex items-center justify-center py-20","data-testid":"bi-loading",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx(xe,{className:"w-8 h-8 animate-spin text-teal-400"}),e.jsx("p",{className:"text-gray-400 text-sm",children:"Carregando Business Intelligence..."})]})});if(u||!l)return e.jsx("div",{className:"flex items-center justify-center py-20","data-testid":"bi-error",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-12 h-12 rounded-xl bg-red-500/10 border border-red-500/20 flex items-center justify-center",children:e.jsx(Xe,{className:"w-6 h-6 text-red-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white/80 font-medium text-sm",children:"Não foi possível carregar os dados"}),e.jsx("p",{className:"text-white/40 text-xs mt-1",children:"Verifique sua conexão e tente novamente"})]}),e.jsxs("button",{onClick:()=>f(),disabled:j,className:"inline-flex items-center gap-2 px-4 py-2 bg-teal-600/20 hover:bg-teal-600/30 border border-teal-500/30 rounded-lg text-sm text-teal-400 transition-colors","data-testid":"button-retry",children:[e.jsx(xe,{className:`w-3.5 h-3.5 ${j?"animate-spin":""}`}),j?"Carregando...":"Tentar novamente"]})]})});const{overview:p,entryFlows:g,revenueByPaymentMethod:w,revenueByProduct:y,topUsersLtv:F,revenueByUtmSource:c,revenueByUtmCampaign:m,dailyTimeSeries:$,aiCostBreakdown:D,funnelStats:A}=l,o=Math.max(...$.map(v=>v.revenue),1),L=Math.max(...$.map(v=>v.orders),1);return e.jsxs("div",{className:"space-y-6","data-testid":"bi-dashboard",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold bg-gradient-to-r from-teal-400 to-violet-400 bg-clip-text text-transparent","data-testid":"text-bi-title",children:"Business Intelligence"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Apenas receita real (Cartão + PIX) · ",new Date(l.generatedAt).toLocaleString("pt-BR")," · USD/BRL: ",p.usdBrlRate.toFixed(2)]})]}),e.jsxs("button",{onClick:()=>f(),disabled:j,className:"flex items-center gap-2 px-3 py-1.5 bg-gray-800 hover:bg-gray-700 rounded-lg text-sm text-gray-300 transition-colors border border-gray-700","data-testid":"button-refresh-bi",children:[e.jsx(xe,{className:`w-3.5 h-3.5 ${j?"animate-spin":""}`}),"Atualizar"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3","data-testid":"bi-kpi-cards",children:[e.jsx(fr,{label:"Receita Bruta",value:yt(p.totalGrossRevenue),icon:e.jsx(nt,{className:"w-4 h-4"}),color:"text-emerald-400",subtitle:`Líquida: ${yt(p.totalNetRevenue)}`,testId:"kpi-revenue"}),e.jsx(fr,{label:"Custo IA",value:yt(p.totalAiCostBRL),icon:e.jsx(Ht,{className:"w-4 h-4"}),color:"text-orange-400",subtitle:`${D.reduce((v,I)=>v+I.callCount,0)} chamadas`,testId:"kpi-ai-cost"}),e.jsx(fr,{label:"Margem Bruta",value:yt(p.grossMargin),icon:p.grossMargin>=0?e.jsx($r,{className:"w-4 h-4"}):e.jsx(Tc,{className:"w-4 h-4"}),color:p.grossMargin>=0?"text-emerald-400":"text-red-400",subtitle:un(p.grossMarginPercent),testId:"kpi-margin"}),e.jsx(fr,{label:"Pedidos Reais",value:p.totalRealOrders.toString(),icon:e.jsx(Jt,{className:"w-4 h-4"}),color:"text-blue-400",subtitle:`Ticket: ${yt(p.avgTicket)}`,testId:"kpi-orders"}),e.jsx(fr,{label:"Usuários",value:p.totalUsers.toString(),icon:e.jsx(Re,{className:"w-4 h-4"}),color:"text-violet-400",subtitle:`ARPU: ${yt(p.arpu)}`,testId:"kpi-users"}),e.jsx(fr,{label:"Funil",value:`${A.chatConversionRate.toFixed(1)}%`,icon:e.jsx(Ie,{className:"w-4 h-4"}),color:"text-teal-400",subtitle:`${A.chatConversions}/${A.totalChatSessions} chats`,testId:"kpi-funnel"})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4","data-testid":"bi-entry-flows",children:g.map(v=>e.jsxs("div",{className:`bg-gradient-to-br ${Kg(v.name)}
2 border rounded-xl p-5`,"data-testid":`flow-card-${v.name.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("span",{className:Gg(v.name),children:Ug(v.name)}),e.jsx("h3",{className:"font-semibold text-white",children:v.name})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-400 text-xs",children:"Usuários"}),e.jsx("p",{className:"text-white font-medium","data-testid":`text-flow-users-${v.name}`,children:v.totalUsers})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-400 text-xs",children:"Pagantes"}),e.jsx("p",{className:"text-emerald-400 font-medium","data-testid":`text-flow-paying-${v.name}`,children:v.payingUsers})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-400 text-xs",children:"Pedidos"}),e.jsx("p",{className:"text-white font-medium",children:v.orders})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-400 text-xs",children:"Conversão"}),e.jsx("p",{className:"text-amber-400 font-medium",children:un(v.conversionRate)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-400 text-xs",children:"Receita Bruta"}),e.jsx("p",{className:"text-emerald-400 font-medium",children:yt(v.grossRevenue)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-400 text-xs",children:"ARPU"}),e.jsx("p",{className:"text-white font-medium",children:yt(v.arpu)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-400 text-xs",children:"Custo IA"}),e.jsx("p",{className:"text-orange-400 font-medium",children:yt(v.aiCost)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-400 text-xs",children:"Margem"}),e.jsxs("p",{className:`font-medium ${v.margin>=0?"text-emerald-400":"text-red-400"}`,children:[yt(v.margin)," (",un(v.marginPercent),")"]})]})]})]},v.name))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-gray-900/50 border border-gray-800 rounded-xl p-5","data-testid":"bi-payment-methods",children:[e.jsxs("h3",{className:"font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-400"}),"Receita por Método de Pagamento"]}),e.jsxs("div",{className:"space-y-3",children:[w.map(v=>{const I=p.totalGrossRevenue>0?v.grossRevenue/p.totalGrossRevenue*100:0;return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`payment-${v.method}`,children:[Vg(v.method),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex justify-between items-baseline mb-1",children:[e.jsx("span",{className:"text-sm text-white",children:v.label}),e.jsx("span",{className:"text-sm font-medium text-emerald-400",children:yt(v.grossRevenue)})]}),e.jsx("div",{className:"w-full bg-gray-800 rounded-full h-2",children:e.jsx("div",{className:`h-2 rounded-full ${v.method==="pix"?"bg-emerald-500":v.method==="card"?"bg-blue-500":"bg-amber-500"}`,style:{width:`${Math.max(I,2)}%`}})}),e.jsxs("div",{className:"flex justify-between mt-1",children:[e.jsxs("span",{className:"text-xs text-gray-500",children:[v.orders," pedido(s)"]}),e.jsx("span",{className:"text-xs text-gray-500",children:un(I)})]})]})]},v.method)}),w.length===0&&e.jsx("p",{className:"text-gray-500 text-sm text-center py-4",children:"Nenhuma venda real registrada"})]})]}),e.jsxs("div",{className:"bg-gray-900/50 border border-gray-800 rounded-xl p-5","data-testid":"bi-ai-costs",children:[e.jsxs("h3",{className:"font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-orange-400"}),"Custo IA por Categoria"]}),e.jsx("div",{className:"space-y-2.5",children:D.map(v=>{const I=p.totalAiCostBRL>0?v.costBRL/p.totalAiCostBRL*100:0;return e.jsxs("div",{"data-testid":`ai-cost-${v.category}`,children:[e.jsxs("div",{className:"flex justify-between items-baseline mb-1",children:[e.jsx("span",{className:"text-sm text-white",children:v.category}),e.jsx("span",{className:"text-sm font-medium text-orange-400",children:yt(v.costBRL)})]}),e.jsx("div",{className:"w-full bg-gray-800 rounded-full h-1.5",children:e.jsx("div",{className:"h-1.5 rounded-full bg-gradient-to-r from-orange-500 to-amber-500",style:{width:`${Math.max(I,2)}%`}})}),e.jsxs("div",{className:"flex justify-between mt-0.5",children:[e.jsxs("span",{className:"text-[10px] text-gray-500",children:[v.callCount," chamadas"]}),e.jsxs("span",{className:"text-[10px] text-gray-500",children:[Bg(v.totalTokens)," tokens"]})]})]},v.category)})})]})]}),e.jsxs("div",{className:"bg-gray-900/50 border border-gray-800 rounded-xl p-5","data-testid":"bi-products",children:[e.jsxs("h3",{className:"font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(Zs,{className:"w-4 h-4 text-teal-400"}),"Receita por Produto/Serviço"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-gray-400 text-xs border-b border-gray-800",children:[e.jsx("th",{className:"text-left py-2 pr-4",children:"Produto"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Pedidos"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Receita Bruta"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Receita Líquida"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Custo IA"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Margem"}),e.jsx("th",{className:"text-right py-2 pl-2",children:"Margem 
2%"})]})}),e.jsxs("tbody",{children:[y.map(v=>e.jsxs("tr",{className:"border-b border-gray-800/50 hover:bg-gray-800/30","data-testid":`product-row-${v.type}`,children:[e.jsx("td",{className:"py-2.5 pr-4 text-white",children:v.label}),e.jsx("td",{className:"py-2.5 px-2 text-right text-gray-300",children:v.orders}),e.jsx("td",{className:"py-2.5 px-2 text-right text-emerald-400",children:yt(v.grossRevenue)}),e.jsx("td",{className:"py-2.5 px-2 text-right text-gray-300",children:yt(v.netRevenue)}),e.jsx("td",{className:"py-2.5 px-2 text-right text-orange-400",children:yt(v.aiCost)}),e.jsx("td",{className:`py-2.5 px-2 text-right font-medium ${v.margin>=0?"text-emerald-400":"text-red-400"}`,children:yt(v.margin)}),e.jsx("td",{className:`py-2.5 pl-2 text-right ${v.marginPercent>=0?"text-emerald-400":"text-red-400"}`,children:un(v.marginPercent)})]},v.type)),y.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"py-4 text-center text-gray-500",children:"Nenhum produto vendido"})})]})]})})]}),e.jsxs("div",{className:"bg-gray-900/50 border border-gray-800 rounded-xl p-5","data-testid":"bi-daily-chart",children:[e.jsxs("h3",{className:"font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-teal-400"}),"Receita Diária (90 dias)"]}),e.jsx("div",{className:"flex items-end gap-[2px] h-32 overflow-x-auto",children:$.map(v=>{const I=o>0?v.revenue/o*100:0,de=L>0?v.orders/L*100:0;return e.jsxs("div",{className:"flex flex-col items-center min-w-[6px] flex-1 group relative",children:[e.jsxs("div",{className:"w-full flex flex-col-reverse h-28",children:[v.revenue>0&&e.jsx("div",{className:"w-full bg-gradient-to-t from-emerald-600 to-emerald-400 rounded-t-sm min-h-[2px]",style:{height:`${Math.max(I,3)}%`}}),v.orders>0&&v.revenue===0&&e.jsx("div",{className:"w-full bg-gray-600 rounded-t-sm min-h-[2px]",style:{height:`${Math.max(de,5)}%`}})]}),e.jsxs("div",{className:"absolute bottom-full mb-1 hidden group-hover:block bg-gray-800 border border-gray-700 rounded px-2 py-1 text-[10px] z-10 whitespace-nowrap",children:[e.jsx("p",{className:"text-gray-300",children:new Date(v.date).toLocaleDateString("pt-BR")}),e.jsx("p",{className:"text-emerald-400",children:yt(v.revenue)}),e.jsxs("p",{className:"text-gray-400",children:[v.orders," pedido(s)"]}),e.jsxs("p",{className:"text-violet-400",children:[v.newUsers," novo(s)"]})]})]},v.date)})}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-gray-500",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-emerald-500 rounded-sm"})," Receita"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-gray-600 rounded-sm"})," Pedidos (sem receita)"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-gray-900/50 border border-gray-800 rounded-xl p-5","data-testid":"bi-utm-sources",children:[e.jsxs("h3",{className:"font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-violet-400"}),"Receita por Origem (UTM Source)"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-gray-400 text-xs border-b border-gray-800",children:[e.jsx("th",{className:"text-left py-2 pr-4",children:"Origem"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Usuários"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Pedidos"}),e.jsx("th",{className:"text-right py-2 pl-2",children:"Receita"})]})}),e.jsx("tbody",{children:c.map(v=>e.jsxs("tr",{className:"border-b border-gray-800/50","data-testid":`utm-source-${v.source}`,children:[e.jsx("td",{className:"py-2 pr-4 text-white",children:v.source}),e.jsx("td",{className:"py-2 px-2 text-right text-gray-300",children:v.users}),e.jsx("td",{className:"py-2 px-2 text-right text-gray-300",children:v.orders}),e.jsx("td",{className:"py-2 pl-2 text-right text-emerald-400",children:yt(v.revenue)})]},v.source))})]})})]}),e.jsxs("div",{className:"bg-gray-900/50 border border-gray-800 rounded-xl p-5","data-testid":"bi-utm-campaigns",children:[e.jsxs("h3",{className:"font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-teal-400"}),"Receita por Campanha (UTM Campaign)"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-gray-400 text-xs border-b border-gray-800",children:[e.jsx("th",{className:"text-left py-2 pr-4",children:"Campanha"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Usuários"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Pedidos"}),e.jsx("th",{className:"text-right py-2 pl-2",children:"Receita"})]})}),e.jsx("tbody",{children:m.map(v=>e.jsxs("tr",{className:"border-b border-gray-800/50","data-testid":`utm-campaign-${v.campaign}`,children:[e.jsx("td",{className:"py-2 pr-4 text-white",children:v.campaign}),e.jsx("td",{className:"py-2 px-2 text-right text-gray-300",children:v.users}),e.jsx("td",{className:"py-2 px-2 text-right text-gray-300",children:v.orders}),e.jsx("td",{className:"py-2 pl-2 text-right text-emerald-400",children:yt(v.revenue)})]},v.campaign))})]})})]})]}),e.jsxs("div",{className:"bg-gray-900/50 border border-gray-800 rounded-xl p-5","data-testid":"bi-ltv-table",children:[e.jsxs("h3",{className:"font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 text-violet-400"}),"LTV por Cliente (Todos)"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-gray-400 text-xs border-b border-gray-800",children:[e.jsx("th",{className:"text-left py-2 pr-3",children:"Cliente"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Fluxo"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Origem"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Receita Real"}),e.jsx("th",{className:"text-right py-2 px-2",children:"+ Créditos/Beta"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Pedidos"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Custo IA"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Margem"}),e.jsx("th",{className:"text-left py-2 pl-2",children:"Desde"})]})}),e.jsxs("tbody",{children:[F.map(v=>e.jsxs("tr",{className:"border-b border-gray-800/50 hover:bg-gray-800/30","data-testid":`ltv-user-${v.id}`,children:[e.jsx("td",{className:"py-2.5 pr-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-white text-sm",children:v.name||"—"}),e.jsx("p",{className:"text-gray-500 text-[10px]",children:v.email})]})}),e.jsx("td",{className:"py-2.5 px-2",children:e.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${v.entryFlow==="Chat"?"bg-violet-500/20 text-violet-400":"bg-teal-500/20 text-teal-400"}`,children:v.entryFlow})}),e.jsxs("td",{className:"py-2.5 px-2",children:[e.jsx("span",{className:"text-xs text-gray-300",children:v.firstSource}),v.allSources.length>1&&e.jsxs("span",{className:"text-[10px] text-amber-400 ml-1",children:["+",v.allSources.length-1]})]}),e.jsx("td",{className:"py-2.5 px-2 text-right text-emerald-400 font-medium",children:yt(v.totalSpend)}),e.jsx("td",{className:"py-2.5 px-2 text-right text-gray-500",children:v.creditsBetaSpend>0?yt(v.creditsBetaSpend):"—"}),e.jsx("td",{className:"py-2.5 px-2 text-right text-gray-300",children:v.allOrderCount}),e.jsx("td",{className:"py-2.5 px-2 text-right text-orange-400",children:yt(v.aiCost)}),e.jsx("td",{className:`py-2.5 px-2 text-right font-medium ${v.margin>=0?"text-emerald-400":"text-red-400"}`,children:yt(v.margin)}),e.jsx("td",{className:"py-2.5 pl-2 text-xs text-gray-500",children:v.firstSeen?new Date(v.firstSeen).toLocaleDateString("pt-BR"):"—"})]},v.id)),F.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"py-4 text-center text-gray-500",children:"Nenhum usuário"})})]})]})})]}),e.jsxs("div",{className:"bg-gray-900/50 border border-gray-800 rounded-xl p-5","data-testid":"bi-funnel-stats",children:[e.jsxs("h3",{className:"font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(Ot,{className:"w-4 h-4 text-amber-400"}),"Estatísticas do Funil"]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold text-white",children:A.totalChatSessions}),e.jsx("p",{className:"text-xs text-gray-400",children:"Sessões de Chat"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-400",children:A.chatConversions}),e.jsx("p",{className:"text-xs text-gray-400",children:"Convertidos (Lead)"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold text-amber-400",children:A.totalCheckoutSessions}),e.jsx("p",{className:"text-xs text-gray-400",children:"Checkouts Criados"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold text-violet-400",children:A.paidCheckoutSessions}),e.jsx("p",{className:"text-xs text-gray-400",children:"Checkouts Pagos"})]})]})]})]})}function fr({label:a,value:r,icon:l,color:n,subtitle:u,testId:f}){return e.jsxs("div",{className:"bg-gray-900/50 border border-gray-800 rounded-xl p-4","data-testid":f,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx("span",{className:n,children:l}),e.jsx("span",{className:"text-[10px] text-gray-400 uppercase tracking-wider",children:a})]}),e.jsx("p",{className:`text-lg font-bold ${n}`,children:r}),e.jsx("p",{className:"text-[10px] text-gray-500 mt-0.5",children:u})]})}function Wg(a){return a?a.evidenceKind==="generic"||a.evidenceKind==="full"?a.evidenceKind:a.evidenceSubmitted?a.dossiePdfPath&&a.dossiePdfPath.includes("dossie-defesa-")?"generic":"full":null:null}function Hg(a){const l={OPENED:{color:"bg-yellow-500/20 text-yellow-300 border-yellow-500/30",label:"Aberta"},ACKNOWLEDGED:{color:"bg-blue-500/20 text-blue-300 border-blue-500/30",label:"Reconhecida"},ACCEPTED:{color:"bg-red-500/20 text-red-300 border-red-500/30",label:"Aceita (Perdida)"},REJECTED:{color:"bg-green-500/20 text-green-300 border-green-500/30",label:"Rejeitada (Ganha)"},CANCELED:{color:"bg-gray-500/20 text-gray-300 border-gray-500/30",label:"Cancelada"},IN_ANALYSIS:{color:"bg-purple-500/20 text-purple-300 border-purple-500/30",label:"Em Análise"},WAITING_RETURN:{color:"bg-orange-500/20 text-orange-300 border-orange-500/30",label:"Aguard. Retorno"}}[a]||{color:"bg-gray-500/20 text-gray-300 border-gray-500/30",label:a};return e.jsx(E,{className:`${l.color} border`,children:l.label})}function Xg(a,r){return a.length<=r?a:a.slice(0,r)+"..."}function Jg({disputeId:a,onSelect:r,onClose:l}
2){const[n,u]=d.useState(""),[f,j]=d.useState([]),[p,g]=d.useState(!1),w=d.useRef(null),y=d.useRef(null);d.useEffect(()=>{w.current?.focus()},[]);const F=d.useCallback(async m=>{if(m.trim().length<2){j([]);return}g(!0);try{const $=await fetch(`/api/admin/disputes/search-clients?q=${encodeURIComponent(m.trim())}`,{credentials:"include"});if(!$.ok){j([]);return}const D=await $.json();j(D.clients||[])}catch{j([])}finally{g(!1)}},[]),c=m=>{u(m),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>F(m),300)};return e.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4",onClick:m=>{m.target===m.currentTarget&&l()},"data-testid":"modal-client-search",children:e.jsxs("div",{className:"bg-[#1a1a2e] border border-white/10 rounded-xl w-full max-w-lg shadow-2xl max-h-[80vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[e.jsxs("h3",{className:"text-white font-semibold flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-orange-400"}),"Buscar Cliente para Vincular"]}),e.jsx("button",{onClick:l,className:"text-white/40 hover:text-white","data-testid":"button-close-search-modal",children:e.jsx(ea,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"p-4 border-b border-white/10",children:[e.jsxs("div",{className:"relative",children:[e.jsx(St,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/30"}),e.jsx(J,{ref:w,value:n,onChange:m=>c(m.target.value),placeholder:"Pesquisar por nome, email ou telefone...",className:"bg-white/5 border-white/10 text-white pl-10 h-10","data-testid":"input-search-client"}),p&&e.jsx(T,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-orange-400 animate-spin"})]}),e.jsx("p",{className:"text-white/30 text-xs mt-2",children:"Digite pelo menos 2 caracteres para buscar"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-2 space-y-1 min-h-[120px] max-h-[400px]",children:[!p&&f.length===0&&n.length>=2&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-white/30",children:[e.jsx(Hi,{className:"w-8 h-8 mb-2"}),e.jsx("p",{className:"text-sm",children:"Nenhum cliente encontrado"})]}),!p&&n.length<2&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-white/20",children:[e.jsx(St,{className:"w-8 h-8 mb-2"}),e.jsx("p",{className:"text-sm",children:"Aguardando pesquisa..."})]}),f.map(m=>e.jsxs("button",{onClick:()=>r(m.id),className:"w-full text-left p-3 rounded-lg hover:bg-orange-500/10 border border-transparent hover:border-orange-500/30 transition-all group","data-testid":`button-select-client-${m.id}`,children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hi,{className:"w-4 h-4 text-orange-400 shrink-0"}),e.jsx("span",{className:"text-white font-medium text-sm truncate",children:m.name})]}),m.email&&e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{className:"w-3 h-3 text-white/30 shrink-0"}),e.jsx("span",{className:"text-white/50 text-xs truncate",children:m.email})]}),m.phone&&e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(Ul,{className:"w-3 h-3 text-white/30 shrink-0"}),e.jsx("span",{className:"text-white/50 text-xs",children:m.phone})]})]}),e.jsxs("div",{className:"text-right shrink-0 ml-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-teal-300 text-xs",children:[e.jsx(Gl,{className:"w-3 h-3"}),m.orderCount," pedido",m.orderCount!==1?"s":""]}),m.totalSpent>0&&e.jsxs("div",{className:"text-white/40 text-[10px] mt-0.5",children:["R$ ",(m.totalSpent/100).toFixed(2)]})]})]}),e.jsxs("div",{className:"mt-1.5 text-[10px] text-white/20 font-mono truncate group-hover:text-white/30",children:["ID: ",m.id]})]},m.id))]})]})})}function Yg(){const{toast:a}=st(),[r,l]=d.useState(null),[n,u]=d.useState(""),[f,j]=d.useState(""),[p,g]=d.useState({}),[w,y]=d.useState(null),[F,c]=d.useState(null),{data:m=[],isLoading:$,refetch:D}=z({queryKey:["/api/admin/disputes"],refetchInterval:3e4}),A=d.useCallback(async(h,te,M)=>{c(M);const ae=new AbortController,ye=setTimeout(()=>ae.abort(),900*1e3);try{const Me=te==="zip"?`/api/admin/users/${h}/dossie-zip`:`/api/admin/users/${h}/dossie`,se=await fetch(Me,{credentials:"include",signal:ae.signal});if(!se.ok){let ge=`Falha ao gerar dossiê (${se.status})`;try{const ut=await se.json();ut?.error&&(ge=ut.error)}catch{}throw new Error(ge)}const Ne=await se.blob(),ie=te==="zip"?"zip":"pdf",X=window.URL.createObjectURL(Ne),B=document.createElement("a");B.href=X,B.download=`dossie-${h.slice(0,8)}.${ie}`,document.body.appendChild(B),B.click(),B.remove(),window.URL.revokeObjectURL(X),a({title:"Dossiê pronto",description:te==="zip"?"ZIP das partes baixado.":"PDF completo baixado."})}catch(Me){const se=Me?.name==="AbortError";a({title:"Erro ao baixar dossiê",description:se?"A geração demorou demais (15 min). Tente novamente.":Me?.message||"Erro desconhecido",variant:"destructive"})}finally{clearTimeout(ye),c(null)}},[a]),o=W({mutationFn:async({userId:h,disputeId:te})=>(await N("POST","/api/admin/disputes/send-manual",{userId:h,disputeId:te})).json(),onSuccess:h=>{a({title:"Sucesso",description:h.message||"Dossiê enviado manualmente"}),u(""),j(""),K.invalidateQueries({queryKey:["/api/admin/disputes"]})},onError:h=>{a({title:"Erro",description:h.message,variant:"destructive"})}}),L=W({mutationFn:async()=>(await N("POST","/api/admin/disputes/sync")).json(),onSuccess:h=>{a({title:"Sincronização",description:h.message}),K.invalidateQueries({queryKey:["/api/admin/disputes"]})},onError:h=>{a({title:"Erro",description:h.message,variant:"destructive"})}}),v=W({mutationFn:async()=>(await N("POST","/api/admin/disputes/enrich-all")).json(),onSuccess:h=>{a({title:"Enriquecimento",description:h.message}),K.invalidateQueries({queryKey:["/api/admin/disputes"]})},onError:h=>{a({title:"Erro",description:h.message,variant:"destructive"})}}),I=W({mutationFn:async()=>
2(await N("POST","/api/admin/disputes/clean-owner-names")).json(),onSuccess:h=>{a({title:"Limpeza",description:h.message}),K.invalidateQueries({queryKey:["/api/admin/disputes"]})},onError:h=>{a({title:"Erro",description:h.message,variant:"destructive"})}}),de=W({mutationFn:async({disputeRecordId:h,userId:te})=>(await N("POST",`/api/admin/disputes/${h}/assign-user`,{userId:te})).json(),onSuccess:(h,te)=>{a({title:"Sucesso",description:h.message}),g(M=>({...M,[te.disputeRecordId]:""})),K.invalidateQueries({queryKey:["/api/admin/disputes"]})},onError:h=>{a({title:"Erro",description:h.message,variant:"destructive"})}});W({mutationFn:async h=>(await N("POST",`/api/admin/disputes/${h}/retry-resolve`)).json(),onSuccess:h=>{a({title:h.success?"Sucesso":"Info",description:h.message}),K.invalidateQueries({queryKey:["/api/admin/disputes"]})},onError:h=>{a({title:"Erro",description:h.message,variant:"destructive"})}});const me=W({mutationFn:async h=>(await N("POST",`/api/admin/disputes/${h}/run-pipeline`)).json(),onSuccess:h=>{a({title:"Sucesso",description:h.message}),K.invalidateQueries({queryKey:["/api/admin/disputes"]})},onError:h=>{a({title:"Erro",description:h.message,variant:"destructive"})}});W({mutationFn:async h=>(await N("POST",`/api/admin/disputes/${h}/enrich`)).json(),onSuccess:h=>{a({title:"Enriquecido",description:h.message}),K.invalidateQueries({queryKey:["/api/admin/disputes"]})},onError:h=>{a({title:"Erro",description:h.message,variant:"destructive"})}});const ne=W({mutationFn:async h=>(await N("POST",`/api/admin/disputes/${h}/send-dossie-generic`)).json(),onSuccess:h=>{a({title:"Dossiê Enviado",description:h.message}),K.invalidateQueries({queryKey:["/api/admin/disputes"]})},onError:h=>{a({title:"Erro",description:h.message,variant:"destructive"})}}),Z=m.filter(h=>["OPENED","ACKNOWLEDGED","IN_ANALYSIS","WAITING_RETURN"].includes(h.status)),S=m.filter(h=>h.evidenceSubmitted),re=m.filter(h=>!h.userId),_=m.reduce((h,te)=>h+(te.value||0),0),ee=L.isPending||v.isPending||I.isPending;return e.jsxs("div",{className:"space-y-6","data-testid":"disputes-dashboard",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-bold text-white flex items-center gap-2",children:[e.jsx(Ks,{className:"w-5 h-5 text-orange-400"}),"Disputas PIX (MED)"]}),e.jsx("p",{className:"text-sm text-white/50 mt-1",children:"Automação de dossiê + evidências via API Woovi"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(b,{onClick:()=>v.mutate(),variant:"outline",size:"sm",className:"gap-1.5",disabled:ee,"data-testid":"button-enrich-all",children:[v.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(He,{className:"w-3.5 h-3.5"}),"Identificar Clientes"]}),e.jsxs(b,{onClick:()=>L.mutate(),variant:"outline",size:"sm",className:"gap-1.5",disabled:ee,"data-testid":"button-sync-disputes",children:[L.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Ym,{className:"w-3.5 h-3.5"}),"Sincronizar Woovi"]}),e.jsxs(b,{onClick:()=>I.mutate(),variant:"outline",size:"sm",className:"gap-1.5 border-red-500/30 text-red-400 hover:bg-red-500/10",disabled:ee,"data-testid":"button-clean-owner-names",children:[I.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(As,{className:"w-3.5 h-3.5"}),"Limpar Dados Woovi"]}),e.jsxs(b,{onClick:()=>D(),variant:"outline",size:"sm",className:"gap-1.5","data-testid":"button-refresh-disputes",children:[e.jsx(xe,{className:"w-3.5 h-3.5"})," Atualizar"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(je,{className:"bg-white/5 border-white/10",children:e.jsxs(ve,{className:"p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-white",children:m.length}),e.jsx("div",{className:"text-[10px] text-white/50",children:"Total"})]})}),e.jsx(je,{className:"bg-yellow-500/10 border-yellow-500/20",children:e.jsxs(ve,{className:"p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-yellow-300",children:Z.length}),e.jsx("div",{className:"text-[10px] text-yellow-300/70",children:"Ativas"})]})}),e.jsx(je,{className:"bg-green-500/10 border-green-500/20",children:e.jsxs(ve,{className:"p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-300",children:S.length}),e.jsx("div",{className:"text-[10px] text-green-300/70",children:"Com Evidência"})]})}),e.jsx(je,{className:"bg-red-500/10 border-red-500/20",children:e.jsxs(ve,{className:"p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-red-300",children:re.length}),e.jsx("div",{className:"text-[10px] text-red-300/70",children:"Sem Cliente"})]})}),e.jsx(je,{className:"bg-white/5 border-white/10",children:e.jsxs(ve,{className:"p-3 text-center",children:[e.jsxs("div",{className:"text-2xl font-bold text-white",children:["R$ ",(_/100).toFixed(2)]}),e.jsx("div",{className:"text-[10px] text-white/50",children:"Valor Total"})]})})]}),e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsxs(Fe,{className:"pb-3",children:[e.jsxs(De,{className:"text-sm text-white flex items-center gap-2",children:[e.jsx(ct,{className:"w-4 h-4 text-orange-400"}),"Enviar Dossiê Manualmente"]}),e.jsx(su,{className:"text-xs text-white/50",children:"Para disputas pré-automação ou casos onde o webhook não chegou"})]}),e.jsx(ve,{children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx("div",{className:"flex-1",children:e.jsx(J,{placeholder:"ID do Usuário (UUID)",value:n,onChange:h=>u(h.target.value),className:"bg-white/5 border-white/10 text-white text-sm","data-testid":"input-manual-user-id"})}),e.jsx("div",{className:"flex-1",children:e.jsx(J,{placeholder:"ID da Disputa na Woovi (endToEndId)",value:f,onChange:h=>j(h.target.value),className:"bg-white/5 border-white/10 text-white text-sm","data-testid":"input-manual-dispute-id"})}),e.jsxs(b,{onClick:()=>o.mutate({userId:n.trim(),disputeId:f.trim()}),disabled:!n.trim()||!f.trim()||o.isPending,className:"bg-orange-600 hover:bg-orange-700 gap-1.5 shrink-0","data-testid":"button-send-manual-dossie",children:[o.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin"}):e.jsx(ct,{className:"w-4 h-4"}),"Enviar Dossiê"]})]})})]}),$?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-orange-400"})}):m.length===0?e.jsx(je,{className:"bg-white/5 border-white/10",children:e.jsxs(ve,{className:"p-8 text-center",children:[e.jsx(Ks,{className:"w-12 h-12 text-white/20 mx-auto mb-3"}),e.jsx("p",{className:"text-white/50 text-sm",children:"Nenhuma disputa registrada"}),e.jsx("p",{className:"text-white/30 text-xs mt-1",children:'Clique em "Sincronizar Woovi" para importar disputas'})]})}):e.jsx("div",{className:"space-y-3",children:m.map(h=>{const te=Wg(h),M=te==="generic",ae=te===null?"Enviar Dossiê":M?"Enviar Dossiê Completo":h.errorMessage?"Re-enviar":"Atualizar Dossiê",ye=te!=="full"||!!h.errorMessage;return e.jsx(je,{className:"bg-white/5 border-white/10 hover:border-white/20 transition-colors","data-testid":`card-dispute-${h.id}`,children:e.jsxs(ve,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Hg(h.status),M&&e.jsxs(E,{className:"bg-amber-500/20 text-amber-300 border border-amber-500/30 gap-1","data-testid":`badge-generic-evidence-${h.id}`,children:[e.jsx(Ce,{className:"w-3 h-3"})," Só Defesa Genérica"]}),te==="full"&&e.jsxs(E,{className:"bg-green-500/20 text-green-300 border border-green-500/30 gap-1","data-testid":`badge-full-evidence-${h.id}`,children:[e.jsx(is,{className:"w-3 h-3"})," Dossiê Completo Enviado"]}),!h.userId&&e.jsxs(E,{className:"bg-orange-500/20 text-orange-300 border border-orange-500/30 gap-1",children:[e.jsx(Hi,{className:"w-3 h-3"})," Sem Cliente"]})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-3 flex-wrap text-xs",children:[e.jsxs("span",{className:"text-white/60 flex items-center gap-1",children:[e.jsx(Zl,{className:"w-3 h-3"}
2),new Date(h.createdAt).toLocaleString("pt-BR")]}),h.value!=null&&e.jsxs("span",{className:"text-white font-semibold flex items-center gap-1",children:[e.jsx(nt,{className:"w-3 h-3"}),"R$ ",(h.value/100).toFixed(2)]}),h.disputerName&&e.jsxs("span",{className:"text-teal-300 font-medium flex items-center gap-1",children:[e.jsx(Hi,{className:"w-3 h-3"}),h.disputerName]})]}),h.disputeReason&&e.jsxs("div",{className:"mt-2 text-xs text-white/50 bg-white/5 rounded px-2 py-1.5 leading-relaxed",children:[e.jsx(tt,{className:"w-3 h-3 inline mr-1 text-white/30"}),r===h.id?h.disputeReason:Xg(h.disputeReason,150)]}),e.jsxs("div",{className:"mt-1 text-[10px] text-white/30 font-mono truncate",children:["E2E: ",h.endToEndId]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1.5 shrink-0",children:[h.userId&&e.jsxs(b,{size:"sm",variant:ye?"default":"outline",className:`gap-1 text-xs h-7 ${ye?M?"bg-amber-600 hover:bg-amber-700":"bg-orange-600 hover:bg-orange-700":""}`,disabled:me.isPending,onClick:()=>me.mutate(h.id),"data-testid":`button-send-evidence-${h.id}`,children:[me.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):te==="full"?e.jsx(xe,{className:"w-3 h-3"}):e.jsx(ct,{className:"w-3 h-3"}),ae]}),!h.evidenceSubmitted&&!h.userId&&e.jsxs(e.Fragment,{children:[e.jsxs(b,{size:"sm",className:"gap-1 text-xs bg-orange-600 hover:bg-orange-700 h-7",disabled:ne.isPending,onClick:()=>ne.mutate(h.id),"data-testid":`button-send-generic-dossie-${h.id}`,children:[ne.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(ct,{className:"w-3 h-3"}),"Enviar Dossiê"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"gap-1 text-xs h-7",onClick:()=>y(h.id),"data-testid":`button-search-client-${h.id}`,children:[e.jsx(St,{className:"w-3 h-3"}),"Buscar Cliente"]})]}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-7",onClick:()=>l(r===h.id?null:h.id),"data-testid":`button-expand-dispute-${h.id}`,children:r===h.id?e.jsx(ta,{className:"w-4 h-4"}):e.jsx(Ct,{className:"w-4 h-4"})})]})]}),r===h.id&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-white/10 space-y-3 text-xs",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40 block",children:"Dispute ID (Woovi)"}),e.jsx("span",{className:"text-white/70 font-mono text-[10px]",children:h.disputeId||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40 block",children:"User ID"}),e.jsx("span",{className:`font-mono text-[10px] ${h.userId?"text-white/70":"text-orange-300"}`,children:h.userId||"Não identificado"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40 block",children:"Order ID"}),e.jsx("span",{className:"text-white/70 font-mono text-[10px]",children:h.orderId||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40 block",children:"Status"}),e.jsx("span",{className:"text-white/70",children:h.status})]})]}),h.disputerName&&e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40",children:"Pagador: "}),e.jsx("span",{className:"text-teal-300 font-medium",children:h.disputerName})]}),h.disputerEmail&&e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40",children:"Email: "}),e.jsx("span",{className:"text-white/70",children:h.disputerEmail})]}),h.disputerPhone&&e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40",children:"Telefone: "}),e.jsx("span",{className:"text-white/70",children:h.disputerPhone})]}),h.disputeReason&&e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40 block mb-1",children:"Motivo da Disputa:"}),e.jsx("div",{className:"p-2 bg-white/5 rounded text-white/60 whitespace-pre-wrap leading-relaxed",children:h.disputeReason})]}),!h.userId&&e.jsxs("div",{className:"p-3 bg-orange-500/10 border border-orange-500/20 rounded space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-orange-300 text-xs font-medium flex items-center gap-1",children:[e.jsx(Ka,{className:"w-3 h-3"})," Vincular cliente"]}),e.jsxs(b,{size:"sm",className:"bg-orange-600 hover:bg-orange-700 h-
27 text-xs gap-1",onClick:()=>y(h.id),"data-testid":`button-search-client-expanded-${h.id}`,children:[e.jsx(St,{className:"w-3 h-3"}),"Buscar por Nome/Email/Tel"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(J,{placeholder:"Ou cole o UUID diretamente...",value:p[h.id]||"",onChange:Me=>g(se=>({...se,[h.id]:Me.target.value})),className:"bg-white/5 border-white/10 text-white text-xs h-8 flex-1","data-testid":`input-assign-user-${h.id}`}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-8 text-xs gap-1",disabled:!p[h.id]?.trim()||de.isPending,onClick:()=>de.mutate({disputeRecordId:h.id,userId:p[h.id].trim()}),"data-testid":`button-assign-user-${h.id}`,children:[de.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(Ka,{className:"w-3 h-3"}),"Vincular UUID"]})]})]}),h.userId&&e.jsx("div",{className:`p-3 rounded border ${M?"bg-amber-500/10 border-amber-500/20":te==="full"?"bg-white/5 border-white/10":"bg-green-500/10 border-green-500/20"}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("p",{className:`text-xs ${M?"text-amber-300":te==="full"?"text-white/50":"text-green-300"}`,children:[te===null&&"Cliente vinculado. Pronto para enviar o dossiê completo como evidência.",M&&"A Woovi só recebeu a defesa genérica até agora — envie o dossiê completo do cliente pra substituir.",te==="full"&&(h.errorMessage?"A última tentativa de reenvio falhou — tente novamente.":"Dossiê completo já enviado. Você pode reenviar/atualizar quando quiser.")]}),e.jsxs(b,{size:"sm",variant:ye?"default":"outline",className:`h-8 text-xs gap-1 ${ye?M?"bg-amber-600 hover:bg-amber-700":"bg-orange-600 hover:bg-orange-700":""}`,disabled:me.isPending,onClick:()=>me.mutate(h.id),"data-testid":`button-run-pipeline-expanded-${h.id}`,children:[me.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(Us,{className:"w-3 h-3"}),te===null?"Gerar Dossiê + Enviar Evidência":ae]})]})}),h.dossiePdfPath&&e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40",children:"Dossiê PDF: "}),e.jsx("span",{className:"text-white/70 font-mono text-[10px]",children:h.dossiePdfPath})]}),h.userId&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(b,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1",disabled:F===`${h.id}-zip`,onClick:()=>A(h.userId,"zip",`${h.id}-zip`),"data-testid":`button-dossie-zip-${h.id}`,children:[F===`${h.id}-zip`?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(Ym,{className:"w-3 h-3"}),"Baixar ZIP dividido"]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"h-7 text-xs gap-1 text-white/60",disabled:F===`${h.id}-pdf`,onClick:()=>A(h.userId,"pdf",`${h.id}-pdf`),"data-testid":`button-dossie-pdf-${h.id}`,children:[F===`${h.id}-pdf`?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(tt,{className:"w-3 h-3"}),"PDF completo"]})]}),h.evidenceSubmittedAt&&e.jsxs("div",{children:[e.jsx("span",{className:"text-white/40",children:"Evidência enviada em: "}),e.jsx("span",{className:"text-green-300",children:new Date(h.evidenceSubmittedAt).toLocaleString("pt-BR")})]}),h.errorMessage&&e.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/20 rounded text-red-300",children:[e.jsx(Ce,{className:"w-3 h-3 inline mr-1"}),h.errorMessage]}),h.evidenceWooviResponse&&e.jsxs("details",{className:"text-white/40",children:[e.jsx("summary",{className:"cursor-pointer hover:text-white/60",children:"Resposta Woovi (JSON)"}),e.jsx("pre",{className:"mt-1 p-2 bg-black/30 rounded text-[10px] overflow-auto max-h-40",children:JSON.stringify(h.evidenceWooviResponse,null,2)})]})]})]})},h.id)})}),w&&e.jsx(Jg,{disputeId:w,onClose:()=>y(null),onSelect:h=>{de.mutate({disputeRecordId:w,userId:h},{onSuccess:()=>{y(null)}})}})]})}const nh={discovered:{label:"Descoberto",color:"bg-gray-500/20 text-gray-400"},ready_to_contact:{label:"Pronto",color:"bg-blue-500/20 text-blue-400"},scored:{label:"Avaliado",color:"bg-purple-500/20 text-purple-400"},low_fit:{label:"Baixo Fit",color:"bg-orange-500/20 text-orange-400"},contacted:{label:"Contactado",color:"bg-yellow-500/20 text-yellow-400"}
2,sequence_complete:{label:"Sequência Completa",color:"bg-amber-500/20 text-amber-400"},responded:{label:"Em Negociação",color:"bg-cyan-500/20 text-cyan-400"},onboarded:{label:"Respondeu Positivamente",color:"bg-emerald-500/20 text-emerald-400"},active:{label:"Ativo",color:"bg-teal-500/20 text-teal-400"},declined:{label:"Respondeu Negativamente",color:"bg-red-500/20 text-red-400"}},yn={"pt-BR":"🇧🇷",en:"🇺🇸",es:"🇪🇸",fr:"🇫🇷",de:"🇩🇪",it:"🇮🇹",ja:"🇯🇵",ko:"🇰🇷",zh:"🇨🇳",ar:"🇸🇦",hi:"🇮🇳"},Zg=[{code:"pt-BR",name:"Português (BR)",flag:"🇧🇷"},{code:"en",name:"English",flag:"🇺🇸"},{code:"es",name:"Español",flag:"🇪🇸"},{code:"fr",name:"Français",flag:"🇫🇷"},{code:"de",name:"Deutsch",flag:"🇩🇪"},{code:"it",name:"Italiano",flag:"🇮🇹"},{code:"ja",name:"日本語",flag:"🇯🇵"},{code:"zh",name:"中文",flag:"🇨🇳"},{code:"ko",name:"한국어",flag:"🇰🇷"},{code:"ar",name:"العربية",flag:"🇸🇦"}];function eb(){const{toast:a}=st(),[r,l]=d.useState("all"),[n,u]=d.useState("all"),[f,j]=d.useState(""),[p,g]=d.useState(""),[w,y]=d.useState("pipeline"),[F,c]=d.useState(!1);d.useEffect(()=>{const X=setTimeout(()=>g(f.trim()),350);return()=>clearTimeout(X)},[f]);const{data:m}=z({queryKey:["/api/admin/influencers/languages"],queryFn:()=>N("GET","/api/admin/influencers/languages").then(X=>X.json())}),{data:$}=z({queryKey:["/api/admin/influencers/worker-status"],queryFn:()=>N("GET","/api/admin/influencers/worker-status").then(X=>X.json()),refetchInterval:1e4}),D=W({mutationFn:X=>N("POST","/api/admin/influencers/worker-toggle",{enabled:X}).then(B=>B.json()),onSuccess:X=>{a({title:X.active?"Worker ligado":"Worker desligado",description:X.active?"O AI Influencer Negotiator está ativo e rodando ciclos automaticamente.":"O worker foi desligado. Nenhum ciclo automático será executado."}),K.invalidateQueries({queryKey:["/api/admin/influencers/worker-status"]})},onError:()=>{a({title:"Erro",description:"Não foi possível alterar o estado do worker.",variant:"destructive"})}}),[A,o]=d.useState(["pt-BR"]);d.useEffect(()=>{m?.languages&&o(m.languages)},[m]);const L=W({mutationFn:X=>N("PUT","/api/admin/influencers/languages",{languages:X}),onSuccess:()=>{a({title:"Idiomas atualizados",description:"O negotiator agora vai trabalhar apenas nos idiomas selecionados."}),K.invalidateQueries({queryKey:["/api/admin/influencers/languages"]})},onError:()=>{a({title:"Erro",description:"Selecione pelo menos um idioma.",variant:"destructive"})}}),v=X=>{o(B=>B.includes(X)?B.length===1?B:B.filter(ge=>ge!==X):[...B,X])},{data:I,isLoading:de}=z({queryKey:["/api/admin/influencers/stats"],queryFn:()=>N("GET","/api/admin/influencers/stats").then(X=>X.json()),refetchInterval:3e4}),{data:me,isLoading:ne}=z({queryKey:["/api/admin/influencers",r,n,p],queryFn:()=>{const X=new URLSearchParams;return r!=="all"&&X.set("status",r),n!=="all"&&X.set("language",n),p&&X.set("search",p),X.set("limit","100"),N("GET",`/api/admin/influencers?${X}`).then(B=>B.json())},refetchInterval:3e4}),{data:Z,isLoading:S}=z({queryKey:["/api/admin/influencers/roi"],queryFn:()=>N("GET","/api/admin/influencers/roi").then(X=>X.json()),refetchInterval:6e4,enabled:w==="roi"}),{data:re,isLoading:_}=z({queryKey:["/api/admin/influencers/logs"],queryFn:()=>N("GET","/api/admin/influencers/logs?limit=200").then(X=>X.json()),refetchInterval:1e4,enabled:w==="logs"}),{data:ee,isLoading:h}=z({queryKey:["/api/admin/influencers/sequence-stats"],queryFn:()=>N("GET","/api/admin/influencers/sequence-stats").then(X=>X.json()),refetchInterval:15e3,enabled:w==="sequence"}),[te,M]=d.useState("all"),{data:ae,isLoading:ye}=z({queryKey:["/api/admin/influencers/emails",te],queryFn:()=>{const X=te!=="all"?`/api/admin/influencers/emails?prospectId=${te}&limit=200`:"/api/admin/influencers/emails?limit=200";return N("GET",X).then(B=>B.json())},refetchInterval:15e3,enabled:w==="emails"}),Me=W({mutationFn:()=>N("POST","/api/admin/influencers/run-cycle"),onSuccess:()=>{a({title:"Ciclo iniciado",description:"O AI Influencer Negotiator está buscando e contactando influencers..."}),setTimeout(()=>K.invalidateQueries({queryKey:["/api/admin/influencers"]}),1e4)}}),se=W({mutationFn:({id:X,status:B})=>N("PATCH",`/api/admin/influencers/${X}`,{status:B}),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/influencers"]}),K.invalidateQueries({queryKey:["/api/admin/influencers/stats"]})}}),Ne=W({mutationFn:X=>N("POST",`/api/admin/influencers/${X}/onboard`).then(B=>B.json()),onSuccess:X=>{a({title:"Influencer onboarded!",description:`Código de referral: ${X.referralCode}. Créditos e email de boas-vindas enviados.`}),K.invalidateQueries({queryKey:["/api/admin/influencers"]}),K.invalidateQueries({queryKey:["/api/admin/influencers/stats"]}),K.invalidateQueries({queryKey:["/api/admin/influencers/roi"]})},onError:()=>{a({title:"Erro no onboarding",description:"Não foi possível fazer o onboard deste influencer.",variant:"destructive"})}}),ie=W({mutationFn:X=>N("POST","/api/admin/blog/generate-multilang",{language:X}),onSuccess:()=>{a({title:"Artigo em geração",description:"O artigo multi-idioma está sendo gerado pelo SEO engine..."})}});return e.jsxs("div",{className:"space-y-6","data-testid":"section-influencer-pipeline",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg sm:text-xl font-bold text-white flex items-center gap-2",children:[e.jsx(Vi,{className:"w-5 h-5 text-amber-400"}),"AI Influencer Negotiator"]}),e.jsx("p",{className:"text-xs sm:text-sm text-white/50 mt-1",children:"Descoberta, contato e negociação automática com influencers"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>c(!F),className:`border-white/10 text-xs h-8 ${F?"text-amber-400 bg-amber-500/10":"text-white/50 hover:text-white/80"}`,"data-testid":"button-toggle-lang-config",children:[e.jsx(Wm,{className:"w-3.5 h-3.5 mr-1"}),"Idiomas"]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>ie.mutate(),disabled:ie.isPending,className:"border-purple-500/30 text-purple-400 hover:bg-purple-500/10 text-xs h-8","data-testid":"button-generate-multilang",children:[e.jsx(pt,{className:"w-3.5 h-3.5 mr-1"}),"SEO"]}),e.jsxs(b,{size:"sm",onClick:()=>Me.mutate(),disabled:Me.isPending||!$?.active,className:"bg-amber-600 hover:bg-amber-700 text-xs h-8 disabled:opacity-40","data-testid":"button-run-influencer-cycle",children:[Me.isPending?e.jsx(xe,{className:"w-3.5 h-3.5 mr-1 animate-spin"}):e.jsx(Us,{className:"w-3.5 h-3.5 mr-1"}),"Rodar Ciclo"]}),e.jsxs("button",{onClick:()=>D.mutate(!$?.active),disabled:D.isPending,className:`relative inline-flex h-8 items-center gap-2 rounded-lg px-3 text-xs font-medium transition-all duration-300 ${$?.active?"bg-emerald-500/15 border border-emerald-500/40 text-emerald-400 hover:bg-emerald-500/25":"bg-red-500/10 border border-red-500/30 text-red-400 hover:bg-red-500/20"} ${D.isPending?"opacity-60 cursor-wait":"cursor-pointer"}`,"data-testid":"button-worker-toggle",children:[D.isPending?e.jsx(xe,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(fc,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:$?.active?"Ligado":"Desligado"}),e.jsx("span",{className:`w-2 h-2 rounded-full ${$?.active?"bg-emerald-400 animate-pulse":"bg-red-400"}`})]})]})]}),I&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-3",children:[e.jsx(rs,{icon:Re,label:"Total",value:I.total||0}),e.jsx(rs,{icon:St,label:"Descobertos",value:(I.byStatus?.discovered||0)+(I.byStatus?.ready_to_contact||0)+(I.byStatus?.scored||0),color:"text-blue-400"}),e.jsx(rs,{icon:Ge,label:"Contactados",value:(I.byStatus?.contacted||0)+(I.byStatus?.sequence_complete||0),color:"text-yellow-400"}),e.jsx(rs,{icon:Ie,label:"Responderam",value:I.byStatus?.responded||0,color:"text-green-400"}),e.jsx(rs,{icon:Vi,label:"Onboarded",value:(I.byStatus?.onboarded||0)+(I.byStatus?.active||0),color:"text-emerald-400"}),e.jsx(rs,{icon:pt,label:"Idiomas",value:Object.keys(I.byLanguage||{}).length,color:"text-purple-400"})]}),F&&e.jsxs("div",{className:"bg-white/5 border border-amber-500/20 rounded-xl p-4","data-testid":"section-lang-config",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-white/70 flex items-center gap-2",children:[e.jsx(Wm,{className:"w-4 h-4 text-amber-400"}),"Idiomas Ativos do Negotiator"]}),e.jsxs(b,{size:"sm",onClick:()=>L.mutate(A),disabled:L.isPending,className:"bg-amber-600 hover:bg-amber-700 h-7 text-xs px-3","data-testid":"button-save-languages",children:[L.isPending?e.jsx(xe,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(Ua,{className:"w-3 h-3 mr-1"}),"Salvar"]})]}),e.jsx("p",{className:"text-xs text-white/40 mb-3",children:"Selecione em quais idiomas o AI Negotiator deve buscar e contactar influencers."}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 ga
2p-2",children:Zg.map(X=>{const B=A.includes(X.code);return e.jsxs("button",{onClick:()=>v(X.code),className:`flex items-center gap-2 px-3 py-2 rounded-lg border text-sm transition-all ${B?"border-amber-500/50 bg-amber-500/15 text-white":"border-white/10 bg-white/5 text-white/40 hover:text-white/60 hover:border-white/20"}`,"data-testid":`toggle-lang-${X.code}`,children:[e.jsx("span",{className:"text-base",children:X.flag}),e.jsx("span",{className:"truncate",children:X.name}),B&&e.jsx(Ua,{className:"w-3.5 h-3.5 text-amber-400 ml-auto flex-shrink-0"})]},X.code)})})]}),e.jsxs("div",{className:"flex gap-1 bg-white/5 rounded-lg p-1 overflow-x-auto",children:[e.jsx("button",{onClick:()=>y("pipeline"),className:`flex-1 min-w-0 py-2 px-2 sm:px-4 rounded-md text-xs sm:text-sm font-medium transition-colors whitespace-nowrap ${w==="pipeline"?"bg-amber-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":"tab-pipeline",children:"Pipeline"}),e.jsx("button",{onClick:()=>y("sequence"),className:`flex-1 min-w-0 py-2 px-2 sm:px-4 roun
2ded-md text-xs sm:text-sm font-medium transition-colors whitespace-nowrap ${w==="sequence"?"bg-amber-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":"tab-sequence",children:"Sequência"}),e.jsx("button",{onClick:()=>y("roi"),className:`flex-1 min-w-0 py-2 px-2 sm:px-4 rounded-md text-xs sm:text-sm font-medium transition-colors whitespace-nowrap ${w==="roi"?"bg-amber-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":"tab-roi",children:"ROI"}),e.jsx("button",{onClick:()=>y("emails"),className:`flex-1 min-w-0 py-2 px-2 sm:px-4 rounded-md text-xs sm:text-sm font-medium transition-colors whitespace-nowrap ${w==="emails"?"bg-amber-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":"tab-emails",children:"Emails"}),e.jsx("button",{onClick:()=>y("logs"),className:`flex-1 min-w-0 py-2 px-2 sm:px-4 rounded-md text-xs sm:text-sm font-medium transition-colors whitespace-nowrap ${w==="logs"?"bg-amber-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":"tab-logs",children:"Logs"})]}),w==="emails"?e.jsx(ib,{data:ae,isLoading:ye,prospects:me,prospectFilter:te,setProspectFilter:M}):w==="logs"?e.jsx(ab,{data:re,isLoading:_}):w==="sequence"?e.jsx(tb,{data:ee,isLoading:h}):w==="roi"?e.jsx(sb,{data:Z,isLoading:S}):e.jsxs(e.Fragment,{children:[I?.byLanguage&&Object.keys(I.byLanguage).length>0&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsx("h3",{className:"text-sm font-medium text-white/70 mb-3",children:"Por Idioma"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(I.byLanguage).sort((X,B)=>B[1]-X[1]).map(([X,B])=>e.jsxs("div",{className:"flex items-center gap-1.5 bg-white/5 rounded-lg px-3 py-1.5 text-sm",children:[e.jsx("span",{children:yn[X]||"🌐"}),e.jsx("span",{className:"text-white/70",children:X}),e.jsx("span",{className:"text-amber-400 font-medium",children:B})]},X))})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs("div",{className:"relative w-full sm:w-[280px]",children:[e.jsx(St,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-white/30"}),e.jsx(J,{placeholder:"Pesquisar por nome, email, nicho...",value:f,onChange:X=>j(X.target.value),className:"pl-8 bg-white/5 border-white/10 text-sm h-8 sm:h-9 placeholder:text-white/25","data-testid":"input-search-influencers"})]}),e.jsxs(Se,{value:r,onValueChange:l,children:[e.jsxs($e,{className:"w-[140px] sm:w-[180px] bg-white/5 border-white/10 text-xs sm:text-sm h-8 sm:h-9","data-testid":"select-status-filter",children:[e.jsx(Xl,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5 mr-1 text-white/40"}),e.jsx(Ae,{placeholder:"Status"})]}),e.jsxs(Pe,{children:[e.jsx(U,{value:"all",children:"Todos Status"}),Object.entries(nh).map(([X,{label:B}])=>e.jsx(U,{value:X,children:B},X))]})]}),e.jsxs(Se,{value:n,onValueChange:u,children:[e.jsxs($e,{className:"w-[120px] sm:w-[160px] bg-white/5 border-white/10 text-xs sm:text-sm h-8 sm:h-9","data-testid":"select-lang-filter",children:[e.jsx(pt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5 mr-1 text-white/40"}),e.jsx(Ae,{placeholder:"Idioma"})]}),e.jsxs(Pe,{children:[e.jsx(U,{value:"all",children:"Todos Idiomas"}),Object.entries(yn).map(([X,B])=>e.jsxs(U,{value:X,children:[B," ",X]},X))]})]})]}),ne?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(xe,{className:"w-6 h-6 animate-spin text-amber-400"})}):e.jsxs("div",{className:"space-y-2",children:[(me||[]).length===0&&e.jsxs("div",{className:"text-center py-12 text-white/40",children:[e.jsx(Vi,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:'Nenhum influencer encontrado. Clique em "Rodar Ciclo Agora" para iniciar a descoberta.'})]}),(me||[]).map(X=>{const B=nh[X.status]||{label:X.status,color:"bg-gray-500/20 text-gray-400"};return e.jsx("div",{className:"bg-white/5 border border-white/10 rounded-xl p-3 sm:p-4 hover:border-white/20 transition-colors","data-testid":`card-influencer-${X.id}`,children:e.jsxs("div",{className:"flex flex-col gap-2",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:"flex flex-wrap items-center gap-1.5 mb-1",children:[e.jsx("span",{className:"font-medium text-white text-sm sm:text-base truncate max-w-[150px] sm:max-w-none",children:X.name}),e.jsx(E,{className:`text-[9px] sm:text-[10px] shrink-0 ${B.color}`,children:B.label}),e.jsxs("span",{className:"text-[10px] sm:text-xs text-white/30 shrink-0",children:[yn[X.language]||""," ",X.language]}),X.fitScore>0&&e.jsxs("span",{className:"text-[10px] sm:text-xs text-amber-400 shrink-0",children:["⭐ ",X.fitScore]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[10px] sm:text-xs text-white/40",children:[e.jsx("span",{className:"capitalize",children:X.platform}
2),e.jsxs("span",{children:[X.followers?.toLocaleString()," seguidores"]}),e.jsx("span",{children:X.niche}),X.country&&e.jsx("span",{className:"uppercase",children:X.country})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[X.profileUrl&&e.jsx("a",{href:X.profileUrl,target:"_blank",rel:"noopener noreferrer",className:"p-1.5 hover:bg-white/10 rounded-lg transition-colors",children:e.jsx(vs,{className:"w-3.5 h-3.5 text-white/40"})}),X.email&&e.jsx("a",{href:`mailto:${X.email}`,className:"p-1.5 hover:bg-white/10 rounded-lg transition-colors",title:X.email,children:e.jsx(Ge,{className:"w-3.5 h-3.5 text-white/40"})})]})]}),X.bio&&e.jsx("p",{className:"text-[10px] sm:text-xs text-white/30 line-clamp-1",children:X.bio}),X.contentSummary&&e.jsx("p",{className:"text-[10px] sm:text-xs text-purple-400/60 line-clamp-1",children:X.contentSummary}),X.responseText&&e.jsxs("div",{className:"p-2 bg-green-500/5 border border-green-500/20 rounded-lg",children:[e.jsx("p",{className:"text-[10px] sm:text-xs text-green-400/70 font-medium mb-0.5",children:"Resposta do influencer:"}),e.jsx("p",{className:"text-[10px] sm:text-xs text-white/60 line-clamp-3",children:X.responseText})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[X.emailSentAt&&e.jsxs("span",{className:"text-[9px] sm:text-[10px] text-yellow-400/50",children:["✉️ ",new Date(X.emailSentAt).toLocaleDateString("pt-BR")]}),X.respondedAt&&e.jsxs("span",{className:"text-[9px] sm:text-[10px] text-green-400/50",children:["Resp: ",new Date(X.respondedAt).toLocaleDateString("pt-BR")]}),(X.status==="contacted"||X.status==="sequence_complete")&&e.jsxs("span",{className:`text-[9px] sm:text-[10px] px-2 py-0.5 rounded-md font-medium ${X.sequenceDay>=7?"bg-red-500/15 text-red-400":X.sequenceDay>=4?"bg-orange-500/15 text-orange-400":X.sequenceDay>=2?"bg-yellow-500/15 text-yellow-400":"bg-blue-500/15 text-blue-400"}`,"data-testid":`sequence-badge-${X.id}`,children:["📧 ",X.sequenceDay||1,"/7"]}),X.referralCode&&e.jsx("span",{className:"text-[9px] sm:text-[10px] text-emerald-400 bg-emerald-500/10 px-1.5 py-0.5 rounded",children:X.referralCode}),X.status==="responded"&&e.jsxs("div",{className:"flex gap-1 ml-auto",children:[e.jsxs(b,{size:"sm",variant:"ghost",className:"text-emerald-400 hover:bg-emerald-500/10 text-[10px] sm:text-xs h-6 px-2",onClick:()=>Ne.mutate(X.id),disabled:Ne.isPending,"data-testid":`button-onboard-${X.id}`,children:[Ne.isPending?e.jsx(xe,{className:"w-3 h-3 animate-spin mr-0.5"}):e.jsx(fh,{className:"w-3 h-3 mr-0.5"}),"Liberar Créditos"]}),e.jsx(b,{size:"sm",variant:"ghost",className:"text-red-400 hover:bg-red-500/10 text-[10px] sm:text-xs h-6 px-2",onClick:()=>se.mutate({id:X.id,status:"declined"}),"data-testid":`button-mark-declined-${X.id}`,children:"Recusou"})]})]})]})},X.id)})]})]})]})}const lh={1:{label:"Dia 1",angle:"Primeiro contato — proposta inicial",color:"text-blue-400"},2:{label:"Dia 2",angle:"Lembrete amigável",color:"text-sky-400"},3:{label:"Dia 3",angle:"Prova social — outros influencers",color:"text-cyan-400"},4:{label:"Dia 4",angle:"Valor para a audiência",color:"text-teal-400"},5:{label:"Dia 5",angle:"Urgência suave — vagas limitadas",color:"text-yellow-400"},6:{label:"Dia 6",angle:"Parceria de longo prazo",color:"text-orange-400"},7:{label:"Dia 7",angle:"Fechamento final — última chance",color:"text-red-400"}};function tb({data:a,isLoading:r}){if(r)return e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(xe,{className:"w-6 h-6 animate-spin text-amber-400"})});if(!a)return e.jsxs("div",{className:"text-center py-12 text-white/40",children:[e.jsx(ct,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Ainda sem dados de sequência. Os dados aparecerão quando influencers forem contactados em produção."})]});const l=Math.max(...Object.values(a.byDay||{}).map(n=>Number(n)||0),1);return e.jsxs("div",{className:"space-y-4","data-testid":"section-sequence-dashboard",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-white/40",children:"Atualiza automaticamente a cada 15 segundos"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-green-400 animate-pulse"}),e.jsx("span",{className:"text-xs text-white/40",children:"Ao vivo"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-3",children:[e.jsx(rs,{icon:ct,label:"Emails Hoje",value:a.emailsTodayCount||0,color:"text-amber-400"}),e.jsx(rs,{icon:Ge,label:"Total Contactados",value:a.totalContacted||0,color:"text-blue-400"}),e.jsx(rs,{icon:du,label:"Em Sequência",value:a.totalInSequence||0,color:"text-yellow-400"}),e.jsx(rs,{icon:ns,label:"Aguardando Envio",value:a.totalWaiting||0,color:"text-orange-400"}),e.jsx(rs,{icon:be,label:"Seq. Completas",value:a.totalSequenceComplete||0,color:"text-purple-400"}),e.jsx(rs,{icon:Qa,label:"Responderam",value:a.totalResponded||0,color:"text-green-400"}),e.jsx(rs,{icon:He,label:"Taxa Resposta",value:`${a.responseRate||0}%`,color:"text-emerald-400"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("h3",{className:"text-sm font-medium text-white/70 mb-4 flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-amber-400"}),"Funil da Sequência — Influencers por Dia"]}),e.jsx("div",{className:"space-y-3",children:[1,2,3,4,5,6,7].map(n=>{const u=a.byDay?.[n]||0,f=a.respondedByDay?.[n]||0,j=l>0?u/l*100:0,p=lh[n];return e.jsxs("div",{className:"group","data-testid":`sequence-day-row-${n}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-bold ${p.color}`,children:p.label}),e.jsx("span",{className:"text-[10px] text-white/30 hidden sm:inline",children:p.angle})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[f>0&&e.jsxs("span",{className:"text-[10px] text-green-400 bg-green-500/10 px-1.5 py-0.5 rounded",children:[f," responderam"]}),e.jsx("span",{className:"text-xs text-white/70 font-medium w-8 text-right",children:u})]})]}),e.jsxs("div",{className:"h-6 bg-white/5 rounded-lg overflow-hidden relative",children:[e.jsx("div",{className:`h-full rounded-lg transition-all duration-500 ${n<=2?"bg-gradient-to-r from-blue-600/60 to-blue-500/40":n<=4?"bg-gradient-to-r from-cyan-600/60 to-cyan-500/40":n<=6?"bg-gradient-to-r from-orange-600/60 to-orange-500/40":"bg-gradient-to-r from-red-600/60 to-red-500/40"}`,style:{width:`${Math.max(j,2)}%`}}),f>0&&e.jsx("div",{className:"absolute top-0 h-full bg-green-500/30 rounded-lg",style:{width:`${Math.max(f/l*100,1)}%`}})]})]},n)})}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 pt-3 border-t border-white/5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-white/30",children:[e.jsx("div",{className:"w-3 h-2 rounded bg-blue-500/40"}),"Influencers neste dia"]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-white/30",children:[e.jsx("div",{className:"w-3 h-2 rounded bg-green-500/30"}),"Responderam neste dia"]})]})]}),a.byLang&&Object.keys(a.byLang).length>0&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"p-3 border-b border-white/10",children:e.jsxs("h3",{className:"text-sm font-medium text-white/70 flex items-center gap-2",children:[e.jsx(pt,{className:"w-4 h-4 text-purple-400"}),"Sequência por Idioma"]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-xs text-white/40 border-b border-white/5",children:[e.jsx("th",{className:"text-left p-3",children:"Idioma"}),e.jsx("th",{className:"text-right p-3",children:"Contactados"}),e.jsx("th",{className:"text-right p-3",children:"Responderam"}
2),e.jsx("th",{className:"text-right p-3",children:"Seq. Completa"}),e.jsx("th",{className:"text-right p-3",children:"Taxa"})]})}),e.jsx("tbody",{children:Object.entries(a.byLang).sort((n,u)=>u[1].total-n[1].total).map(([n,u])=>{const f=u.total>0?(u.responded/u.total*100).toFixed(1):"0";return e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5 transition-colors","data-testid":`sequence-lang-${n}`,children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:yn[n]||"🌐"}),e.jsx("span",{className:"text-white/70",children:n})]})}),e.jsx("td",{className:"p-3 text-right text-blue-400 font-medium",children:u.total}),e.jsx("td",{className:"p-3 text-right text-green-400 font-medium",children:u.responded}),e.jsx("td",{className:"p-3 text-right text-purple-400",children:u.sequenceComplete}),e.jsx("td",{className:"p-3 text-right",children:e.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${Number(f)>10?"bg-green-500/15 text-green-400":Number(f)>5?"bg-yellow-500/15 text-yellow-400":"bg-white/10 text-white/50"}`,children:[f,"%"]})})]},n)})})]})})]}),a.recentSequenceEmails&&a.recentSequenceEmails.length>0&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"p-3 border-b border-white/10",children:e.jsxs("h3",{className:"text-sm font-medium text-white/70 flex items-center gap-2",children:[e.jsx(ct,{className:"w-4 h-4 text-amber-400"}),"Últimos Emails de Sequência"]})}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:a.recentSequenceEmails.map(n=>{const u=n.sentAt?new Date(n.sentAt):new Date,f=n.emailType?.replace("sequence_day_","")||"?",j=lh[Number(f)];return e.jsxs("div",{className:"flex items-start gap-3 px-4 py-3 border-b border-white/5 hover:bg-white/5 transition-colors","data-testid":`sequence-email-${n.id}`,children:[e.jsxs("div",{className:`mt-0.5 flex-shrink-0 w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold ${Number(f)<=2?"bg-blue-500/20 text-blue-400":Number(f)<=4?"bg-cyan-500/20 text-cyan-400":Number(f)<=6?"bg-orange-500/20 text-orange-400":"bg-red-500/20 text-red-400"}`,children:["D",f]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[e.jsx("span",{className:"text-sm text-white/80 font-medium truncate",children:n.prospectName||n.toEmail}),j&&e.jsx("span",{className:`text-[10px] ${j.color}`,children:j.angle})]}),e.jsx("p",{className:"text-xs text-white/50 truncate",children:n.subject})]}),e.jsxs("div",{className:"flex-shrink-0 text-right",children:[e.jsx("p",{className:"text-[10px] text-white/25",children:u.toLocaleDateString("pt-BR")}),e.jsx("p",{className:"text-[10px] text-white/35 font-mono",children:u.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})]})]},n.id)})})]})]})}function sb({data:a,isLoading:r}){if(r)return e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(xe,{className:"w-6 h-6 animate-spin text-amber-400"})});if(!a||!a.influencers||a.influencers.length===0)return e.jsxs("div",{className:"text-center py-12 text-white/40",children:[e.jsx(ft,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum influencer onboarded ainda. Os dados de ROI aparecerão aqui quando houver influencers ativos."})]});const{summary:l,influencers:n}=a;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsx(rs,{icon:Vi,label:"Influencers Ativos",value:l.totalInfluencers,color:"text-emerald-400"}),e.jsx(rs,{icon:Re,label:"Signups Gerados",value:l.totalSignups,color:"text-blue-400"}),e.jsx(rs,{icon:nt,label:"Receita Total",value:`R$ ${l.totalRevenue.toFixed(2)}`,color:"text-green-400"}),e.jsx(rs,{icon:fh,label:"Créditos Investidos",value:l.totalCreditsInvested.toLocaleString(),color:"text-amber-400"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"p-3 border-b border-white/10",children:e.jsx("h3",{className:"text-sm font-medium text-white/70",children:"ROI por Influencer"})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-xs text-white/40 border-b border-white/5",children:[e.jsx("th",{className:"text-left p-3",children:"Influencer"}),e.jsx("th",{className:"text-left p-3",children:"Plataforma"}),e.jsx("th",{className:"text-left p-3",children:"Código"}),e.jsx("th",{className:"text-right p-3",children:"Signups"}),e.jsx("th",{className:"text-right p-3",children:"Pedidos"}),e.jsx("th",{className:"text-right p-3",children:"Receita"}),e.jsx("th",{className:"text-right p-3",children:"Créditos"}),e.jsx("th",{className:"text-left p-3",children:"Desde"})]})}),e.jsx("tbody",{children:n.map(u=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5 transition-colors","data-testid":`row-roi-${u.id}`,children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-white font-medium",children:u.name}),e.jsx("span",{className:"text-xs",children:yn[u.language]||""})]})}),e.jsx("td",{className:"p-3 text-white/50 capitalize",children:u.platform}),e.jsx("td",{className:"p-3",children:e.jsx("span",{className:"text-xs bg-emerald-500/10 text-emerald-400 px-2 py-0.5 rounded font-mono",children:u.referralCode})}),e.jsx("td",{className:"p-3 text-right text-blue-400 font-medium",children:u.signups}),e.jsx("td",{className:"p-3 text-right text-white/60",children:u.totalOrders}),e.jsxs("td",{className:"p-3 text-right text-green-400 font-medium",children:["R$ ",u.totalRevenue.toFixed(2)]}),e.jsx("td",{className:"p-3 text-right text-amber-400",children:u.creditsAwarded.toLocaleStr
2ing()}),e.jsx("td",{className:"p-3 text-white/40 text-xs",children:u.onboardedAt?new Date(u.onboardedAt).toLocaleDateString("pt-BR"):"—"})]},u.id))})]})})]})]})}function ab({data:a,isLoading:r}){if(r)return e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(xe,{className:"w-6 h-6 animate-spin text-amber-400"})});const l=Array.isArray(a)?a:[];if(l.length===0)return e.jsxs("div",{className:"text-center py-12 text-white/40",children:[e.jsx(Ac,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum log registrado ainda. Rode um ciclo para ver a atividade do negotiator."})]});const n={info:{icon:js,color:"text-blue-400",bg:"bg-blue-500/10"},warn:{icon:Ce,color:"text-yellow-400",bg:"bg-yellow-500/10"},error:{icon:Xe,color:"text-red-400",bg:"bg-red-500/10"}};return e.jsxs("div",{className:"space-y-2","data-testid":"section-influencer-logs",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-xs text-white/40",children:"Atualiza automaticamente a cada 10 segundos"}),e.jsxs("span",{className:"text-xs text-white/30",children:[l.length," registros"]})]}),e.jsx("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden max-h-[600px] overflow-y-auto",children:l.map(u=>{const f=n[u.level]||n.info,j=f.icon,p=u.createdAt?new Date(u.createdAt):new Date,g=u.message.includes("Cycle")||u.message.includes("cycle")||u.message.includes("Onboarded")||u.message.includes("email sent")||u.message.includes("Welcome email");return e.jsxs("div",{className:`flex items-start gap-3 px-4 py-2.5 border-b border-white/5 hover:bg-white/5 transition-colors ${g?f.bg:""}`,"data-testid":`log-entry-${u.id}`,children:[e.jsx("div",{className:`mt-0.5 flex-shrink-0 ${f.color}`,children:e.jsx(j,{className:"w-3.5 h-3.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-white/80 break-words",children:u.message}),u.data&&e.jsx("p",{className:"text-xs text-white/30 mt-0.5 font-mono break-all truncate",children:u.data})]}),e.jsxs("div",{className:"flex-shrink-0 text-right",children:[e.jsx("p",{className:"text-[10px] text-white/25",children:p.toLocaleDateString("pt-BR")}),e.jsx("p",{className:"text-[10px] text-white/35 font-mono",children:p.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"})})]})]},u.id)})})]})}function ib({data:a,isLoading:r,prospects:l,prospectFilter:n,setProspectFilter:u}){const[f,j]=d.useState(null);if(r)return e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(xe,{className:"w-6 h-6 animate-spin text-amber-400"})});const p=Array.isArray(a)?a:[],g=Array.from(new Map(p.filter(c=>c.prospectId&&c.prospectName).map(c=>[c.prospectId,c.prospectName])).entries()),w={outreach:"Primeiro Contato",follow_up_1:"Follow-up 1",follow_up_2:"Follow-up Final",sequence_day_2:"Sequência Dia 2",sequence_day_3:"Sequência Dia 3",sequence_day_4:"Sequência Dia 4",sequence_day_5:"Sequência Dia 5",sequence_day_6:"Sequência Dia 6",sequence_day_7:"Sequência Dia 7",welcome:"Boas-vindas",reply:"Resposta"},y={};for(const c of p){const m=c.prospectId||"unknown";y[m]||(y[m]=[]),y[m].push(c)}const F=Object.entries(y).map(([c,m])=>({prospectId:c,prospectName:m[0]?.prospectName||"Desconhecido",emails:m.sort(($,D)=>new Date($.sentAt).getTime()-new Date(D.sentAt).getTime()),lastActivity:new Date(m[0]?.sentAt||0),hasInbound:m.some($=>$.direction==="inbound")})).sort((c,m)=>m.lastActivity.getTime()-c.lastActivity.getTime());return e.jsxs("div",{className:"space-y-3","data-testid":"section-influencer-emails",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-white/40",children:"Atualiza automaticamente a cada 15 segundos"}),e.jsxs("div",{className:"flex items-center gap-2",children:[g.length>0&&e.jsxs("select",{value:n,onChange:c=>u(c.target.value),className:"bg-white/10 border border-white/10 rounded-lg text-xs text-white/70 px-2 py-1.5","data-testid":"filter-email-prospect",children:[e.jsx("option",{value:"all",children:"Todos os Influenciad
2ores"}),g.map(([c,m])=>e.jsx("option",{value:c,children:m},c))]}),e.jsxs("span",{className:"text-xs text-white/30",children:[p.length," emails · ",F.length," conversas"]})]})]}),p.length===0?e.jsxs("div",{className:"text-center py-12 text-white/40",children:[e.jsx(Ge,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum email enviado ainda."}),e.jsx("p",{className:"text-xs text-white/30 mt-1",children:"Os emails aparecerão aqui quando o sistema entrar em contato com influenciadores em produção."})]}):e.jsx("div",{className:"space-y-3",children:F.map(c=>e.jsxs("div",{className:`bg-white/5 border rounded-xl overflow-hidden ${c.hasInbound?"border-green-500/30":"border-white/10"}`,"data-testid":`email-conversation-${c.prospectId}`,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 cursor-pointer hover:bg-white/5 transition-colors",onClick:()=>j(f===c.emails[0]?.id?null:c.emails[0]?.id),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${c.hasInbound?"bg-green-400 animate-pulse":"bg-amber-400"}`}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-white",children:c.prospectName}),e.jsxs("p",{className:"text-xs text-white/40",children:[c.emails.length," ",c.emails.length===1?"email":"emails"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.hasInbound&&e.jsx(E,{className:"bg-green-500/20 text-green-400 text-[10px]",children:"Respondeu"}),e.jsx("span",{className:"text-[10px] text-white/30",children:c.lastActivity.toLocaleDateString("pt-BR")}),e.jsx(Ct,{className:`w-4 h-4 text-white/30 transition-transform ${f===c.emails[0]?.id?"rotate-180":""}`})]})]}),f===c.emails[0]?.id&&e.jsx("div",{className:"border-t border-white/5",children:c.emails.map(m=>{const $=m.direction==="inbound",D=m.sentAt?new Date(m.sentAt):new Date;return e.jsxs("div",{className:`px-4 py-3 border-b border-white/5 last:border-b-0 ${$?"bg-green-500/5":""}`,"data-testid":`email-entry-${m.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-5 h-5 rounded-full flex items-center justify-center text-[10px] ${$?"bg-green-500/20 text-green-400":"bg-amber-500/20 text-amber-400"}`,children:$?"←":"→"}),e.jsx("span",{className:"text-xs font-medium text-white/70",children:$?m.fromEmail:`Para: ${m.toEmail}`}),e.jsx(E,{className:`text-[10px] ${$?"bg-green-500/15 text-green-400":"bg-amber-500/15 text-amber-400"}`,children:w[m.emailType]||m.emailType})]}),e.jsxs("span",{className:"text-[10px] text-white/30",children:[D.toLocaleDateString("pt-BR")," ",D.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})]})]}),e.jsxs("p",{className:"text-xs font-medium text-white/80 mb-1",children:["📧 ",m.subject]}),e.jsx("div",{className:"text-xs text-white/50 whitespace-pre-line leading-relaxed max-h-[200px] overflow-y-auto",children:m.body})]},m.id)})})]},c.prospectId))})]})}function rs({icon:a,label:r,value:l,color:n}){return e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(a,{className:`w-3.5 h-3.5 ${n||"text-white/40"}`}),e.jsx("span",{className:"text-xs text-white/50",children:r})]}),e.jsx("p",{className:`text-xl font-bold ${n||"text-white"}`,children:l})]})}function dh(a){try{return new Date(a).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return""}}const Sc={discovered:{label:"Descoberto",color:"bg-gray-500/20 text-gray-300"},enriched:{label:"Enriquecido",color:"bg-slate-500/20 text-slate-300"},scored:{label:"Avaliado",color:"bg-purple-500/20 text-purple-300"},low_fit:{label:"Baixo Fit",color:"bg-orange-500/20 text-orange-300"},ready_to_contact:{label:"Pronto p/ contato",color:"bg-blue-500/20 text-blue-300"},contacted:{label:"Contactado",color:"bg-yellow-500/20 text-yellow-300"},responded_positive:{label:"Respondeu (positivo)",color:"bg-emerald-500/20 text-emerald-300"},responded_negative:{label:"Respondeu (negativo)",color:"bg-red-500/20 text-red-300"},responded_question:{label:"Respondeu (dúvida)",color:"bg-cyan-500/20 text-cyan-300"},handoff:{label:"Lead quente (Central)",color:"bg-teal-500/20 text-teal-300"},suppressed:{label:"Suprimido",color:"bg-zinc-600/30 text-zinc-400"}
2,sequence_complete:{label:"Sequência completa",color:"bg-amber-500/20 text-amber-300"}},rb=[{value:"all",label:"Todas as personas"},{value:"medico",label:"Médicos"},{value:"advogado",label:"Advogados"},{value:"psicologo",label:"Psicólogos"},{value:"pastor",label:"Pastores"},{value:"palestrante",label:"Palestrantes"},{value:"pesquisador",label:"Pesquisadores"},{value:"professor",label:"Professores"},{value:"outro",label:"Outros"}],nb={opt_out:"Opt-out",bounce:"Bounce",complaint:"Reclamação",manual:"Manual",negative_reply:"Resposta negativa"},lb={positive:"Interessado",question:"Dúvida / precisa humano",negative:"Não tem interesse",unsubscribe:"Pediu descadastro"},hc=a=>Array.isArray(a)?a.join(", "):"",pc=a=>a.split(",").map(r=>r.trim()).filter(Boolean);function uc({status:a}){const r=a&&Sc[a]||{label:a||"—",color:"bg-gray-500/20 text-gray-300"};return e.jsx(E,{className:`${r.color} border-0 font-medium`,children:r.label})}function db(){const{toast:a}=st(),[r,l]=d.useState("cockpit"),[n,u]=d.useState(null),[f,j]=d.useState("all"),[p,g]=d.useState("all"),[w,y]=d.useState("recent"),[F,c]=d.useState(""),[m,$]=d.useState(""),[D,A]=d.useState(null),[o,L]=d.useState(null),[v,I]=d.useState(""),[de,me]=d.useState(""),[ne,Z]=d.useState(""),[S,re]=d.useState("");d.useEffect(()=>{const R=setTimeout(()=>$(F.trim()),350);return()=>clearTimeout(R)},[F]);const{data:_}=z({queryKey:["/api/admin/prospector/config"],queryFn:()=>N("GET","/api/admin/prospector/config").then(R=>R.json())});d.useEffect(()=>{if(_?.config){const R=_.config;L({enabled:!!R.enabled,outreachEnabled:!!R.outreachEnabled,planAttachEnabled:!!R.planAttachEnabled,sources:Array.isArray(R.sources)&&R.sources.length?R.sources:_.defaultSources||[],niches:hc(R.niches),languages:hc(R.languages),countries:hc(R.countries),dailySendCap:R.dailySendCap??50,warmupPerDay:R.warmupPerDay??10})}},[_]);const{data:ee,isLoading:h}=z({queryKey:["/api/admin/prospector/stats"],queryFn:()=>N("GET","/api/admin/prospector/stats").then(R=>R.json()),refetchInterval:3e4}),{data:te,isLoading:M}=z({queryKey:["/api/admin/prospector/prospects",f,p,w,m],queryFn:()=>{const R=new URLSearchParams;return f!=="all"&&R.set("status",f),p!=="all"&&R.set("persona",p),R.set("orderBy",w),m&&R.set("search",m),R.set("limit","150"),N("GET",`/api/admin/prospector/prospects?${R}`).then(Ee=>Ee.json())},refetchInterval:45e3,enabled:r==="prospects"}),{data:ae}=z({queryKey:["/api/admin/prospector/prospects",D],queryFn:()=>N("GET",`/api/admin/prospector/prospects/${D}`).then(R=>R.json()),enabled:!!D}),{data:ye}=z({queryKey:["/api/admin/prospector/suppressions"],queryFn:()=>N("GET","/api/admin/prospector/suppressions?limit=500").then(R=>R.json()),enabled:r==="suppressions"}),{data:Me,isLoading:se}=z({queryKey:["/api/admin/prospector/prospects","queue-ready"],queryFn:()=>N("GET","/api/admin/prospector/prospects?status=ready_to_contact&orderBy=fit&limit=100").then(R=>R.json()),enabled:r==="sequence",refetchInterval:45e3}),{data:Ne}=z({queryKey:["/api/admin/prospector/metrics"],queryFn:()=>N("GET","/api/admin/prospector/metrics").then(R=>R.json()),enabled:r==="cockpit",refetchInterval:6e4}),{data:ie,refetch:X}=z({queryKey:["/api/admin/prospector/activity"],queryFn:()=>N("GET","/api/admin/prospector/activity").then(R=>R.json()),enabled:r==="cockpit",refetchInterval:R=>R.state.data?.running?1500:5e3}),B=W({mutationFn:R=>N("PATCH","/api/admin/prospector/config",R).then(Ee=>Ee.json()),onSuccess:()=>{a({title:"Config salva",description:"As mudanças valem no próximo ciclo do motor."}),K.invalidateQueries({queryKey:["/api/admin/prospector/config"]}),K.invalidateQueries({queryKey:["/api/admin/prospector/stats"]})},onError:()=>a({title:"Erro",description:"Não foi possível salvar a config.",variant:"destructive"})}),ge=W({mutationFn:()=>N("POST","/api/admin/prospector/run-cycle",{}).then(R=>R.json()),onSuccess:R=>{a({title:R?.masterEnabled?"Ciclo disparado":"Motor desligado (env)",description:R?.masterEnabled?"Acompanhe o progresso na caixinha ao vivo abaixo.":"ENABLE_AUTHOR_PROSPECTOR está OFF — o ciclo não fez nada. Ligue a env para operar.",variant:R?.masterEnabled?void 0:"destructive"}),X(),setTimeout(()=>X(),1200),setTimeout(()=>X(),3e3)},onError:()=>a({title:"Erro",description:"Não foi possível disparar o ciclo.",variant:"destructive"})}),ut=W({mutationFn:()=>N("POST","/api/admin/prospector/reenrich-contactless",{}).then(R=>R.json()),onSuccess:R=>{const Ee=Number(R?.reopened||0);a({title:Ee>0?`${Ee} prospect(s) reabertos p/ buscar contato`:"Nada a reabrir",description:Ee>0?R?.masterEnabled?"Rodando um ciclo agora — acompanhe os e-mails aparecendo na caixinha ao vivo.":"Reabertos, mas o motor está OFF (env). Ligue ENABLE_AUTHOR_PROSPECTOR para reprocessar.":"Todos os enriquecidos já têm e-mail (ou estão suprimidos).",variant:Ee>0&&!R?.masterEnabled?"destructive":void 0}),K.invalidateQueries({queryKey:["/api/admin/prospector/prospects"]}),K.invalidateQueries({queryKey:["/api/admin/prospector/stats"]}),X(),setTimeout(()=>X(),1500),setTimeout(()=>X(),4e3)},onError:()=>a({title:"Erro",description:"Não foi possível reabrir o enriquecimento.",variant:"destructive"})}),at=W({mutationFn:R=>N("POST",`/api/admin/prospector/prospects/${R.id}/status`,{status:R.status}).then(Ee=>Ee.json()),onSuccess:()=>{a({title:"Status atualizado"}),K.invalidateQueries({queryKey:["/api/admin/prospector/prospects"]}),K.invalidateQueries({queryKey:["/api/admin/prospector/stats"]})},onError:()=>a({title:"Erro",description:"Não foi possível mudar o status.",variant:"destructive"})}),$t=W({mutationFn:R=>N("POST","/api/admin/prospector/suppress",{email:R.email,reason:"manual",note:R.note}).then(Ee=>Ee.json()),onSuccess:()=>{a({title:"E-mail suprimido",description:"Nunca mais será contactado pelo motor."}),I(""),me(""),K.invalidateQueries({queryKey:["/api/admin/prospector/suppressions"]})},onError:()=>a({title:"Erro",description:"Verifique o e-mail informado.",variant:"destructive"})}),pa=W({mutationFn:R=>N("POST","/api/admin/prospector/lgpd/forget",{email:R.email,note:R.note}).then(Ee=>Ee.json()),onSuccess:R=>{a({title:"Titular removido (LGPD)",description:`Dados anonimizados e e-mail suprimido${typeof R?.anonymized=="number"?` — ${R.anonymized} registro(s)`:""}.`}),Z(""),re(""),K.invalidateQueries({queryKey:["/api/admin/prospector/suppressions"]}),K.invalidateQueries({queryKey:["/api/admin/prospector/prospects"]}),K.invalidateQueries({queryKey:["/api/admin/prospector/stats"]}),K.invalidateQueries({queryKey:["/api/admin/prospector/metrics"]})},onError:()=>a({title:"Erro",description:"Verifique o e-mail informado.",variant:"destructive"})}),Ms=W({mutationFn:R=>N("POST",`/api/admin/prospector/prospects/${R.id}/preview`,R.kind?{kind:R.kind}:{}).then(Ee=>Ee.json()),onSuccess:R=>{R?.subject&&R?.body?u({subject:R.subject,body:R.body,kind:R.kind,hasPlan:!!R.hasPlan}
2):a({title:"Sem preview",description:"Não foi possível compor o e-mail.",variant:"destructive"})},onError:()=>a({title:"Erro",description:"Não foi possível gerar a prévia.",variant:"destructive"})}),fe=W({mutationFn:R=>N("POST",`/api/admin/prospector/prospects/${R.id}/send`,R.kind?{kind:R.kind}:{}).then(Ee=>Ee.json()),onSuccess:R=>{const Ee=R?.result;Ee?.sent?a({title:"E-mail enviado",description:"O contato foi registrado no histórico do prospect."}):a({title:"Não enviado",description:Ee?.reason||"O envio foi bloqueado por uma salvaguarda.",variant:"destructive"}),K.invalidateQueries({queryKey:["/api/admin/prospector/prospects"]}),K.invalidateQueries({queryKey:["/api/admin/prospector/stats"]})},onError:()=>a({title:"Erro",description:"Falha ao enviar o e-mail.",variant:"destructive"})}),sa=!!(_?.masterEnabled??ee?.masterEnabled),Ha=_?.availableSources||[],Aa=ee?.byStatus||{},Tn=ee?.total??0,ki=te?.prospects||[],le=ye?.suppressions||[],aa=Me?.prospects||[],Pa=R=>{L(Ee=>{if(!Ee)return Ee;const ds=new Set(Ee.sources||[]);return ds.has(R)?ds.delete(R):ds.add(R),{...Ee,sources:Array.from(ds)}})},Ji=()=>{o&&B.mutate({enabled:o.enabled,outreachEnabled:o.outreachEnabled,planAttachEnabled:o.planAttachEnabled,sources:o.sources,niches:pc(o.niches),languages:pc(o.languages),countries:pc(o.countries),dailySendCap:Number(o.dailySendCap)||0,warmupPerDay:Number(o.warmupPerDay)||0})},Kt=d.useMemo(()=>["discovered","enriched","scored","ready_to_contact","contacted","responded_positive","responded_question","handoff","low_fit","responded_negative","suppressed","sequence_complete"],[]);return e.jsxs("div",{className:"space-y-6","data-testid":"author-prospector-root",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-blue-500/10",children:e.jsx(Re,{className:"w-6 h-6 text-blue-400"})}),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2",children:["Prospecção de Autores",sa?e.jsxs(E,{className:"bg-emerald-500/20 text-emerald-300 border-0 gap-1",children:[e.jsx(fc,{className:"w-3 h-3"})," Motor ligado"]}):e.jsxs(E,{className:"bg-red-500/20 text-red-300 border-0 gap-1",children:[e.jsx(fc,{className:"w-3 h-3"})," Env OFF"]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Descobre profissionais que já publicaram conteúdo público e os convida a virar autores."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(b,{variant:"outline",onClick:()=>ut.mutate(),disabled:ut.isPending,className:"gap-2","data-testid":"button-reenrich-contactless",title:"Reprocessa os prospects já enriquecidos que ficaram sem e-mail, buscando o contato no registro público ORCID e no site pessoal do autor.",children:[ut.isPending?e.jsx(xe,{className:"w-4 h-4 animate-spin"}):e.jsx(St,{className:"w-4 h-4"}),"Buscar contatos que faltam"]}),e.jsxs(b,{onClick:()=>ge.mutate(),disabled:ge.isPending,className:"gap-2","data-testid":"button-run-cycle",children:[ge.isPending?e.jsx(xe,{className:"w-4 h-4 animate-spin"}):e.jsx(Us,{className:"w-4 h-4"}),"Rodar ciclo agora"]})]})]}),!sa&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-lg bg-amber-500/10 border border-amber-500/30 text-sm text-amber-200",children:[e.jsx(Ce,{className:"w-4 h-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["O motor está ",e.jsx("strong",{children:"desligado no nível do servidor"})," (env ",e.jsx("code",{children:"ENABLE_AUTHOR_PROSPECTOR"}),"). Você pode configurar tudo aqui, mas nada roda até a env ser habilitada e republicada. Nenhum e-mail é enviado nesta fase."]})]}),e.jsx("div",{className:"flex gap-2 border-b border-white/10",children:[{k:"cockpit",label:"Funil & Configuração"},{k:"sequence",label:"Sequência"},{k:"prospects",label:"Prospects"},{k:"suppressions",label:"Supressões (LGPD)"}].map(R=>e.jsx("button",{onClick:()=>l(R.k),className:`px-3 py-2 text-sm font-medium -mb-px border-b-2 transition ${r===R.k?"border-blue-400 text-blue-300":"border-transparent text-muted-foreground hover:text-white"}`,"data-testid":`tab-${R.k}`,children:R.label},R.k))}),r==="cockpit"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(je,{className:"border-blue-500/30 bg-blue-500/[0.03]","data-testid":"card-activity",children:[e.jsx(Fe,{className:"pb-3",children:e.jsxs(De,{className:"text-base flex items-center gap-2",children:[ie?.running?e.jsx(xe,{className:"w-4 h-4 text-blue-400 animate-spin"}):e.jsx(jt,{className:"w-4 h-4 text-blue-400"}),"Atividade ao vivo",ie?.running?e.jsxs(E,{className:"bg-blue-500/20 text-blue-200 border-0 gap-1","data-testid":"badge-activity-running",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"})," Rodando"]}):e.jsx(E,{className:"bg-zinc-600/30 text-zinc-300 border-0","data-testid":"badge-activity-idle",children:"Ocioso"})]})}),e.jsxs(ve,{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-sm",children:ie?.running?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-blue-200 font-medium","data-testid":"activity-phase",children:ie.phaseLabel}),e.jsxs("span",{className:"text-muted-foreground",children:["Ciclo #",ie.cycleNumber," · ",ie.trigger==="manual"?"manual":"agendado"]}),typeof ie.elapsedMs=="number"&&e.jsxs("span",{className:"text-muted-foreground",children:[Math.round(ie.elapsedMs/1e3),"s decorridos"]})]}):ie?.finishedAt?e.jsxs("span",{className:"text-muted-foreground","data-testid":"activity-last-result",children:["Último ciclo ",ie.lastResult?.ran?"concluído com sucesso":"não executou"," · ",dh(ie.finishedAt)]}):e.jsx("span",{className:"text-muted-foreground",children:"Nenhum ciclo executado nesta sessão do servidor ainda."})}),!ie?.running&&ie?.lastResult&&!ie.lastResult.ran&&ie.lastResult.reason&&e.jsxs("div",{className:"flex items-start gap-2 text-xs text-amber-200","data-testid":"activity-blocked-reason",children:[e.jsx(Ce,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}
2),e.jsxs("span",{children:["O ciclo não executou: ",e.jsx("code",{children:ie.lastResult.reason}),'. Confirme se o "Motor ligado" (abaixo) está ativo.']})]}),e.jsx("div",{className:"rounded-lg bg-black/40 border border-white/10 p-3 max-h-64 overflow-y-auto font-mono text-xs space-y-1","data-testid":"activity-log",children:(ie?.events?.length??0)===0?e.jsxs("p",{className:"text-muted-foreground font-sans",children:["Sem eventos ainda. Clique em ",e.jsx("strong",{children:'"Rodar ciclo agora"'})," para ver o motor trabalhando em tempo real (descoberta, enriquecimento, e-mail encontrado…)."]}):[...ie.events].reverse().map((R,Ee)=>e.jsxs("div",{className:"flex gap-2","data-testid":`activity-line-${Ee}`,children:[e.jsx("span",{className:"text-zinc-500 shrink-0",children:dh(R.ts)}),e.jsx("span",{className:R.level==="error"?"text-red-300":R.level==="warn"?"text-amber-300":"text-zinc-200",children:R.message})]},Ee))})]})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3 flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4"})," Funil (",Tn," prospects · ",ee?.sentToday??0,"/",ee?.dailySendCap??0," e-mails hoje)"]}),h?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando…"}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3",children:Kt.map(R=>e.jsx(je,{className:"bg-card/50",children:e.jsxs(ve,{className:"p-3",children:[e.jsx("div",{className:"text-2xl font-bold","data-testid":`stat-${R}`,children:Aa[R]||0}),e.jsx("div",{className:"mt-1",children:e.jsx(uc,{status:R})})]})},R))})]}),Ne&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsxs(je,{className:"bg-card/50","data-testid":"card-metric-outreach",children:[e.jsx(Fe,{className:"pb-2",children:e.jsx(De,{className:"text-sm text-muted-foreground",children:"E-mails & resposta"})}),e.jsxs(ve,{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Enviados"}),e.jsx("span",{className:"font-semibold","data-testid":"metric-emails-sent",children:Ne.emailVolume?.outbound??0})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Respostas"}),e.jsx("span",{className:"font-semibold","data-testid":"metric-emails-replies",children:Ne.emailVolume?.inbound??0})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Taxa de resposta"}),e.jsxs("span",{className:"font-semibold text-emerald-300","data-testid":"metric-reply-rate",children:[((Ne.replyRate??0)*100).toFixed(1),"%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Leads quentes (handoff)"}),e.jsx("span",{className:"font-semibold text-blue-300","data-testid":"metric-handoffs",children:Ne.handoffs??0})]})]})]}),e.jsxs(je,{className:"bg-card/50","data-testid":"card-metric-intents",children:[e.jsx(Fe,{className:"pb-2",children:e.jsx(De,{className:"text-sm text-muted-foreground",children:"Classificação de respostas"})}),e.jsx(ve,{className:"space-y-1 text-sm",children:Object.keys(Ne.intents||{}).length===0?e.jsx("p",{className:"text-muted-foreground",children:"Sem respostas classificadas ainda."}):Object.entries(Ne.intents).map(([R,Ee])=>e.jsxs("div",{className:"flex justify-between","data-testid":`metric-intent-${R}`,children:[e.jsx("span",{className:"text-muted-foreground",children:lb[R]||R}),e.jsx("span",{className:"font-semibold",children:String(Ee)})]},R))})]}),e.jsxs(je,{className:"bg-card/50","data-testid":"card-metric-ai-cost",children:[e.jsx(Fe,{className:"pb-2",children:e.jsx(De,{className:"text-sm text-muted-foreground",children:"Custo de IA (acumulado)"})}),e.jsxs(ve,{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Custo total"}),e.jsxs("span",{className:"font-semibold text-amber-300","data-testid":"metric-ai-cost",children:["R$ ",(Ne.ai?.costBRL??0).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Chamadas de IA"}),e.jsx("span",{className:"font-semibold","data-testid":"metric-ai-calls",children:Ne.ai?.callCount??0})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"E-mail encontrado"}),e.jsxs("span",{className:"font-semibold","data-testid":"metric-email-found-rate",children:[((Ne.emailFoundRate??0)*100).toFixed(0),"%"]})]})]})]})]}),o&&e.jsxs(je,{children:[e.jsx(Fe,{children:e.jsxs(De,{className:"text-base flex items-center gap-2",children:[e.jsx(Xl,{className:"w-4 h-4"})," Configuração do motor"]})}),e.jsxs(ve,{className:"space-y-5",children:[e.jsxs("div",{className:"grid sm:grid-cols-3 gap-4",children:[e.jsxs("label",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card/50 border border-white/5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Motor ligado"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Descoberta + enriquecimento"})]}),e.jsx(rt,{checked:o.enabled,onCheckedChange:R=>L({...o,enabled:R}),"data-testid":"switch-enabled"})]}),e.jsxs("label",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card/50 border border-white/5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Outreach (envi
2o)"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disparo de e-mails (Fase 2)"})]}),e.jsx(rt,{checked:o.outreachEnabled,onCheckedChange:R=>L({...o,outreachEnabled:R}),"data-testid":"switch-outreach"})]}),e.jsxs("label",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card/50 border border-white/5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Anexar plano pronto"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Gera planejamento (Fase 2)"})]}),e.jsx(rt,{checked:o.planAttachEnabled,onCheckedChange:R=>L({...o,planAttachEnabled:R}),"data-testid":"switch-plan-attach"})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-sm mb-2 block",children:"Fontes de descoberta"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Ha.map(R=>{const Ee=(o.sources||[]).includes(R.key);return e.jsxs("button",{onClick:()=>Pa(R.key),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition ${Ee?"bg-blue-500/20 text-blue-200 border-blue-400/50":"bg-card/50 text-muted-foreground border-white/10 hover:border-white/30"}`,"data-testid":`source-${R.key}`,children:[Ee&&e.jsx(be,{className:"w-3 h-3 inline mr-1"}),R.label]},R.key)})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-sm",children:"Nichos (separados por vírgula)"}),e.jsx($s,{value:o.niches,onChange:R=>L({...o,niches:R.target.value}),placeholder:"cardiologia, direito tributário, psicologia infantil…",className:"mt-1 h-20","data-testid":"input-niches"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-sm",children:"Idiomas (ex: pt-BR, en)"}),e.jsx(J,{value:o.languages,onChange:R=>L({...o,languages:R.target.value}),className:"mt-1","data-testid":"input-languages"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-sm",children:"Países (ex: BR, PT)"}),e.jsx(J,{value:o.countries,onChange:R=>L({...o,countries:R.target.value}),className:"mt-1","data-testid":"input-countries"})]})]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-sm",children:"Cap diário de envios"}),e.jsx(J,{type:"number",min:0,value:o.dailySendCap,onChange:R=>L({...o,dailySendCap:R.target.value}),className:"mt-1","data-testid":"input-daily-cap"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-sm",children:"Warmup por dia"}),e.jsx(J,{type:"number",min:0,value:o.warmupPerDay,onChange:R=>L({...o,warmupPerDay:R.target.value}),className:"mt-1","data-testid":"input-warmup"})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(b,{onClick:Ji,disabled:B.isPending,className:"gap-2","data-testid":"button-save-config",children:[B.isPending?e.jsx(xe,{className:"w-4 h-4 animate-spin"}):e.jsx(Ic,{className:"w-4 h-4"}),"Salvar configuração"]})})]})]})]}),r==="sequence"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[e.jsxs(E,{className:`${o?.outreachEnabled?"bg-emerald-500/20 text-emerald-300":"bg-zinc-600/30 text-zinc-300"} border-0 gap-1`,children:[e.jsx(Ge,{className:"w-3 h-3"})," Outreach ",o?.outreachEnabled?"ligado":"desligado"]}),o?.planAttachEnabled&&e.jsxs(E,{className:"bg-blue-500/20 text-blue-300 border-0 gap-1",children:[e.jsx(tt,{className:"w-3 h-3"})," Anexa plano pronto"]}),e.jsxs("span",{className:"text-muted-foreground",children:[ee?.sentToday??0,"/",ee?.dailySendCap??0," e-mails hoje"]})]}),(!sa||!o?.outreachEnabled)&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-lg bg-amber-500/10 border border-amber-500/30 text-sm text-amber-200",children:[e.jsx(Ce,{className:"w-4 h-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Qualquer ",e.jsx("strong",{children:"envio"})," — automático ",e.jsx("em",{children:"ou"})," manual — exige a env ",e.jsx("code",{children:"ENABLE_PROSPECTOR_OUTREACH"})," ligada e o interruptor ",e.jsx("strong",{children:"Outreach (envio)"})," ativo. Enquanto estiverem desligados, você ainda pode ",e.jsx("strong",{children:"pré-visualizar"})," a cópia de qualquer prospect à vontade (nenhum e-mail é enviado)."]})]}),e.jsxs(je,{children:[e.jsx(Fe,{children:e.jsxs(De,{className:"text-base flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4"})," Cadência da sequência"]})}),e.jsxs(ve,{children:[e.jsx("div",{className:"grid sm:grid-cols-4 gap-3 text-sm",children:[{d:"Dia 0",t:"Primeiro contato",desc:"E-mail hiper-personalizado com a melhor prova de valor.",c:"text-blue-300"},{d:"+4 dias",t:"Follow-up 1",desc:"Reforço leve, só se não houve resposta.",c:"text-cyan-300"},{d:"+8 dias",t:"Follow-up 2",desc:"Último toque; encerra a sequência.",c:"text-amber-300"},{d:"Fim",t:"Sequência completa",desc:"Para de contactar; aguarda resposta.",c:"text-zinc-300"}].map((R,Ee)=>e.jsxs("div",{className:"p-3 rounded-lg bg-card/50 border border-white/5",children:[e.jsx("div",{className:`text-xs font-semibold ${R.c}`,children:R.d}
2),e.jsx("div",{className:"font-medium mt-0.5",children:R.t}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:R.desc})]},Ee))}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Respostas positivas/dúvidas viram ",e.jsx("strong",{children:"lead quente na Central"})," e a sequência para automaticamente. Respostas negativas e opt-outs entram em supressão."]})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[{s:"ready_to_contact",label:"Prontos p/ contato"},{s:"contacted",label:"Em sequência"},{s:"sequence_complete",label:"Sequência completa"},{s:"handoff",label:"Leads quentes"}].map(R=>e.jsxs("button",{onClick:()=>{j(R.s),l("prospects")},className:"p-3 rounded-lg bg-card/50 border border-white/5 hover:border-blue-400/40 transition text-left","data-testid":`seq-stat-${R.s}`,children:[e.jsx("div",{className:"text-2xl font-bold",children:Aa[R.s]||0}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:R.label})]},R.s))}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3 flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"})," Próximos na fila (prontos para o 1º contato)"]}),se?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando fila…"}):aa.length===0?e.jsxs("div",{className:"text-center py-10 text-muted-foreground",children:[e.jsx(Ge,{className:"w-10 h-10 mx-auto mb-2 opacity-40"}),e.jsx("p",{children:"Ninguém pronto para contato ainda. Rode um ciclo para enriquecer prospects com e-mail válido."})]}):e.jsx("div",{className:"space-y-2",children:aa.map(R=>e.jsxs("div",{className:"w-full p-3 rounded-lg bg-card/50 border border-white/5 flex items-center gap-3","data-testid":`seq-row-${R.id}`,children:[e.jsxs("button",{onClick:()=>A(R.id),className:"flex items-center gap-3 flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"w-10 text-center",children:[e.jsx("div",{className:"text-lg font-bold text-blue-300",children:R.fitScore??0}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"fit"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:R.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[R.persona,R.institution,R.email].filter(Boolean).join(" · ")||R.source})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsxs(b,{size:"sm",variant:"outline",className:"gap-1",onClick:()=>Ms.mutate({id:R.id}),disabled:Ms.isPending,"data-testid":`seq-preview-${R.id}`,children:[e.jsx(tt,{className:"w-3 h-3"})," Prévia"]}),e.jsxs(b,{size:"sm",className:"gap-1",onClick:()=>fe.mutate({id:R.id}),disabled:fe.isPending,"data-testid":`seq-send-${R.id}`,children:[e.jsx(Ge,{className:"w-3 h-3"})," Enviar"]})]})]},R.id))})]})]}),r==="prospects"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(St,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(J,{value:F,onChange:R=>c(R.target.value),placeholder:"Buscar por nome, e-mail, instituição…",className:"pl-9","data-testid":"input-search-prospects"})]}),e.jsxs(Se,{value:f,onValueChange:j,children:[e.jsx($e,{className:"w-[180px]","data-testid":"select-status",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"all",children:"Todos os status"}),Object.keys(Sc).map(R=>e.jsx(U,{value:R,children:Sc[R].label},R))]})]}),e.jsxs(Se,{value:p,onValueChange:g,children:[e.jsx($e,{className:"w-[170px]","data-testid":"select-persona",children:e.jsx(Ae,{})}),e.jsx(Pe,{children:rb.map(R=>e.jsx(U,{value:R.value,children:R.label},R.value))})]}),e.jsxs(Se,{value:w,onValueChange:R=>y(R),children:[e.jsx($e,{className:"w-[150px]","data-testid":"select-order",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"recent",children:"Mais recentes"}),e.jsx(U,{value:"fit",children:"Maior fit"})]})]})]}),M?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando prospects…"}):ki.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Re,{className:"w-10 h-10 mx-auto mb-2 opacity-40"}),e.jsx("p",{children:"Nenhum prospect ainda. Rode um ciclo (com a env ligada) para descobrir autores."})]}):e.jsx("div",{className:"space-y-2",children:ki.map(R=>e.jsxs("button",{onClick:()=>A(R.id),className:"w-full text-left p-3 rounded-lg bg-card/50 border border-white/5 hover:border-blue-400/40 transition flex items-center gap-3","data-testid":`row-prospect-${R.id}`,children:[e.jsxs("div",{className:"w-10 text-center",children:[e.jsx("div",{className:"text-lg font-bold text-blue-300",children:R.fitScore??0}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"fit"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:R.name}),e.jsx(uc,{status:R.status})]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[R.persona,R.institution,R.email].filter(
2Boolean).join(" · ")||R.source})]}),e.jsx("div",{className:"text-xs text-muted-foreground shrink-0 hidden sm:block",children:R.source})]},R.id))})]}),r==="suppressions"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(je,{children:[e.jsx(Fe,{children:e.jsxs(De,{className:"text-base flex items-center gap-2",children:[e.jsx(nc,{className:"w-4 h-4"})," Suprimir e-mail (nunca contactar)"]})}),e.jsxs(ve,{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(J,{value:v,onChange:R=>I(R.target.value),placeholder:"[email protected]",className:"flex-1","data-testid":"input-suppress-email"}),e.jsx(J,{value:de,onChange:R=>me(R.target.value),placeholder:"Motivo/nota (opcional)",className:"flex-1","data-testid":"input-suppress-note"}),e.jsx(b,{onClick:()=>$t.mutate({email:v.trim(),note:de.trim()||void 0}),disabled:$t.isPending||!v.trim(),variant:"destructive","data-testid":"button-suppress",children:"Suprimir"})]})]}),e.jsxs(je,{className:"border-red-500/30",children:[e.jsxs(Fe,{children:[e.jsxs(De,{className:"text-base flex items-center gap-2",children:[e.jsx(nc,{className:"w-4 h-4 text-red-400"})," Esquecer titular (LGPD)"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Anonimiza todos os dados pessoais desse e-mail (nome, perfil, corpo/assunto dos e-mails e o plano de livro derivado) em TODAS as linhas dele e o suprime para sempre. Não apaga as linhas — mantém o histórico anônimo por auditoria. Ação irreversível."})]}),e.jsxs(ve,{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(J,{value:ne,onChange:R=>Z(R.target.value),placeholder:"[email protected]",className:"flex-1","data-testid":"input-forget-email"}),e.jsx(J,{value:S,onChange:R=>re(R.target.value),placeholder:"Nº do pedido / nota (opcional)",className:"flex-1","data-testid":"input-forget-note"}),e.jsx(b,{onClick:()=>pa.mutate({email:ne.trim(),note:S.trim()||void 0}),disabled:pa.isPending||!ne.trim(),variant:"destructive","data-testid":"button-forget",children:pa.isPending?e.jsx(xe,{className:"w-4 h-4 animate-spin"}):"Esquecer"})]})]}),e.jsx("div",{className:"space-y-2",children:le.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Nenhuma supressão registrada."}):le.map(R=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-card/50 border border-white/5","data-testid":`row-suppression-${R.id}`,children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:R.email}),R.note&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:R.note})]}),e.jsx(E,{className:"bg-zinc-600/30 text-zinc-300 border-0",children:nb[R.reason]||R.reason})]},R.id))})]}),e.jsx(Je,{open:!!D,onOpenChange:R=>!R&&A(null),children:e.jsx(Ye,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:ae?.prospect?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{children:e.jsxs(et,{className:"flex items-center gap-2",children:[ae.prospect.name,e.jsx(uc,{status:ae.prospect.status})]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(fa,{label:"Persona",value:ae.prospect.persona}),e.jsx(fa,{label:"Profissão",value:ae.prospect.profession}),e.jsx(fa,{label:"Instituição",value:ae.prospect.institution}),e.jsx(fa,{label:"Fonte",value:ae.prospect.source}),e.jsx(fa,{label:"E-mail",value:ae.prospect.email}),e.jsx(fa,{label:"Status do e-mail",value:ae.prospect.emailStatus}),e.jsx(fa,{label:"Idioma / País",value:[ae.prospect.language,ae.prospect.country].filter(Boolean).join(" / ")}),e.jsx(fa,{label:"Fit score",value:String(ae.prospect.fitScore??0)}),e.jsx(fa,{label:"Obras / Citações",value:`${ae.prospect.worksCount??0} / ${ae.prospect.citationsCount??0}`}),ae.prospect.whatsapp&&e.jsx(fa,{label:"WhatsApp",value:ae.prospect.whatsapp})]}),ae.prospect.fitReason&&e.jsxs("div",{className:"p-3 rounded-lg bg-card/50 border border-white/5",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Motivo do fit"}),e.jsx("p",{children:ae.prospect.fitReason})]}),ae.prospect.bestContentTitle&&e.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/5 border border-blue-400/20",children:[e.jsxs("div",{className:"text-xs text-blue-300 mb-1 flex items-center gap-1",children:[e.jsx(tt,{className:"w-3 h-3"})," Melhor conteúdo (",ae.prospect.bestContentType||"—",")"]}),e.jsx("div",{className:"font-medium",children:ae.prospect.bestContentTitle}),ae.prospect.bestContentSummary&&e.jsx("p",{className:"text-muted-foreground mt-1",children:ae.prospect.bestContentSummary}),ae.prospect.bestContentUrl&&e.jsxs("a",{href:ae.prospect.bestContentUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-blue-300 hover:underline mt-2 text-xs",children:[e.jsx(vs,{className:"w-3 h-3"})," Abrir conteúdo"]})]}),ae.prospect.profileUrl&&e.jsxs("a",{href:ae.prospect.profileUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-blue-300 hover:underline text-xs",children:[e.jsx(pt,{className:"w-3 h-3"})," Perfil público"]}),Array.isArray(ae.emails)&&ae.emails.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-muted-foreground mb-2 flex items-center gap-1",children:[e.jsx(Ge,{className:"w-3 h-3"})," Histórico de e-mails"]}
2),e.jsx("div",{className:"space-y-2",children:ae.emails.map(R=>e.jsxs("div",{className:"p-2 rounded bg-card/50 border border-white/5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:R.subject}),e.jsx(E,{className:"bg-white/5 text-muted-foreground border-0 text-[10px] shrink-0",children:R.emailType})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-3 whitespace-pre-wrap",children:R.body})]},R.id))})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-white/10",children:[ae.prospect.email&&e.jsxs(e.Fragment,{children:[e.jsxs(b,{size:"sm",variant:"outline",className:"gap-1",onClick:()=>Ms.mutate({id:ae.prospect.id}),disabled:Ms.isPending,"data-testid":"button-preview-email",children:[e.jsx(tt,{className:"w-3 h-3"})," Pré-visualizar e-mail"]}),e.jsxs(b,{size:"sm",className:"gap-1",onClick:()=>fe.mutate({id:ae.prospect.id}),disabled:fe.isPending,"data-testid":"button-send-email",children:[e.jsx(Ge,{className:"w-3 h-3"})," Enviar e-mail agora"]})]}),e.jsxs(b,{size:"sm",variant:"destructive",className:"gap-1",onClick:()=>at.mutate({id:ae.prospect.id,status:"suppressed"}),disabled:at.isPending,"data-testid":"button-suppress-prospect",children:[e.jsx(nc,{className:"w-3 h-3"})," Suprimir"]}),ae.prospect.status!=="ready_to_contact"&&e.jsx(b,{size:"sm",variant:"outline",onClick:()=>at.mutate({id:ae.prospect.id,status:"ready_to_contact"}),disabled:at.isPending,"data-testid":"button-mark-ready",children:"Marcar pronto p/ contato"})]})]})]}):e.jsxs("div",{className:"py-8 text-center text-muted-foreground flex items-center justify-center gap-2",children:[e.jsx(xe,{className:"w-4 h-4 animate-spin"})," Carregando…"]})})}),e.jsx(Je,{open:!!n,onOpenChange:R=>!R&&u(null),children:e.jsx(Ye,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:n&&e.jsxs(e.Fragment,{children:[e.jsx(Ze,{children:e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"})," Prévia do e-mail",e.jsx(E,{className:"bg-white/5 text-muted-foreground border-0 text-[10px]",children:n.kind}),n.hasPlan&&e.jsx(E,{className:"bg-blue-500/20 text-blue-300 border-0 text-[10px]",children:"com plano pronto"})]})}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Assunto"}),e.jsx("div",{className:"p-2 rounded bg-card/50 border border-white/5 font-medium",children:n.subject})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Corpo"}),e.jsx("div",{className:"p-3 rounded bg-card/50 border border-white/5 whitespace-pre-wrap leading-relaxed",children:n.body})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Esta é uma composição de exemplo — o envio real regenera a cópia no momento do disparo. Nenhum e-mail foi enviado."})]})]})})})]})}function fa({label:a,value:r}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:a}),e.jsx("div",{className:"truncate",children:r||"—"})]})}const oh={planning:{label:"Planejando",color:"bg-blue-500/20 text-blue-400",icon:e.jsx(Rc,{className:"w-3 h-3"})},generating:{label:"Gerando",color:"bg-amber-500/20 text-amber-400",icon:e.jsx(T,{className:"w-3 h-3 animate-spin"})},writing:{label:"Escrevendo",color:"bg-purple-500/20 text-purple-400",icon:e.jsx(tt,{className:"w-3 h-3"})},completed:{label:"Completo",color:"bg-emerald-500/20 text-emerald-400",icon:e.jsx(be,{className:"w-3 h-3"})}},ob={pt:"🇧🇷","pt-BR":"🇧🇷",en:"🇺🇸",es:"🇪🇸",fr:"🇫🇷",de:"🇩🇪",it:"🇮🇹",ja:"🇯🇵",ko:"🇰🇷",zh:"🇨🇳"};function cb(){const{toast:a}=st(),[r,l]=d.useState(""),[n,u]=d.useState(""),[f,j]=d.useState("all"),[p,g]=d.useState(null),[w,y]=d.useState(null),[F,c]=d.useState("");d.useEffect(()=>{const S=setTimeout(()=>u(r.trim()),350);return()=>clearTimeout(S)},[r]);const{data:m,isLoading:$}=z({queryKey:["/api/admin/books/search",n,f],queryFn:()=>{const S=new URLSearchParams;return n&&S.set("q",n),f!=="all"&&S.set("status",f),N("GET",`/api/admin/books/search?${S}`).then(re=>re.json())},refetchInterval:3e4}),{data:D}=z({queryKey:["/api/admin/books/stats"],queryFn:()=>N("GET","/api/admin/books/stats").then(S=>S.json()),refetchInterval:6e4}),{data:A,isLoading:o,isError:L}=z({queryKey:["/api/admin/books/detail",p],queryFn:()=>N("GET",`/api/admin/books/${p}/detail`).then(S=>S.json()),enabled:!!p,retry:1}),v=W({mutationFn:S=>N("POST",`/api/admin/books/${S.bookId}/reassign`,{targetUserId:S.targetUserId}).then(re=>re.json()),onSuccess:S=>{a({title:"Livro transferido!",description:S.message}),y(null),c(""),K.invalidateQueries({queryKey:["/api/admin/books/search"]}),K.invalidateQueries({queryKey:["/api/admin/books/detail"]})},onError:S=>{a({title:"Erro ao transferir",description:S.message,variant:"destructive"})}}),I=S=>{navigator.clipboard.writeText(S),a({title:"Copiado!",description:S.slice(0,60)})},de=D?.total??(m||[]).length,me=D?.paid??(m||[]).filter(S=>S.isPaid).length,ne=D?.byStatus?.completed??0,Z=D?.byStatus?.generating??0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-white","data-testid":"text-total-books",children:de}),e.jsx("div",{className:"text-xs text-white/40",children:"Total Livros"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-400","data-testid":"text-paid-books",children:me}),e.jsx("div",{className:"text-xs text-white/40",children:"Pagos"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-purple-400","data-testid":"text-completed-books",children:ne}),e.jsx("div",{className:"text-xs text-white/40",children:"Completos"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-amber-400","data-testid":"text-generating-books",children:Z}),e.jsx("div",{className:"text-xs text-white/40",children:"Gerando"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-[400px]",children:[e.jsx(St,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/30"}),e.jsx(J,{placeholder:"Pesquisar por título, autor, email, ID...",value:r,onChange:S=>l(S.target.value),className:"pl-9 bg-white/5 border-white/10 text-sm h-9 placeholder:text-white/25","data-testid":"input-search-books"})]}),e.jsxs(Se,{value:f,onValueChange:j,children:[e.jsx($e,{className:"w-[160px] bg-white/5 border-white/10 text-xs sm:text-sm h-9","data-testid":"select-book-status-filter",children:e.jsx(Ae,{placeholder:"Status"})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"all",children:"Todos Status"}),Object.entries(oh).map(([S,{label:re}])=>e.jsx(U,{value:S,children:re},S))]})]})]}),$?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(xe,{className:"w-6 h-6 animate-spin text-amber-400"})}):(m||[]).length===0?e.jsxs("div",{className:"text-center py-12 text-white/40",children:[e.jsx(ot,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum livro encontrado"})]}):e.jsx("div",{className:"space-y-2",children:(m||[]).map(S=>{const re=oh[S.status]||{label:S.status,color:"bg-gray-500/20 text-gray-400",icon:e.jsx(Xe,{className:"w-3 h-3"})},_=p===S.id;return e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden hover:border-white/20 transition-colors","data-testid":`card-book-${S.id}`,children:[e.jsx("div",{className:"p-3 sm:p-4 cursor-pointer",onClick:()=>g(_?null:S.id),"data-testid":`button-expand-book-${S.id}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[S.coverImage?e.jsx("img",{src:S.coverImage,alt:S.title,className:"w-12 h-16 sm:w-14 sm:h-[76px] rounded-lg object-cover border border-white/10 shrink-0"}):e.jsx("div",{className:"w-12 h-16 sm:w-14 sm:h-[76px] rounded-lg bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:e.jsx(ot,{className:"w-5 h-5 text-white/20"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-1",children:[e.jsx("span",{className:"font-semibold text-white text-sm sm:text-base truncate max-w-[250px]","data-testid":`text-book-title-${S.id}`,children:S.title}),e.jsxs(E,{className:`text-[9px] sm:text-[10px] shrink-0 ${re.color}`,children:[re.icon,e.jsx("span",{className:"ml-1",children:re.label})]}),S.isPaid&&e.jsxs(E,{className:"text-[9px] sm:text-[10px] bg-emerald-500/20 text-emerald-400 shrink-0",children:[e.jsx(nt,{className:"w-2.5 h-2.5"})," Pago"]}),S.language&&e.jsxs("span",{className:"text-[10px] text-white/30",children:[ob[S.language]||"🌐"," ",S.language]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[10px] sm:text-xs text-white/40",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rc,{className:"w-3 h-3"})," ",S.author]}),S.genre&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ot,{className:"w-3 h-3"})," ",S.genre]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ge,{className:"w-3 h-3"})," ",S.userEmail]}),S.userName&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hi,{className:"w-3 h-3"})," ",S.userName]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-[10px] text-white/25",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zl,{className:"w-3 h-3"}),new Date(S.createdAt).toLocaleDateString("pt-BR")]}),S.progress>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ns,{className:"w-3 h-3"})," ",S.progress,"%"]})]})]}),e.jsx("div",{className:"shrink-0 flex items-center",children:_?e.jsx(ta,{className:"w-4 h-4 text-white/30"}):e.jsx(Ct,{className:"w-4 h-4 text-white/30"})})]})}),_&&e.jsx(xb,{bookId:S.id,detail:A,isLoading:o,isError:L,onCopy:I,onReassign:()=>y(S.id),onRetry:()=>K.invalidateQueries({queryKey:["/api/admin/books/detail",S.id]})})]},S.id)})}),e.jsx(Je,{open:!!w,onOpenChange:S=>{S||(y(null),c(""))},children:e.jsxs(Ye,{className:"bg-[#1a1a2e] border-white/10",children:[e.jsxs(Ze,{children:[e.jsx(et,{className:"text-white",children:"Transferir Livro"}),e.jsx(mt,{className:"text-white/50",children:"Digite o email ou ID do novo proprietário para transferir este livro."})]}),e.jsx(J,{placeholder:"Email ou ID do novo proprietário",value:F,onChange:S=>c(S.target.value),className:"bg-white/5 border-white/10 text-white","data-testid":"input-reassign-target"}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>{y(null),c("")},className:"border-white/10 text-white/70","data-testid":"button-cancel-reassign",children:"Cancelar"}),e.jsxs(b,{onClick:()=>w&&F&&v.mutate({bookId:w,targetUserId:F}),disabled:!F||v.isPending,className:"bg-amber-500 hover:bg-amber-600 text-black","data-testid":"button-confirm-reassign",children:[v.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(ka,{className:"w-4 h-4 mr-2"}),"Transferir"]})]})]})})]})}function xb({bookId:a,detail:r,isLoading:l,isError:n,onCopy:u,onReassign:f,onRetry:j}){if(n)return e.jsxs("div",{className:"border-t border-white/10 p-4 flex flex-col items-center justify-center gap-2",children:[e.jsx(Xe,{className:"w-5 h-5 text-red-400"}),e.jsx("p",{className:"text-sm text-red-400",children:"Erro ao carregar detalhes"}),e.jsxs(b,{variant:"outline",size:"sm",onClick:j,className:"border-white/10 text-white/60","data-testid":"button-retry-detail",children:[e.jsx(xe,{className:"w-3 h-3 mr-1"})," Tentar novamente"]})]});if(l||!r)return e.jsx("div",{className:"border-t border-white/10 p-4 flex items-center justify-center",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-amber-400"})});const{book:p,user:g,chapters:w,covers:y,illustrations:F,checkout:c,metadata:m}=r;return e.jsx("div",{className:"border-t border-white/10 bg-white/[0.02]","data-testid":`detail-panel-book-${a}`,children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-xs font-semibold text-white/60 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(ot,{className:"w-3.5 h-3.5"})," Informações do Livro"]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-2 text-sm",children:[e.jsx(vt,{label:"ID",value:p.id,onCopy:u,mono:!0}),e.jsx(vt,{label:"Título",value:p.title||"Sem título"}),e.jsx(vt,{label:"Subtítulo",value:p.subtitle}),e.jsx(vt,{label:"Autor",value:p.author||"Desconhecido"}),e.jsx(vt,{label:"Gênero",value:p.genre}),e.jsx(vt,{label:"Idioma",value:p.language||"pt"}),e.jsx(vt,{label:"Status",value:p.status}),e.jsx(vt,{label:"Progresso",value:`${p.progress||0}%`}),e.jsx(vt,{label:"Pago",value:p.isPaid?"Sim ✅":"Não"}),e.jsx(vt,{label:"Criado",value:p.createdAt?new Date(p.createdAt).toLocaleStr
2ing("pt-BR"):"-"}),e.jsx(vt,{label:"Atualizado",value:p.updatedAt?new Date(p.updatedAt).toLocaleString("pt-BR"):"-"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-xs font-semibold text-white/60 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Hi,{className:"w-3.5 h-3.5"})," Proprietário"]}),g?e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-2 text-sm",children:[e.jsx(vt,{label:"User ID",value:g.id,onCopy:u,mono:!0}),e.jsx(vt,{label:"Nome",value:g.name||"-"}),e.jsx(vt,{label:"Email",value:g.email,onCopy:u}),e.jsx(vt,{label:"Pen Name",value:g.penName||"-"}),e.jsx(vt,{label:"Role",value:g.role})]}):e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3 text-sm text-red-400 flex items-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4"}),"Usuário não encontrado (ID: ",p?.userId,")"]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:f,className:"w-full border-amber-500/30 text-amber-400 hover:bg-amber-500/10","data-testid":"button-reassign-book",children:[e.jsx(ka,{className:"w-3.5 h-3.5 mr-2"}),"Transferir para outro usuário"]})]})]}),c&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-white/60 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Bt,{className:"w-3.5 h-3.5"})," Checkout / Pagamento"]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-2 text-sm",children:[e.jsx(vt,{label:"Checkout ID",value:c.id,onCopy:u,mono:!0}),e.jsx(vt,{label:"Email do Checkout",value:c.email,onCopy:u}),e.jsx(vt,{label:"Valor",value:c.totalAmount?`R$ ${c.totalAmount.toFixed(2)}`:"-"}),e.jsx(vt,{label:"Status",value:c.status}),e.jsx(vt,{label:"Pago em",value:c.paidAt?new Date(c.paidAt).toLocaleString("pt-BR"):"-"}),c.stripePaymentIntentId&&e.jsx(vt,{label:"Stripe PI",value:c.stripePaymentIntentId,onCopy:u,mono:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-lg font-bold text-white",children:w.length}),e.jsxs("div",{className:"text-xs text-white/40 flex items-center justify-center gap-1",children:[e.jsx(tt,{className:"w-3 h-3"})," Capítulos"]}),w.length>0&&e.jsxs("div",{className:"text-[10px] text-white/25 mt-1",children:[w.reduce(($,D)=>$+(D.contentLength||0),0).toLocaleString()," caracteres"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-lg font-bold text-white",children:y.length}),e.jsxs("div",{className:"text-xs text-white/40 flex items-center justify-center gap-1",children:[e.jsx(Va,{className:"w-3 h-3"})," Capas"]}),y.filter($=>$.selected).length>0&&e.jsx("div",{className:"text-[10px] text-emerald-400 mt-1",children:"1 selecionada"})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-lg font-bold text-white",children:F.length}),e.jsxs("div",{className:"text-xs text-white/40 flex items-center justify-center gap-1",children:[e.jsx(yr,{className:"w-3 h-3"})," Ilustrações"]})]})]}),w.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-white/60 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(tt,{className:"w-3.5 h-3.5"})," Capítulos"]}),e.jsx("div",{className:"bg-white/5 rounded-lg divide-y divide-white/5",children:w.sort(($,D)=>($.orderIndex||0)-(D.orderIndex||0)).map(($,D)=>e.jsxs("div",{className:"px-3 py-2 flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-[10px] text-white/20 font-mono w-5 text-right",children:D+1}),e.jsx("span",{className:"text-white/70 truncate",children:$.title||`Capítulo ${D+1}`})]}),e.jsx("span",{className:"text-[10px] text-white/25 shrink-0",children:$.contentLength>0?`${($.contentLength/1e3).toFixed(1)}k`:"vazio"})]},$.id))})]}),y.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-white/60 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Va,{className:"w-3.5 h-3.5"})," Capas Geradas"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:y.map($=>e.jsxs("div",{className:`relative rounded-lg overflow-hidden border ${$.selected?"border-emerald-500 ring-1 ring-emerald-500/30":"border-white/10"}`,children:[e.jsx(vc,{src:$.imageUrl,alt:$.style||"Capa",widths:[96,128,160,200],sizes:"(max-width: 640px) 64px, 80px",className:"w-16 h-24 sm:w-20 sm:h-28 object-cover"}),$.selected&&e.jsx("div",{className:"absolute top-1 right-1 bg-emerald-500 rounded-full p-0.5",children:e.jsx(be,{className:"w-2.5 h-2.5 text-white"})}),$.style&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-black/60 px-1 py-0.5 text-[8px] text-white/70 text-center truncate",children:$.style})]},$.id))})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-white/60 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(pt,{className:"w-3.5 h-3.5"})," Metadados de Publicação"]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-2 text-sm",children:[m.description&&e.jsx(vt,{label:"Descrição",value:m.description.slice(0,200)+(m.description.length>200?"...":"")}),m.bisacCategories&&e.jsx(vt,{label:"BISAC",value:Array.isArray(m.bisacCategories)?m.bisacCategories.join(", "):String(m.bisacCategories)}),m.keywords&&e.jsx(vt,{label:"Keywords",value:Array.isArray(m.keywords)?m.keywords.join(", "):String(m.keywords)}),m.isbn&&e.jsx(vt,{label:"ISBN",value:m.isbn,onCopy:u})]})]}),p.planData&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-white/60 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Ot,{className:"w-3.5 h-3.5"})," Plano do Livro"]}),e.jsx("div",{className:"bg-white/5 rounded-lg p-3 text-xs text-white/40 max-h-[200px] overflow-y-auto",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[10px]",children:typeof p.planData=="str
2ing"?p.planData:JSON.stringify(p.planData,null,2).slice(0,2e3)})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:`/api/admin/books/${a}/pdf`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-3 py-1.5 bg-white/5 hover:bg-white/10 border border-white/10 rounded-lg text-xs text-white/60 hover:text-white transition-colors","data-testid":`link-download-pdf-${a}`,children:[e.jsx(Rt,{className:"w-3 h-3"})," PDF"]}),e.jsxs("a",{href:`/api/admin/books/${a}/epub`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-3 py-1.5 bg-white/5 hover:bg-white/10 border border-white/10 rounded-lg text-xs text-white/60 hover:text-white transition-colors","data-testid":`link-download-epub-${a}`,children:[e.jsx(Rt,{className:"w-3 h-3"})," EPUB"]}),e.jsxs("a",{href:`/api/admin/books/${a}/docx`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-3 py-1.5 bg-white/5 hover:bg-white/10 border border-white/10 rounded-lg text-xs text-white/60 hover:text-white transition-colors","data-testid":`link-download-docx-${a}`,children:[e.jsx(Rt,{className:"w-3 h-3"})," DOCX"]})]})]})})}function vt({label:a,value:r,onCopy:l,mono:n}){return!r||r==="-"?e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-white/30 text-xs w-24 shrink-0",children:a}),e.jsx("span",{className:"text-white/20 text-xs",children:"-"})]}):e.jsxs("div",{className:"flex items-baseline gap-2 group",children:[e.jsx("span",{className:"text-white/30 text-xs w-24 shrink-0",children:a}),e.jsx("span",{className:`text-white/70 text-xs break-all ${n?"font-mono text-[11px]":""}`,children:r}),l&&e.jsx("button",{onClick:u=>{u.stopPropagation(),l(r)},className:"opacity-0 group-hover:opacity-100 transition-opacity p-0.5 hover:bg-white/10 rounded","data-testid":`button-copy-${a.toLowerCase().replace(/\s/g,"-")}`,children:e.jsx(ha,{className:"w-3 h-3 text-white/30"})})]})}function mb(){const{data:a,isLoading:r}=z({queryKey:["/api/admin/instagram-killswitch"],refetchInterval:6e4});return r||!a?null:a.organicBlocked?e.jsx("div",{className:"rounded-2xl border border-amber-500/40 bg-gradient-to-br from-amber-950/60 via-orange-950/40 to-red-950/40 p-5 shadow-lg shadow-amber-500/10","data-testid":"banner-instagram-killswitch-blocked",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 w-12 h-12 rounded-full bg-amber-500/20 border border-amber-500/40 flex items-center justify-center",children:e.jsx(Xe,{className:"w-6 h-6 text-amber-300"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsx("h4",{className:"text-base font-semibold text-amber-100",children:"Publicação orgânica no Instagram DESATIVADA"}),e.jsx(E,{className:"bg-amber-500/20 text-amber-200 border-amber-500/40 text-[10px]",children:"3 camadas de defesa ativas"})]}),e.jsxs("p",{className:"text-sm text-amber-100/85 leading-relaxed mb-3",children:["Nada será publicado nos perfis (feed, stories, carrossel) e nenhuma IA gera conteúdo pra Instagram (zero gasto de token). Auto-resposta de comentários e DMs também pausada."," ",e.jsx("strong",{className:"text-amber-50",children:"Anúncios pagos do Meta Ads continuam funcionando normalmente"})," ","— esses são construídos manualmente."]}),e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"text-xs text-amber-300 cursor-pointer hover:text-amber-200 select-none flex items-center gap-1",children:[e.jsx(Ct,{className:"w-3.5 h-3.5 group-open:rotate-180 transition-transform"}),"Detalhes técnicos e como reativar (apenas com aprovação)"]}),e.jsxs("div",{className:"mt-3 space-y-3 text-xs",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-amber-200/70 font-medium mb-1",children:"O que está bloqueado:"}),e.jsx("ul",{className:"list-disc list-inside space-y-0.5 text-amber-100/70",children:(a.affects||[]).map((l,n)=>e.jsx("li",{children:l},n))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-emerald-300/80 font-medium mb-1",children:"O que continua funcionando:"}),e.jsx("ul",{className:"list-disc list-inside space-y-0.5 text-emerald-100/70",children:(a.doesNotAffect||[]).map((l,n)=>e.jsx("li",{children:l},n))})]}),e.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-black/30 p-3",children:[e.jsx("div",{className:"text-amber-200 font-medium mb-1.5",children:"Para reativar (não recomendado):"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-amber-100/80",children:[e.jsxs("li",{children:["Definir env var ",e.jsxs("code",{className:"bg-black/50 px-1.5 py-0.5 rounded text-amber-200",children:[a.envVar,"=true"]})]}),e.jsxs("li",{children:["Reiniciar workflow ",e.jsx("em",{children:"Start application"})]}),e.jsx("li",{children:"Reabilitar flags individuais nesta tela (Configurações)"})]})]}),e.jsx("div",{className:"text-amber-300/60 italic text-[11px]",children:"Motivo: proteção a autores que não autorizaram divulgação. Caso real registrado em novembro/2025 (autora ameaçou processo)."})]})]})]})]})}):e.jsx("div",{className:"rounded-2xl border border-rose-500/50 bg-gradient-to-br from-rose-950/60 to-red-950/50 p-4 shadow-lg shadow-rose-500/20","data-testid":"banner-instagram-killswitch-enabled",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-full bg-rose-500/20 border border-rose-500/40 flex items-center justify-center",children:e.jsx(Cr,{className:"w-5 h-5 text-rose-300"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"text-sm font-semibold text-rose-100 mb-1",children:"⚠️ Publicação orgânica HABILITADA — Instagram pode postar automaticamente"}),e.jsxs("p",{className:"text-xs text-rose-100/80",children:["Env var ",e.jsxs("code",{className:"bg-black/40 px-1 py-0.5 rounded",children:[a.envVar,"=",String(a.envValue)]}),". Para desativar: remova a variável (ou defina como ",e.jsx("code",{children:"false"}),") e reinicie. Confira cada flag em Configurações antes de qualquer publicação."]})]})]})})}function hb(){const[a,r]=d.useState("dashboard");return st(),e.jsxs("div",{className:"space-y-6","data-testid":"social-media-tab",children:[e.jsx(mb,{}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-4",children:[{key:"dashboard",label:"Dashboard",icon:ft},{key:"launches",label:"Lançamentos",icon:ot},{key:"posts",label:"Publicações",icon:ls},{key:"stories",label:"Stories",icon:Cr},{key:"content",label:"Conteúdo IA",icon:yi},{key:"viral",label:"Carrossel Viral",icon:Ie},{key:"comments",label:"Comentários",icon:Qa},{key:"conversations",label:"DMs",icon:Ut},{key:"social-seller",label:"Social Seller",icon:lt},{key:"logs",label:"Logs",icon:Ac},{key:"settings",label:"Configurações",icon:qa}].map(({key:l,label:n,icon:u})=>e.jsxs(b,{size:"sm",variant:a===l?"default":"outline",onClick:()=>r(l),className:a===l?"bg-orange-600 hover:bg-orange-700 text-white":"border-orange-500/30 text-orange-300 hover:bg-orange-500/10","data-testid":`button-social-subtab-${l}`,children:[e.jsx(u,{className:"w-3.5 h-3.5 mr-1"})," ",n]},l))}),a==="dashboard"&&e.jsx(pb,{}),a==="launches"&&e.jsx(ub,{}),a==="posts"&&e.jsx(gb,{}),a==="stories"&&e.jsx(bb,{}),a==="content"&&e.jsx(jb,{}),a==="viral"&&e.jsx(wb,{}),a==="comments"&&e.jsx(Nb,{}),a==="conversations"&&e.jsx(fb,{}),a==="social-seller"&&e.jsx(yb,{}),a==="logs"&&e.jsx(Cb,{}),a==="settings"&&e.jsx(kb,{})]})}function pb(){const{data:a,isLoading:r,refetch:l}=z({queryKey:["/api/admin/social-media/dashboard"],refetchInterval:6e4});if(r)return e.jsxs("div",{className:"flex items-center gap-2 text-orange-300",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Carregando dashboard..."]});const n=a?.stats||{};return e.jsxs("div",{className:"space-y-6","data-testid":"social-dashboard",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold text-orange-400 flex items-center gap-2",children:[e.jsx(ls,{className:"w-5 h-5"})," Instagram @sabhia.books"]}),e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>l(),className:"border-orange-500/30 text-orange-300","data-testid":"button-refresh-social",children:[e.jsx(xe,{className:"w-3.5 h-3.5 mr-1"})," Atualizar"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(xi,{icon:ls,label:"Posts Publicados",value:n.totalPosts||0,color:"text-green-400"}),e.jsx(xi,{icon:ns,label:"Pendentes",value:n.pendingPosts||0,color:"text-yellow-400"}),e.jsx(xi,{icon:dt,label:"Falhas",value:n.failedPosts||0,color:"text-red-400"}),e.jsx(xi,{icon:Re,label:"Seguidores",value:n.followers||0,color:"text-blue-400"}),e.jsx(xi,{icon:Qa,label:"Comentários",value:n.totalComments||0,color:"text-orange-400"}),e.jsx(xi,{icon:Xe,label:"Sem Resposta",value:n.unrepliedComments||0,color:"text-yellow-400"}),e.jsx(xi,{icon:Ut,label:"DMs Ativos",value:n.activeConversations||0,color:"text-purple-400"}),e.jsx(xi,{icon:yr,label:"Mídias",value:n.mediaCount||0,color:"text-cyan-400"})]}),a?.facebookStatus&&!a.facebookStatus.configured&&e.jsxs("div",{className:"bg-blue-500/10 border border-blue-500/30 rounded-xl p-4 flex items-center gap-3","data-testid":"fb-status-banner",children:[e.jsx(Xi,{className:"w-5 h-5 text-blue-400 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-blue-300",children:"Cross-post para Facebook desativado"}),e.jsxs("p",{className:"text-xs text-white/40 mt-0.5",children:["Configure o Facebook Page ID na aba Meta Ads ",">"," Configuração para publicar automaticamente no Facebook junto com Instagram."]})]})]}),a?.facebookStatus?.configured&&e.jsxs("div",{className:"bg-emerald-500/10 border border-emerald-500/30 rounded-xl p-3 flex items-center gap-3","data-testid":"fb-status-banner-ok",children:[e.jsx(Xi,{className:"w-4 h-4 text-emerald-400 shrink-0"}),e.jsx("p",{className:"text-xs text-emerald-300",children:"Cross-post Facebook ativo — posts serão publicados automaticamente no Instagram + Facebook."})]}),e.jsxs("div",{className:"bg-gradient-to-br from-zinc-800/80 to-zinc-900/60 rounded-xl border border-orange-500/20 p-5",children:[e.jsxs("h4",{className:"text-sm font-semibold text-orange-400 mb-4 flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"})," Funcionalidades Ativas"]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:[e.jsx(wr,{icon:ot,title:"Auto-Publicar Livros",description:"Quando um livro é concluído, publica automaticamente no Instagram com imagem premium e caption IA",color:"text-green-400",bgColor:"bg-green-500/10",borderColor:"border-green-500/20"}),e.jsx(wr,{icon:tt,title:"Auto-Publicar Blog",description:"Cada artigo novo no blog gera automaticamente uma imagem e post no Instagram",color:"text-blue-400",bgColor:"bg-blue-500/10",borderColor:"border-blue-500/20"}),e.jsx(wr,{icon:yi,title:"Conteúdo Original IA",description:"Gera dicas de escrita, citações, fatos literários e prompts criativos diariamente",color:"text-purple-400",bgColor:"bg-purple-500/10",borderColor:"border-purple-500/20"}),e.jsx(wr,{icon:Qi,title:"Respostas IA (Comentários)",description:"Responde comentários automaticamente no idioma do usuário com tom amigável",color:"text-orange-400",bgColor:"bg-orange-500/10",borderColor:"border-orange-500/20"}),e.jsx(wr,{icon:Ut,title:"Respostas IA (DMs)",description:"Conversa com leads no Direct, responde dúvidas e direciona para sabhia.ai",color:"text-cyan-400",bgColor:"bg-cyan-500/10",borderColor:"border-cyan-500/20"}),e.jsx(wr,{icon:Cr,title:"Stories Automáticos",description:"Publica Stories 9:16 para lançamentos de livros e artigos do blog",color:"text-pink-400",bgColor:"bg-pink-500/10",borderColor:"border-pink-500/20"})]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 p-4",children:[e.jsxs("h4",{className:"text-sm font-medium text-orange-300 mb-3 flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4"})," Posts Recentes"]}),e.jsxs("div",{className:"space-y-2 max-h-[300px] overflow-auto",children:[(a?.recentPosts||[]).slice(0,8).map(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-zinc-700/30 rounded text-xs",children:[e.jsx(Dc,{type:u.type}),e.jsx("span",{className:"flex-1 truncate text-zinc-300",children:u.title||u.caption?.substring(0,60)||"Sem título"}),e.jsx(ed,{status:u.status})]},u.id)),(!a?.recentPosts||a.recentPosts.length===0)&&e.jsx("p",{className:"text-zinc-500 text-xs",children:"Nenhum post ainda"})]})]}),e.jsxs("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 p-4",children:[e.jsxs("h4",{className:"text-sm font-medium text-orange-300 mb-3 flex items-center gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"})," Últimas DMs"]}),e.jsxs("div",{className:"space-y-2 max-h-[300px] overflow-auto",children:[(a?.conversations||[]).slice(0,8).map(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-zinc-700/30 rounded text-xs",children:[e.jsxs("span",{className:"text-orange-400 font-medium",children:["@",u.username||u.igUserId]}),e.jsx("span",{className:"text-zinc-500",children:"·"}),e.jsx("span",{className:"text-zinc-400",children:u.lastMessageAt?new Date(u.lastMessageAt).toLocaleDateString("pt-BR"):""}),u.isManualTakeover&&e.jsx(E,{className:"text-[9px] bg-yellow-500/20 text-yellow-400",children:"Manual"})]},u.id)),(!a?.conversations||a.conversations.length===0)&&e.jsx("p",{className:"text-zinc-500 text-xs",children:"Nenhuma conversa"})]})]})]})]})}
2function wr({icon:a,title:r,description:l,color:n,bgColor:u,borderColor:f}){return e.jsxs("div",{className:`rounded-lg border ${f} ${u} p-3`,"data-testid":`feature-card-${r.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx(a,{className:`w-4 h-4 ${n}`}),e.jsx("span",{className:`text-sm font-medium ${n}`,children:r})]}),e.jsx("p",{className:"text-[11px] text-zinc-400 leading-relaxed",children:l})]})}function xi({icon:a,label:r,value:l,color:n}){return e.jsxs("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(a,{className:`w-4 h-4 ${n}`}),e.jsx("span",{className:"text-[11px] text-zinc-400",children:r})]}),e.jsx("span",{className:`text-xl font-bold ${n}`,children:typeof l=="number"?l.toLocaleString("pt-BR"):l})]})}function ub(){const{toast:a}=st(),[r,l]=d.useState(null),{data:n,isLoading:u,isError:f,refetch:j}=z({queryKey:["/api/admin/social-media/publishable-books"]}),p=W({mutationFn:async c=>(await N("POST","/api/admin/social-media/generate-book-post",{bookId:c})).json(),onSuccess:c=>{a({title:"Post gerado com sucesso!",description:"Imagem e legenda criados pela IA"}),j(),c.post&&l(c.post)},onError:c=>a({title:"Erro ao gerar post",description:c.message,variant:"destructive"})}),g=W({mutationFn:async c=>(await N("POST",`/api/admin/social-media/book-post/${c}/publish`)).json(),onSuccess:()=>{a({title:"Publicado no Instagram!"}),j(),l(null)},onError:c=>a({title:"Erro ao publicar",description:c.message,variant:"destructive"})}),w=W({mutationFn:async c=>(await N("POST",`/api/admin/social-media/book-post/${c}/regenerate`)).json(),onSuccess:c=>{a({title:"Post regenerado!"}),j(),c.post&&l(c.post)},onError:c=>a({title:"Erro ao regenerar",description:c.message,variant:"destructive"})});if(u)return e.jsxs("div",{className:"flex items-center gap-2 text-orange-300",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Carregando livros..."]});if(f)return e.jsxs("div",{className:"text-center py-12",children:[e.jsx(dt,{className:"w-10 h-10 mx-auto mb-3 text-red-400 opacity-60"}),e.jsx("p",{className:"text-red-400 mb-2",children:"Erro ao carregar livros"}),e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>j(),className:"border-red-500/30 text-red-300",children:[e.jsx(xe,{className:"w-3.5 h-3.5 mr-1"})," Tentar novamente"]})]});const y=n||[],F=c=>{const $={published:{label:"Publicado",cls:"bg-green-500/20 text-green-400 border-green-500/30"},ready:{label:"Na fila",cls:"bg-blue-500/20 text-blue-400 border-blue-500/30"},generating:{label:"Gerando...",cls:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30"},publishing:{label:"Publicando...",cls:"bg-orange-500/20 text-orange-400 border-orange-500/30"},failed:{label:"Falhou",cls:"bg-red-500/20 text-red-400 border-red-500/30"},pending:{label:"Pendente",cls:"bg-zinc-500/20 text-zinc-400 border-zinc-500/30"}}[c]||{label:c,cls:"bg-zinc-500/20 text-zinc-400 border-zinc-500/30"};return e.jsx(E,{variant:"outline",className:$.cls,children:$.label})};return e.jsxs("div",{className:"space-y-4","data-testid":"social-launches",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold text-orange-400 flex items-center gap-2",children:[e.jsx(ot,{className:"w-5 h-5"})," Lançamentos de Livros"]}),e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>j(),className:"border-orange-500/30 text-orange-300","data-testid":"button-refresh-launches",children:[e.jsx(xe,{className:"w-3.5 h-3.5 mr-1"})," Atualizar"]})]}),e.jsx("p",{className:"text-sm text-zinc-400",children:"Livros com capa pronta para divulgar no Instagram. Gere uma imagem promocional com IA e publique."}),y.length===0?e.jsxs("div",{className:"text-center py-12 text-zinc-500",children:[e.jsx(ot,{className:"w-10 h-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"Nenhum livro com capa finalizada encontrado."})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:y.map(c=>e.jsxs("div",{className:"bg-gradient-to-br from-zinc-800/80 to-zinc-900/60 rounded-xl border border-orange-500/20 p-4 space-y-3","data-testid":`card-launch-book-${c.id}`,children:[e.jsxs("div",{className:"flex gap-3",children:[c.coverImage&&e.jsx("img",{src:c.coverImage,alt:c.title,className:"w-16 h-20 object-cover rounded-lg border border-zinc-700","data-testid":`img-cover-${c.id}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-semibold text-white text-sm truncate","data-testid":`text-title-${c.id}`,children:c.title}),e.jsx("p",{className:"text-xs text-zinc-400 truncate",children:c.author||"Autor desconhecido"}),c.genre&&e.jsx("p",{className:"text-xs text-teal-400 mt-0.5",children:c.genre})]})]}),e.jsx("div",{className:"flex items-center justify-between",children:c.igPost?e.jsxs("div",{className:"flex items-center gap-2",children:[F(c.igPost.status),c.igPost.publishedAt&&e.jsx("span",{className:"text-xs text-zinc-500",children:new Date(c.igPost.publishedAt).toLocaleDateString("pt-BR")})]}):e.jsx(E,{variant:"outline",className:"bg-zinc-700/30 text-zinc-400 border-zinc-600/30",children:"Sem post"})}),e.jsx("div",{className:"flex gap-2",children:c.igPost?e.jsxs(e.Fragment,{children:[(c.igPost.status==="ready"||c.igPost.status==="failed")&&e.jsxs(e.Fragment,{children:[e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>l(c.igPost),className:"border-blue-500/30 text-blue-300 hover:bg-blue-500/10","data-testid":`button-preview-post-${c.id}`,children:[e.jsx(ht,{className:"w-3.5 h-3.5 mr-1"})," Ver"]}),e.jsxs(b,{size:"sm",onClick:()=>g.mutate(c.igPost.id),disabled:g.isPending,className:"bg-green-600 hover:bg-green-700 text-white flex-1","data-testid":`button-publish-post-${c.id}`,children:[g.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin mr-1"}):e.jsx(ct,{className:"w-3.5 h-3.5 mr-1"}),"Publicar"]})]}),c.igPost.status==="published"&&e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>l(c.igPost),className:"border-green-500/30 text-green-300 hover:bg-green-500/10","data-testid":`button-view-published-${c.id}`,children:[e.jsx(ht,{className:"w-3.5 h-3.5 mr-1"})," Ver Publicado"]}
2),(c.igPost.status==="generating"||c.igPost.status==="publishing")&&e.jsxs(b,{size:"sm",disabled:!0,className:"flex-1 opacity-60",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin mr-1"})," ",c.igPost.status==="generating"?"Gerando...":"Publicando..."]}),c.igPost.status!=="generating"&&c.igPost.status!=="publishing"&&e.jsx(b,{size:"sm",variant:"outline",onClick:()=>w.mutate(c.igPost.id),disabled:w.isPending,className:"border-orange-500/30 text-orange-300 hover:bg-orange-500/10","data-testid":`button-regenerate-post-${c.id}`,children:w.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Sr,{className:"w-3.5 h-3.5"})})]}):e.jsxs(b,{size:"sm",onClick:()=>p.mutate(c.id),disabled:p.isPending,className:"bg-orange-600 hover:bg-orange-700 text-white flex-1","data-testid":`button-generate-post-${c.id}`,children:[p.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin mr-1"}):e.jsx(qe,{className:"w-3.5 h-3.5 mr-1"}),"Gerar Post"]})}),c.igPost?.status==="failed"&&c.igPost.errorMessage&&e.jsx("p",{className:"text-xs text-red-400 bg-red-500/10 rounded px-2 py-1 truncate","data-testid":`text-error-${c.id}`,children:c.igPost.errorMessage})]},c.id))}),r&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm",onClick:()=>l(null),"data-testid":"modal-preview-post",children:e.jsxs("div",{className:"bg-zinc-900 rounded-2xl border border-orange-500/30 max-w-lg w-full mx-4 max-h-[90vh] overflow-y-auto",onClick:c=>c.stopPropagation(),children:[e.jsxs("div",{className:"p-4 border-b border-zinc-800 flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold text-orange-400 flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4"})," Preview do Post"]}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>l(null),className:"text-zinc-400 hover:text-white","data-testid":"button-close-preview",children:"✕"})]}),r.imageUrl&&e.jsx("img",{src:r.imageUrl,alt:"Preview",className:"w-full aspect-[4/5] object-cover","data-testid":"img-preview-post"}),r.caption&&e.jsx("div",{className:"p-4",children:e.jsx("pre",{className:"whitespace-pre-wrap text-sm text-zinc-300 font-sans leading-relaxed","data-testid":"text-preview-caption",children:r.caption})}),e.jsxs("div",{className:"p-4 border-t border-zinc-800 flex gap-2",children:[(r.status==="ready"||r.status==="failed")&&e.jsxs(b,{size:"sm",onClick:()=>g.mutate(r.id),disabled:g.isPending,className:"bg-green-600 hover:bg-green-700 text-white flex-1","data-testid":"button-publish-from-preview",children:[g.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin mr-1"}):e.jsx(ct,{className:"w-3.5 h-3.5 mr-1"}),"Publicar no Instagram"]}),e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>{w.mutate(r.id),l(null)},disabled:w.isPending,className:"border-orange-500/30 text-orange-300 hover:bg-orange-500/10","data-testid":"button-regenerate-from-preview",children:[e.jsx(Sr,{className:"w-3.5 h-3.5 mr-1"})," Regenerar"]})]})]})})]})}function gb(){const{toast:a}=st(),[r,l]=d.useState(""),[n,u]=d.useState(""),f=new URLSearchParams;r&&f.set("type",r),n&&f.set("status",n);const j=f.toString(),{data:p=[],isLoading:g,refetch:w}=z({queryKey:["/api/admin/social-media/posts",j],queryFn:()=>N("GET",`/api/admin/social-media/posts${j?"?"+j:""}`).then($=>$.json())}),y=W({mutationFn:$=>N("POST",`/api/admin/social-media/posts/${$}/publish`),onSuccess:()=>{a({title:"Publicando..."}),w()},onError:$=>a({title:"Erro ao publicar",description:$.message,variant:"destructive"})}),F=W({mutationFn:$=>N("DELETE",`/api/admin/social-media/posts/${$}`),onSuccess:()=>{a({title:"Post removido"}),w()}}),c=W({mutationFn:$=>N("POST","/api/admin/social-media/generate-content",{type:$}),onSuccess:()=>{a({title:"Conteúdo sendo gerado..."}),setTimeout(()=>w(),1e4)},onError:$=>a({title:"Erro",description:$.message,variant:"destructive"})}),m=p.filter($=>$.type!=="story");return e.jsxs("div",{className:"space-y-4","data-testid":"social-posts-section",children:[e.jsxs("div",{className:"bg-gradient-to-r from-zinc-800/60 to-zinc-900/40 rounded-lg border border-orange-500/15 p-4 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ls,{className:"w-5 h-5 text-orange-400"}),e.jsx("h3",{className:"text-base font-semibold text-orange-400",children:"Publicações no Feed"})]}),e.jsxs("p",{className:"text-xs text-zinc-400",children:["Posts publicados no Instagram e Facebook: lançamentos de livros, artigos do blog e conteúdo original gerado pela IA. ",e.jsxs("span",{className:"text-pink-400",children:[e.jsx(ls,{className:"w-3 h-3 inline"})," IG"]})," + ",e.jsxs("span",{className:"text-blue-400",children:[e.jsx(Xi,{className:"w-3 h-3 inline"})," FB"]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 justify-between",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("select",{className:"bg-zinc-800 border border-zinc-600 rounded px-2 py-1 text-xs text-zinc-300",value:r,onChange:$=>l($.target.value),"data-testid":"select-post-type-filter",children:[e.jsx("option",{value:"",children:"Todos os tipos"}),e.jsx("option",{value:"book_launch",children:"Lançamento de Livro"}),e.jsx("option",{value:"blog_article",children:"Artigo do Blog"}),e.jsx("option",{value:"original_content",children:"Conteúdo Original IA"})]}),e.jsxs("select",{className:"bg-zinc-800 border border-zinc-600 rounded px-2 py-1 text-xs text-zinc-300",value:n,onChange:$=>u($.target.value),"data-testid":"select-post-status-filter",children:[e.jsx("option",{value:"",children:"Todos status"}),e.jsx("option",{value:"pending",children:"Pendente"}),e.jsx("option",{value:"generating",children:"Gerando"}),e.jsx("option",{value:"ready",children:"Na fila"}),e.jsx("option",{value:"published",children:"Publicado"}),e.jsx("option",{value:"failed",children:"Falhou"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{size:"sm",onClick:()=>c.mutate(void 0),disabled:c.isPending,className:"bg-orange-600 hover:bg-orange-700 text-white text-xs","data-testid":"button-generate-content",children:[c.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(qe,{className:"w-3 h-3 mr-1"}),"Gerar Conteúdo"]}),e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>w(),className:"border-orange-500/30 text-orange-300 text-xs","data-testid":"button-refresh-posts",children:[e.jsx(xe,{className:"w-3 h-3 mr-1"})," Atualizar"]})]})]}),g?e.jsxs("div",{className:"text-zinc-400 text-sm flex items-center gap-2",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Carregando posts..."]}):m.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ls,{className:"w-12 h-12 text-zinc-600 mx-auto mb-3"}),e.jsx("p",{className:"text-zinc-500 text-sm mb-1",children:"Nenhuma publicação encontrada"}),e.jsx("p",{className:"text-zinc-600 text-xs",children:'Clique em "Gerar Conteúdo" para criar seu primeiro post'})]}):e.jsx("div",{className:"space-y-2",children:m.map($=>e.jsx(vb,{post:$,onPublish:()=>y.mutate($.id),onDelete:()=>F.mutate($.id),isPublishing:y.isPending},$.id))})]})}function bb(){const{toast:a}=st(),{data:r=[],isLoading:l,refetch:n}=z({queryKey:["/api/admin/social-media/posts","stories"],queryFn:()=>N("GET","/api/admin/social-media/posts?type=story").then(j=>j.json())}),u=W({mutationFn:j=>N("POST",`/api/admin/social-media/posts/${j}/publish`),onSuccess:()=>{a({title:"Publicando Story..."}),n()},onError:j=>a({title:"Erro",description:j.message,variant:"destructive"})}),f=W({mutationFn:j=>N("DELETE",`/api/admin/social-media/posts/${j}`),onSuccess:()=>{a({title:"Story removido"}),n()}});return e.jsxs("div",{className:"space-y-4","data-testid":"social-stories-section",children:[e.jsxs("div",{className:"bg-gradient-to-r from-zinc-800/60 to-zinc-900/40 rounded-lg border border-pink-500/15 p-4 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Cr,{className:"w-5 h-5 text-pink-400"}),e.jsx("h3",{className:"text-base font-semibold text-pink-400",children:"Instagram Stories"})]}),e.jsx("p",{className:"text-xs text-zinc-400",children:"Stories automáticos em formato 9:16 (1080x1920). Publicados automaticamente junto com lançamentos de livros e artigos do blog."})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>n(),className:"border-orange-500/30 text-orange-300 text-xs","data-testid":"button-refresh-stories",children:[e.jsx(xe,{className:"w-3 h-3 mr-1"})," Atualizar"]})}),l?e.jsxs("div",{className:"text-zinc-400 text-sm flex items-center gap-2",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Carregando stories..."]}):r.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Cr,{className:"w-12 h-12 text-zinc-600 mx-auto mb-3"}),e.jsx("p",{className:"text-zinc-500 text-sm mb-1",children:"Nenhum Story ainda"}),e.jsx("p",{className:"text-zinc-600 text-xs",children:"Stories são gerados automaticamente quando um livro é publicado ou artigo do blog é criado"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:r.map(j=>e.jsxs("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 overflow-hidden","data-testid":`card-story-${j.id}`,children:[j.imageUrl&&e.jsxs("div",{className:"aspect-[9/16] relative",children:[e.jsx("img",{src:j.imageUrl,alt:"",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx(ed,{status:j.status})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"text-[11px] text-zinc-300 truncate",children:j.title||"Story"}),e.jsx("p",{className:"text-[10px] text-zinc-500 mt-0.5",children:j.publishedAt?new Date(j.publishedAt).toLocaleStr
2ing("pt-BR"):new Date(j.createdAt).toLocaleString("pt-BR")}),e.jsxs("div",{className:"flex gap-1 mt-2",children:[(j.status==="ready"||j.status==="failed")&&e.jsxs(b,{size:"sm",onClick:()=>u.mutate(j.id),className:"h-6 px-2 text-[10px] bg-green-600 hover:bg-green-700 flex-1","data-testid":`button-publish-story-${j.id}`,children:[e.jsx(Us,{className:"w-2.5 h-2.5 mr-0.5"})," Publicar"]}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>f.mutate(j.id),className:"h-6 px-1.5 text-red-400 hover:text-red-300","data-testid":`button-delete-story-${j.id}`,children:e.jsx(As,{className:"w-2.5 h-2.5"})})]})]})]},j.id))})]})}function jb(){const{toast:a}=st(),r=W({mutationFn:n=>N("POST","/api/admin/social-media/generate-content",{type:n}),onSuccess:()=>{a({title:"Conteúdo sendo gerado pela IA..."})},onError:n=>a({title:"Erro",description:n.message,variant:"destructive"})}),l=[{type:"tip",icon:Rc,title:"Dica de Escrita",description:"Gera uma dica prática e valiosa sobre o processo de escrita, publicação ou marketing de livros",color:"text-emerald-400",bgColor:"bg-emerald-500/10",borderColor:"border-emerald-500/20",hoverBg:"hover:bg-emerald-500/20"},{type:"quote",icon:ou,title:"Citação Inspiradora",description:"Gera uma citação motivacional sobre escrita, literatura ou criatividade de autores famosos",color:"text-amber-400",bgColor:"bg-amber-500/10",borderColor:"border-amber-500/20",hoverBg:"hover:bg-amber-500/20"},{type:"fact",icon:pt,title:"Fato Literário",description:"Gera um fato curioso e surpreendente sobre o mundo dos livros, autores ou história literária",color:"text-sky-400",bgColor:"bg-sky-500/10",borderColor:"border-sky-500/20",hoverBg:"hover:bg-sky-500/20"},{type:"prompt",icon:qe,title:"Prompt Criativo",description:"Gera um prompt de escrita criativa para engajar seguidores e incentivar a escrita",color:"text-violet-400",bgColor:"bg-violet-500/10",borderColor:"border-violet-500/20",hoverBg:"hover:bg-violet-500/20"}];return e.jsxs("div",{className:"space-y-4","data-testid":"social-content-section",children:[e.jsxs("div",{className:"bg-gradient-to-r from-zinc-800/60 to-zinc-900/40 rounded-lg border border-purple-500/15 p-4 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(yi,{className:"w-5 h-5 text-purple-400"}),e.jsx("h3",{className:"text-base font-semibold text-purple-400",children:"Gerador de Conteúdo IA"})]}),e.jsx("p",{className:"text-xs text-zinc-400",children:"A IA gera automaticamente conteúdo original para o Instagram. Cada tipo cria uma imagem premium 4:5 com texto em dourado e uma caption otimizada com hashtags. O conteúdo é gerado automaticamente de acordo com a frequência configurada, mas você também pode gerar manualmente abaixo."})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:l.map(({type:n,icon:u,title:f,description:j,color:p,bgColor:g,borderColor:w,hoverBg:y})=>e.jsx("div",{className:`rounded-xl border ${w} ${g} p-4 transition-colors ${y}`,"data-testid":`content-type-${n}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`p-2.5 rounded-lg ${g} border ${w}`,children:e.jsx(u,{className:`w-6 h-6 ${p}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:`text-sm font-semibold ${p} mb-1`,children:f}),e.jsx("p",{className:"text-[11px] text-zinc-400 leading-relaxed mb-3",children:j}),e.jsxs(b,{size:"sm",onClick:()=>r.mutate(n),disabled:r.isPending,className:"bg-orange-600 hover:bg-orange-700 text-white text-xs h-8","data-testid":`button-generate-${n}`,children:[r.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(qe,{className:"w-3 h-3 mr-1"}),"Gerar ",f]})]})]})},n))}),e.jsxs("div",{className:"bg-zinc-800/30 rounded-lg border border-zinc-700/50 p-4 mt-2",children:[e.jsxs("h4",{className:"text-sm font-medium text-zinc-300 mb-2 flex items-center gap-2",children:[e.jsx(Zl,{className:"w-4 h-4 text-zinc-400"})," Como funciona a automação"]}),e.jsxs("div",{className:"space-y-2 text-xs text-zinc-500",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(be,{className:"w-3.5 h-3.5 text-green-500 mt-0.5 shrink-0"}),e.jsx("span",{children:"O worker automático gera conteúdo original diariamente (entre 8h e 21h) de acordo com a frequência definida nas configurações"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(be,{className:"w-3.5 h-3.5 text-green-500 mt-0.5 shrink-0"}),e.jsx("span",{children:"Os tipos de conteúdo são alternados automaticamente para manter variedade no feed"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(be,{className:"w-3.5 h-3.5 text-green-500 mt-0.5 shrink-0"}),e.jsx("span",{children:"Cada post é gerado com imagem premium (4:5), caption em português com emojis e hashtags relevantes"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(be,{className:"w-3.5 h-3.5 text-green-500 mt-0.5 shrink-0"}),e.jsx("span",{children:"O logo da SÁBHIA é automaticamente adicionado em cada imagem"})]})]})]})]})}function vb({post:a,onPublish:r,onDelete:l,isPublishing:n}){const[u,f]=d.useState(!1);return e.jsxs("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 p-3","data-testid":`card-post-${a.id}`,children:[e.jsxs("div",{className:"flex items-start gap-3",children:[a.imageUrl&&e.jsx("img",{src:a.imageUrl,alt:"",className:"w-16 h-20 object-cover rounded"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx(Dc,{type:a.type}),e.jsx(ed,{status:a.status}),a.mediaType==="CAROUSEL"&&e.jsx(E,{className:"text-[9px] bg-purple-500/20 text-purple-300",children:"Carrossel"}),a.isStory&&e.jsx(E,{className:"text-[9px] bg-pink-500/20 text-pink-300",children:"Story"})]}),e.jsx("p",{className:"text-sm text-zinc-200 font-medium truncate",children:a.title||"Sem título"}),e.jsxs("p",{className:"text-[11px] text-zinc-500 mt-0.5",children:[a.publishedAt?`Publicado: ${new Date(a.publishedAt).toLocaleStr
2ing("pt-BR")}`:`Criado: ${new Date(a.createdAt).toLocaleString("pt-BR")}`,a.status==="published"&&e.jsxs("span",{className:"ml-2 inline-flex items-center gap-1.5",children:[a.igMediaId?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-pink-400",title:`Publicado no Instagram (${a.igMediaId})`,children:[e.jsx(ls,{className:"w-3 h-3"})," IG"]}):e.jsx("span",{className:"inline-flex items-center gap-0.5 text-zinc-500",title:"Não publicado no Instagram",children:e.jsx(ls,{className:"w-3 h-3"})}),a.fbPostId?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-blue-400",title:`Publicado no Facebook (${a.fbPostId})`,children:[e.jsx(Xi,{className:"w-3 h-3"})," FB"]}):a.isStory?null:e.jsx("span",{className:"inline-flex items-center gap-0.5 text-zinc-600",title:"Não publicado no Facebook",children:e.jsx(Xi,{className:"w-3 h-3"})})]})]}),a.errorMessage&&e.jsxs("p",{className:"text-[11px] text-red-400 mt-1",children:["Erro: ",a.errorMessage.substring(0,100)]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[(a.status==="ready"||a.status==="failed")&&e.jsx(b,{size:"sm",onClick:r,disabled:n,className:`h-7 px-2 text-xs ${a.status==="failed"?"bg-orange-600 hover:bg-orange-700":"bg-green-600 hover:bg-green-700"}`,"data-testid":`button-publish-post-${a.id}`,children:a.status==="failed"?e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"w-3 h-3 mr-1"})," Tentar Novamente"]}):e.jsxs(e.Fragment,{children:[e.jsx(ct,{className:"w-3 h-3 mr-1"})," Publicar"]})}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>f(!u),className:"h-7 px-2 text-xs text-zinc-400","data-testid":`button-expand-post-${a.id}`,children:u?e.jsx(ta,{className:"w-3 h-3"}):e.jsx(Ct,{className:"w-3 h-3"})}),e.jsx(b,{size:"sm",variant:"ghost",onClick:l,className:"h-7 px-2 text-xs text-red-400 hover:text-red-300","data-testid":`button-delete-social-post-${a.id}`,children:e.jsx(As,{className:"w-3 h-3"})})]})]}),u&&a.caption&&e.jsx("div",{className:"mt-3 p-2 bg-zinc-900/50 rounded text-xs text-zinc-300 whitespace-pre-wrap max-h-[200px] overflow-auto",children:a.caption})]})}function Nb(){const{toast:a}=st(),[r,l]=d.useState(""),{data:n=[],isLoading:u,refetch:f}=z({queryKey:["/api/admin/social-media/comments",r],queryFn:()=>{const p=new URLSearchParams;return r&&p.set("replied",r),N("GET",`/api/admin/social-media/comments${p.toString()?"?"+p:""}`).then(g=>g.json())}}),j=W({mutationFn:()=>N("POST","/api/admin/social-media/poll-comments"),onSuccess:()=>{a({title:"Buscando comentários..."}),setTimeout(()=>f(),15e3)}});return e.jsxs("div",{className:"space-y-4","data-testid":"social-comments-section",children:[e.jsxs("div",{className:"bg-gradient-to-r from-zinc-800/60 to-zinc-900/40 rounded-lg border border-orange-500/15 p-4 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-orange-400"}),e.jsx("h3",{className:"text-base font-semibold text-orange-400",children:"Comentários do Instagram"})]}),e.jsx("p",{className:"text-xs text-zinc-400",children:"A IA responde automaticamente os comentários nos posts, detectando o idioma do comentário e respondendo de forma natural e amigável."})]}),e.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[e.jsxs("select",{className:"bg-zinc-800 border border-zinc-600 rounded px-2 py-1 text-xs text-zinc-300",value:r,onChange:p=>l(p.target.value),"data-testid":"select-comment-filter",children:[e.jsx("option",{value:"",children:"Todos"}),e.jsx("option",{value:"false",children:"Sem resposta"}),e.jsx("option",{value:"true",children:"Respondidos"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(b,{size:"sm",onClick:()=>j.mutate(),disabled:j.isPending,className:"bg-orange-600 hover:bg-orange-700 text-white text-xs","data-testid":"button-poll-comments",children:[j.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(xe,{className:"w-3 h-3 mr-1"}),"Buscar Comentários"]})})]}),u?e.jsxs("div",{className:"text-zinc-400 text-sm",children:[e.jsx(T,{className:"w-4 h-4 animate-spin inline mr-2"}),"Carregando..."]}):n.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Qa,{className:"w-12 h-12 text-zinc-600 mx-auto mb-3"}),e.jsx("p",{className:"text-zinc-500 text-sm mb-1",children:"Nenhum comentário encontrado"}),e.jsx("p",{className:"text-zinc-600 text-xs",children:"Os comentários são buscados automaticamente a cada 5 minutos pelo worker"})]}):e.jsx("div",{className:"space-y-2",children:n.map(p=>e.jsxs("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 p-3","data-testid":`card-comment-${p.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"text-orange-400 font-medium text-sm",children:["@",p.username]}),e.jsx("span",{className:"text-zinc-500 text-[10px]",children:p.timestamp?new Date(p.timestamp).toLocaleStr
2ing("pt-BR"):""}),p.replied?e.jsxs(E,{className:"text-[9px] bg-green-500/20 text-green-400",children:[e.jsx(be,{className:"w-2.5 h-2.5 mr-0.5"})," Respondido"]}):e.jsxs(E,{className:"text-[9px] bg-yellow-500/20 text-yellow-400",children:[e.jsx(Xe,{className:"w-2.5 h-2.5 mr-0.5"})," Pendente"]})]}),e.jsx("p",{className:"text-sm text-zinc-300 mb-1",children:p.text}),p.replyText&&e.jsxs("div",{className:"ml-4 mt-2 p-2 bg-zinc-900/50 rounded border-l-2 border-orange-500/30",children:[e.jsx("p",{className:"text-xs text-orange-300 mb-0.5",children:"@sabhia.books respondeu:"}),e.jsx("p",{className:"text-xs text-zinc-300",children:p.replyText})]})]},p.id))})]})}function fb(){const{toast:a}=st(),[r,l]=d.useState(null),[n,u]=d.useState(""),{data:f}=z({queryKey:["/api/admin/meta-config/token-status"],queryFn:()=>N("GET","/api/admin/meta-config/token-status").then(o=>o.json()).catch(()=>null),refetchInterval:6e4}),{data:j}=z({queryKey:["/api/admin/social-media/settings"],queryFn:()=>N("GET","/api/admin/social-media/settings").then(o=>o.json()).catch(()=>null)}),p=W({mutationFn:()=>N("POST","/api/admin/meta-config/detect-page"),onSuccess:async o=>{const L=await o.json();K.invalidateQueries({queryKey:["/api/admin/meta-config/token-status"]}),a({title:L.tokenUpgraded?"Token corrigido para Page Token!":"Página detectada",description:L.pageName||""})},onError:o=>a({title:"Erro",description:o.message,variant:"destructive"})}),{data:g=[],isLoading:w,refetch:y}=z({queryKey:["/api/admin/social-media/conversations"],queryFn:()=>N("GET","/api/admin/social-media/conversations").then(o=>o.json())}),{data:F=[],refetch:c}=z({queryKey:["/api/admin/social-media/conversations",r,"messages"],queryFn:()=>r?N("GET",`/api/admin/social-media/conversations/${r}/messages`).then(o=>o.json()):Promise.resolve([]),enabled:!!r,refetchInterval:r?1e4:!1}),m=W({mutationFn:o=>N("POST",`/api/admin/social-media/conversations/${o.convId}/reply`,{message:o.message}),onSuccess:()=>{u(""),c(),a({title:"Mensagem enviada"})},onError:o=>a({title:"Erro",description:o.message,variant:"destructive"})}),$=W({mutationFn:o=>N("POST",`/api/admin/social-media/messages/${o}/retry`),onSuccess:()=>{c(),a({title:"Mensagem reenviada com sucesso!"})},onError:o=>a({title:"Falha no reenvio",description:o.message,variant:"destructive"})}),D=W({mutationFn:o=>N("POST",`/api/admin/social-media/conversations/${o.convId}/takeover`,{takeover:o.takeover}),onSuccess:()=>{y(),a({title:"Status atualizado"})}}),A=g.find(o=>o.id===r);return e.jsxs("div",{className:"space-y-4","data-testid":"social-conversations-section",children:[e.jsxs("div",{className:"bg-gradient-to-r from-zinc-800/60 to-zinc-900/40 rounded-lg border border-cyan-500/15 p-4 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ut,{className:"w-5 h-5 text-cyan-400"}),e.jsx("h3",{className:"text-base font-semibold text-cyan-400",children:"Direct Messages (DMs)"})]}),e.jsx("p",{className:"text-xs text-zinc-400",children:"A IA conversa automaticamente com leads no Direct do Instagram, respondendo dúvidas sobre a plataforma e direcionando para sabhia.ai. Você pode assumir manualmente qualquer conversa a qualquer momento."})]}),f&&f.status!=="ok"&&e.jsxs("div",{className:"bg-red-500/10 border border-red-500/30 rounded-lg p-3 flex items-start gap-3","data-testid":"dm-token-warning",children:[e.jsx(Xe,{className:"w-5 h-5 text-red-400 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-red-300",children:"IA não consegue responder DMs"}),e.jsx("p",{className:"text-xs text-red-300/70 mt-1",children:f.dmIssue||f.message||"Problema com o token Meta. Verifique a configuração."}),f.dmErrorCount24h>0&&e.jsxs("p",{className:"text-xs text-red-400/60 mt-1",children:[f.dmErrorCount24h," erro(s) nas últimas 24h"]})]}),f.issueType==="wrong_type"&&e.jsxs(b,{size:"sm",onClick:()=>p.mutate(),disabled:p.isPending,className:"bg-orange-600 hover:bg-orange-700 text-white text-xs shrink-0","data-testid":"button-fix-token",children:[p.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(He,{className:"w-3 h-3 mr-1"}),"Corrigir Token"]})]}),f?.status==="ok"&&j&&!j.autoReplyDms&&e.jsxs("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-3 flex items-center gap-3","data-testid":"dm-disabled-warning",children:[e.jsx(Xe,{className:"w-4 h-4 text-yellow-400 shrink-0"}),e.jsxs("p",{className:"text-xs text-yellow-300",children:["Respostas automáticas de DMs estão ",e.jsx("strong",{children:"desabilitadas"}),". Ative em Configurações para a IA responder automaticamente."]})]}),f?.status==="ok"&&j?.autoReplyDms&&e.jsxs("div",{className:"bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2 flex items-center gap-2","data-testid":"dm-status-ok",children:[e.jsx(be,{className:"w-4 h-4 text-green-400 shrink-0"}),e.jsx("p",{className:"text-xs text-green-300/80",children:"Social Seller ativo — IA respondendo DMs automaticamente"})]}),f&&(f.failedMessages24h>0||f.dmErrorCount24h>0)&&e.jsxs("div",{className:"bg-amber-500/10 border border-amber-500/25 rounded-lg p-3 flex items-start gap-3","data-testid":"dm-errors-warning",children:[e.jsx(Xe,{className:"w-4 h-4 text-amber-400 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[f.failedMessages24h>0&&e.jsxs("p",{className:"text-xs text-amber-300",children:[f.failedMessages24h," mensagem(ns) falharam nas últimas 24h"]}),f.dmErrorCount24h>0&&e.jsxs("p",{className:"text-xs text-amber-300/70",children:[f.dmErrorCount24h," erro(s) de DM nas últimas 24h"]}),f.lastDmError&&e.jsxs("p",{className:"text-[10px] text-amber-400/60 break-all",children:["Último erro: ",f.lastDmError.substring(0,200)]})]})]}),e.jsxs("div",{className:"flex gap-4 min-h-[400px]",children:[e.jsxs("div",{className:"w-1/3 space-y-2 max-h-[500px] overflow-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-sm font-medium text-orange-300",children:"Conversas"}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>y(),className:"text-xs text-zinc-400","data-testid":"button-refresh-convs",children:e.jsx(xe,{className:"w-3 h-3"})})]}),w?e.jsxs("div",{className:"text-zinc-400 text-xs",children:[e.jsx(T,{className:"w-3 h-3 animate-spin inline mr-1"}),"Carregando..."]}):g.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Ut,{className:"w-8 h-8 text-zinc-600 mx-auto mb-2"}),e.jsx("p",{className:"text-zinc-500 text-xs",children:"Nenhuma conversa"})]}):g.map(o=>e.jsxs("div",{onClick:()=>l(o.id),className:`p-2 rounded cursor-pointer transition-colors ${r===o.id?"bg-orange-500/20 border border-orange-500/30":"bg-zinc-800/50 border border-zinc-700 hover:bg-zinc-700/50"}`,"data-testid":`conv-item-${o.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-orange-400",children:["@",o.username||o.igUserId?.substring(0,12)]}),o.isManualTakeover&&e.jsx(E,{className:"text-[8px] bg-yellow-500/20 text-yellow-400",children:"Manual"})]}),e.jsx("span",{className:"text-[10px] text-zinc-500",children:o.lastMessageAt?new Date(o.lastMessageAt).toLocaleStr
2ing("pt-BR"):""})]},o.id))]}),e.jsx("div",{className:"flex-1 flex flex-col bg-zinc-800/30 rounded-lg border border-zinc-700",children:r?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-3 border-b border-zinc-700 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("span",{className:"text-sm font-medium text-orange-400",children:["@",A?.username||"Usuário"]}),A?.isManualTakeover&&e.jsx(E,{className:"ml-2 text-[9px] bg-yellow-500/20 text-yellow-400",children:"Modo Manual"})]}),e.jsx(b,{size:"sm",variant:"outline",onClick:()=>D.mutate({convId:r,takeover:!A?.isManualTakeover}),className:"text-xs border-zinc-600","data-testid":"button-toggle-takeover",children:A?.isManualTakeover?"Reativar IA":"Assumir Manual"})]}),e.jsx("div",{className:"flex-1 overflow-auto p-3 space-y-2 max-h-[350px]",children:[...F].reverse().map((o,L)=>{const v=o.status==="failed"&&o.direction==="outgoing";return e.jsx("div",{className:`flex ${o.direction==="outgoing"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[70%] p-2 rounded-lg text-xs ${v?"bg-red-600/20 border border-red-500/30 text-red-200":o.direction==="outgoing"?"bg-orange-600/30 text-orange-100":"bg-zinc-700 text-zinc-200"}`,children:[o.text,v&&e.jsxs("div",{className:"mt-1.5 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-red-400",children:[e.jsx(dt,{className:"w-3 h-3"}),e.jsx("span",{children:"Falha no envio"})]}),o.errorDetails&&e.jsx("p",{className:"text-[8px] text-red-400/70 break-all",children:o.errorDetails.substring(0,120)}),e.jsxs(b,{size:"sm",variant:"ghost",onClick:()=>$.mutate(o.id),disabled:$.isPending,className:"h-5 px-2 text-[9px] text-orange-400 hover:text-orange-300 hover:bg-orange-500/10","data-testid":`button-retry-msg-${o.id}`,children:[$.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(Sr,{className:"w-3 h-3 mr-1"}),"Reenviar"]})]}),e.jsx("span",{className:"block text-[9px] text-zinc-500 mt-1",children:o.sentAt?new Date(o.sentAt).toLocaleTimeString("pt-BR"):""})]})},o.id||L)})}),e.jsxs("div",{className:"p-3 border-t border-zinc-700 flex gap-2",children:[e.jsx(J,{value:n,onChange:o=>u(o.target.value),placeholder:"Escreva uma mensagem...",className:"bg-zinc-800 border-zinc-600 text-zinc-200 text-sm",onKeyDown:o=>o.key==="Enter"&&n.trim()&&m.mutate({convId:r,message:n.trim()}),"data-testid":"input-dm-reply"}),e.jsx(b,{size:"sm",onClick:()=>n.trim()&&m.mutate({convId:r,message:n.trim()}),disabled:!n.trim()||m.isPending,className:"bg-orange-600 hover:bg-orange-700","data-testid":"button-send-dm",children:e.jsx(ct,{className:"w-3.5 h-3.5"})})]})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-zinc-500 text-sm",children:"Selecione uma conversa"})})]})]})}function wb(){const{toast:a}=st(),[r,l]=d.useState(!1),{data:n,isLoading:u}=z({queryKey:["/api/admin/social-media/posts","viral_carousel"],queryFn:()=>N("GET","/api/admin/social-media/posts?type=viral_carousel&limit=20").then(g=>g.json()),refetchInterval:r?5e3:3e4}),f=W({mutationFn:()=>N("POST","/api/admin/social-media/generate-viral-carousel"),onSuccess:()=>{l(!0),a({title:"Geração iniciada",description:"O carrossel viral está sendo criado com IA. Isso pode levar alguns minutos."}),setTimeout(()=>{K.invalidateQueries({queryKey:["/api/admin/social-media/posts","viral_carousel"]})},1e4),setTimeout(()=>l(!1),18e4)},onError:g=>a({title:"Erro",description:g.message,variant:"destructive"})}),j=W({mutationFn:g=>N("POST",`/api/admin/social-media/posts/${g}/publish`),onSuccess:()=>{a({title:"Publicado!",description:"Carrossel publicado no Instagram"}),K.invalidateQueries({queryKey:["/api/admin/social-media/posts","viral_carousel"]})},onError:g=>a({title:"Erro ao publicar",description:g.message,variant:"destructive"})}),p=(n||[]).filter(g=>g.status==="generating");return d.useEffect(()=>{p.length>0&&!r&&l(!0),p.length===0&&r&&K.invalidateQueries({queryKey:["/api/admin/social-media/posts","viral_carousel"]})},[p.length]),e.jsxs("div",{className:"space-y-6","data-testid":"viral-carousel-section",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold text-orange-400 flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5"})," Carrosséis Virais"]}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:"Carrosséis com conteúdo pesquisado por IA no estilo viral — temas impactantes do universo editorial"})]}),e.jsx(b,{onClick:()=>f.mutate(),disabled:f.isPending||r,className:"bg-gradient-to-r from-orange-600 to-red-600 hover:from-orange-700 hover:to-red-700 text-white","data-testid":"button-generate-viral-carousel",children:f.isPending||r?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 animate-spin mr-2"})," Gerando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"w-4 h-4 mr-2"})," Gerar Carrossel Viral"]})})]}),r&&p.length>0&&e.jsxs("div",{className:"bg-orange-500/10 border border-orange-500/30 rounded-lg p-4 flex items-center gap-3",children:[e.jsx(T,{className:"w-5 h-5 animate-spin text-orange-400"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-orange-300 font-medium",children:"Gerando carrossel viral..."}),e.jsx("p",{className:"text-xs text-zinc-500",children:"A IA está pesquisando temas, gerando imagens e montando os slides. Isso pode levar 2-5 minutos."})]})]}),u?e.jsxs("div",{className:"text-zinc-400",children:[e.jsx(T,{className:"w-4 h-4 animate-spin inline mr-2"}),"Carregando..."]}):!n||n.length===0?e.jsxs("div",{className:"text-center py-12 text-zinc-500",children:[e.jsx(Ie,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum carrossel viral gerado ainda"}),e.jsx("p",{className:"text-xs mt-1",children:'Clique em "Gerar Carrossel Viral" para criar o primeiro'})]}):e.jsx("div",{className:"space-y-4",children:n.map(g=>e.jsx("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 overflow-hidden","data-testid":`card-viral-carousel-${g.id}`,children:e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dc,{type:g.type}),e.jsx(ed,{status:g.status}),g.status==="published"&&e.jsxs(e.Fragment,{children:[g.igMediaId?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-pink-400",title:`IG: ${g.igMediaId}`,children:[e.jsx(ls,{className:"w-3 h-3"})," IG"]}):e.jsx("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-zinc-500",children:e.jsx(ls,{className:"w-3 h-3"})}),g.fbPostId?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-blue-400",title:`FB: ${g.fbPostId}`,children:[e.jsx(Xi,{className:"w-3 h-3"})," FB"]}):e.jsx("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-zinc-600",children:e.jsx(Xi,{className:"w-3 h-3"})})]}),e.jsx("span",{className:"text-sm text-zinc-200 font-medium",children:g.title})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(g.status==="ready"||g.status==="failed")&&e.jsx(b,{size:"sm",onClick:()=>j.mutate(g.id),disabled:j.isPending,className:g.status==="failed"?"bg-orange-600 hover:bg-orange-700 text-white text-xs":"bg-green-600 hover:bg-green-700 text-white text-xs","data-testid":`button-publish-viral-${g.id}`,children:g.status==="failed"?e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"w-3 h-3 mr-1"})," Tentar Novamente"]}):e.jsxs(e.Fragment,{children:[e.jsx(Us,{className:"w-3 h-3 mr-1"})," Publicar"]})}),e.jsx("span",{className:"text-[10px] text-zinc-500",children:new Date(g.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"})})]})]}),g.carouselUrls&&g.carouselUrls.length>0&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2 scrollbar-thin","data-testid":`carousel-preview-${g.id}`,children:g.carouselUrls.map((w,y)=>e.jsxs("div",{className:"flex-shrink-0 w-36 h-44 rounded-lg overflow-hidden border border-zinc-600 relative",children:[e.jsx("img",{src:w,alt:`Slide ${y+1}`,className:"w-full h-full object-cover","data-testid":`img-viral-slide-${g.id}-${y}`}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-black/60 text-center py-0.5",children:e.jsxs("span",{className:"text-[9px] text-zinc-300",children:[y+1,"/",g.carouselUrls.length]})})]},y))}),g.caption&&e.jsxs("details",{className:"mt-2",children:[e.jsx("summary",{className:"text-xs text-zinc-400 cursor-pointer hover:text-zinc-300",children:"Ver caption"}),e.jsx("p",{className:"text-xs text-zinc-400 mt-2 whitespace-pre-wrap bg-zinc-900/50 rounded p-2 max-h-40 overflow-y-auto",children:g.caption})]}),g.errorMessage&&e.jsx("p",{className:"text-xs text-red-400 mt-2 bg-red-500/10 rounded p-2",children:g.errorMessage})]})},g.id))})]})}function yb(){const{toast:a}=st(),[r,l]=d.useState([{question:"Quero criar meu livro!",payload:"CRIAR_LIVRO"},{question:"Como funciona a SÁBHIA?",payload:"COMO_FUNCIONA"},{question:"Quanto custa?",payload:"PRECO"},{question:"Quero saber mais",payload:"SABER_MAIS"}]),{data:n,isLoading:u}=z({queryKey:["/api/admin/social-media/funnel"],refetchInterval:6e4}),{data:f,isLoading:j}=z({queryKey:["/api/admin/social-media/ice-breakers"]}),{data:p}=z({queryKey:["/api/admin/social-media/conversations"]}),{data:g}=z({queryKey:["/api/admin/social-media/follower-stats"],refetchInterval:6e4}),w=W({mutationFn:async()=>(await N("POST","/api/admin/social-media/poll-followers")).json(),onSuccess:A=>{K.invalidateQueries({queryKey:["/api/admin/social-media/follower-stats"]}),a({title:A.newFollowers>0?`${A.newFollowers}
2 novos seguidores detectados!`:"Nenhum novo seguidor encontrado"})},onError:A=>{a({title:"Erro",description:A.message,variant:"destructive"})}}),y=W({mutationFn:async A=>(await N("POST","/api/admin/social-media/ice-breakers",{iceBreakers:A})).json(),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/social-media/ice-breakers"]}),a({title:"Ice breakers configurados!"})},onError:A=>{a({title:"Erro",description:A.message,variant:"destructive"})}});d.useEffect(()=>{f&&Array.isArray(f)&&f.length>0&&l(f.map(A=>({question:A.question||"",payload:A.payload||""})))},[f]);const F=n||{awareness:0,interest:0,desire:0,action:0,total:0},c=Math.max(F.total,1),m=(p||[]).filter(A=>A.leadScore>0||A.conversationStage!=="awareness").sort((A,o)=>(o.leadScore||0)-(A.leadScore||0)).slice(0,10),$={awareness:"bg-blue-500",interest:"bg-amber-500",desire:"bg-orange-500",action:"bg-emerald-500"},D={awareness:"Descoberta",interest:"Interesse",desire:"Desejo",action:"Ação"};return e.jsxs("div",{className:"space-y-6","data-testid":"social-seller-tab",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("h3",{className:"text-lg font-semibold text-orange-400 flex items-center gap-2",children:[e.jsx(lt,{className:"w-5 h-5"})," Social Seller AI"]}),e.jsx(E,{className:"bg-violet-500/20 text-violet-300 border-violet-500/30 text-[10px]",children:"BETA"})]}),e.jsxs("div",{className:"bg-gradient-to-br from-zinc-800/80 to-zinc-900/60 rounded-xl border border-violet-500/20 p-5 space-y-4",children:[e.jsxs("h4",{className:"text-sm font-semibold text-violet-400 flex items-center gap-2",children:[e.jsx(Gl,{className:"w-4 h-4"})," Funil de Conversão"]}),u?e.jsxs("div",{className:"flex items-center gap-2 text-white/50 text-sm",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Carregando..."]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-4 gap-3",children:["awareness","interest","desire","action"].map(A=>e.jsxs("div",{className:"bg-zinc-800/60 rounded-lg p-3 text-center border border-white/5",children:[e.jsx("div",{className:`text-2xl font-bold ${A==="awareness"?"text-blue-400":A==="interest"?"text-amber-400":A==="desire"?"text-orange-400":"text-emerald-400"}`,children:F[A]}),e.jsx("div",{className:"text-[10px] text-white/50 mt-1 uppercase tracking-wider",children:D[A]}),e.jsxs("div",{className:"text-[9px] text-white/30 mt-0.5",children:[(F[A]/c*100).toFixed(0),"%"]})]},A))}),e.jsx("div",{className:"flex h-3 rounded-full overflow-hidden bg-zinc-700/50",children:["awareness","interest","desire","action"].map(A=>{const o=F[A]/c*100;return o===0?null:e.jsx("div",{className:`${$[A]} transition-all`,style:{width:`${o}%`}},A)})})]})]}),e.jsxs("div",{className:"bg-gradient-to-br from-zinc-800/80 to-zinc-900/60 rounded-xl border border-blue-500/20 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-semibold text-blue-400 flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4"})," Novos Seguidores"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-[10px] gap-1 h-7 border-blue-500/30 text-blue-400",disabled:w.isPending,onClick:()=>w.mutate(),"data-testid":"btn-poll-followers",children:[w.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"})," Atualizar"]})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-zinc-800/60 rounded-lg p-3 text-center border border-white/5",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-400","data-testid":"text-followers-today",children:g?.todayNew??0}),e.jsx("div",{className:"text-[10px] text-white/50 mt-1 uppercase tracking-wider",children:"Hoje"})]}),e.jsxs("div",{className:"bg-zinc-800/60 rounded-lg p-3 text-center border border-white/5",children:[e.jsx("div",{className:"text-2xl font-bold text-white/80","data-testid":"text-followers-total",children:g?.total??0}),e.jsx("div",{className:"text-[10px] text-white/50 mt-1 uppercase tracking-wider",children:"Total Rastreado"})]}),e.jsxs("div",{className:"bg-zinc-800/60 rounded-lg p-3 text-center border border-white/5",children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-400","data-testid":"text-followers-engaged",children:g?.engagedCount??0}),e.jsx("div",{className:"text-[10px] text-white/50 mt-1 uppercase tracking-wider",children:"Engajaram"})]}),e.jsxs("div",{className:"bg-zinc-800/60 rounded-lg p-3 text-center border border-white/5",children:[e.jsxs("div",{className:"text-2xl font-bold text-orange-400","data-testid":"text-followers-conversion",children:[g?.total?(g.engagedCount/g.total*100).toFixed(0):0,"%"]}),e.jsx("div",{className:"text-[10px] text-white/50 mt-1 uppercase tracking-wider",children:"Conversão"})]})]}),e.jsx("p",{className:"text-[10px] text-white/30",children:"Seguidores detectados automaticamente a cada 30 min. Quando interagem (DM, comentário, ice breaker), recebem tratamento VIP com boas-vindas especial."})]}),e.jsxs("div",{className:"bg-gradient-to-br from-zinc-800/80 to-zinc-900/60 rounded-xl border border-teal-500/20 p-5 space-y-4",children:[e.jsxs("h4",{className:"text-sm font-semibold text-teal-400 flex items-center gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"})," Ice Breakers (Mensagem de Boas-vindas)"]}),e.jsx("p",{className:"text-[11px] text-white/40",children:"Opções que aparecem quando alguém abre o chat pela primeira vez. Configure frases estratég
2icas que guiem para a venda."}),e.jsx("div",{className:"space-y-2",children:r.map((A,o)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{value:A.question,onChange:L=>{const v=[...r];v[o]={...v[o],question:L.target.value},l(v)},placeholder:"Texto que aparece no botão...",className:"flex-1 bg-zinc-800/60 border-white/10 text-white text-sm h-9","data-testid":`input-icebreaker-${o}`}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-9 w-9 p-0 text-red-400/50 hover:text-red-400",onClick:()=>l(r.filter((L,v)=>v!==o)),"data-testid":`btn-remove-icebreaker-${o}`,children:e.jsx(ea,{className:"w-3.5 h-3.5"})})]},o))}),e.jsxs("div",{className:"flex gap-2",children:[r.length<4&&e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-teal-500/30 text-teal-400",onClick:()=>l([...r,{question:"",payload:`CUSTOM_${r.length}`}]),"data-testid":"btn-add-icebreaker",children:[e.jsx(_t,{className:"w-3 h-3"})," Adicionar"]}),e.jsxs(b,{size:"sm",className:"text-xs gap-1 bg-teal-600 hover:bg-teal-500 text-white",disabled:y.isPending||r.some(A=>!A.question.trim()),onClick:()=>y.mutate(r.filter(A=>A.question.trim())),"data-testid":"btn-save-icebreakers",children:[y.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(Ic,{className:"w-3 h-3"})," Salvar Ice Breakers"]})]})]}),m.length>0&&e.jsxs("div",{className:"bg-gradient-to-br from-zinc-800/80 to-zinc-900/60 rounded-xl border border-orange-500/20 p-5 space-y-3",children:[e.jsxs("h4",{className:"text-sm font-semibold text-orange-400 flex items-center gap-2",children:[e.jsx(cu,{className:"w-4 h-4"})," Top Leads (",m.length,")"]}),e.jsx("div",{className:"space-y-2",children:m.map(A=>e.jsxs("div",{className:"flex items-center justify-between bg-zinc-800/40 rounded-lg px-3 py-2 border border-white/5","data-testid":`lead-row-${A.id}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${$[A.conversationStage||"awareness"]}`}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-white font-medium",children:A.username?`@${A.username}`:`ID: ${A.igUserId?.substring(0,12)}...`}),e.jsx("span",{className:"text-[10px] text-white/40 ml-2",children:D[A.conversationStage||"awareness"]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-16 h-1.5 rounded-full bg-zinc-700 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${(A.leadScore||0)>=60?"bg-emerald-500":(A.leadScore||0)>=30?"bg-amber-500":"bg-blue-500"}`,style:{width:`${A.leadScore||0}%`}})}),e.jsx("span",{className:"text-[10px] text-white/50 font-mono w-8 text-right",children:A.leadScore||0})]})})]},A.id))})]}),e.jsxs("div",{className:"bg-zinc-800/40 rounded-xl border border-white/5 p-4 space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold text-white/50 uppercase tracking-wider",children:"Como funciona o Social Seller"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 text-[11px] text-white/40",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ut,{className:"w-3.5 h-3.5 mt-0.5 text-teal-400 shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{className:"text-white/60",children:"DMs Inteligentes:"})," IA responde cada mensagem com tom humano, adaptando ao estágio da conversa (descoberta → interesse → desejo → ação)"]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Qa,{className:"w-3.5 h-3.5 mt-0.5 text-violet-400 shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{className:"text-white/60",children:"Private Reply:"})," Quando alguém comenta nos posts, a IA responde publicamente E envia uma DM personalizada"]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(lt,{className:"w-3.5 h-3.5 mt-0.5 text-orange-400 shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{className:"text-white/60",children:"Lead Scoring:"})," Cada lead recebe uma pontuação (0-100) baseada no engajamento e estágio da conversa"]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Gl,{className:"w-3.5 h-3.5 mt-0.5 text-emerald-400 shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{className:"text-white/60",children:"Ice Breakers:"})," Mensagens de boas-vindas que aparecem quando alguém abre o chat pela primeira vez"]})]})]})]})]})}function kb(){const{toast:a}=st(),{data:r,isLoading:l}
2=z({queryKey:["/api/admin/social-media/settings"],queryFn:()=>N("GET","/api/admin/social-media/settings").then(j=>j.json())}),[n,u]=d.useState({});d.useEffect(()=>{r&&u(r)},[r]);const f=W({mutationFn:j=>N("PUT","/api/admin/social-media/settings",j),onSuccess:()=>{a({title:"Configurações salvas"}),K.invalidateQueries({queryKey:["/api/admin/social-media/settings"]})},onError:j=>a({title:"Erro",description:j.message,variant:"destructive"})});return l?e.jsxs("div",{className:"text-zinc-400",children:[e.jsx(T,{className:"w-4 h-4 animate-spin inline mr-2"}),"Carregando..."]}):e.jsxs("div",{className:"space-y-6 max-w-2xl","data-testid":"social-settings-section",children:[e.jsx("h3",{className:"text-lg font-semibold text-orange-400",children:"Configurações do Social Media Manager"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-zinc-400 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(ot,{className:"w-3.5 h-3.5"})," Publicação Automática"]}),e.jsx(Ki,{label:"Auto-publicar lançamentos de livros",description:"Gera post quando a capa fica pronta e publica automaticamente respeitando o limite diário",checked:n.autoPublishBookLaunches??!0,onChange:j=>u({...n,autoPublishBookLaunches:j}),testId:"switch-auto-book"}),e.jsx(Ki,{label:"Auto-publicar artigos do blog",description:"Gera imagem + caption para cada novo artigo do blog",checked:n.autoPublishBlogArticles??!0,onChange:j=>u({...n,autoPublishBlogArticles:j}),testId:"switch-auto-blog"}),e.jsx(Ki,{label:"Publicar Stories",description:"Cria stories automáticos para lançamentos e artigos",checked:n.enableStories??!0,onChange:j=>u({...n,enableStories:j}),testId:"switch-stories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-zinc-400 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(yi,{className:"w-3.5 h-3.5"})," Conteúdo Original IA"]}),e.jsx(Ki,{label:"Gerar conteúdo original",description:"Cria posts com dicas, citações e fatos sobre escrita diariamente",checked:n.enableOriginalContent??!0,onChange:j=>u({...n,enableOriginalContent:j}),testId:"switch-original-content"}),e.jsx(Ki,{label:"Carrosséis virais automáticos",description:"Gera carrosséis com temas virais do universo editorial automaticamente",checked:n.enableViralCarousels??!0,onChange:j=>u({...n,enableViralCarousels:j}),testId:"switch-viral-carousels"}),e.jsxs("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(He,{className:"w-4 h-4 text-orange-400"}),e.jsx("span",{className:"text-sm font-semibold text-zinc-200",children:"Motor de Produção de Conteúdo"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-zinc-200 block",children:"Carrosséis virais por dia"}),e.jsx(J,{type:"number",min:0,max:10,value:n.viralCarouselFrequencyPerDay??n.viralCarouselFrequencyPerWeek??1,onChange:j=>u({...n,viralCarouselFrequencyPerDay:Math.min(10,Math.max(0,parseInt(j.target.value)||0))}),className:"bg-zinc-800 border-zinc-600 w-24 text-zinc-200","data-testid":"input-viral-frequency-daily"}),e.jsx("p",{className:"text-[10px] text-zinc-500",children:"0 a 10 carrosséis por dia (verifica a cada 2h)"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-zinc-200 block",children:"Posts de conteúdo por dia"}),e.jsx(J,{type:"number",min:0,max:10,value:n.contentFrequencyPerDay??1,onChange:j=>u({...n,contentFrequencyPerDay:Math.min(10,Math.max(0,parseInt(j.target.value)||0))}),className:"bg-zinc-800 border-zinc-600 w-24 text-zinc-200","data-testid":"input-content-frequency"}),e.jsx("p",{className:"text-[10px] text-zinc-500",children:"0 a 10 posts originais por dia (verifica a cada 2h)"})]})]}),e.jsxs("div",{className:"space-y-1 pt-2 border-t border-zinc-700",children:[e.jsx("label",{className:"text-sm text-zinc-200 block",children:"Limite diário total de publicações"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(J,{type:"number",min:1,max:50,value:n.maxDailyPosts??25,onChange:j=>u({...n,maxDailyPosts:Math.min(50,Math.max(1,parseInt(j.target.value)||25))}),className:"bg-zinc-800 border-zinc-600 w-24 text-zinc-200","data-testid":"input-max-daily-posts"}),e.jsx("p",{className:"text-[10px] text-zinc-500 flex-1",children:"Segurança: limite m
2áximo de posts publicados por dia no Instagram (API permite até 100, recomendado até 25)"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-zinc-200 block",children:"Lançamentos de livros por dia"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(J,{type:"number",min:1,max:20,value:n.bookLaunchPostsPerDay??3,onChange:j=>u({...n,bookLaunchPostsPerDay:Math.min(20,Math.max(1,parseInt(j.target.value)||3))}),className:"bg-zinc-800 border-zinc-600 w-24 text-zinc-200","data-testid":"input-book-launch-per-day"}),e.jsx("p",{className:"text-[10px] text-zinc-500 flex-1",children:"Livros novos com post pronto entram na fila e são publicados automaticamente até este limite por dia"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-zinc-400 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Qi,{className:"w-3.5 h-3.5"})," Respostas Automáticas IA"]}),e.jsx(Ki,{label:"Responder comentários automaticamente",description:"IA responde comentários no idioma do usuário",checked:n.autoReplyComments??!0,onChange:j=>u({...n,autoReplyComments:j}),testId:"switch-auto-comments"}),e.jsx(Ki,{label:"Responder DMs automaticamente",description:"IA conversa com clientes potenciais via DM",checked:n.autoReplyDms??!0,onChange:j=>u({...n,autoReplyDms:j}),testId:"switch-auto-dms"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-zinc-400 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(qa,{className:"w-3.5 h-3.5"})," Webhook"]}),e.jsxs("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 p-3",children:[e.jsx("label",{className:"text-sm text-zinc-200 block mb-1",children:"Token de verificação do Webhook"}),e.jsx(J,{value:n.webhookVerifyToken??"",onChange:j=>u({...n,webhookVerifyToken:j.target.value}),placeholder:"sabhia_ig_webhook_2024",className:"bg-zinc-800 border-zinc-600 text-zinc-200","data-testid":"input-webhook-token"}),e.jsx("p",{className:"text-[10px] text-zinc-500 mt-1",children:"Use este token ao configurar o webhook no Meta Developers"})]})]}),e.jsxs(b,{onClick:()=>f.mutate(n),disabled:f.isPending,className:"bg-orange-600 hover:bg-orange-700 text-white","data-testid":"button-save-social-settings",children:[f.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin mr-2"}):null,"Salvar Configurações"]})]})}function Cb(){const{toast:a}=st(),[r,l]=d.useState(""),[n,u]=d.useState(""),[f,j]=d.useState(0),[p,g]=d.useState(null),w=50,y=W({mutationFn:I=>N("POST",`/api/admin/social-media/posts/${I}/publish`),onSuccess:()=>{a({title:"Republicação iniciada",description:"O post está sendo publicado novamente."}),K.invalidateQueries({queryKey:["/api/admin/social-media/logs"]}),K.invalidateQueries({queryKey:["/api/admin/social-media/posts"]})},onError:I=>a({title:"Erro ao republicar",description:I.message,variant:"destructive"})}),{data:F,isLoading:c,refetch:m}=z({queryKey:["/api/admin/social-media/logs",r,n,f],queryFn:async()=>{const I=new URLSearchParams;return r&&I.set("level",r),n&&I.set("category",n),I.set("limit",String(w)),I.set("offset",String(f*w)),(await N("GET",`/api/admin/social-media/logs?${I.toString()}`)).json()},refetchInterval:15e3}),$=F?.logs||[],D=F?.total||0,A=Math.ceil(D/w),o=()=>{const I=new URLSearchParams;r&&I.set("level",r),n&&I.set("category",n),window.open(`/api/admin/social-media/logs/export?${I.toString()}`,"_blank")},L={success:{label:"Sucesso",className:"bg-green-500/20 text-green-400",icon:be},info:{label:"Info",className:"bg-blue-500/20 text-blue-400",icon:Xe},warn:{label:"Aviso",className:"bg-yellow-500/20 text-yellow-400",icon:Xe},error:{label:"Erro",className:"bg-red-500/20 text-red-400",icon:dt}},v={instagram:"Instagram API",book_launch:"Lançamento Livro",blog_article:"Artigo Blog",content_ai:"Conteúdo IA",viral_carousel:"C
2arrossel Viral",comments:"Comentários",dms:"DMs",worker:"Worker"};return e.jsxs("div",{className:"space-y-4","data-testid":"logs-section",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold text-orange-400 flex items-center gap-2",children:[e.jsx(Ac,{className:"w-5 h-5"})," Logs do Social Media"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>m(),className:"border-orange-500/30 text-orange-300 hover:bg-orange-500/10","data-testid":"button-refresh-logs",children:[e.jsx(xe,{className:"w-3.5 h-3.5 mr-1"})," Atualizar"]}),e.jsxs(b,{size:"sm",variant:"outline",onClick:o,className:"border-orange-500/30 text-orange-300 hover:bg-orange-500/10","data-testid":"button-export-logs",children:[e.jsx(Rt,{className:"w-3.5 h-3.5 mr-1"})," Exportar CSV"]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("select",{value:r,onChange:I=>{l(I.target.value),j(0)},className:"bg-zinc-800 border border-zinc-700 rounded px-3 py-1.5 text-sm text-zinc-300","data-testid":"select-log-level",children:[e.jsx("option",{value:"",children:"Todos os níveis"}),e.jsx("option",{value:"success",children:"Sucesso"}),e.jsx("option",{value:"info",children:"Info"}),e.jsx("option",{value:"warn",children:"Aviso"}),e.jsx("option",{value:"error",children:"Erro"})]}),e.jsxs("select",{value:n,onChange:I=>{u(I.target.value),j(0)},className:"bg-zinc-800 border border-zinc-700 rounded px-3 py-1.5 text-sm text-zinc-300","data-testid":"select-log-category",children:[e.jsx("option",{value:"",children:"Todas as categorias"}),e.jsx("option",{value:"instagram",children:"Instagram API"}),e.jsx("option",{value:"book_launch",children:"Lançamento Livro"}),e.jsx("option",{value:"blog_article",children:"Artigo Blog"}),e.jsx("option",{value:"content_ai",children:"Conteúdo IA"}),e.jsx("option",{value:"viral_carousel",children:"Carrossel Viral"}),e.jsx("option",{value:"comments",children:"Comentários"}),e.jsx("option",{value:"dms",children:"DMs"}),e.jsx("option",{value:"worker",children:"Worker"})]}),(r||n)&&e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>{l(""),u(""),j(0)},className:"text-zinc-400 hover:text-white",children:"Limpar filtros"}),e.jsxs("span",{className:"ml-auto text-xs text-zinc-500 self-center","data-testid":"text-log-count",children:[D," registros"]})]}),c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-orange-400"})}):$.length===0?e.jsx("div",{className:"text-center py-8 text-zinc-500",children:"Nenhum log encontrado. Os eventos aparecem aqui quando o Social Media executa ações."}):e.jsx("div",{className:"space-y-1",children:$.map(I=>{const de=L[I.level]||L.info,me=de.icon,ne=p===I.id;return e.jsx("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700/50 px-4 py-2.5 hover:bg-zinc-800/80 transition-colors cursor-pointer",onClick:()=>I.details&&g(ne?null:I.id),"data-testid":`log-entry-${I.id}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(me,{className:`w-4 h-4 mt-0.5 shrink-0 ${de.className.split(" ")[1]}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(E,{className:`text-[9px] ${de.className}`,children:de.label}),e.jsx(E,{className:"text-[9px] bg-zinc-600/30 text-zinc-400",children:v[I.category]||I.category}),e.jsx("span",{className:"text-xs text-zinc-500",children:I.action}),I.postId&&e.jsxs("span",{className:"text-[9px] text-zinc-600",children:["Post #",I.postId]})]}),e.jsx("p",{className:"text-sm text-zinc-200 mt-1",children:I.message}),ne&&I.details&&e.jsx("pre",{className:"text-[11px] text-zinc-400 mt-2 bg-zinc-900/50 p-2 rounded whitespace-pre-wrap break-all border border-zinc-700/30","data-testid":`log-details-${I.id}`,children:I.details}),I.level==="error"&&I.postId&&e.jsx(b,{size:"sm",onClick:Z=>{Z.stopPropagation(),y.mutate(I.postId)},disabled:y.isPending,className:"mt-2 h-6 px-3 text-[10px] bg-orange-600 hover:bg-orange-700 text-white","data-testid":`button-retry-log-${I.id}`,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-2.5 h-2.5 animate-spin mr-1"})," Republicando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"w-2.5 h-2.5 mr-1"})," Tentar Publicar Novamente"]})})]}),e.jsx("span",{className:"text-[10px] text-zinc-500 whitespace-nowrap shrink-0",children:I.createdAt?new Date(I.createdAt).toLocaleStr
2ing("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):""}),I.details&&e.jsx(Ct,{className:`w-3.5 h-3.5 text-zinc-500 shrink-0 transition-transform ${ne?"rotate-180":""}`})]})},I.id)})}),A>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2 pt-2","data-testid":"log-pagination",children:[e.jsx(b,{size:"sm",variant:"outline",disabled:f===0,onClick:()=>j(f-1),className:"text-xs border-zinc-700 text-zinc-400",children:"Anterior"}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["Página ",f+1," de ",A]}),e.jsx(b,{size:"sm",variant:"outline",disabled:f>=A-1,onClick:()=>j(f+1),className:"text-xs border-zinc-700 text-zinc-400",children:"Próxima"})]})]})}function Ki({label:a,description:r,checked:l,onChange:n,testId:u}){return e.jsxs("div",{className:"bg-zinc-800/50 rounded-lg border border-zinc-700 p-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-zinc-200",children:a}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:r})]}),e.jsx(rt,{checked:l,onCheckedChange:n,"data-testid":u})]})}function Dc({type:a}){const l={book_launch:{label:"Lançamento",className:"bg-green-500/20 text-green-400"},blog_article:{label:"Blog",className:"bg-blue-500/20 text-blue-400"},original_content:{label:"Conteúdo IA",className:"bg-purple-500/20 text-purple-400"},viral_carousel:{label:"Viral",className:"bg-red-500/20 text-red-400"},story:{label:"Story",className:"bg-pink-500/20 text-pink-400"}}[a]||{label:a,className:"bg-zinc-500/20 text-zinc-400"};return e.jsx(E,{className:`text-[9px] ${l.className}`,children:l.label})}function ed({status:a}){const l={pending:{label:"Pendente",className:"bg-zinc-500/20 text-zinc-400",icon:ns},generating:{label:"Gerando",className:"bg-yellow-500/20 text-yellow-400",icon:T},ready:{label:"Pronto",className:"bg-orange-500/20 text-orange-400",icon:be},publishing:{label:"Publicando",className:"bg-blue-500/20 text-blue-400",icon:T},published:{label:"Publicado",className:"bg-green-500/20 text-green-400",icon:be},failed:{label:"Falhou",className:"bg-red-500/20 text-red-400",icon:dt}}[a]||{label:a,className:"bg-zinc-500/20 text-zinc-400",icon:Xe},n=l.icon;return e.jsxs(E,{className:`text-[9px] ${l.className}`,children:[e.jsx(n,{className:"w-2.5 h-2.5 mr-0.5"}),l.label]})}function Ba(a){return a.toLocaleString("pt-BR")}function Eh(a){return`${a.toFixed(1)}%`}function $c(a){const r=Date.now()-new Date(a).getTime(),l=Math.floor(r/6e4);if(l<60)return`${l}min`;const n=Math.floor(l/60);return n<24?`${n}h`:`${Math.floor(n/24)}d`}function mi({label:a,value:r,total:l}){const n=l>0?r/l*100:0,u=n>=80?"bg-emerald-500":n>=50?"bg-amber-500":"bg-red-500",f=n>=80?"text-emerald-400":n>=50?"text-amber-400":"text-red-400";return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xs text-gray-400 w-24 shrink-0",children:a}),e.jsx("div",{className:"flex-1 bg-white/5 rounded-full h-2.5 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${u} transition-all duration-500`,style:{width:`${n}%`}})}),e.jsx("span",{className:`text-xs font-medium w-14 text-right ${f}`,children:Eh(n)})]})}const ch={Purchase:1,AddPaymentInfo:2,InitiateCheckout:3,AddToCart:4,Lead:5,CompleteRegistration:6,ViewContent:7,PageView:8},xh={Purchase:"text-emerald-400",AddPaymentInfo:"text-teal-400",InitiateCheckout:"text-violet-400",AddToCart:"text-amber-400",Lead:"text-blue-400",CompleteRegistration:"text-cyan-400",ViewContent:"text-gray-300",PageView:"text-gray-500"};function Sb(){const{user:a}=Sa(),r=!!a&&a.role==="admin",{data:l,isLoading:n,error:u,refetch:f,isFetching:j}=z({queryKey:["/api/admin/meta-tracking"],enabled:r,refetchInterval:3e4});if(n)return e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(T,{className:"w-8 h-8 animate-spin text-teal-400"})});if(u||!l)return e.jsx("div",{className:"flex items-center justify-center py-20","data-testid":"meta-tracking-error",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-12 h-12 rounded-xl bg-red-500/10 border border-red-500/20 flex items-center justify-center",children:e.jsx(Xe,{className:"w-6 h-6 text-red-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white/80 font-medium text-sm",children:"Não foi possível carregar os dados"}),e.jsx("p",{className:"text-white/40 text-xs mt-1",children:"Verifique sua conexão e tente novamente"})]}),e.jsxs("button",{onClick:()=>f(),disabled:j,className:"inline-flex items-center gap-2 px-4 py-2 bg-teal-600/20 hover:bg-teal-600/30 border border-teal-500/30 rounded-lg text-sm text-teal-400 transition-colors","data-testid":"button-retry-meta",children:[e.jsx(xe,{className:`w-3.5 h-3.5 ${j?"animate-spin":""}`}),j?"Carregando...":"Tentar novamente"]})]})});const p=[...l.byEvent].sort((g,w)=>(ch[g.eventName]||99)-(ch[w.eventName]||99));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 rounded-xl bg-gradient-to-br from-blue-600/20 to-indigo-600/20 border border-blue-500/20",children:e.jsx(jt,{className:"w-5 h-5 text-blue-400"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white","data-testid":"text-meta-tracking-title",children:"Meta Tracking Quality"}),e.jsx("p",{className:"text-xs text-gray-500",children:"Qualidade dos dados enviados para otimização de campanhas"})]})]}),e.jsx(Pb,{}),e.jsx($b,{}),e.jsx(Tb,{}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(_l,{label:"Eventos Total",value:Ba(l.summary.totalEvents),icon:e.jsx(ft,{className:"w-4 h-4"}),color:"text-white"}),e.jsx(_l,{label:"Taxa de Sucesso",value:Eh(l.summary.successRate),icon:l.summary.successRate>=95?e.jsx(be,{className:"w-4 h-4"}):e.jsx(Ce,{className:"w-4 h-4"}),color:l.summary.successRate>=95?"text-emerald-400":"text-amber-400"}
2),e.jsx(_l,{label:"Últimas 24h",value:Ba(l.summary.last24h),icon:e.jsx(He,{className:"w-4 h-4"}),color:"text-teal-400"}),e.jsx(_l,{label:"Últimos 7 dias",value:Ba(l.summary.last7d),icon:e.jsx(Ie,{className:"w-4 h-4"}),color:"text-violet-400"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 text-blue-400"}),"Event Match Quality (Dados Enviados)"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(mi,{label:"Email (em)",value:l.matchQuality.withEmail,total:l.matchQuality.totalEvents}),e.jsx(mi,{label:"Telefone (ph)",value:l.matchQuality.withPhone,total:l.matchQuality.totalEvents}),e.jsx(mi,{label:"Nome (fn/ln)",value:l.matchQuality.withName,total:l.matchQuality.totalEvents}),e.jsx(mi,{label:"Cidade (ct)",value:l.matchQuality.withCity,total:l.matchQuality.totalEvents}),e.jsx(mi,{label:"FBP Cookie",value:l.matchQuality.withFbp,total:l.matchQuality.totalEvents}),e.jsx(mi,{label:"FBC Click",value:l.matchQuality.withFbc,total:l.matchQuality.totalEvents}),e.jsx(mi,{label:"IP Address",value:l.matchQuality.withIp,total:l.matchQuality.totalEvents}),e.jsx(mi,{label:"User Agent",value:l.matchQuality.withUserAgent,total:l.matchQuality.totalEvents})]})]}),e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white mb-4 flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-violet-400"}),"Eventos por Tipo"]}),e.jsxs("div",{className:"space-y-2",children:[p.map(g=>e.jsxs("div",{className:"flex items-center justify-between py-1.5 border-b border-white/5 last:border-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:`text-sm font-medium ${xh[g.eventName]||"text-gray-300"}`,children:g.eventName})}),e.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[e.jsx("span",{className:"text-gray-400",children:Ba(g.total)}),e.jsxs("span",{className:"text-emerald-400 flex items-center gap-1",children:[e.jsx(be,{className:"w-3 h-3"})," ",Ba(g.sent)]}),g.failed>0&&e.jsxs("span",{className:"text-red-400 flex items-center gap-1",children:[e.jsx(dt,{className:"w-3 h-3"})," ",g.failed]}),e.jsx("span",{className:"text-gray-600 w-12 text-right",children:$c(g.lastSeen)})]})]},g.eventName)),p.length===0&&e.jsx("p",{className:"text-xs text-gray-600 text-center py-4",children:"Nenhum evento registrado"})]})]})]}),l.emqTips.length>0&&e.jsxs("div",{className:"bg-amber-500/5 border border-amber-500/20 rounded-xl p-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-amber-400 mb-3 flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4"}),"Dicas para Melhorar o EMQ Score"]}),e.jsx("ul",{className:"space-y-1.5",children:l.emqTips.map((g,w)=>e.jsxs("li",{className:"text-xs text-amber-300/80 flex items-start gap-2",children:[e.jsx("span",{className:"text-amber-500 mt-0.5",children:"•"}),g]},w))})]}),e.jsx(Ab,{}),e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white mb-3 flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-teal-400"}),"Eventos Recentes"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-gray-500 border-b border-white/5",children:[e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Evento"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"FBP"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"FBC"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Usuário"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Quando"})]})}),e.jsxs("tbody",{children:[l.recentEvents.map(g=>e.jsxs("tr",{className:"border-b border-white/[0.03] hover:bg-white/[0.02]",children:[e.jsx("td",{className:`py-2 px-2 font-medium ${xh[g.eventName]||"text-gray-300"}`,children:g.eventName}),e.jsx("td",{className:"py-2 px-2",children:g.sentToMeta?e.jsxs("span",{className:"text-emerald-400 flex items-center gap-1",children:[e.jsx(be,{className:"w-3 h-3"})," OK"]}):e.jsxs("span",{className:"text-red-400 flex items-center gap-1",children:[e.jsx(dt,{className:"w-3 h-3"})," Falha"]})}),e.jsx("td",{className:"py-2 px-2",children:g.hasFbp?e.jsx("span",{className:"text-emerald-400",children:"✓"}):e.jsx("span",{className:"text-gray-600",children:"—"})}),e.jsx("td",{className:"py-2 px-2",children:g.hasFbc?e.jsx("span",{className:"text-emerald-400",children:"✓"}):e.jsx("span",{className:"text-gray-600",children:"—"})}),e.jsx("td",{className:"py-2 px-2 text-gray-400 truncate max-w-[100px]",children:g.userId?g.userId.substring(0,8)+"...":"—"}),e.jsx("td",{className:"py-2 px-2 text-right text-gray-500",children:$c(g.createdAt)})]},g.id)),l.recentEvents.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-center py-6 text-gray-600",children:"Nenhum evento recente"})})]})]})})]})]})}function $b(){const{data:a,isLoading:r,error:l,refetch:n,isFetching:u}=z({queryKey:["/api/admin/meta/pixel-health"],refetchInterval:6e4});if(r)return e.jsx("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-4","data-testid":"pixel-health-loading",children:e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-blue-400"})})});if(l||!a)return e.jsx("div",{className:"bg-red-500/5 border border-red-500/20 rounded-xl p-4","data-testid":"pixel-health-error",children:e.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[e.jsx(Xe,{className:"w-4 h-4"}),e.jsx("span",{children:"Não foi possível carregar Saúde do Pixel"})]})});const f=a.perPixelStats.reduce((p,g)=>p+g.events24h,0),j=a.perPixelStats.some(p=>p.events24h>0);return e.jsx("div",{className:"space-y-4","data-testid":"pixel-health-section",children:e.jsxs("div",{className:"bg-gradient-to-br from-blue-600/10 to-indigo-600/[0.02] border border-blue-500/20 rounded-xl p-4 md:p-5",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx("div",{className:"p-2 rounded-xl bg-blue-500/20 border border-blue-500/30 shrink-0",children:e.jsx(lt,{className:"w-5 h-5 text-blue-300"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-white","data-testid":"text-pixel-health-title",children:"Saúde do Pixel Meta"}),e.jsxs("button",{onClick:()=>n(),disabled:u,className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/5 hover:bg-white/10 border border-white/10 rounded-lg text-[11px] text-white/60 hover:text-white transition-colors min-h-9","data-testid":"button-refresh-pixel-health",children:[e.jsx(xe,{className:`w-3 h-3 ${u?"animate-spin":""}`}),"Atualizar"]})]}),e.jsx("p",{className:"text-xs text-white/50 mt-0.5",children:"Eventos enviados por pixel — confirme aqui que o pixel certo está recebendo as conversões."})]})]}),e.jsx("div",{className:"mb-4 rounded-xl bg-amber-500/10 border border-amber-500/30 p-3 md:p-4","data-testid":"pixel-health-banner",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx(Ce,{className:"w-4 h-4 text-amber-300 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-[12px] md:text-[13px] text-amber-100/90 leading-relaxed space-y-2",children:[e.jsx("p",{className:"font-medium text-amber-200",children:"Atenção: a Sábhia envia eventos para o pixel abaixo. Isso NÃO muda a configuração das suas campanhas no Meta Ads Manager."}),e.jsxs("p",{className:"text-amber-200/80",children:["Se algum conjunto de anúncios estiver otimizando por um pixel diferente do listado acima, ele"," ",e.jsx("span",{className:"underline",children:"não recebe sinal de conversão"}
2)," — performance cai mesmo o site funcionando bem."]}),e.jsxs("p",{className:"text-amber-200/80",children:["Verifique cada conjunto em ",e.jsx("strong",{children:"Meta Ads Manager → Editar → Conversão → Conjunto de dados"})," e troque para o pixel atual:",a.uniquePixelIds.map(p=>e.jsx("code",{className:"ml-1 px-1.5 py-0.5 rounded bg-amber-950/50 text-amber-100 text-[11px]",children:p},p))]})]})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 md:gap-3 mb-4",children:[e.jsxs("div",{className:"bg-white/[0.03] border border-white/5 rounded-lg p-3","data-testid":"card-pixel-summary-pixels",children:[e.jsx("div",{className:"text-[10px] text-white/40 uppercase tracking-wider mb-1",children:"Pixels Ativos"}),e.jsx("div",{className:"text-xl font-bold text-white",children:a.uniquePixelIds.length})]}),e.jsxs("div",{className:"bg-white/[0.03] border border-white/5 rounded-lg p-3","data-testid":"card-pixel-summary-events",children:[e.jsx("div",{className:"text-[10px] text-white/40 uppercase tracking-wider mb-1",children:"Eventos 24h"}),e.jsx("div",{className:`text-xl font-bold ${j?"text-emerald-300":"text-amber-300"}`,children:Ba(f)})]}),e.jsxs("div",{className:"bg-white/[0.03] border border-white/5 rounded-lg p-3","data-testid":"card-pixel-summary-accounts",children:[e.jsx("div",{className:"text-[10px] text-white/40 uppercase tracking-wider mb-1",children:"Contas Meta"}),e.jsx("div",{className:"text-xl font-bold text-white",children:a.accounts.length})]})]}),a.warnings.length>0&&e.jsx("div",{className:"mb-4 space-y-2",children:a.warnings.map((p,g)=>{const w=p.level==="error"?"bg-red-500/10 border-red-500/30 text-red-200":p.level==="warn"?"bg-amber-500/10 border-amber-500/30 text-amber-200":"bg-blue-500/10 border-blue-500/30 text-blue-200",y=p.level==="error"?dt:p.level==="warn"?Ce:Xe;return e.jsxs("div",{className:`flex items-start gap-2 rounded-lg border ${w} p-2.5 text-[12px]`,"data-testid":`pixel-health-warning-${g}`,children:[e.jsx(y,{className:"w-3.5 h-3.5 shrink-0 mt-0.5"}),e.jsx("span",{children:p.message})]},g)})}),e.jsxs("div",{className:"space-y-3",children:[a.accountsByPixel.map(p=>{const g=a.perPixelStats.find($=>$.pixelId===p.pixelId),w=g?.lastSuccessAt?new Date(g.lastSuccessAt):null,y=w?Math.floor((Date.now()-w.getTime())/6e4):null,F=!!g&&g.events24h>0&&(g.failed24h===0||g.success24h/Math.max(g.events24h,1)>=.9),c=F?"border-emerald-500/30 bg-emerald-500/5":g&&g.events24h>0?"border-amber-500/30 bg-amber-500/5":"border-white/10 bg-white/[0.02]",m=F?"bg-emerald-400":g&&g.events24h>0?"bg-amber-400":"bg-white/30";return e.jsxs("div",{className:`rounded-xl border ${c} p-3 md:p-4`,"data-testid":`pixel-card-${p.pixelId}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${m}`}),e.jsx("code",{className:"text-sm font-mono font-bold text-white","data-testid":`pixel-id-${p.pixelId}`,children:p.pixelId})]}),e.jsxs("div",{className:"text-[11px] text-white/50 mt-1",children:["Usado por ",p.accounts.length," ",p.accounts.length===1?"conta Meta":"contas Meta",":"," ",p.accounts.map(($,D)=>e.jsxs("span",{children:[D>0&&e.jsx("span",{className:"text-white/30",children:", "}),e.jsx("span",{className:"text-white/70",children:$.name}),$.isDefault&&e.jsx("span",{className:"ml-1 text-[9px] px-1 py-0.5 rounded bg-blue-500/20 text-blue-200 align-middle",children:"padrão"})]},$.configId))]})]}),e.jsxs("a",{href:`https://business.facebook.com/events_manager2/list/pixel/${p.pixelId}/overview`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-3 py-1.5 bg-blue-500/20 hover:bg-blue-500/30 border border-blue-500/30 rounded-lg text-[11px] text-blue-200 transition-colors min-h-9","data-testid":`link-events-manager-${p.pixelId}`,children:[e.jsx(Ka,{className:"w-3 h-3"}),"Abrir no Events Manager"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 mt-3",children:[e.jsxs("div",{className:"bg-black/30 rounded-lg px-2.5 py-2 border border-white/5",children:[e.jsx("div",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"1h"}),e.jsx("div",{className:"text-sm font-semibold text-white",children:g?Ba(g.events1h):"—"})]}),e.jsxs("div",{className:"bg-black/30 rounded-lg px-2.5 py-2 border border-white/5",children:[e.jsx("div",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"24h"}),e.jsx("div",{className:"text-sm font-semibold text-white",children:g?Ba(g.events24h):"—"}),g&&g.failed24h>0&&e.jsxs("div",{className:"text-[9px] text-red-400 mt-0.5",children:[g.failed24h," falha",g.failed24h>1?"s":""]})]}),e.jsxs("div",{className:"bg-black/30 rounded-lg px-2.5 py-2 border border-white/5",children:[e.jsx("div",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"7d"}),e.jsx("div",{className:"text-sm font-semibold text-white",children:g?Ba(g.events7d):"—"})]}),e.jsxs("div",{className:"bg-black/30 rounded-lg px-2.5 py-2 border border-white/5",children:[e.jsx("div",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Último OK"}),e.jsx("div",{className:"text-sm font-semibold text-white",children:y===null?"—":y<60?`${y}min`:y<1440?`${Math.floor(y/60)}h`:`${Math.floor(y/1440)}d`})]})]}),g?.lastError&&e.jsxs("div",{className:"mt-2 text-[11px] text-red-300/80 bg-red-500/10 border border-red-500/20 rounded-lg px-2.5 py-1.5 break-all","data-testid":`pixel-last-error-${p.pixelId}`,children:["Último erro: ",g.lastError]}),e.jsx("div",{className:"mt-3 pt-3 border-t border-white/5 space-y-1",children:p.accounts.map($=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px]","data-testid":`account-row-${$.configId}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[$.connectionStatus==="connected"?e.jsx(be,{className:"w-3 h-3 text-emerald-400 shrink-0"}):e.jsx(Xe,{className:"w-3 h-3 text-amber-400 shrink-0"}),e.jsx("span",{className:"text-white/60 truncate",children:$.name})]}),e.jsx("code",{className:"text-white/40 truncate",children:$.adAccountId||"(sem ad account)"})]},$.configId))})]},p.pixelId)}),a.accountsByPixel.length===0&&e.jsx("div",{className:"text-center py-6 text-white/40 text-sm",children:"Nenhum pixel configurado — vá em Configurações Meta para adicionar."})]})]})})}function Ab(){const{data:a,isLoading:r}=z({queryKey:["/api/admin/ads/emq"],refetchInterval:12e4});if(r)return e.jsx("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-4",children:e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-teal-400"})})});if(!a?.available)return e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white mb-2 flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4 text-violet-400"}),"Event Match Quality (EMQ)"]}),e.jsx("p",{className:"text-xs text-white/40",children:a?.message||"Configure o Pixel para ver o EMQ Score"})]});const l=a.emqScore||0,n=l>7?"text-emerald-400":l>=5?"text-amber-400":"text-red-400",u=l>7?"from-emerald-500/10 to-emerald-500/[0.02]":l>=5?"from-amber-500/10 to-amber-500/[0.02]":"from-red-500/10 to-red-500/[0.02]",f=l>7?"border-emerald-500/20":l>=5?"border-amber-500/20":"border-red-500/20";return e.jsxs("div",{className:`bg-gradient-to-r ${u} border ${f} rounded-xl p-4`,"data-testid":"emq-score-section",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4 text-violet-400"}),"Event Match Quality (EMQ) — Meta Pixel"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"text-[10px] text-white/40",children:["Pixel ",a.pixelId]})})]}),e.jsxs("div",{className:"flex items-center gap-6 mb-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"relative w-20 h-20",children:[e.jsxs("svg",{viewBox:"0 0 100 100",className:"w-full h-full -rotate-90",children:[e.jsx("circle",{cx:"50",cy:"50",r:"40",fill:"none",stroke:"rgba(255,255,255,0.05)",strokeWidth:"8"}),e.jsx("circle",{cx:"50",cy:"50",r:"40",fill:"none",stroke:l>7?"rgb(52, 211, 153)":l>=5?"rgb(251, 191, 36)":"rgb(248, 113, 113)",strokeWidth:"8",strokeLinecap:"round",strokeDasharray:`${l/10*251.2} 251.2`})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:`text-xl font-bold ${n}`,children:l})})]}),e.jsx("p",{className:"text-[10px] text-white/40 mt-1",children:"de 10"})]}),e.jsx("div",{className:"flex-1 space-y-1.5",children:a.emqFactors?.map((j,p)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[j.status==="active"?e.jsx(be,{className:"w-3 h-3 text-emerald-400 shrink-0"}):e.jsx(dt,{className:"w-3 h-3 text-red-400 shrink-0"}),e.jsx("span",{className:`${j.status==="active"?"text-white/70":"text-white/30"}`,children:j.factor}),e.jsxs("span",{className:"text-white/20 ml-auto text-[10px]",children:["+",j.score.toFixed(1)]})]},p))})]}),a.recommendations?.length>0&&e.jsx("div",{className:"space-y-1.5 pt-3 border-t border-white/5",children:a.recommendations.map((j,p)=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsx(lt,{className:"w-3 h-3 text-violet-400 shrink-0 mt-0.5"}),e.jsx("span",{className:"text-white/50",children:j})]},p))})]})}function _l({label:a,value:r,icon:l,color:n}){return e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-500 mb-1",children:[l,e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wider",children:a})]}),e.jsx("p",{className:`text-xl font-bold ${n}`,children:r})]})}function Pb(){const{data:a,isLoading:r,error:l,refetch:n,isFetching:u}=z({queryKey:["/api/admin/login-health"],refetchInterval:6e4});if(r)return e.jsx("div",{className:"bg-[#101012] border border-white/10 rounded-2xl p-6 flex items-center justify-center","data-testid":"login-health-loading",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-teal-400"})});if(l||!a)return e.jsx("div",{className:"bg-[#101012] border border-red-500/20 rounded-2xl p-6","data-testid":"login-health-error",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xe,{className:"w-5 h-5 text-red-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-white/80",children:"Não foi possível carregar a saúde do login"}),e.jsx("p",{className:"text-xs text-white/40",children:"Verifique se o endpoint /api/admin/login-health está disponível"})]}),e.jsxs("button",{onClick:()=>n(),disabled:u,className:"text-xs px-3 py-1.5 rounded-lg bg-teal-600/20 hover:bg-teal-600/30 border border-teal-500/30 text-teal-300 transition-colors","data-testid":"button-retry-login-health",children:[e.jsx(xe,{className:`w-3 h-3 inline mr-1 ${u?"animate-spin":""}`}),"Tentar novamente"]})]})});const{summary:f,recent:j}=a,p=f.verificationRate,g=p>=70?"text-emerald-400":p>=40?"text-amber-400":"text-red-400",w=p>=70?"from-emerald-600/20 to-teal-600/20 border-emerald-500/30":p>=40?"from-amber-600/20 to-orange-600/20 border-amber-500/30":"from-red-600/20 to-rose-600/20 border-red-500/30",y=c=>c==="verified"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/15 text-emerald-300 border border-emerald-500/30",children:[e.jsx(be,{className:"w-2.5 h-2.5"}),"Verificado"]}
2):c==="expired"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-white/5 text-white/40 border border-white/10",children:[e.jsx(ns,{className:"w-2.5 h-2.5"}),"Expirado"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-violet-500/15 text-violet-300 border border-violet-500/30",children:[e.jsx(jt,{className:"w-2.5 h-2.5"}),"Aguardando"]}),F=c=>{const m=c.usedAt||c.expiresAt;return $c(m)};return e.jsxs("div",{className:"bg-[#101012] border border-white/10 rounded-2xl overflow-hidden","data-testid":"login-health-section",children:[e.jsxs("div",{className:"p-5 border-b border-white/5 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-xl bg-gradient-to-br from-teal-600/20 to-violet-600/20 border border-teal-500/20",children:e.jsx(xu,{className:"w-5 h-5 text-teal-400"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-sm font-bold text-white","data-testid":"text-login-health-title",children:"Saúde do Login (OTP)"}),e.jsx("p",{className:"text-xs text-white/40",children:"Códigos enviados, verificação e taxa de sucesso (últimas 24h)"})]}),e.jsx("button",{onClick:()=>n(),disabled:u,className:"p-2 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 transition-colors","data-testid":"button-refresh-login-health",title:"Atualizar",children:e.jsx(xe,{className:`w-3.5 h-3.5 text-white/60 ${u?"animate-spin":""}`})})]}),e.jsxs("div",{className:"p-5 space-y-5",children:[e.jsx("div",{className:`rounded-xl p-4 bg-gradient-to-br ${w} border`,children:e.jsxs("div",{className:"flex items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-white/50 font-semibold",children:"Taxa de verificação 24h"}),e.jsxs("p",{className:`text-3xl font-bold mt-1 ${g}`,"data-testid":"text-login-rate",children:[f.verificationRate.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-white/50 mt-1",children:[f.verified24h.toLocaleString("pt-BR")," de ",f.sent24h.toLocaleString("pt-BR")," códigos confirmados"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40",children:"Tempo médio"}),e.jsxs("p",{className:"text-sm font-mono text-white/80","data-testid":"text-login-avg-time",children:[f.avgSecondsToVerify,"s"]})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Ol,{label:"Enviados (24h)",value:f.sent24h.toLocaleString("pt-BR"),icon:e.jsx(Ge,{className:"w-3.5 h-3.5"}),color:"text-teal-400",testId:"stat-otp-sent"}),e.jsx(Ol,{label:"Verificados (24h)",value:f.verified24h.toLocaleString("pt-BR"),icon:e.jsx(be,{className:"w-3.5 h-3.5"}),color:"text-emerald-400",testId:"stat-otp-verified"}),e.jsx(Ol,{label:"Ativos agora",value:f.activeNow.toLocaleString("pt-BR"),icon:e.jsx(jt,{className:"w-3.5 h-3.5"}),color:"text-violet-400",testId:"stat-otp-active"}),e.jsx(Ol,{label:"Expirados sem uso",value:f.expiredUnused24h.toLocaleString("pt-BR"),icon:e.jsx(ns,{className:"w-3.5 h-3.5"}),color:"text-amber-400",testId:"stat-otp-expired"})]}),j.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40 font-semibold mb-2",children:"Últimos códigos"}),e.jsx("div",{className:"space-y-1.5",children:j.map(c=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-lg bg-white/[0.02] border border-white/5","data-testid":`row-otp-${c.id}`,children:[e.jsx("span",{className:"text-xs font-mono text-white/70 flex-1 truncate",children:c.emailMasked}),y(c.status),e.jsx("span",{className:"text-[10px] text-white/40 w-12 text-right",children:F(c)})]},c.id))})]})]})]})}function Ol({label:a,value:r,icon:l,color:n,testId:u}){return e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-3","data-testid":u,children:[e.jsxs("div",{className:`flex items-center gap-1.5 ${n} mb-1`,children:[l,e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-semibold",children:a})]}),e.jsx("p",{className:"text-lg font-bold text-white",children:r})]})}function Tb(){const{data:a,isLoading:r,refetch:l,isFetching:n}=z({queryKey:["/api/admin/meta-tracking-health"],refetchInterval:6e4});if(r)return e.jsx("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-6 flex items-center justify-center",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-teal-400"})});if(!a||!a.accounts?.length)return e.jsx("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-4",children:e.jsx("p",{className:"text-xs text-white/40",children:"Nenhuma conta Meta configurada."})});const u=a.totalAccounts>0?a.healthyAccounts/a.totalAccounts*100:0,f=u===100?"from-emerald-600/20 to-teal-600/20 border-emerald-500/20":u>=50?"from-amber-600/20 to-orange-600/20 border-amber-500/20":"from-red-600/20 to-rose-600/20 border-red-500/20",j=a.accounts.filter(c=>c.isActive!==!1),p=j.filter(c=>c.tokenStatus==="expired"),g=j.filter(c=>c.tokenStatus==="invalid"),w=j.filter(c=>c.accountStatus&&c.accountStatus!==1),y=j.filter(c=>c.health==="critical"),F=p.length>0||g.length>0||w.length>0||y.length>0;return e.jsxs("div",{className:`bg-gradient-to-r ${f} border rounded-xl p-4`,"data-testid":"multi-account-health",children:[F&&e.jsxs("div",{className:"mb-3 p-3 rounded-lg bg-red-500/10 border border-red-500/30 flex items-start gap-2.5","data-testid":"banner-tracking-critical",children:[e.jsx(Ce,{className:"w-4 h-4 text-red-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold text-red-300 mb-1",children:"Atenção: tracking Meta com falhas"}),e.jsxs("ul",{className:"text-[11px] text-white/70 space-y-0.5 list-disc list-inside",children:[p.length>0&&e.jsxs("li",{children:[e.jsx("span",{className:"font-medium text-amber-200",children:p.length})," conta(s) com token Meta ",e.jsx("span",{className:"text-amber-200",children:"expirado"}),":"," ",e.jsx("span",{className:"font-medium text-white/90",children:p.map(c=>c.name).join(", ")}),'. Renove o token na aba "Meta Config".']}),g.length>0&&e.jsxs("li",{children:[e.jsx("span",{className:"font-medium text-red-200",children:g.length})," conta(s) com token Meta ",e.jsx("span",{className:"text-red-200",children:"inválido/revogado"}),":"," ",e.jsx("span",{className:"font-medium text-white/90",children:g.map(c=>c.name).join(", ")}),'. Reconecte o token na aba "Meta Config".']}),w.length>0&&e.jsxs("li",{children:[e.jsx("span",{className:"font-medium text-red-200",children:w.length})," conta(s) Meta Ads bloqueada(s) ou restrita(s):"," ",e.jsx("span",{className:"font-medium text-white/90",children:w.map(c=>`${c.name} (status ${c.accountStatus})`).join(", ")}),"."]}),y.length>0&&p.length===0&&g.length===0&&w.length===0&&e.jsxs("li",{children:[e.jsx("span",{className:"font-medium text-red-200",children:y.length})," conta(s) em estado crítico — verifique Pixel/Token/AdAccount."]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mu,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Saúde Multi-Conta Meta"}),e.jsxs("span",{className:"text-[10px] text-white/40 ml-2",children:[a.healthyAccounts,"/",a.totalAccounts," contas saudáveis"]})]}),e.jsxs("button",{onClick:()=>l(),disabled:n,className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-white/5 hover:bg-white/10 border border-white/10 text-[10px] text-white/70 transition-colors","data-testid":"button-refresh-multi-account",children:[e.jsx(xe,{className:`w-3 h-3 ${n?"animate-spin":""}`}),"Atualizar"]})]}),a.sharedPixels.length>0&&e.jsxs("div",{className:"mb-3 p-2.5 rounded-lg bg-violet-500/10 border border-violet-500/20 flex items-start gap-2",children:[e.jsx(Ka,{className:"w-3.5 h-3.5 text-violet-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-[11px] text-white/70",children:[e.jsx("span",{className:"font-medium text-violet-300",children:"Pixel compartilhado detectado:"})," ",a.sharedPixels.map(c=>`${c.pixelId} (${c.count} contas)`).join(", "),". CAPI envia 1 evento por Pixel para evitar duplicação."]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:a.accounts.map(c=>{const m=c.health==="healthy"?{color:"text-emerald-400",bg:"bg-emerald-500/10 border-emerald-500/30",icon:e.jsx(be,{className:"w-3 h-3"}),label:"Saudável"}:c.health==="warning"?{color:"text-amber-400",bg:"bg-amber-500/10 border-amber-500/30",icon:e.jsx(Ce,{className:"w-3 h-3"}),label:"Atenção"}:{color:"text-red-400",bg:"bg-red-500/10 border-red-500/30",icon:e.jsx(dt,{className:"w-3 h-3"}),label:"Crítico"},$=c.tokenStatus==="valid"?{color:"text-emerald-400",label:"OK"}:c.tokenStatus==="expired"?{color:"text-amber-400",label:"Expirado"}:c.tokenStatus==="invalid"?{color:"text-red-400",label:"Inválido"}:{color:"text-white/30",label:"—"},D=!c.accountStatus||c.accountStatus===1;return e.jsxs("div",{className:"bg-[#101012]/60 border border-white/10 rounded-lg p-3 space-y-2","data-testid":`card-account-health-${c.id}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm font-semibold text-white truncate","data-testid":`text-account-name-${c.id}`,children:c.name}),c.isDefault&&e.jsx(wn,{className:"w-3 h-3 text-amber-400 shrink-0"}),!c.isActive&&e.jsx("span",{className:"text-[9px] text-white/30 uppercase",children:"inativa"})]}),e.jsxs("div",{className:"text-[10px] text-white/40 mt-0.5",children:["Pixel: ",e.jsx("span",{className:"font-mono",children:c.pixelId||"—"}),c.adAccountId&&e.jsxs(e.Fragment,{children:[" · Ad: ",e.jsxs("span",{className:"font-mono",children:["act_",c.adAccountId]})]})]})]}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md border ${m.bg} ${m.color} text-[10px] font-medium shrink-0`,children:[m.icon,m.label]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 text-[10px]",children:[e.jsxs("div",{className:"flex items-center gap-1 text-white/60",children:[e.jsx(hu,{className:`w-3 h-3 ${$.color}`}),e.jsxs("span",{className:$.color,children:["Token ",$.label]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-white/60",children:[D?e.jsx(be,{className:"w-3 h-3 text-emerald-400"}):e.jsx(Ce,{className:"w-3 h-3 text-red-400"}),e.jsxs("span",{className:D?"text-emerald-400":"text-red-400",children:["Conta ",D?"Ativa":`Bloq (${c.accountStatus})`]})]}),e.jsxs("div",{className:"text-white/60",children:[e.jsx("span",{className:"text-white/30",children:"24h:"})," ",c.orders24h," pedidos"]}),e.jsxs("div",{className:"text-white/60",children:[e.jsx("span",{className:"text-white/30",children:"7d:"})," ",c.orders7d," pedidos"]}),c.coverage24h!==null&&e.jsxs("div",{className:"col-span-2 text-white/60",children:[e.jsx("span",{className:"text-white/30",children:"CAPI 24h:"})," ",e.jsxs("span",{className:c.coverage24h>=90?"text-emerald-400":c.coverage24h>=50?"text-amber-400":"text-red-400",children:[c.coverage24h.toFixed(0),"% cobertura"]}),e.jsxs("span",{className:"text-white/30",children:[" (",c.purchaseSent24h,"/",c.orders24h,")"]})]}),e.jsxs("div",{className:"col-span-2 text-white/40 text-[9px]",children:["Touchpoints atribuídos 24h: ",c.touchpoints24h]})]}),c.tokenError&&e.jsx("div",{className:"text-[10px] text-red-400/80 bg-red-500/5 border border-red-500/20 rounded px-2 py-1",children:c.tokenError}),c.accountStatusReason&&e.jsx("div",{className:"text-[10px] text-amber-400/80 bg-amber-500/5 border border-amber-500/20 rounded px-2 py-1",children:c.accountStatusReason})]},c.id)})})]})}function Bl(a,r="BRL"){return new Intl.NumberFormat("pt-BR",{style:"currency",currency:r}).format(a/100)}function Eb({status:a}){const r={paid:"bg-emerald-900/50 text-emerald-400 border-emerald-700",delivered:"bg-blue-900/50 text-blue-400 border-blue-700",pending:"bg-yellow-900/50 text-yellow-400 border-yellow-700",expired:"bg-gray-800 text-gray-400 border-gray-700"};return e.jsx(E,{className:`text-[10px] ${r[a]||r.pending}`,children:a})}function Ib(){const[a,r]=d.useState(!1),{data:l,isLoading:n}=z({queryKey:["/api/admin/ebook-funnel/metrics"],refetchInterval:3e4}),{data:u,isLoading:f}=z({queryKey:["/api/admin/ebook-funnel/orders"],enabled:a,refetchInterval:3e4}),{data:j}=z({queryKey:["/api/admin/ebook-funnel/funnel"],refetchInterval:6e4});if(n)return e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(T,{className:"w-8 h-8 animate-spin text-emerald-400"})});const p=l,g=p?Object.entries(p.revenueByDay).sort(([w],[y])=>w.localeCompare(y)).slice(-30).map(([w,y])=>({day:w.slice(5),revenue:y/100})):[];return e.jsxs("div",{className:"space-y-6","data-testid":"ebook-funnel-tab",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(je,{className:"bg-gray-900 border-gray-800",children:e.jsxs(ve,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-gray-400 text-xs mb-1",children:[e.jsx(nt,{className:"w-3.5 h-3.5"})," Receita Total"]}),e.jsx("div",{className:"text-xl font-bold text-white","data-testid":"text-ebook-total-revenue",children:p?Bl(p.total.revenue):"—"}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1",children:["Hoje: ",p?Bl(p.today.revenue):"—"]})]})}),e.jsx(je,{className:"bg-gray-900 border-gray-800",children:e.jsxs(ve,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-gray-400 text-xs mb-1",children:[e.jsx(Jt,{className:"w-3.5 h-3.5"})," Vendas"]}),e.jsx("div",{className:"text-xl font-bold text-white","data-testid":"text-ebook-total-sales",children:p?.total.paid??0}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1",children:["Hoje: ",p?.today.paid??0," | Semana: ",p?.week.paid??0]})]})}),e.jsx(je,{className:"bg-gray-900 border-gray-800",children:e.jsxs(ve,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-gray-400 text-xs mb-1",children:[e.jsx(Ie,{className:"w-3.5 h-3.5"})," Conversão"]}),e.jsx("div",{className:"text-xl font-bold text-white","data-testid":"text-ebook-conversion",children:p?p.total.conversionRate.toFixed(1)+"%":"—"}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1",children:[p?.total.sessions??0," sessões → ",p?.total.paid??0," pagos"]})]})}),e.jsx(je,{className:"bg-gray-900 border-gray-800",children:e.jsxs(ve,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-gray-400 text-xs mb-1",children:[e.jsx(Re,{className:"w-3.5 h-3.5"})," Ticket Médio"]}),e.jsx("div",{className:"text-xl font-bold text-white","data-testid":"text-ebook-avg-ticket",children:p?Bl(p.total.avgTicket):"—"}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1",children:["Pending: ",p?.total.pending??0]})]})})]}),g.length>0&&e.jsxs(je,{className:"bg-gray-900 border-gray-800",children:[e.jsx(Fe,{className:"pb-2",children:e.jsx(De,{className:"text-sm text-gray-300",children:"Receita por Dia (últimos 30 dias)"})}),e.jsx(ve,{children:e.jsx("div",{className:"h-48",children:e.jsx(Cn,{width:"100%",height:"100%",children:e.jsxs($h,{data:g,children:[e.jsx(Sn,{strokeDasharray:"3 3",stroke:"#333"}),e.jsx($n,{dataKey:"day",tick:{fill:"#888",fontSize:10}}
2),e.jsx(Wi,{tick:{fill:"#888",fontSize:10}}),e.jsx(An,{contentStyle:{background:"#1a1a2e",border:"1px solid #333",borderRadius:8,color:"#fff"},formatter:w=>[`R$ ${w.toFixed(2)}`,"Receita"]}),e.jsx(Nc,{type:"monotone",dataKey:"revenue",stroke:"#10b981",fill:"#10b98133",strokeWidth:2})]})})})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(je,{className:"bg-gray-900 border-gray-800",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm text-gray-300 flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 text-yellow-400"})," Bump Take Rate"]})}),e.jsx(ve,{children:p&&Object.keys(p.bumps).length>0?e.jsx("div",{className:"space-y-3",children:Object.entries(p.bumps).map(([w,y])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-gray-300",children:w==="cover_premium"?"Capa Premium":w==="publication_kit"?"Kit Publicação":w}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-white font-medium",children:y}),e.jsx(E,{className:"bg-emerald-900/50 text-emerald-400 border-emerald-700 text-[10px]",children:p.bumpTakeRate[w]})]})]},w))}):e.jsx("p",{className:"text-gray-500 text-sm",children:"Nenhum bump vendido ainda"})})]}),j&&j.funnel.length>0&&e.jsxs(je,{className:"bg-gray-900 border-gray-800",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs(De,{className:"text-sm text-gray-300 flex items-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4 text-blue-400"})," Funil de Conversão"]})}),e.jsx(ve,{children:e.jsx("div",{className:"space-y-2",children:j.funnel.map((w,y)=>{const F=Math.max(...j.funnel.map(m=>m.count),1),c=w.count/F*100;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-gray-500 w-28 text-right truncate",children:w.step}),e.jsxs("div",{className:"flex-1 h-5 bg-gray-800 rounded overflow-hidden relative",children:[e.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-600 to-emerald-400 rounded transition-all",style:{width:`${Math.max(c,2)}%`}}),e.jsx("span",{className:"absolute inset-0 flex items-center justify-center text-[10px] text-white font-medium",children:w.count})]}),y<j.funnel.length-1&&e.jsx(vh,{className:"w-3 h-3 text-gray-600 shrink-0"})]},w.step)})})})]}),e.jsxs(je,{className:"bg-gray-900 border-gray-800",children:[e.jsx(Fe,{className:"pb-2",children:e.jsx(De,{className:"text-sm text-gray-300",children:"Países"})}),e.jsx(ve,{children:p&&Object.keys(p.countries).length>0?e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(p.countries).sort(([,w],[,y])=>y-w).map(([w,y])=>e.jsxs(E,{className:"bg-gray-800 text-gray-300 border-gray-700 text-xs",children:[w,": ",y]},w))}):e.jsx("p",{className:"text-gray-500 text-sm",children:"Sem dados de país"})})]})]}),e.jsxs(je,{className:"bg-gray-900 border-gray-800",children:[e.jsx(Fe,{className:"pb-2",children:e.jsxs("button",{onClick:()=>r(!a),className:"flex items-center gap-2 w-full text-left","data-testid":"button-toggle-ebook-orders",children:[e.jsxs(De,{className:"text-sm text-gray-300 flex items-center gap-2",children:[e.jsx(Jt,{className:"w-4 h-4"})," Pedidos Recentes"]}),a?e.jsx(ta,{className:"w-4 h-4 text-gray-400 ml-auto"}):e.jsx(Ct,{className:"w-4 h-4 text-gray-400 ml-auto"})]})}),a&&e.jsx(ve,{children:f?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-gray-400"})}):u?.orders.length?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-gray-500 border-b border-gray-800",children:[e.jsx("th",{className:"text-left py-2 px-2",children:"Email"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Livro"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Status"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Valor"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Bumps"}),e.jsx("th",{className:"text-left py-2 px-2",children:"País"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Data"})]})}),e.jsx("tbody",{children:u.orders.map(w=>e.jsxs("tr",{className:"border-b border-gray-800/50 hover:bg-gray-800/30",children:[e.jsx("td",{className:"py-2 px-2 text-gray-300 max-w-[150px] truncate",children:w.email}),e.jsx("td",{className:"py-2 px-2 text-gray-300 max-w-[180px] truncate",children:w.bookTitle}),e.jsx("td",{className:"py-2 px-2",children:e.jsx(Eb,{status:w.status})}),e.jsx("td",{className:"py-2 px-2 text-right text-white font-medium",children:Bl(w.totalAmount,w.currency)}),e.jsx("td",{className:"py-2 px-2",children:w.selectedBumps?.length?e.jsx("div",{className:"flex gap-1",children:w.selectedBumps.map(y=>e.jsx(E,{className:"bg-purple-900/50 text-purple-300 border-purple-700 text-[9px]",children:y==="cover_premium"?"Capa":y==="publication_kit"?"Kit":y},y))}):e.jsx("span",{className:"text-gray-600",children:"—"})}
2),e.jsx("td",{className:"py-2 px-2 text-gray-400",children:w.country}),e.jsx("td",{className:"py-2 px-2 text-gray-500",children:new Date(w.createdAt).toLocaleDateString("pt-BR")})]},w.id))})]})}):e.jsx("p",{className:"text-gray-500 text-sm text-center py-4",children:"Nenhum pedido do funil de e-book ainda"})})]})]})}const Rb=[{value:1,label:"24h"},{value:7,label:"7 dias"},{value:14,label:"14 dias"},{value:30,label:"30 dias"}],Fb=[5,10,20,30,50];function Db(a){try{return new Date(a+"T00:00:00").toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}catch{return a}}function Mb({onUserClick:a}){const[r,l]=d.useState(7),[n,u]=d.useState(10),[f,j]=d.useState(3),{data:p,isLoading:g,refetch:w,isFetching:y}=z({queryKey:["/api/admin/illustrations/quality",r,n,f],queryFn:async()=>{const c=new URLSearchParams({days:String(r),minRate:String(n),minTotal:String(f)}),m=await fetch(`/api/admin/illustrations/quality?${c}`,{credentials:"include"});if(!m.ok)throw new Error("Erro ao carregar qualidade");return m.json()},refetchInterval:6e4}),F=d.useMemo(()=>p?.daily?.length?Math.max(...p.daily.map(c=>c.total)):0,[p]);return e.jsxs("div",{className:"space-y-6","data-testid":"quality-dashboard",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5 text-amber-400"})," Qualidade da Geração"]}),e.jsx("p",{className:"text-xs text-zinc-400 mt-1",children:"Livros com alta taxa de placeholders ou bloqueios de segurança nas ilustrações."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"flex items-center gap-1 bg-white/5 border border-white/10 rounded-lg p-1",children:Rb.map(c=>e.jsx("button",{onClick:()=>l(c.value),className:_a("text-xs px-2.5 py-1 rounded-md transition-colors",r===c.value?"bg-white/15 text-white":"text-zinc-400 hover:text-white"),"data-testid":`button-quality-days-${c.value}`,children:c.label},c.value))}),e.jsxs("div",{className:"flex items-center gap-1 bg-white/5 border border-white/10 rounded-lg p-1",children:[e.jsx("span",{className:"text-[10px] text-zinc-500 px-2",children:"Min %"}),Fb.map(c=>e.jsxs("button",{onClick:()=>u(c),className:_a("text-xs px-2 py-1 rounded-md transition-colors",n===c?"bg-white/15 text-white":"text-zinc-400 hover:text-white"),"data-testid":`button-quality-rate-${c}`,children:[c,"%"]},c))]}),e.jsxs("div",{className:"flex items-center gap-1 bg-white/5 border border-white/10 rounded-lg px-2 py-1",children:[e.jsx("span",{className:"text-[10px] text-zinc-500",children:"Min total"}),e.jsx("input",{type:"number",min:1,max:500,value:f,onChange:c=>j(Math.max(1,Number(c.target.value)||1)),className:"w-12 bg-transparent text-xs text-white text-center outline-none","data-testid":"input-quality-min-total"})]}),e.jsxs("button",{onClick:()=>w(),disabled:y,className:"flex items-center gap-1 text-xs px-2.5 py-1.5 rounded-lg bg-white/5 border border-white/10 text-zinc-300 hover:bg-white/10 disabled:opacity-50","data-testid":"button-quality-refresh",children:[e.jsx(xe,{className:_a("h-3.5 w-3.5",y&&"animate-spin")})," Atualizar"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(gn,{label:"Livros sinalizados",value:p?.totals.flaggedBooks??0,testId:"text-quality-flagged"}),e.jsx(gn,{label:"Total ilustrações",value:p?.totals.total??0,testId:"text-quality-total"}),e.jsx(gn,{label:"Bloqueadas (safety)",value:p?.totals.safety??0,tone:"amber",testId:"text-quality-safety"}),e.jsx(gn,{label:"Falhas",value:p?.totals.failed??0,tone:"red",testId:"text-quality-failed"}),e.jsx(gn,{label:"Com reembolso",value:p?.totals.refunded??0,tone:"red",testId:"text-quality-refunded"})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.02] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Tendência diária"}),e.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-zinc-500",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-emerald-500/60"})," Concluídas"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-amber-500/70"})," Bloqueadas"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-red-500/70"})," Falhas"]})]})]}),p?.daily?.length?e.jsx("div",{className:"space-y-2","data-testid":"quality-daily-chart",children:p.daily.map(c=>{const m=F>0?c.total/F*100:0,$=c.total>0?c.completed/c.total*100:0,D=c.total>0?c.safety/c.total*100:0,A=c.total>0?c.failed/c.total*100:0;return e.jsxs("div",{className:"flex items-center gap-3 text-xs","data-testid":`quality-daily-${c.date}`,children:[e.jsx("div",{className:"w-12 text-zinc-400 shrink-0",children:Db(c.date)}),e.jsx("div",{className:"flex-1 h-5 rounded bg-white/5 overflow-hidden relative",children:e.jsxs("div",{className:"h-full flex",style:{width:`${m}%`,minWidth:c.total>0?"2px":0},children:[e.jsx("div",{className:"bg-emerald-500/60 h-full",style:{width:`${$}%`}}),e.jsx("div",{className:"bg-amber-500/70 h-full",style:{width:`${D}%`}}),e.jsx("div",{className:"bg-red-500/70 h-full",style:{width:`${A}%`}})]})}),e.jsx("div",{className:"w-16 text-right text-zinc-300 tabular-nums",children:c.total}),e.jsxs("div",{className:_a("w-14 text-right tabular-nums",c.safetyRate>=n?"text-amber-300":"text-zinc-500"),children:[c.safetyRate,"%"]})]},c.date)})}):e.jsx("div",{className:"text-xs text-zinc-500 py-6 text-center",children:"Sem dados no período."})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.02] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Livros 
2sinalizados"}),e.jsxs("span",{className:"text-[10px] text-zinc-500",children:["≥ ",n,"% de bloqueio · mínimo ",f," ilustrações"]})]}),g?e.jsx("div",{className:"text-xs text-zinc-500 py-6 text-center",children:"Carregando..."}):p?.books?.length?e.jsx("div",{className:"overflow-x-auto","data-testid":"quality-books-table",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-zinc-500 border-b border-white/10",children:[e.jsx("th",{className:"font-normal py-2 pr-3",children:"Livro"}),e.jsx("th",{className:"font-normal py-2 pr-3",children:"Cliente"}),e.jsx("th",{className:"font-normal py-2 pr-3 text-right",children:"Total"}),e.jsx("th",{className:"font-normal py-2 pr-3 text-right",children:"Safety"}),e.jsx("th",{className:"font-normal py-2 pr-3 text-right",children:"Falhas"}),e.jsx("th",{className:"font-normal py-2 pr-3 text-right",children:"Taxa"}),e.jsx("th",{className:"font-normal py-2 pr-3",children:"Categorias"}),e.jsx("th",{className:"font-normal py-2 pr-3",children:"Status"}),e.jsx("th",{className:"font-normal py-2"})]})}),e.jsx("tbody",{children:p.books.map(c=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/[0.03]","data-testid":`row-quality-${c.bookId}`,children:[e.jsxs("td",{className:"py-2 pr-3 max-w-[220px]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-white truncate",title:c.title,children:[e.jsx(ot,{className:"h-3 w-3 text-zinc-500 shrink-0"}),e.jsx("span",{className:"truncate","data-testid":`text-quality-title-${c.bookId}`,children:c.title})]}),e.jsx("div",{className:"text-[10px] text-zinc-500 mt-0.5 font-mono",children:c.bookId.slice(0,8)})]}),e.jsx("td",{className:"py-2 pr-3",children:c.userEmail?e.jsx("button",{className:"text-zinc-300 hover:text-white underline-offset-2 hover:underline truncate max-w-[180px] inline-block text-left",onClick:()=>a?.(c.userId,c.userEmail||void 0),"data-testid":`button-quality-user-${c.bookId}`,children:c.userEmail}):e.jsx("span",{className:"text-zinc-600",children:"—"})}),e.jsx("td",{className:"py-2 pr-3 text-right tabular-nums text-zinc-300",children:c.total}),e.jsx("td",{className:"py-2 pr-3 text-right tabular-nums text-amber-300",children:c.safety}),e.jsx("td",{className:"py-2 pr-3 text-right tabular-nums text-red-300",children:c.failed}),e.jsx("td",{className:"py-2 pr-3 text-right",children:e.jsxs("span",{className:_a("inline-block px-1.5 py-0.5 rounded tabular-nums font-semibold",c.blockRate>=50?"bg-red-500/20 text-red-300":c.blockRate>=25?"bg-amber-500/20 text-amber-300":"bg-zinc-500/20 text-zinc-300"),"data-testid":`text-quality-rate-${c.bookId}`,children:[c.blockRate,"%"]})}),e.jsx("td",{className:"py-2 pr-3 max-w-[200px]",children:e.jsx("div",{className:"flex flex-wrap gap-1",children:c.topCategories.length===0?e.jsx("span",{className:"text-zinc-600",children:"—"}):c.topCategories.map((m,$)=>e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-white/5 text-zinc-400 truncate max-w-[120px]",title:`${m.category}: ${m.count}`,children:[m.category,": ",m.count]},$))})}),e.jsx("td",{className:"py-2 pr-3",children:c.refunded?e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-red-500/20 text-red-300","data-testid":`badge-refunded-${c.bookId}`,children:[e.jsx(Ce,{className:"h-3 w-3"})," Reembolso"]}):e.jsx("span",{className:"text-[10px] text-zinc-600",children:"OK"})}),e.jsx("td",{className:"py-2",children:e.jsxs(jh,{href:`/ilustrar/${c.bookId}`,className:"inline-flex items-center gap-1 text-[11px] text-blue-300 hover:text-blue-200","data-testid":`link-quality-editor-${c.bookId}`,children:["Editor ",e.jsx(vs,{className:"h-3 w-3"})]})})]},c.bookId))})]})}):e.jsxs("div",{className:"text-xs text-emerald-400/80 py-6 text-center flex items-center justify-center gap-2",children:[e.jsx(Ks,{className:"h-4 w-4"})," Nenhum livro acima do limite no período."]})]})]})}function gn({label:a,value:r,tone:l,testId:n}){const u=l==="red"?"text-red-300":l==="amber"?"text-amber-300":"text-white";return e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.02] px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wide",children:a}),e.jsx("div",{className:_a("text-xl font-semibold mt-1 tabular-nums",u),"data-testid":n,children:r})]})}async function kn(a,r){const l=await fetch(a,{credentials:"include",...r}),n=await l.json().catch(()=>({}));if(!l.ok)throw new Error(n?.message||`Erro ${l.status}`);return n}
2function Lb({onReady:a,resumePendingUpload:r}){const[l,n]=d.useState(r?"processing":"idle"),[u,f]=d.useState(0),[j,p]=d.useState(""),[g,w]=d.useState(!1),y=d.useRef(null),F=d.useRef(null),c=d.useRef(null);d.useEffect(()=>{if(l!=="processing")return;const $=async()=>{try{const D=await kn("/api/admin/interview-popup/mux-status");D.status==="ready"?(n("ready"),a()):D.status==="error"&&(n("error"),p("O Mux não conseguiu processar o vídeo. Tente enviar novamente."))}catch{}};return $(),F.current=setInterval($,5e3),()=>{F.current&&clearInterval(F.current)}},[l,a]);async function m($,D=!1){D?f(0):(n("uploading"),f(0),p(""),w(!1));try{const{uploadUrl:A}=await kn("/api/admin/interview-popup/upload",{method:"POST"}),o=$.type?$:new File([$],$.name,{type:"video/mp4"});await new Promise((L,v)=>{const I=uu({endpoint:A,file:o,chunkSize:30720,maxChunkSize:61440,dynamicChunkSize:!0,attempts:8,delayBeforeAttempt:2,retryCodes:[0,408,409,429,500,502,503,504]});y.current=I,I.on("progress",de=>f(Math.round(Number(de?.detail)||0))),I.on("offline",()=>w(!0)),I.on("online",()=>w(!1)),I.on("error",de=>{y.current=null,v(new Error(de?.detail?.message?String(de.detail.message):"Falha desconhecida no upload."))}),I.on("success",()=>{y.current=null,L()})}),w(!1),n("processing")}catch(A){const o=A?.message?String(A.message):"",L=/server responded with \d/i.test(o);if(!D&&L)return m($,!0);n("error"),w(!1);const v=/server responded with 0\b/i.test(o),I=o&&!v?` (${o}).`:".";p(D?`Falha ao enviar mesmo após reiniciar automaticamente${I} Verifique sua conexão e tente novamente.`:`Falha ao enviar após várias tentativas${I} Verifique sua conexão e tente novamente.`)}}return l==="ready"?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-emerald-300","data-testid":"status-upload-ready",children:[e.jsx(be,{className:"w-4 h-4"})," Vídeo processado pelo Mux · pronto para exibição"]}):l==="processing"?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-amber-300","data-testid":"status-upload-processing",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Mux está processando o vídeo… (pode levar alguns minutos)"]}):l==="uploading"?e.jsxs("div",{className:"space-y-2","data-testid":"status-upload-progress",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}),g?"Sem conexão — o envio retoma sozinho quando voltar…":"Enviando vídeo para o Mux…"]}),e.jsxs("span",{className:"font-mono",children:[u,"%"]})]}),e.jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-white/10",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-teal-400 to-cyan-500 transition-all",style:{width:`${u}%`}})})]}):e.jsxs("div",{className:"space-y-2",children:[l==="error"&&e.jsxs("div",{className:"flex items-start gap-2 text-xs text-red-300","data-testid":"status-upload-error",children:[e.jsx(Ce,{className:"w-4 h-4 shrink-0 mt-0.5"}),e.jsx("span",{children:j})]}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:$=>{const D=$.target.files?.[0];D&&m(D),$.target.value=""},"data-testid":"input-interview-video-file"}),e.jsxs(b,{type:"button",variant:"outline",className:"gap-2",onClick:()=>c.current?.click(),"data-testid":"button-upload-interview-video",children:[e.jsx(bu,{className:"w-4 h-4"}),l==="error"?"Tentar novamente":"Enviar vídeo do computador"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"O arquivo sobe direto do navegador para o Mux (não passa pelo servidor). Ao substituir, o vídeo antigo continua no ar até o novo ficar pronto."})]})}function bn({icon:a,label:r,win:l,suffix:n}){return e.jsx(je,{className:"bg-white/5 border-white/10",children:e.jsxs(ve,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-2",children:[e.jsx(a,{className:"w-3.5 h-3.5"})," ",r]}),e.jsxs("div",{className:"text-2xl font-bold text-white","data-testid":`metric-${r}
2`,children:[l.total.toLocaleString("pt-BR"),n||""]}),e.jsxs("div",{className:"mt-1 flex gap-3 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:["7d: ",e.jsx("span",{className:"text-white/80 font-semibold",children:l.d7.toLocaleString("pt-BR")})]}),e.jsxs("span",{children:["30d: ",e.jsx("span",{className:"text-white/80 font-semibold",children:l.d30.toLocaleString("pt-BR")})]})]})]})})}function zb(){const{toast:a}=st(),r=$a(),l=z({queryKey:["/api/admin/interview-popup/config"],queryFn:()=>kn("/api/admin/interview-popup/config")}),n=z({queryKey:["/api/admin/interview-popup/metrics"],queryFn:()=>kn("/api/admin/interview-popup/metrics"),refetchInterval:6e4}),[u,f]=d.useState(""),[j,p]=d.useState(""),[g,w]=d.useState(""),[y,F]=d.useState(3),[c,m]=d.useState(!1);d.useEffect(()=>{l.data&&!c&&(f(l.data.title),p(l.data.subtitle),w(l.data.ctaText),F(l.data.maxShowsPerUser),m(!0))},[l.data,c]);const $=W({mutationFn:o=>kn("/api/admin/interview-popup/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),onSuccess:()=>{r.invalidateQueries({queryKey:["/api/admin/interview-popup/config"]}),a({title:"Configuração salva"})},onError:o=>{a({title:"Erro ao salvar",description:o?.message,variant:"destructive"})}}),D=l.data,A=n.data;return e.jsxs("div",{className:"space-y-6","data-testid":"panel-interview-popup",children:[e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{children:e.jsxs(De,{className:"flex items-center gap-2 text-white text-base",children:[e.jsx(gu,{className:"w-4 h-4 text-teal-300"})," Entrevista Vale do Silício — vídeo e copy"]})}),e.jsx(ve,{className:"space-y-5",children:l.isLoading?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Carregando…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Vídeo atual"}),D?.playbackUrl?e.jsx("video",{src:D.playbackUrl,controls:!0,preload:"metadata",className:"w-full rounded-lg border border-white/10 bg-black aspect-video","data-testid":"video-interview-preview"}):e.jsx("div",{className:"flex aspect-video items-center justify-center rounded-lg border border-dashed border-white/15 bg-black/40 text-xs text-muted-foreground",children:"Nenhum vídeo enviado ainda"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Enviar / substituir vídeo"}),e.jsx(Lb,{resumePendingUpload:!!D?.hasPendingUpload,onReady:()=>{r.invalidateQueries({queryKey:["/api/admin/interview-popup/config"]}),a({title:"Vídeo pronto!",description:"O vídeo foi processado pelo Mux e já pode ser exibido."})}},D?.hasPendingUpload?"resume":"fresh")]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Título"}),e.jsx(J,{value:u,onChange:o=>f(o.target.value),className:"bg-white/5 border-white/10","data-testid":"input-interview-title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Subtítulo"}),e.jsx(J,{value:j,onChange:o=>p(o.target.value),className:"bg-white/5 border-white/10","data-testid":"input-interview-subtitle"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Texto do CTA"}),e.jsx(J,{value:g,onChange:o=>w(o.target.value),className:"bg-white/5 border-white/10","data-testid":"input-interview-cta"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Teto de exibições por usuário"}),e.jsx(J,{type:"number",min:1,max:50,value:y,onChange:o=>F(Number(o.target.value)||1),className:"bg-white/5 border-white/10 w-32","data-testid":"input-interview-max-shows"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 pt-1",children:[e.jsxs(b,{onClick:()=>$.mutate({title:u,subtitle:j,ctaText:g,maxShowsPerUser:y,enabled:D?.enabled}),disabled:$.isPending,className:"gap-2","data-testid":"button-save-interview-config",children:[$.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin"}):e.jsx(Ic,{className:"w-4 h-4"}),"Salvar configuração"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{checked:!!D?.enabled,disabled:$.isPending||!(D?.muxStatus==="ready"&&D?.muxPlaybackId),onCheckedChange:o=>$.mutate({enabled:o}),"data-testid":"switch-interview-enabled"}),e.jsx("span",{className:"text-sm text-white/80",children:D?.enabled?"Popup ativo":"Popup desativado"}),!(D?.muxStatus==="ready"&&D?.muxPlaybackId)&&e.jsx("span",{className:"text-[11px] text-amber-300/80",children:"(envie um vídeo antes de ativar)"})]})]})]})})]}),e.jsxs(je,{className:"bg-white/5 border-white/10",children:[e.jsx(Fe,{children:e.jsxs(De,{className:"flex items-center gap-2 text-white text-base",children:[e.jsx(ht,{className:"w-4 h-4 text-teal-300"})," Métricas do popup"]})}),e.jsx(ve,{children:n.isLoading?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Carregando…"]}):A?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(je,{className:"bg-teal-500/10 border-teal-400/25",children:e.jsxs(ve,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-teal-200/80 mb-1",children:[e.jsx(Re,{className:"w-3.5 h-3.5"})," Usuários alcançados"]}),e.jsx("div",{className:"text-2xl font-bold text-white","data-testid":"metric-reached",children:A.reached.toLocaleStr
2ing("pt-BR")})]})}),e.jsx(je,{className:"bg-teal-500/10 border-teal-400/25",children:e.jsxs(ve,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-teal-200/80 mb-1",children:[e.jsx(Hm,{className:"w-3.5 h-3.5"})," Taxa de conclusão"]}),e.jsxs("div",{className:"text-2xl font-bold text-white","data-testid":"metric-completion-rate",children:[A.completionRate,"%"]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-1",children:[A.watchedUsers.toLocaleString("pt-BR")," usuários assistiram até o fim"]})]})}),e.jsx(je,{className:"bg-teal-500/10 border-teal-400/25",children:e.jsxs(ve,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-teal-200/80 mb-1",children:[e.jsx(Jl,{className:"w-3.5 h-3.5"})," CTR do botão"]}),e.jsxs("div",{className:"text-2xl font-bold text-white","data-testid":"metric-ctr",children:[A.ctr,"%"]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-1",children:[A.clickedUsers.toLocaleString("pt-BR")," usuários clicaram no CTA"]})]})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(bn,{icon:ht,label:"Exibições",win:A.shows}),e.jsx(bn,{icon:Us,label:"Plays",win:A.plays}),e.jsx(bn,{icon:Hm,label:"Conclusões",win:A.completions}),e.jsx(bn,{icon:Jl,label:"Cliques CTA",win:A.ctaClicks}),e.jsx(bn,{icon:dt,label:"Dispensas",win:A.dismissals})]})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sem dados ainda."})})]})]})}const gc=[{value:"Palette",label:"Paleta",icon:Va},{value:"CheckCircle2",label:"Check",icon:be},{value:"Languages",label:"Idiomas",icon:fn},{value:"Printer",label:"Impressora",icon:Sh},{value:"FileText",label:"Documento",icon:tt},{value:"Star",label:"Estrela",icon:wn},{value:"Sparkles",label:"Brilhos",icon:qe},{value:"Bot",label:"IA/Robô",icon:Qi},{value:"Wrench",label:"Ferramenta",icon:Pn},{value:"BookOpen",label:"Livro",icon:ot},{value:"CreditCard",label:"Cartão",icon:Bt},{value:"Edit2",label:"Editar",icon:Yl},{value:"Globe",label:"Global",icon:pt},{value:"Zap",label:"Raio",icon:He},{value:"TrendingUp",label:"Gráfico",icon:Ie},{value:"Shield",label:"Escudo",icon:as}],mh=[{value:"services_tab",label:"Aba Serviços (publicação)"},{value:"post_planning",label:"Após planejamento"},{value:"publication",label:"Publicação"},{value:"all",label:"Todos os locais"}],hh=[{value:"ai",label:"IA (automático)"},{value:"human",label:"Humano (Digiwork)"},{value:"webhook",label:"Webhook externo"}],qb=[{value:"escrita",label:"Escrita"},{value:"design",label:"Design"},{value:"revisao",label:"Revisão"},{value:"traducao",label:"Tradução"},{value:"publicacao",label:"Publicação"},{value:"marketing",label:"Marketing"},{value:"outro",label:"Outro"}],_b={pending:"Pendente",confirmed:"Confirmado",completed:"Concluído",cancelled:"Cancelado",failed:"Falhou",refunded:"Reembolsado",test:"Teste",processed:"Processado",received:"Recebido",rejected:"Rejeitado",invalid:"Inválido",skipped:"Ignorado",error:"Erro"},bc={title:"",description:"",longDescription:"",price:0,type:"design",iconName:"Palette",recurring:!1,active:!0,displayLocation:"services_tab",executionType:"ai",category:"outro",sortOrder:0,estimatedDays:0,availableForManualSale:!1,allowOfferInChat:!1,defaultDiscountPct:0,extraFieldsConfig:null};function Ob(){const{toast:a}=st(),r=$a(),[l,n]=d.useState(!1),[u,f]=d.useState(""),[j,p]=d.useState(""),[g,w]=d.useState(null),[y,F]=d.useState(!1),[c,m]=d.useState(null),$=async()=>{const S=u.trim();if(S){F(!0),m(null),w(null);try{const re=await fetch(`/api/admin/woovi/charge/${encodeURIComponent(S)}`,{credentials:"include"});if(re.ok){const _=await re.json();w(_),_?.localStatus?.type==="checkout_session"&&_.localStatus.id&&!j&&p(_.localStatus.id)}else{const _=await re.json().catch(()=>({}));m(_.message||`Erro ${re.status}`)}}catch(re){m(re?.message||"Falha de rede")}finally{F(!1)}}},{data:D,isLoading:A}=z({queryKey:["/api/admin/woovi/health"],refetchInterval:15e3}),{data:o}=z({queryKey:["/api/admin/woovi/orphans"],refetchInterval:3e4}),L=()=>{r.invalidateQueries({queryKey:["/api/admin/woovi/health"]}),r.invalidateQueries({queryKey:["/api/admin/woovi/orphans"]}),r.invalidateQueries({queryKey:["/api/admin/webhook-events"]})},v=W({mutationFn:async()=>(await N("POST","/api/admin/woovi/reconcile-now",{})).json(),onSuccess:S=>{const re=S?.report;a({title:"Reconciliação PIX executada",description:re?`Escaneadas ${re.scanned} • Confirmadas ${re.confirmed} • Já pagas ${re.alreadyPaid} • Órfãs ${re.orphans}`:"Concluída"}),L()},onError:S=>{a({variant:"destructive",title:"Falha ao reconciliar",description:S?.message||"Erro inesperado"})}}),I=W({mutationFn:async S=>
2(await N("POST","/api/admin/woovi/recover-charge",S)).json(),onSuccess:(S,re)=>{a({title:"Charge recuperada",description:`Vinculada à sessão ${S?.resolvedCheckoutId||"(legacy)"} • R$${S?.chargeValue?(S.chargeValue/100).toFixed(2):"?"}`}),L(),l&&(n(!1),f(""),p(""))},onError:S=>{a({variant:"destructive",title:"Falha ao recuperar",description:S?.message||"Erro inesperado"})}});if(A||!D)return null;const de=D.reconciler||{},me=o?.orphans||D.orphans||[],ne=D.countsLast72h||{},Z=D.appIdConfigured&&de.enabled;return e.jsxs("div",{className:`bg-white/5 border ${Z?"border-green-500/20":"border-amber-500/20"} rounded-xl p-5 space-y-4`,"data-testid":"card-woovi-health",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${Z?"bg-green-500/10":"bg-amber-500/10"}`,children:e.jsx(Oa,{className:`w-5 h-5 ${Z?"text-green-400":"text-amber-400"}`})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-white font-semibold text-sm","data-testid":"text-woovi-health-title",children:"Reconciliação PIX (Woovi)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Webhook + reconciler automático a cada 2min"})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsx(E,{className:`text-[10px] ${de.enabled?"bg-green-500/20 text-green-400 border-green-500/30":"bg-amber-500/20 text-amber-400 border-amber-500/30"}`,"data-testid":"badge-woovi-reconciler-status",children:de.enabled?"Reconciler ON":"Reconciler OFF"}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-8 border-white/10 hover:bg-white/10",onClick:()=>v.mutate(),disabled:v.isPending,"data-testid":"button-woovi-reconcile-now",children:[v.isPending?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(xe,{className:"w-3 h-3 mr-1"}),"Reconciliar agora"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-black/20 rounded-lg p-3 border border-white/5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Janela"}),e.jsxs("p",{className:"text-sm text-white font-semibold mt-1",children:[de.windowHours||6,"h"]})]}),e.jsxs("div",{className:"bg-black/20 rounded-lg p-3 border border-white/5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Último ciclo"}),e.jsx("p",{className:"text-sm text-white font-semibold mt-1","data-testid":"text-woovi-last-run",children:de.lastRunAt?new Date(de.lastRunAt).toLocaleTimeString("pt-BR"):"—"})]}),e.jsxs("div",{className:"bg-black/20 rounded-lg p-3 border border-white/5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Confirmadas (último)"}),e.jsx("p",{className:"text-sm text-green-400 font-semibold mt-1","data-testid":"text-woovi-confirmed-last",children:de.lastReport?.confirmed??0})]}),e.jsxs("div",{className:"bg-black/20 rounded-lg p-3 border border-white/5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Órfãs (último)"}),e.jsx("p",{className:`text-sm font-semibold mt-1 ${(de.lastReport?.orphans??0)>0?"text-amber-400":"text-white"}`,"data-testid":"text-woovi-orphans-last",children:de.lastReport?.orphans??0})]})]}),Object.keys(ne).length>0&&e.jsxs("div",{className:"bg-black/20 border border-white/5 rounded-lg p-3",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-2",children:"Eventos webhook (72h)"}),e.jsx("div",{className:"flex flex-wrap gap-2","data-testid":"list-woovi-event-counts",children:Object.entries(ne).map(([S,re])=>e.jsxs(E,{variant:"outline",className:"text-[10px] border-white/10 text-white/80",children:[S,": ",e.jsx("span",{className:"ml-1 font-mono",children:re})]},S))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:D.lastEvent?e.jsxs(e.Fragment,{children:["Último evento Woovi: ",e.jsx("span",{className:"text-white font-mono",children:D.lastEvent.event})," (",D.lastEvent.status,") — ",D.lastEvent.createdAt?new Date(D.lastEvent.createdAt).toLocaleStr
2ing("pt-BR"):"-"]}):"Nenhum evento Woovi recebido nas últimas 72h"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("a",{href:"/admin/pix-diversificacao",className:"inline-flex items-center gap-1 h-7 px-2 rounded-md text-[10px] text-muted-foreground hover:text-white hover:bg-white/5","data-testid":"link-pix-diversificacao",children:["Diversificação de PIX (Woovi/Asaas) ",e.jsx(vs,{className:"w-3 h-3"})]}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 text-[10px] text-muted-foreground hover:text-white",onClick:()=>n(!0),"data-testid":"button-woovi-advanced-recovery",children:"Recuperação avançada…"})]})]}),me.length>0&&e.jsxs("div",{className:"bg-amber-500/5 border border-amber-500/20 rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-3.5 h-3.5 text-amber-400"}),e.jsxs("p",{className:"text-xs text-amber-400 font-semibold",children:["Charges órfãs (",me.length,")"]}),e.jsx("p",{className:"text-[10px] text-muted-foreground ml-2",children:"— charges Woovi pagas sem order correspondente"})]}),e.jsx("div",{className:"space-y-1.5 max-h-[320px] overflow-y-auto",children:me.map(S=>{const re=S.correlationId||"",_=typeof S.chargeValue=="number"?`R$${(S.chargeValue/100).toFixed(2)}`:null,ee=S.suggestedCheckoutSessionId;return e.jsxs("div",{className:"flex items-start gap-3 bg-black/20 rounded-md px-3 py-2 border border-white/5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-[11px] text-white font-mono truncate","data-testid":`text-orphan-corr-${re}`,children:re||"(sem correlationID)"}),_&&e.jsx(E,{variant:"outline",className:"text-[10px] border-green-500/30 text-green-400",children:_}),S.payerName&&e.jsxs("span",{className:"text-[10px] text-muted-foreground truncate",children:["por ",S.payerName]})]}),S.payerEmail&&e.jsxs("p",{className:"text-[10px] text-blue-300/80 mt-0.5","data-testid":`text-orphan-email-${re}`,children:["✉ ",S.payerEmail]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[S.event," • ",S.createdAt?new Date(S.createdAt).toLocaleString("pt-BR"):"-",S.errorMessage?` • ${S.errorMessage}`:""]}),ee&&e.jsxs("p",{className:"text-[10px] text-blue-400/80 font-mono mt-0.5","data-testid":`text-orphan-suggested-${re}`,children:["Sessão sugerida: ",ee.slice(0,32),"…"]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 shrink-0",children:[e.jsxs(pi,{children:[e.jsx(ui,{asChild:!0,children:e.jsxs(b,{size:"sm",variant:"outline",className:"h-7 border-amber-500/30 text-amber-400 hover:bg-amber-500/10",disabled:!re||I.isPending,"data-testid":`button-recover-orphan-${re}`,children:[I.isPending&&I.variables?.correlationID===re?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(He,{className:"w-3 h-3 mr-1"}),"Recuperar"]})}),e.jsxs(gi,{className:"bg-[#0a0a0a] border-white/10 text-white","data-testid":`alert-confirm-recover-${re}`,children:[e.jsxs(bi,{children:[e.jsx(ji,{className:"text-white",children:"Confirmar recuperação"}),e.jsxs(vi,{className:"text-muted-foreground text-xs space-y-1",children:[e.jsxs("span",{className:"block",children:["Esta ação confirma o pagamento PIX ",e.jsx("span",{className:"text-white font-mono",children:re})," ",_?`(${_})`:""," e dispara ",e.jsx("strong",{children:"entrega/upsell/email/SMS"})," imediatamente. ",e.jsx("strong",{children:"Não é reversível."})]}),ee&&e.jsxs("span",{className:"block text-blue-400/80",children:["Será vinculada à sessão: ",e.jsxs("span",{className:"font-mono",children:[ee.slice(0,40),"…"]})]})]})]}),e.jsxs(Ni,{children:[e.jsx(fi,{"data-testid":`button-recover-cancel-${re}`,children:"Cancelar"}),e.jsx(wi,{onClick:()=>I.mutate({correlationID:re}),"data-testid":`button-recover-confirm-${re}`,children:"Confirmar e recuperar"})]})]})]}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-6 text-[10px] text-muted-foreground hover:text-white",onClick:()=>{f(re),p(ee||""),n(!0)},"data-testid":`button-link-orphan-${re}`,children:"Vincular manualmente…"})]})]},S.id)})})]}),e.jsx(Je,{open:l,onOpenChange:n,children:e.jsxs(Ye,{className:"bg-[#0a0a0a] border-white/10 text-white max-w-md","data-testid":"dialog-woovi-advanced-rec
2overy",children:[e.jsxs(Ze,{children:[e.jsx(et,{className:"text-white",children:"Recuperação avançada PIX"}),e.jsx(mt,{className:"text-muted-foreground text-xs",children:"Use para vincular manualmente uma charge órfã da Woovi a uma checkout session específica. A charge precisa estar COMPLETED na Woovi. A confirmação é idempotente."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(O,{htmlFor:"advanced-corr-id",className:"text-xs text-muted-foreground",children:"correlationID (Woovi)"}),e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(J,{id:"advanced-corr-id",value:u,onChange:S=>{f(S.target.value),w(null),m(null)},placeholder:"checkout_xxxx_123 ou chatckt_xxxx_123",className:"bg-black/30 border-white/10 text-white font-mono text-xs flex-1","data-testid":"input-advanced-correlation-id"}),e.jsxs(b,{type:"button",variant:"outline",size:"sm",onClick:$,disabled:!u.trim()||y,className:"text-xs whitespace-nowrap border-white/10","data-testid":"button-lookup-woovi-charge",children:[y?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):null,"Buscar na Woovi"]})]})]}),c&&e.jsx("p",{className:"text-[11px] text-red-400","data-testid":"text-lookup-error",children:c}),g&&e.jsxs("div",{className:"rounded-md border border-white/10 bg-black/30 p-2 text-[11px] space-y-1","data-testid":"box-lookup-result",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status Woovi:"}),e.jsx(E,{className:`text-[10px] ${g.charge?.status==="COMPLETED"?"bg-green-500/20 text-green-400 border-green-500/30":"bg-amber-500/20 text-amber-400 border-amber-500/30"}`,children:g.charge?.status||"?"}),typeof g.charge?.value=="number"&&e.jsxs("span",{className:"text-green-400 font-mono",children:["R$ ",(g.charge.value/100).toFixed(2)]})]}),g.charge?.customer?.email&&e.jsxs("p",{className:"text-muted-foreground truncate",children:["✉ ",g.charge.customer.email]}),e.jsxs("p",{className:"text-muted-foreground",children:["Local: ",e.jsx("span",{className:"text-white",children:g.localStatus?.type||"none"}),g.localStatus?.status?` (${g.localStatus.status})`:""]})]}),e.jsxs("div",{children:[e.jsx(O,{htmlFor:"advanced-checkout-id",className:"text-xs text-muted-foreground",children:"checkoutSessionId (opcional — sobrescreve a inferência)"}),e.jsx(J,{id:"advanced-checkout-id",value:j,onChange:S=>p(S.target.value),placeholder:"(deixe vazio para auto-detectar)",className:"bg-black/30 border-white/10 text-white font-mono text-xs mt-1","data-testid":"input-advanced-checkout-session-id"})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"ghost",onClick:()=>n(!1),"data-testid":"button-advanced-recovery-cancel",children:"Cancelar"}),e.jsxs(b,{onClick:()=>I.mutate({correlationID:u.trim(),checkoutSessionId:j.trim()||void 0}),disabled:!u.trim()||I.isPending,"data-testid":"button-advanced-recovery-confirm",children:[I.isPending?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(He,{className:"w-3 h-3 mr-1"}),"Confirmar recuperação"]})]})]})})]})}function Bb(){const[a,r]=d.useState(null);if(d.useEffect(()=>{fetch("/api/admin/webhook-health",{credentials:"include"}).then(j=>j.ok?j.json():null).then(j=>r(j)).catch(()=>{})},[]),!a)return null;const l=a.status==="ok",n=a.status==="signature_failed",u=l?"border-green-500/20":n?"border-red-500/20":"border-amber-500/20",f=l?"bg-green-500/5":n?"bg-red-500/5":"bg-amber-500/5";return e.jsxs("div",{className:`${f} border ${u} rounded-xl p-5 space-y-4`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${l?"bg-green-500/10":n?"bg-red-500/10":"bg-amber-500/10"}`,children:e.jsx(Bt,{className:`w-5 h-5 ${l?"text-green-400":n?"text-red-400":"text-amber-400"}`})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-white font-semibold text-sm","data-testid":"text-stripe-webhook-title",children:"Webhook Stripe (Cartão de Crédito)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status da integração com pagamentos via cartão"})]}),e.jsx("div",{className:"ml-auto",children:l?e.jsx(E,{className:"bg-green-500/20 text-green-400 border-green-500/30 text-[10px]","data-testid":"badge-stripe-webhook-status",children:"Ativo"}):n?e.jsx(E,{className:"bg-red-500/20 text-red-400 border-red-500/30 text-[10px]","data-testid":"badge-stripe-webhook-status",children:"Erro"}):e.jsx(E,{className:"bg-amber-500/20 text-amber-400 border-amber-500/30 text-[10px]","data-testid":"badge-stripe-webhook-status",children:"Desconhecido"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:`flex items-center gap-2 p-3 rounded-lg border ${a.webhookSecretConfigured?"bg-green-500/5 border-green-500/20":"bg-red-500/5 border-red-500/20"}`,children:[a.webhookSecretConfigured?e.jsx(be,{className:"w-4 h-4 text-green-400"}):e.jsx(dt,{className:"w-4 h-4 text-red-400"}),e.jsxs("span",{className:`text-xs ${a.webhookSecretConfigured?"text-green-400":"text-red-400"}`,children:["STRIPE_WEBHOOK_SECRET ",a.webhookSecretConfigured?"configurado":"NÃO configurado"]})]}),e.jsxs("div",{className:`flex items-center gap-2 p-3 rounded-lg border ${l?"bg-green-500/5 border-green-500/20":n?"bg-red-500/5 border-red-500/20":"bg-
2amber-500/5 border-amber-500/20"}`,children:[l?e.jsx(be,{className:"w-4 h-4 text-green-400"}):n?e.jsx(dt,{className:"w-4 h-4 text-red-400"}):e.jsx(Ce,{className:"w-4 h-4 text-amber-400"}),e.jsx("span",{className:`text-xs ${l?"text-green-400":n?"text-red-400":"text-amber-400"}`,children:l?"Verificação de assinatura OK":n?"Falha na verificação de assinatura":"Aguardando primeiro webhook"})]})]}),a.lastReceivedAt&&e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:["Último webhook: ",e.jsx("span",{className:"text-white",children:new Date(a.lastReceivedAt).toLocaleString("pt-BR")})]}),a.lastEventType&&e.jsxs("p",{children:["Evento: ",e.jsx("span",{className:"text-white font-mono text-[11px]",children:a.lastEventType})]})]}),n&&a.lastError&&e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-red-400 font-medium mb-1",children:"Erro na verificação do webhook:"}),e.jsx("p",{className:"text-[11px] text-red-300/70 font-mono break-all",children:a.lastError}),e.jsx("p",{className:"text-[11px] text-red-300/50 mt-2",children:"Verifique se o STRIPE_WEBHOOK_SECRET corresponde ao configurado no painel do Stripe."})]})]})}function kt({icon:a,label:r,value:l,sub:n,color:u="text-white","data-testid":f}){return e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-1.5 hover:bg-white/[0.07] transition-colors","data-testid":f,children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(a,{className:"w-4 h-4"}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:r})]}),e.jsx("p",{className:`text-2xl font-bold ${u}`,children:l}),n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]})}function Gi({status:a}){const r={confirmed:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",completed:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",pending:"bg-amber-500/20 text-amber-400 border-amber-500/30",cancelled:"bg-red-500/20 text-red-400 border-red-500/30",failed:"bg-red-500/20 text-red-400 border-red-500/30",refunded:"bg-purple-500/20 text-purple-400 border-purple-500/30",test:"bg-blue-500/20 text-blue-400 border-blue-500/30",processed:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",received:"bg-sky-500/20 text-sky-400 border-sky-500/30",rejected:"bg-red-500/20 text-red-400 border-red-500/30",invalid:"bg-orange-500/20 text-orange-400 border-orange-500/30",skipped:"bg-gray-500/20 text-gray-400 border-gray-500/30",error:"bg-red-500/20 text-red-400 border-red-500/30"};return e.jsx("span",{className:`px-2 py-0.5 rounded-full text-[11px] font-medium border ${r[a]||"bg-white/10 text-white/60 border-white/10"}`,children:_b[a]||a})}const ph={pt:"PT",en:"EN",es:"ES",fr:"FR",de:"DE",it:"IT",ja:"JA",zh:"ZH",ko:"KO",ar:"AR",hi:"HI",ru:"RU",tr:"TR"};function Ub({languages:a}){if(!a?.length)return null;const r=l=>l==="completed"?"bg-emerald-500/15 text-emerald-300 border-emerald-500/30":l==="generating"?"bg-violet-500/15 text-violet-300 border-violet-500/30":l==="error"?"bg-red-500/15 text-red-300 border-red-500/30":"bg-zinc-700/40 text-zinc-400 border-white/10";return e.jsx("div",{className:"flex flex-wrap gap-1 mt-1","data-testid":"translation-lang-pills",children:a.map(l=>e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-semibold border inline-flex items-center gap-1 ${r(l.status)}`,title:`${ph[l.lang]||l.lang.toUpperCase()}: ${l.status} (${l.written}/${l.expected})`,"data-testid":`pill-lang-${l.lang}`,children:[ph[l.lang]||l.lang.toUpperCase(),l.status==="completed"&&e.jsx(be,{className:"w-2 h-2"}),l.status==="generating"&&e.jsx(T,{className:"w-2 h-2 animate-spin"}),l.status==="error"&&e.jsx(dt,{className:"w-2 h-2"})]},l.lang))})}const Kb={delivered:{badge:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",label:"Entregue",icon:e.jsx(be,{className:"w-2.5 h-2.5 mr-1"})},partial:{badge:"bg-amber-500/20 text-amber-400 border-amber-500/30",label:"Parcial",icon:e.jsx(Ce,{className:"w-2.5 h-2.5 mr-1"})},missing:{badge:"bg-red-500/20 text-red-400 border-red-500/30",label:"Não entregue",icon:e.jsx(dt,{className:"w-2.5 h-2.5 mr-1"})},in_progress:{badge:"bg-violet-500/20 text-violet-400 border-violet-500/30",label:"Gerando",icon:e.jsx(T,{className:"w-2.5 h-2.5 mr-1 animate-spin"})},failed:{badge:"bg-red-500/20 text-red-400 border-red-500/30",label:"Com falhas",icon:e.jsx(Xe,{className:"w-2.5 h-2.5 mr-1"})},unknown:{badge:"bg-zinc-500/20 text-zinc-300 border-amber-500/40",label:"Verificar",icon:e.jsx(js,{className:"w-2.5 h-2.5 mr-1"})},n_a:{badge:"bg-white/10 text-white/60 border-white/10",label:"—",icon:null}};function Gb({userId:a,orderId:r,orderStatus:l}){const{toast:n}=st(),u=$a(),f=l==="confirmed"||l==="completed"||l==="processed",{data:j,isLoading:p}=z({queryKey:[`/api/admin/users/${a}/orders-delivery`],queryFn:()=>N("GET",`/api/admin/users/${a}/orders-delivery`).then(A=>A.json()),enabled:f,refetchInterval:3e4,staleTime:15e3}),g=j?.orders?.find(A=>A.orderId===r),w=W({mutationFn:()=>N("POST",`/api/admin/orders/${r}/redeliver`).then(A=>A.json()),onSuccess:A=>{A?.alreadyDelivered?n({title:"Já entregue",description:A?.status?.message||"Este pedido já está completo."}):A?.inProgress?n({title:"Já em andamento",description:A?.status?.message||"Aguarde a finalização da geração atual."}):A?.success===!1?n({title:"Não foi possível reentregar",description:A?.message||"Verifique manualmente.",variant:"destructive"}):n({title:"Re-entrega iniciada",description:A?.message||"A IA está gerando o que faltava. Aguarde alguns minutos."}
2),u.invalidateQueries({queryKey:[`/api/admin/users/${a}/orders-delivery`]}),u.invalidateQueries({queryKey:["/api/admin/users"]})},onError:A=>{n({title:"Falha ao reentregar",description:A?.message||"Erro inesperado ao acionar a IA.",variant:"destructive"})}}),[y,F]=d.useState(!1);if(!f)return null;if(p||!g)return e.jsx("span",{className:"text-[10px] text-muted-foreground","data-testid":`text-delivery-loading-${r}`,children:"verificando…"});if(g.status==="n_a")return null;const c=Kb[g.status],m=g.message||(g.expected!=null&&g.actual!=null?`${g.actual} / ${g.expected} entregues`:c.label),$=g.canRedeliver&&(g.status==="missing"||g.status==="partial"||g.status==="failed"),D=!!(g.derivationNote||g.scopeSource);return e.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1 relative",children:[e.jsxs("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-medium border inline-flex items-center ${c.badge}`,title:m,"data-testid":`badge-delivery-${g.status}-${r}`,children:[c.icon,c.label,g.expected!=null&&g.actual!=null&&g.expected>0&&e.jsxs("span",{className:"ml-1 opacity-70",children:[g.actual,"/",g.expected]}),g.status==="unknown"&&g.actual!=null&&e.jsxs("span",{className:"ml-1 opacity-70",children:[g.actual,"/?"]})]}),g.languages&&g.languages.length>0&&e.jsx("span",{className:"basis-full w-full",children:e.jsx(Ub,{languages:g.languages})}),D&&e.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),F(o=>!o)},className:"w-4 h-4 rounded-full bg-zinc-800/80 hover:bg-zinc-700 border border-white/10 inline-flex items-center justify-center text-zinc-300 hover:text-white transition",title:"Como o esperado foi calculado","data-testid":`button-delivery-details-${r}`,children:e.jsx(js,{className:"w-2.5 h-2.5"})}),$&&e.jsx(b,{size:"sm",variant:"outline",className:"h-6 px-2 text-[10px] border-violet-500/30 text-violet-300 hover:bg-violet-500/10",disabled:w.isPending,onClick:A=>{A.stopPropagation(),w.mutate()},title:"Aciona a IA para gerar e entregar o que está faltando neste pedido","data-testid":`button-redeliver-${r}`,children:w.isPending?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}),"Reentregando…"]}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{className:"w-3 h-3 mr-1"}),"Entregar agora"]})}),y&&D&&e.jsxs("div",{className:"absolute top-full left-0 mt-1 z-50 w-72 p-3 rounded-lg border border-violet-500/30 bg-zinc-900/95 backdrop-blur shadow-xl shadow-violet-900/20 text-[11px] text-zinc-100",onClick:A=>A.stopPropagation(),"data-testid":`popover-delivery-details-${r}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"font-semibold bg-gradient-to-r from-violet-300 to-amber-300 bg-clip-text text-transparent",children:"Detalhes da entrega"}),e.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),F(!1)},className:"text-zinc-500 hover:text-zinc-200","data-testid":`button-close-details-${r}`,children:e.jsx(dt,{className:"w-3 h-3"})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-zinc-400",children:"Pago:"}),e.jsx("span",{className:"font-medium","data-testid":`text-detail-expected-${r}`,children:g.expected??"?"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-zinc-400",children:"Entregues:"}),e.jsx("span",{className:"font-medium text-emerald-300","data-testid":`text-detail-actual-${r}`,children:g.actual??0})]}),g.expected!=null&&g.actual!=null&&g.expected>g.actual&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-zinc-400",children:"Faltam:"}),e.jsx("span",{className:"font-medium text-red-300","data-testid":`text-detail-missing-${r}`,children:g.missing})]})]}),g.derivationNote&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[10px] uppercase text-zinc-500 mb-1",children:"Cálculo"}),e.jsx("div",{className:"text-zinc-200 leading-snug","data-testid":`text-detail-derivation-${r}`,children:g.derivationNote})]}),g.scopeKind&&e.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[9px] uppercase text-zinc-500",children:"Fonte:"}),e.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded border ${g.scopeKind==="explicit"?"border-emerald-500/30 text-emerald-300 bg-emerald-500/10":g.scopeKind==="derived"?"border-violet-500/30 text-violet-300 bg-vi
2olet-500/10":g.scopeKind==="constant"?"border-blue-500/30 text-blue-300 bg-blue-500/10":g.scopeKind==="book_state"?"border-amber-500/30 text-amber-300 bg-amber-500/10":"border-zinc-500/30 text-zinc-300 bg-zinc-500/10"}`,children:g.scopeKind==="explicit"?"Explícita (compra)":g.scopeKind==="derived"?"Inferida do valor pago":g.scopeKind==="constant"?"Fixa do produto":g.scopeKind==="book_state"?"Estado do livro":"Indefinida"}),g.scopeConfidence&&e.jsxs("span",{className:"text-[9px] text-zinc-500",children:["• confiança ",g.scopeConfidence==="high"?"alta":g.scopeConfidence==="medium"?"média":"baixa"]})]})]})]})}function Vb(){const{toast:a}=st(),r=$a(),[l,n]=d.useState(null),[u,f]=d.useState(!1),[j,p]=d.useState({name:"",accessToken:"",adAccountId:"",pixelId:"",pageId:"",appSecret:"",instagramAccountId:"",isDefault:!1}),{data:g=[],isLoading:w}=z({queryKey:["/api/admin/meta-configs"],queryFn:()=>N("GET","/api/admin/meta-configs").then(o=>o.json())}),y=W({mutationFn:async o=>o.id?N("PUT",`/api/admin/meta-configs/${o.id}`,o.payload).then(L=>L.json()):N("POST","/api/admin/meta-configs",o.payload).then(L=>L.json()),onSuccess:o=>{r.invalidateQueries({queryKey:["/api/admin/meta-configs"]}),r.invalidateQueries({queryKey:["/api/admin/meta-config"]}),n(null),f(!1),p({name:"",accessToken:"",adAccountId:"",pixelId:"",pageId:"",appSecret:"",instagramAccountId:"",isDefault:!1}),o.connectionTest?a({title:o.connectionTest.success?"Conexão OK":"Erro na conexão",description:o.connectionTest.success?`Conta: ${o.connectionTest.accountName}`:o.connectionTest.error}):a({title:"Conta salva"})},onError:o=>a({title:"Erro",description:o.message,variant:"destructive"})}),F=W({mutationFn:o=>N("DELETE",`/api/admin/meta-configs/${o}`).then(L=>L.json()),onSuccess:()=>{r.invalidateQueries({queryKey:["/api/admin/meta-configs"]}),r.invalidateQueries({queryKey:["/api/admin/meta-config"]}),a({title:"Conta removida"})},onError:o=>a({title:"Erro",description:o.message,variant:"destructive"})}),c=W({mutationFn:o=>N("POST",`/api/admin/meta-configs/${o}/test`).then(L=>L.json()),onSuccess:o=>{r.invalidateQueries({queryKey:["/api/admin/meta-configs"]}),a({title:o.success?"Conexão OK":"Erro",description:o.success?`Conta: ${o.accountName}`:o.error})},onError:o=>a({title:"Erro ao testar",description:o.message,variant:"destructive"})}),m=W({mutationFn:o=>N("POST",`/api/admin/meta-configs/${o}/detect-page`).then(L=>L.json()),onSuccess:o=>{r.invalidateQueries({queryKey:["/api/admin/meta-configs"]}),p(L=>({...L,pageId:o.pageId,instagramAccountId:o.instagramAccountId||L.instagramAccountId})),a({title:`Página detectada: ${o.pageName}`,description:`Page ID: ${o.pageId}${o.instagramAccountId?` | IG: ${o.instagramAccountId}`:""}`})},onError:o=>a({title:"Erro ao detectar",description:o.message,variant:"destructive"})}),$=o=>{n(o.id),f(!1),p({name:o.name||"",accessToken:o.accessToken||"",adAccountId:o.adAccountId||"",pixelId:o.pixelId||"",pageId:o.pageId||"",appSecret:o.appSecret||"",instagramAccountId:o.instagramAccountId||"",isDefault:o.isDefault||!1})},D=()=>{n(null),f(!0),p({name:"",accessToken:"",adAccountId:"",pixelId:"",pageId:"",appSecret:"",instagramAccountId:"",isDefault:!1})},A=o=>e.jsxs("div",{className:"border border-violet-500/20 rounded-xl bg-violet-500/[0.03] p-5 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(O,{className:"text-xs mb-1.5 block",children:"Nome da Conta"}),e.jsx(J,{value:j.name,onChange:L=>p(v=>({...v,name:L.target.value})),placeholder:"Ex: BM Principal",className:"border-white/10 bg-white/5 text-xs","data-testid":"input-meta-account-name"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Meta Access Token"}),e.jsx(J,{type:"password",value:j.accessToken,onChange:L=>p(v=>({...v,accessToken:L.target.value})),placeholder:"EAAxxxxxxxx...",className:"border-white/10 bg-white/5 text-xs font-mono","data-testid":"input-meta-token"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Ad Account ID"}),e.jsx(J,{value:j.adAccountId,onChange:L=>p(v=>({...v,adAccountId:L.target.value})),placeholder:"act_XXXXXXXXX",className:"border-white/10 bg-white/5 text-xs font-mono","data-testid":"input-meta-account-id"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Facebook Page ID"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(J,{value:j.pageId,onChange:L=>p(v=>({...v,pageId:L.target.value})),placeholder:"XXXXXXXXXXXXXXX",className:"border-white/10 bg-white/5 text-xs font-mono flex-1","data-testid":"input-meta-page"}),o&&e.jsxs(b,{size:"sm",variant:"outline",className:"text-[10px] border-violet-500/30 text-violet-400 hover:bg-violet-500/10 whitespace-nowrap","data-testid":"btn-detect-page",onClick:()=>m.mutate(o),disabled:m.isPending,children:[m.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):null," Detectar"]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Meta Pixel ID"}),e.jsx(J,{value:j.pixelId,onChange:L=>p(v=>({...v,pixelId:L.target.value})),placeholder:"XXXXXXXXXXXXXXX",className:"border-white/10 bg-white/5 text-xs font-mono","data-testid":"input-meta-pixel"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Instagram Account ID"}),e.jsx(J,{value:j.instagramAccountId,onChange:L=>p(v=>({...v,instagramAccountId:L.target.value})),placeholder:"XXXXXXXXXXXXXXX",className:"border-white/10 bg-white/5 text-xs font-mono","data-testid":"input-instagram-id"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"App Secret (opcional)"}),e.jsx(J,{type:"password",value:j.appSecret,onChange:L=>p(v=>({...v,appSecret:L.target.value})),placeholder:"xxxxxxxx",className:"border-white/10 bg-white/5 text-xs font-mono","data-testid":"input-meta-secret"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[e.jsxs(b,{size:"sm",className:"bg-violet-600 hover:bg-violet-700 gap-1 text-xs","data-testid":"btn-save-meta-config",onClick:()=>y.mutate({id:o,payload:j}),disabled:y.isPending||!j.name,children:[y.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(is,{className:"w-3 h-3"})," Salvar"]}),e.jsx(b,{size:"sm",variant:"outline",className:"text-xs border-white/10",onClick:()=>{n(null),f(!1)},children:"Cancelar"})]})]});return w?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-violet-400"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white","data-testid":"text-meta-configs-title",children:"Contas Meta Ads"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Gerencie múltiplas contas do Meta Business Manager"})]}),e.jsxs(b,{size:"sm",className:"bg-violet-600 hover:bg-violet-700 gap-1 text-xs","data-testid":"btn-add-meta-config",onClick:D,children:[e.jsx(_t,{className:"w-3 h-3"})," Nova Conta"]})]}),u&&A(),g.map(o=>e.jsx("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4","data-testid":`card-meta-config-${o.id}`,children:l===o.id?A(o.id):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-violet-500/20 flex items-center justify-center",children:e.jsx(He,{className:"w-4 h-4 text-violet-400"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-white","data-testid":`text-meta-config-name-${o.id}`,children:o.name||"Sem nome"}),o.isDefault&&e.jsx(E,{className:"bg-violet-500/20 text-violet-400 border-violet-500/30 text-[9px]","data-testid":`badge-default-${o.id}`,children:"Padrão"}),o.connectionStatus==="connected"&&e.jsx(E,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-[9px]",children:"Conectado"}),o.connectionStatus==="error"&&e.jsx(E,{className:"bg-red-500/20 text-red-400 border-red-500/30 text-[9px]",children:"Erro"})]}),e.jsxs("p",{className:"text-[10px] text-white/40 font-mono",children:[o.adAccountId||"Sem Ad Account"," ",o.pixelId?`| Pixel: ${o.pixelId}`:""]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(b,{size:"sm",variant:"ghost",className:"h-7 px-2 text-[10px] text-white/50 hover:text-white","data-testid":`btn-test-config-${o.id}`,onClick:()=>c.mutate(o.id),disabled:c.isPending,children:[c.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(He,{className:"w-3 h-3"})," Testar"]}),!o.isDefault&&e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 px-2 text-[10px] text-violet-400 hover:text-violet-300","data-testid":`btn-set-default-${o.id}`,onClick:()=>y.mutate({id:o.id,payload:{isDefault:!0}}),children:"Definir Padrão"}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 px-2 text-[10px] text-white/50 hover:text-white","data-testid":`btn-edit-config-${o.id}`,onClick:()=>$(o),children:e.jsx(Ga,{className:"w-3 h-3"})}),!o.isDefault&&e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 px-2 text-[10px] text-red-400 hover:text-red-300","data-testid":`btn-delete-config-${o.id}`,onClick:()=>{confirm("Excluir esta conta?")&&F.mutate(o.id)},children:e.jsx(As,{className:"w-3 h-3"})})]})]})},o.id)),g.length===0&&!u&&e.jsx("div",{className:"text-center py-8 text-white/30 text-sm",children:'Nenhuma conta configurada. Clique em "Nova Conta" para começar.'})]})}function Qb(){const{user:a}=Sa(),r=!!a&&a.role==="admin",{toast:l}
2=st(),[n,u]=d.useState(new Set),[f,j]=d.useState(!1),[p,g]=d.useState(null),[w,y]=d.useState(""),[F,c]=d.useState({instagram:!0,facebook:!1}),{data:m,isLoading:$}=z({queryKey:["/api/admin/instagram-posts"],enabled:r}),{data:D}=z({queryKey:["/api/admin/instagram-posts/queue-status"],refetchInterval:3e4,enabled:r}),A=W({mutationFn:async M=>(await N("POST",`/api/admin/instagram-posts/publish/${M}`)).json(),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/instagram-posts"]}),K.invalidateQueries({queryKey:["/api/admin/instagram-posts/queue-status"]}),l({title:"Post enfileirado",description:"O post será publicado em breve"})},onError:M=>l({title:"Erro",description:M.message,variant:"destructive"})});W({mutationFn:async M=>(await N("POST",`/api/admin/instagram-posts/${M}/retry`)).json(),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/instagram-posts"]}),K.invalidateQueries({queryKey:["/api/admin/instagram-posts/queue-status"]}),l({title:"Retry enfileirado"})},onError:M=>l({title:"Erro",description:M.message,variant:"destructive"})});const o=W({mutationFn:async()=>(await N("POST","/api/admin/instagram-posts/backfill")).json(),onSuccess:M=>{K.invalidateQueries({queryKey:["/api/admin/instagram-posts"]}),K.invalidateQueries({queryKey:["/api/admin/instagram-posts/queue-status"]}),l({title:"Backfill iniciado",description:M.message})},onError:M=>l({title:"Erro",description:M.message,variant:"destructive"})}),L=W({mutationFn:async M=>(await N("POST","/api/admin/instagram-posts/publish-selected",{bookIds:M})).json(),onSuccess:M=>{K.invalidateQueries({queryKey:["/api/admin/instagram-posts"]}),K.invalidateQueries({queryKey:["/api/admin/instagram-posts/queue-status"]}),l({title:"Posts enfileirados",description:M.message}),u(new Set)},onError:M=>l({title:"Erro",description:M.message,variant:"destructive"})}),v=W({mutationFn:async M=>(await N("DELETE","/api/admin/instagram-posts/batch",{ids:M})).json(),onSuccess:M=>{K.invalidateQueries({queryKey:["/api/admin/instagram-posts"]}),l({title:"Posts removidos",description:M.message}),u(new Set),j(!1)},onError:M=>l({title:"Erro",description:M.message,variant:"destructive"})}),I=W({mutationFn:async M=>(await N("POST",`/api/admin/instagram-posts/${M}/regenerate`)).json(),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/instagram-posts"]}),l({title:"Regenerando",description:"Imagem e caption serão regenerados"}),g(null)},onError:M=>l({title:"Erro",description:M.message,variant:"destructive"})}),de=W({mutationFn:async({id:M,caption:ae})=>(await N("POST",`/api/admin/instagram-posts/${M}/update-caption`,{caption:ae})).json(),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/instagram-posts"]}),l({title:"Caption atualizado"})},onError:M=>l({title:"Erro",description:M.message,variant:"destructive"})}),me=W({mutationFn:async({id:M,instagram:ae,facebook:ye})=>(await N("POST",`/api/admin/instagram-posts/${M}/approve-publish`,{instagram:ae,facebook:ye})).json(),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/instagram-posts"]}),K.invalidateQueries({queryKey:["/api/admin/instagram-posts/queue-status"]}),l({title:"Publicação aprovada",description:"O post será publicado em breve"}),g(null)},onError:M=>l({title:"Erro",description:M.message,variant:"destructive"})}),ne=W({mutationFn:async()=>(await N("POST","/api/admin/instagram-posts/regenerate-all")).json(),onSuccess:M=>{K.invalidateQueries({queryKey:["/api/admin/instagram-posts"]}),l({title:"Regenerando todos",description:M.message||"Todos os posts serão regenerados"})},onError:M=>l({title:"Erro",description:M.message,variant:"destructive"})}),Z=M=>{u(ae=>{const ye=new Set(ae);return ye.has(M)?ye.delete(M):ye.add(M),ye})},S=()=>{m&&(n.size===m.length?u(new Set):u(new Set(m.map(M=>M.id))))},_=(m?.filter(M=>n.has(M.id))||[]).filter(M=>M.status==="pending"||M.status==="failed").map(M=>M.bookId),ee={pending:"Pendente",generating:"Gerando...",ready:"Pronto",publishing:"Publicando...",published:"Publicado",failed:"Falha"},h=M=>{const ae={published:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",failed:"bg-red-500/20 text-red-400 border-red-500/30",pending:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",generating:"bg-blue-500/20 text-blue-400 border-blue-500/30",publishing:"bg-purple-500/20 text-purple-400 border-purple-500/30",ready:"bg-teal-500/20 text-teal-400 border-teal-500/30"};return e.jsx(E,{className:ae[M]||"bg-white/10 text-white/60 border-white/10",children:ee[M]||M})},te=M=>{g(M),y(M.caption||""),c({instagram:!0,facebook:!1})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-bold text-white flex items-center gap-2",children:[e.jsx(ls,{className:"w-5 h-5 text-pink-400"})," Instagram Posts"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Posts automáticos do Instagram para @sabhia.books"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(b,{size:"sm",className:"bg-gradient-to-r from-amber-600 to-orange-600 hover:from-amber-700 hover:to-orange-700 gap-1 text-xs",onClick:()=>ne.mutate(),disabled:ne.isPending,"data-testid":"btn-ig-regenerate-all",children:[ne.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),"Regenerar Todos"]}),e.jsxs(b,{size:"sm",className:"bg-gradient-to-r from-pink-600 to-purple-600 hover:from-pink-700 hover:to-purple-700 gap-1 text-xs",onClick:()=>o.mutate(),disabled:o.isPending,"data-testid":"btn-ig-backfill",children:[o.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),"Backfill Novos"]})]})]}),D&&(D.queueLength>0||D.isProcessing)&&e.jsxs("div",{className:"border border-amber-500/30 rounded-lg p-3 bg-amber-500/10 flex items-center gap-3","data-testid":"ig-queue-status",children:[e.jsx(T,{className:"w-4 h-4 animate-spin text-amber-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm font-medium text-amber-300",children:["Fila ativa: ",D.queueLength," post",D.queueLength!==1?"s":""," aguardando"]}),e.jsxs("p",{className:"text-[10px] text-amber-300/60",children:[D.nextPublishInMin>0?`Próximo post em ~${D.nextPublishInMin} min`:"Processando agora...",D.estimatedCompletionMin>0&&` · Estimativa total: ~${D.estimatedCompletionMin} min`]})]})]}
2),e.jsx("div",{className:"grid grid-cols-5 gap-3",children:[{label:"Total",value:m?.length||0,color:"text-white"},{label:"Publicados",value:m?.filter(M=>M.status==="published").length||0,color:"text-emerald-400"},{label:"Pendentes",value:m?.filter(M=>M.status==="pending"||M.status==="generating"||M.status==="publishing"||M.status==="ready").length||0,color:"text-yellow-400"},{label:"Prontos",value:m?.filter(M=>M.status==="ready").length||0,color:"text-teal-400"},{label:"Falhas",value:m?.filter(M=>M.status==="failed").length||0,color:"text-red-400"}].map(M=>e.jsxs("div",{className:"border border-white/10 rounded-lg p-3 bg-white/[0.02] text-center",children:[e.jsx("p",{className:`text-xl font-bold ${M.color}`,children:M.value}),e.jsx("p",{className:"text-[10px] text-white/40",children:M.label})]},M.label))}),n.size>0&&e.jsxs("div",{className:"border border-teal-500/30 rounded-lg p-3 bg-teal-500/10 flex items-center justify-between","data-testid":"ig-selection-bar",children:[e.jsxs("p",{className:"text-sm text-teal-300",children:[n.size," selecionado",n.size!==1?"s":"",_.length>0&&` (${_.length} publicável${_.length!==1?"is":""})`]}),e.jsxs("div",{className:"flex items-center gap-2",children:[_.length>0&&e.jsxs(b,{size:"sm",className:"bg-gradient-to-r from-pink-600 to-purple-600 hover:from-pink-700 hover:to-purple-700 gap-1 text-xs h-7",onClick:()=>L.mutate(_),disabled:L.isPending,"data-testid":"btn-ig-publish-selected",children:[L.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(ct,{className:"w-3 h-3"}),"Publicar Selecionados"]}),e.jsxs(b,{size:"sm",variant:"destructive",className:"gap-1 text-xs h-7",onClick:()=>j(!0),"data-testid":"btn-ig-delete-selected",children:[e.jsx(As,{className:"w-3 h-3"}),"Remover Selecionados"]}),e.jsx(b,{size:"sm",variant:"ghost",className:"text-xs h-7 text-white/50",onClick:()=>u(new Set),"data-testid":"btn-ig-clear-selection",children:"Limpar"})]})]}),f&&e.jsxs("div",{className:"border border-red-500/30 rounded-lg p-4 bg-red-500/10","data-testid":"ig-delete-confirm",children:[e.jsxs("p",{className:"text-sm text-red-300 mb-3",children:["Tem certeza que deseja remover ",n.size," post",n.size!==1?"s":"","? Esta ação não pode ser desfeita."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{size:"sm",variant:"destructive",onClick:()=>v.mutate(Array.from(n)),disabled:v.isPending,"data-testid":"btn-ig-confirm-delete",children:[v.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):null,"Sim, Remover"]}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>j(!1),"data-testid":"btn-ig-cancel-delete",children:"Cancelar"})]})]}),$?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-white/40"})}):m?.length?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5",children:[e.jsx("input",{type:"checkbox",checked:m.length>0&&n.size===m.length,onChange:S,className:"w-4 h-4 rounded border-white/20 bg-white/5 accent-teal-500 cursor-pointer","data-testid":"checkbox-ig-select-all"}),e.jsx("span",{className:"text-[10px] text-white/40",children:n.size===m.length?"Desmarcar Todos":"Selecionar Todos"})]}),m.map(M=>e.jsxs("div",{className:`border rounded-lg p-3 flex items-start gap-3 transition-colors ${n.has(M.id)?"border-teal-500/40 bg-teal-500/5":"border-white/10 bg-white/[0.02] hover:bg-white/[0.04]"}`,"data-testid":`ig-post-${M.id}`,children:[e.jsx("input",{type:"checkbox",checked:n.has(M.id),onChange:()=>Z(M.id),className:"w-4 h-4 rounded border-white/20 bg-white/5 accent-teal-500 cursor-pointer flex-shrink-0 mt-1","data-testid":`checkbox-ig-post-${M.id}`}),M.imageUrl&&e.jsx("img",{src:M.imageUrl,alt:"",className:"w-20 h-25 object-cover rounded-lg flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-white truncate",children:M.bookTitle}),e.jsx("p",{className:"text-xs text-white/50",children:M.authorName}),M.caption&&e.jsx("p",{className:"text-[11px] text-white/40 line-clamp-2",children:M.caption.length>100?M.caption.substring(0,100)+"...":M.caption}),M.errorMessage&&e.jsx("p",{className:"text-[10px] text-red-400 truncate",children:M.errorMessage})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2 flex-shrink-0",children:[h(M.status),M.status==="published"&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[M.publishedAt&&e.jsx("span",{className:"text-[10px] text-white/30",children:new Date(M.publishedAt).toLocaleDateString("pt-BR")}),e.jsx(ls,{className:"w-3.5 h-3.5 text-pink-400"}),M.fbPostId?e.jsx("span",{className:"text-[10px] font-bold text-blue-400 bg-blue-500/20 px-1.5 py-0.5 rounded",title:"Publicado no Facebook",children:"FB ✓"}):e.jsx("span",{className:"text-[10px] font-bold text-white/20 bg-white/5 px-1.5 py-0.5 rounded",title:"Não postado no Facebook",children:"FB ✗"})]}),(M.status==="generating"||M.status==="publishing")&&e.jsx(T,{className:"w-4 h-4 animate-spin text-white/40"}),(M.status==="ready"||M.status==="failed")&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(b,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs text-white/70 hover:text-white",onClick:ae=>{ae.stopPropagation(),te(M)},"data-testid":`btn-ig-preview-${M.id}`,children:[e.jsx(ht,{className:"w-3 h-3 mr-1"}),"Preview"]}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs text-amber-400 hover:text-amber-300",onClick:ae=>{ae.stopPropagation(),I.mutate(M.id)},disabled:I.isPending,"data-testid":`btn-ig-regenerate-${M.id}`,children:e.jsx(xe,{className:"w-3 h-3"})})]}),M.status==="pending"&&e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:ae=>{ae.stopPropagation(),A.mutate(M.bookId)},disabled:A.isPending,"data-testid":`btn-ig-retry-${M.id}`,children:e.jsx(xe,{className:"w-3 h-3"})})]})]},M.id))]}):e.jsx("div",{className:"text-center py-8 text-white/40 text-sm",children:'Nenhum post do Instagram ainda. Clique em "Backfill Novos" para gerar posts para livros com capas.'}),e.jsx(Je,{open:!!p,onOpenChange:M=>{M||g(null)},children:e.jsxs(Ye,{className:"max-w-lg bg-[#0a0a0a] border-white/10 text-white p-0 overflow-hidden",children:[e.jsxs(Ze,{className:"px-6 pt-6 pb-0",children:[e.jsxs(et,{className:"text-white flex items-center gap-2",children:[e.jsx(ls,{className:"w-5 h-5 text-pink-400"}),"Preview do Post"]}),e.jsx(mt,{className:"text-white/50 text-xs",children:"Visualize e aprove o post antes de publicar"})]}),p&&e.jsxs("div",{className:"space-y-4 px-6 pb-6",children:[e.jsxs("div",{className:"border border-white/10 rounded-xl overflow-hidden bg-black",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-white/10",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-gradient-to-br from-pink-500 to-purple-600 flex items-center justify-center text-[10px] font-bold text-white",children:"S"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-white",children:"sabhia.books"}),e.jsx("p",{className:"text-[10px] text-white/40",children:"Patrocinado"})]})]}),p.imageUrl&&e.jsx("img",{src:p.imageUrl,alt:"",className:"w-full aspect-square object-cover"}),e.jsxs("div",{className:"px-3 py-2 flex items-center gap-4",children:[e.jsx(Ah,{className:"w-5 h-5 text-white/70 cursor-pointer hover:text-red-400 transition-colors"}),e.jsx(Ut,{className:"w-5 h-5 text-white/70 cursor-pointer hover:text-white transition-colors"}),e.jsx(ct,{className:"w-5 h-5 text-white/70 cursor-pointer hover:text-white transition-colors"})]}),e.jsx("div",{className:"px-3 pb-2",children:e.jsxs("p",{className:"text-xs text-white/50",children:[e.jsx("span",{className:"font-semibold text-white text-xs",children:"sabhia.books"})," ",p.caption?.substring(0,80),"..."]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-xs text-white/60",children:"Caption"}),e.jsx($s,{value:w,onChange:M=>y(M.target.value),className:"bg-white/5 border-white/10 text-white text-sm min-h-[120px] resize-none","data-testid":"textarea-ig-caption"})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer","data-testid":"checkbox-ig-target-instagram",children:[e.jsx("input",{type:"checkbox",checked:F.instagram,onChange:M=>c(ae=>({...ae,instagram:M.target.checked})),className:"w-4 h-4 rounded border-white/20 bg-white/5 accent-pink-500"}),e.jsx(ls,{className:"w-4 h-4 text-pink-400"}),e.jsx("span",{className:"text-sm text-white/80",children:"Instagram"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer","data-testid":"checkbox-ig-target-facebook",children:[e.jsx("input",{type:"checkbox",checked:F.facebook,onChange:M=>c(ae=>({...ae,facebook:M.target.checked})),className:"w-4 h-4 rounded border-white/20 bg-white/5 accent-blue-500"}),e.jsx("span",{className:"text-[11px] font-bold text-blue-400 bg-blue-500/20 px-1.5 py-0.5 rounded",children:"FB"}),e.jsx("span",{className:"text-sm text-white/80",children:"Facebook Page"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 flex-wrap",children:[e.jsxs(b,{size:"sm",className:"bg-gradient-to-r from-pink-600 to-purple-600 hover:from-pink-700 hover:to-purple-700 gap-1 text-xs",onClick:()=>me.mutate({id:p.id,instagram:F.instagram,facebook:F.facebook}),disabled:me.isPending||!F.instagram&&!F.facebook,"data-testid":"btn-ig-approve-publish",children:[me.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(ct,{className:"w-3 h-3"}),"Publicar"]}),e.jsxs(b,{size:"sm",className:"bg-gradient-to-r from-amber-600 to-orange-600 hover:from-amber-700 hover:to-orange-700 gap-1 text-xs",onClick:()=>I.mutate(p.id),disabled:I.isPending,"data-testid":"btn-ig-regenerate-preview",children:[I.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),"Regenerar Imagem"]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"gap-1 text-xs text-white/60 hover:text-white",onClick:()=>de.mutate({id:p.id,caption:w}),disabled:de.isPending,"data-testid":"btn-ig-save-caption",children:[de.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(Ga,{className:"w-3 h-3"}),"Salvar Caption"]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"gap-1 text-xs text-white/40 hover:text-white",onClick:()=>g(null),"data-testid":"btn-ig-close-preview",children:[e.jsx(ea,{className:"w-3 h-3"}),"Fechar"]})]})]})]})})]})}function uh({orderId:a,userId:r,compact:l=!1}){const n=$a(),{toast:u}=st(),f=W({mutationFn:async()=>(await N("POST",`/api/admin/orders/${a}/recheck-payment`)).json(),onSuccess:j=>{const p=j?.failure,g=j?.stripeStatus;u(p?{title:`Cartão recusado · ${p.messagePtBR}`,description:`${p.card?.brand?.toUpperCase()||"Cartão"} ···${p.card?.last4||"????"} · ${p.declineCode||p.code||"sem código"}`,variant:"destructive"}:g==="succeeded"?{title:"Pagamento confirmado no Stripe",description:"Stripe diz que esse PaymentIntent foi pago. Verifique se o webhook processou — pode ser necessário reconciliar manualmente."}:{title:`Stripe: ${{requires_payment_method:"Aguardando novo método de pagamento (cliente não retentou após re
2cusa)",requires_confirmation:"Aguardando confirmação do cliente",requires_action:"Aguardando ação 3DS do cliente",processing:"Em processamento no Stripe",canceled:"PaymentIntent cancelado no Stripe",requires_capture:"Autorizado, aguardando captura"}[g]||g||"sem status"}`,description:"Sem registro de falha. Stripe ainda não recusou nem confirmou."}),n.invalidateQueries({queryKey:[`/api/admin/users/${r}/journey`]})},onError:j=>{u({title:"Falha ao verificar",description:j?.message||"Erro desconhecido",variant:"destructive"})}});return e.jsxs(b,{size:"sm",variant:"ghost",className:`h-6 px-2 text-[10px] gap-1 ${l?"text-white/40 hover:text-white/80":"text-current hover:opacity-80"}`,onClick:j=>{j.stopPropagation(),f.mutate()},disabled:f.isPending,"data-testid":`btn-recheck-payment-${a}`,children:[f.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),l?"Verificar pagamento":"Verificar de novo"]})}function Wb({userId:a,isExpanded:r}){const{user:l}=Sa(),n=!!l&&l.role==="admin",{data:u,isLoading:f}=z({queryKey:[`/api/admin/users/${a}/journey`],queryFn:()=>N("GET",`/api/admin/users/${a}/journey`).then(L=>L.json()),enabled:n&&r,staleTime:6e4}),[j,p]=d.useState(!1);if(!r)return null;if(f)return e.jsxs("div",{className:"rounded-lg bg-cyan-500/5 border border-cyan-500/10 p-4 flex items-center justify-center gap-2",children:[e.jsx(T,{className:"w-4 h-4 animate-spin text-cyan-400"}),e.jsx("span",{className:"text-xs text-white/40",children:"Carregando jornada..."})]});if(!u||u.timeline.length===0)return e.jsxs("div",{className:"rounded-lg bg-cyan-500/5 border border-cyan-500/10 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-cyan-400"}),e.jsx("span",{className:"text-sm font-medium text-white",children:"Jornada do Cliente"})]}),e.jsx("p",{className:"text-[11px] text-white/30",children:"Sem dados de jornada disponíveis"})]});const g=L=>{const v=new Date(L),de=new Date().getTime()-v.getTime(),me=Math.floor(de/6e4);if(me<60)return`há ${me}min`;const ne=Math.floor(me/60);if(ne<24)return`há ${ne}h`;const Z=Math.floor(ne/24);return Z<30?`há ${Z}d`:v.toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})},w=L=>new Date(L).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),y={method_switch:"Trocou método de pagamento",bump_change:"Alterou itens do pedido",superseded:"Novo pedido criado",expired:"Expirado (tempo limite)"},F=(L,v)=>{switch(L){case"touchpoint":return e.jsx(pt,{className:"w-3.5 h-3.5 text-cyan-400"});case"registration":return e.jsx(is,{className:"w-3.5 h-3.5 text-emerald-400"});case"chat_session":return e.jsx(Ut,{className:"w-3.5 h-3.5 text-violet-400"});case"event":return v.eventName==="Lead"?e.jsx(lt,{className:"w-3.5 h-3.5 text-sky-400"}):v.eventName==="CompleteRegistration"?e.jsx(be,{className:"w-3.5 h-3.5 text-emerald-400"}):v.eventName==="InitiateCheckout"?e.jsx(Jt,{className:"w-3.5 h-3.5 text-orange-400"}):v.eventName==="AddToCart"?e.jsx(Jt,{className:"w-3.5 h-3.5 text-amber-400"}):v.eventName==="Purchase"?e.jsx(is,{className:"w-3.5 h-3.5 text-emerald-400"}):v.eventName==="AddPaymentInfo"?e.jsx(Bt,{className:"w-3.5 h-3.5 text-blue-400"}):e.jsx(He,{className:"w-3.5 h-3.5 text-white/40"});case"order":return v.status==="confirmed"||v.status==="completed"?e.jsx(is,{className:"w-3.5 h-3.5 text-emerald-400"}):v.status==="pending"?e.jsx(ns,{className:"w-3.5 h-3.5 text-amber-400"}):v.status==="cancelled"&&v.cancelReason?e.jsx(dt,{className:"w-3.5 h-3.5 text-white/30"}):e.jsx(dt,{className:"w-3.5 h-3.5 text-red-400"});case"order_group":return e.jsx(dt,{className:"w-3.5 h-3.5 text-white/30"});default:return e.jsx(jt,{className:"w-3.5 h-3.5 text-white/40"})}},c=(L,v)=>{switch(L){case"touchpoint":return"border-cyan-500/30";case"registration":return"border-emerald-500/30";case"chat_session":return"border-violet-500/30";case"order":return v.status==="confirmed"||v.status==="completed"?"border-emerald-500/30":v.status==="cancelled"&&v.cancelReason?"border-white/10":"border-amber-500/30";case"order_group":return"border-white/10";case"event":return v.eventName==="Purchase"?"border-emerald-500/30":"border-sky-500/30";default:return"border-white/10"}},m=L=>{if(!L)return null;const v=[];return L.campaignName&&v.push(L.campaignName),L.adSetName&&v.push(L.adSetName),L.adName&&v.push(L.adName),v.length===0?null:e.jsxs("span",{className:"text-[10px] text-cyan-300/80 flex items-center gap-1 flex-wrap",children:[e.jsx(Xt,{className:"w-2.5 h-2.5 text-cyan-400/60 shrink-0"}),v.map((I,de)=>e.jsxs(Kl.Fragment,{children:[de>0&&e.jsx(ya,{className:"w-2.5 h-2.5 text-white/20 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",title:I,children:I})]},de))]})},$=L=>{const{type:v,data:I}=L;switch(v){case"touchpoint":{const de=I.ad?"Facebook Ads":I.utmSource||(I.referrer?"Referral":"Direto");let me=null;try{me=I.landingPage?new URL(I.landingPage,"https://sabhia.ai").pathname:null}catch{me=I.landingPage||null}const ne=me==="/"?"Landing Page":me==="/chat"?"Chat":me==="/create-my-book"?"Criar Livro":me;return e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("p",{className:"text-[11px] text-white/80",children:["Visitou via ",e.jsx("span",{className:"text-cyan-300 font-medium",children:de}),ne&&e.jsxs(e.Fragment,{children:[" ","→"," ",e.jsx("span",{className:"text-teal-300",children:ne})]})]}),m(I.ad),I.referrer&&!I.utmSource&&e.jsxs("p",{className:"text-[10px] text-white/30 truncate",title:I.referrer,children:["Ref
2: ",I.referrer]})]})}case"registration":return e.jsx("p",{className:"text-[11px] text-emerald-300 font-medium",children:"Se cadastrou na plataforma"});case"chat_session":return e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("p",{className:"text-[11px] text-white/80",children:["Iniciou chat de criação",I.bookTitle&&e.jsxs(e.Fragment,{children:[" ","—"," ",e.jsxs("span",{className:"text-violet-300 font-medium",children:['"',I.bookTitle,'"']})]})]}),I.convertedAt&&e.jsx("p",{className:"text-[10px] text-emerald-400/70",children:"Converteu no chat"}),m(I.ad)]});case"event":{const de={Lead:"Captura de lead",CompleteRegistration:"Registro completo",InitiateCheckout:"Iniciou checkout",AddToCart:"Adicionou ao carrinho",Purchase:"Evento de compra",AddPaymentInfo:"Informou dados de pagamento"};return e.jsx("p",{className:"text-[11px] text-white/80",children:de[I.eventName]||I.eventName})}case"order":{const de={confirmed:"Pago",completed:"Pago",pending:"Pendente",expired:"Expirado",failed:"Falhou"},me={pix:"PIX",card:"Cartão",credits:"Créditos"};if(I.status==="cancelled"&&I.cancelReason)return e.jsxs("p",{className:"text-[11px] text-white/30",children:["Cancelado — ",e.jsx("span",{className:"text-white/40",children:y[I.cancelReason]||I.cancelReason}),I.paymentMethod&&e.jsxs("span",{className:"text-white/20",children:[" (",me[I.paymentMethod]||I.paymentMethod,")"]})]});const ne=I.paymentFailure,Z=I.status==="pending"&&ne&&(I.paymentMethod==="card"||I.paymentMethod==="credit_card"),S={fraud:"border-red-500/40 bg-red-500/15 text-red-200",hard:"border-orange-500/40 bg-orange-500/15 text-orange-200",soft:"border-amber-500/40 bg-amber-500/15 text-amber-200",unknown:"border-white/15 bg-white/5 text-white/60"};return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-[11px] text-white/80",children:[I.status==="confirmed"||I.status==="completed"?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-emerald-300 font-medium",children:"Comprou"})," ","—"," R$ ",Number(I.amount).toFixed(2)]}):I.status==="cancelled"?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-white/40",children:"Cancelado"})," ","—"," R$ ",Number(I.amount).toFixed(2)]}):Z?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-red-300 font-medium",children:"Cartão recusado"})," ","—"," R$ ",Number(I.amount).toFixed(2)]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:I.status==="pending"?"text-amber-300":"text-red-300",children:de[I.status]||I.status})," ","—"," R$ ",Number(I.amount).toFixed(2)]}),I.paymentMethod&&e.jsxs("span",{className:"text-white/40",children:[" (",me[I.paymentMethod]||I.paymentMethod,")"]})]}),Z&&e.jsxs("div",{className:`rounded-md border px-2 py-1.5 text-[10px] ${S[ne.severity]||S.unknown}`,"data-testid":`payment-failure-${I.id}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:ne.messagePtBR}),ne.card?.brand&&ne.card?.last4&&e.jsxs("span",{className:"opacity-80",children:["· ",String(ne.card.brand).toUpperCase()," ···",ne.card.last4]}),ne.declineCode&&e.jsxs("span",{className:"opacity-60 font-mono",children:["· ",ne.declineCode]})]}),ne.message&&ne.message!==ne.messagePtBR&&e.jsxs("div",{className:"mt-0.5 opacity-70 italic truncate",title:ne.message,children:['"',ne.message,'"']}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[I.stripeUrl&&e.jsx("a",{href:I.stripeUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] underline underline-offset-2 hover:opacity-80","data-testid":`link-stripe-${I.id}`,children:"Ver no Stripe ↗"}),e.jsx(uh,{orderId:I.id,userId:a})]})]}),!ne&&I.status==="pending"&&(I.paymentMethod==="card"||I.paymentMethod==="credit_card")&&I.stripePaymentIntentId&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uh,{orderId:I.id,userId:a,compact:!0}),I.stripeUrl&&e.jsx("a",{href:I.stripeUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-white/40 hover:text-white/70 underline underline-offset-2",children:"Stripe ↗"})]}),m(I.ad)]})}case"order_group":{const de={pix:"PIX",card:"Cartão",credits:"Créditos"};return e.jsxs("p",{className:"text-[11px] text-white/30",children:[I.count," pedido",I.count>1?"s":""," cancelado",I.count>1?"s":""," — ",e.jsx("span",{className:"text-white/40",children:y[I.cancelReason]||I.cancelReason}),I.paymentMethod&&e.jsxs("span",{className:"text-white/20",children:[" (",de[I.paymentMethod]||I.paymentMethod,")"]})]})}default:return null}},{summary:D}=u,A=j?u.timeline:u.timeline.slice(0,8),o=u.timeline.length>8;return e.jsxs("div",{className:"rounded-lg bg-cyan-500/5 border border-cyan-500/10 p-3 space-y-3","data-testid":`journey-timeline-${a}`,children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-cyan-400"}),e.jsx("span",{className:"text-sm font-medium text-white",children:"Jornada do Cliente"}),e.jsxs(E,{variant:"outline",className:"text-[9px] border-white/10 text-white/40",children:[u.timeline.length," eventos"]})]})}),D.adAttribution&&e.jsxs("div",{className:"flex items-center gap-2 bg-cyan-500/10 rounded-md px-2.5 py-1.5 text-[10px]",children:[e.jsx(Xt,{className:"w-3 h-3 text-cyan-400 shrink-0"}),e.jsx("span",{className:"text-white/50",children:"Origem:"}),e.jsx("span",{className:"text-cyan-300 font-medium",children:D.source}),e.jsx(ya,{className:"w-3 h-3 text-white/20"}),e.jsx("span",{className:"text-cyan-300 truncate",title:D.adAttribution.campaignName,children:D.adAttribution.campaignName}),e.jsx(ya,{className:"w-3 h-3 text-white/20"}),e.jsx("span",{className:"text-cyan-300 truncate",title:D.adAttribution.adName,children:D.adAttribution.adName}),D.landingPage&&e.jsxs(e.Fragment,{children:[e.jsx(ya,{className:"w-3 h-3 text-white/20"}),e.jsx("span",{className:"text-teal-300",children:(()=>{try{return new URL(D.landingPage,"https://sabhia.ai").pathname}catch{return D.landingPage}})()})]})]}),!D.adAttribution&&e.jsxs("div",{className:"flex items-center gap-2 bg-white/[0.03] rounded-md px-2.5 py-1.5 text-[10px]",children:[e.jsx(pt,{className:"w-3 h-3 text-white/30 shrink-0"}),e.jsx("span",{className:"text-white/50",children:"Origem:"}),e.jsx("span",{className:"text-white/70",children:D.source}),D.landingPage&&e.jsxs(e.Fragment,{children:[e.jsx(ya,{className:"w-3 h-3 text-white/20"}),e.jsx("span",{className:"text-teal-300",children:(()=>{try{return new URL(D.landingPage,"https://sabhia.ai").pathname}catch{return D.landingPage}})()})]})]}),e.jsxs("div",{className:"flex gap-3 text-[10px] text-white/40",children:[D.firstVisit&&e.jsxs("span",{children:["Primeiro acesso: ",e.jsx("span",{className:"text-white/60",children:g(D.firstVisit)})]}),D.registeredAt&&e.jsxs("span",{children:["Cadastro: ",e.jsx("span",{className:"text-white/60",children:g(D.registeredAt)})]}),D.firstPurchaseAt&&e.jsxs("span",{children:["1a compra: ",e.jsx("span",{className:"text-emerald-400/70",children:g(D.firstPurchaseAt)})]}),D.totalOrders>0&&e.jsxs("span",{title:"Apenas PIX/cartão. Pedidos pagos com créditos não somam aqui (cash já entrou no pacote original).",children:[D.totalOrders," pedido",D.totalOrders>1?"s":""," ","—"," ",e.jsxs("span",{className:"text-emerald-400/70",children:["R$ ",D.totalRevenue.toFixed(2)]})," ",e.jsx("span",{className:"text-emerald-400/40",children:"· cash"}),Number(D.creditsRevenue||0)>0&&e.jsxs("span",{className:"text-amber-400/60",children:[" · + R$ ",Number(D.creditsRevenue).toFixed(2)," em créditos"]})]})]}),e.jsxs("div",{className:"relative pl-4",children:[e.jsx("div",{className:"absolute left-[7px] top-2 bottom-2 w-px bg-gradient-to-b from-cyan-500/30 via-white/10 to-transparent"}),e.jsx("div",{className:"space-y-2",children:A.map((L,v)=>e.jsxs("div",{className:"relative flex items-start gap-2.5 group",children:[e.jsx("div",{className:`absolute left-[-13px] top-1.5 w-[15px] h-[15px] rounded-full border-2 ${c(L.type,L.data)} bg-[#0d0d1a] flex items-center justify-center z-10`,children:F(L.type,L.data)}),e.jsx("div",{className:"flex-1 ml-1 min-w-0",children:$(L)}),e.jsx("span",{className:"text-[9px] text-white/25 shrink-0 mt-0.5 tabular-nums",title:L.timestamp?w(L.timestamp):"",children:L.timestamp?g(L.timestamp):""})]},v))})]}),o&&e.jsx("button",{onClick:()=>p(!j),className:"text-[10px] text-cyan-400/60 hover:text-cyan-400 transition-colors flex items-center gap-1 ml-4","data-testid":`btn-show-all-journey-${a}`,children:j?e.jsxs(e.Fragment,{children:[e.jsx(ta,{className:"w-3 h-3"})," Mostrar menos"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-3 h-3"})," Ver todos os ",u.timeline.length," eventos"]})})]})}function gh({testIdPrefix:a,loading:r,error:l,data:n,value:u,onChange:f,showDiagnostics:j,onToggleDiagnostics:p,manualMode:g,onToggleManual:w,manualPageId:y,onManualPageId:F,manualIgId:c,onManualIgId:m,onRefetch:$,applyAllText:D}){const A=n?.pages||[],o=A.length>0,L=A.find(v=>v.id===u);return e.jsxs("div",{"data-testid":`${a}-page-selector`,className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(lt,{className:"w-3 h-3 text-teal-400"})," Página do Facebook & Instagram"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:$,className:"text-[10px] text-white/40 hover:text-white/70 transition-colors flex items-center gap-1","data-testid":`button-${a}-refresh-pages`,title:"Recarregar lista de páginas",children:e.jsx(xe,{className:`w-3 h-3 ${r?"animate-spin":""}`})}),(n?.diagnostics?.length||0)>0&&e.jsxs("button",{type:"button",onClick:p,className:"text-[10px] text-violet-300/70 hover:text-violet-200 transition-colors flex items-center gap-1","data-testid":`button-${a}-toggle-diagnostics`,children:[e.jsx(js,{className:"w-3 h-3"}),j?"Ocultar diagnóstico":"Diagnosticar"]})]})]}),r?e.jsxs("div",{className:"w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white/50 flex items-center gap-2",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"})," Descobrindo páginas (User token + Business Manager)..."]}):l?e.jsxs("div",{className:"w-full bg-rose-500/10 border border-rose-500/30 rounded-lg px-3 py-2 text-xs text-rose-300",children:["Erro ao listar páginas: ",l.message,". Os anúncios usarão a configuração padrão da conta."]}):g?e.jsxs("div",{className:"space-y-2 bg-white/[0.02] border border-violet-500/20 rounded-lg p-3",children:[e.jsxs("p",{className:"text-[11px] text-violet-300/80 flex items-center gap-1.5",children:[e.jsx(Ga,{className:"w-3 h-3"})," Inserção manual — use quando o ID da página é conhecido mas não aparece na lista."]}),e.jsx("input",{type:"text",value:y,onChange:v=>{F(v.target.value),f(v.target.value.trim())},placeholder:"ID da Página do Facebook (ex: 102837465198765)",className:"w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white","data-testid":`input-${a}-manual-page-id`}),e.jsx("input",{type:"text",value:c,onChange:v=>m(v.target.value),placeholder:"ID do Instagram Business (opcional, ex: 17841405822304914)",className:"w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white","data-testid":`input-${a}-manual-ig-id`}),e.jsx("button",{type:"button",onClick:()=>{w(),F(""),m(""),f("")},className:"text-[11px] text-white/50 hover:text-white/80","data-testid":`button-${a}-cancel-manual`,children:"← Voltar para a lista"})]}):o?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("select",{"data-testid":`select-${a}-page`,className:"w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white",value:u,onChange:v=>f(v.target.value),children:[e.jsxs("option",{value:"",children:["Padrão da conta",n?.configured?.pageId?` (Page ${n.configured.pageId.slice(-6)}${n.configured.instagramAccountId?" + IG":""})`:""]}),A.map(v=>e.jsxs("option",{value:v.id,children:[v.name,v.instagram?` + @${v.instagram.username||v.instagram.name||"IG"}`:" (sem IG vinculado)"]},v.id))]}),e.jsxs("button",{type:"button",onClick:w,className:"text-[10px] text-white/40 hover:text-violet-300 flex items-center gap-1","data-testid":`button-${a}-enter-manual`,children:[e.jsx(Ga,{className:"w-3 h-3"})," Não vê sua página? Inserir ID manualmente"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"w-full bg-amber-500/10 border border-amber-500/30 rounded-lg px-3 py-2.5 text-xs text-amber-200/90 space-y-1.5",children:[e.jsxs("p",{className:"font-medium flex items-center gap-1.5",children:[e.jsx(Xe,{className:"w-3.5 h-3.5"})," Nenhuma página descoberta automaticamente."]}),e.jsxs("p",{className:"text-amber-200/70 leading-relaxed",children:["Isso é normal para tokens de ",e.jsx("strong",{children:"System User"})," sem permissão ",e.jsx("code",{className:"text-amber-300",children:"business_management"}),", ou quando o Business Manager não foi detectado a partir da conta de anúncios. A publicação ainda funciona usando a página configurada",n?.configured?.pageId?e.jsxs(e.Fragment,{children:[" (atual: ",e.jsx("code",{className:"text-amber-300",children:n.configured.pageId}),")"]}):"","."]})]}),e.jsxs("button",{type:"button",onClick:w,className:"text-[11px] text-violet-300 hover:text-violet-200 flex items-center gap-1","data-testid":`button-${a}-enter-manual`,children:[e.jsx(Ga,{className:"w-3 h-3"})," Inserir ID da página manualmente"]})]}),u&&L&&!g&&e.jsxs("p",{className:"text-[10px] text-teal-300/70",children:[D?"Todos os anúncios deste lote serão vinculados à página ":"Anúncios serão vinculados à página ",e.jsx("strong",{children:L.name}),L.instagram?` e ao Instagram @${L.instagram.username||L.instagram.name}`:D?" (sem Instagram — anúncios apenas no Facebook)":" (sem Instagram — anúncio será apenas no Facebook)","."]}),u&&g&&y&&e.jsxs("p",{className:"text-[10px] text-violet-300/70",children:["Anúncios serão vinculados à página ",e.jsx("code",{className:"text-violet-200",children:y}),c?e.jsxs(e.Fragment,{children:[" e ao Instagram ",e.jsx("code",{className:"text-violet-200",children:c})]}):" (sem Instagram)","."]}),j&&n?.diagnostics&&e.jsxs("div",{className:"bg-violet-500/5 border border-violet-500/20 rounded-lg p-3 space-y-2 text-[11px]",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-violet-200 font-medium flex items-center gap-1.5",children:[e.jsx(js,{className:"w-3 h-3"})," Diagnóstico da descoberta"]}),n.tokenTypeHint&&e.jsx("span",{className:"text-[10px] text-violet-300/60",children:n.tokenTypeHint})]}),n.businesses&&n.businesses.length>0&&e.jsxs("div",{className:"text-[10px] text-violet-300/80",children:["Business Managers: ",n.businesses.map(v=>`${v.name} (${v.id}
2)`).join(", ")]}),e.jsx("div",{className:"space-y-1",children:n.diagnostics.map((v,I)=>e.jsxs("div",{className:"flex items-start gap-2 font-mono text-[10px]",children:[e.jsxs("span",{className:`shrink-0 px-1.5 py-0.5 rounded ${v.status==="ok"?"bg-emerald-500/20 text-emerald-300":v.status==="empty"?"bg-white/10 text-white/50":"bg-rose-500/20 text-rose-300"}`,children:[v.status==="ok"?"✓":v.status==="empty"?"∅":"✗"," ",v.count]}),e.jsx("span",{className:"text-violet-200/90 break-all",children:v.source}),v.detail&&e.jsxs("span",{className:"text-white/50 break-all",children:["— ",v.detail]})]},I))}),e.jsxs("p",{className:"text-[10px] text-violet-300/50 leading-relaxed pt-1 border-t border-violet-500/10",children:["Tentamos: lista pessoal (",e.jsx("code",{children:"/me/accounts"}),"), Business descoberto pela conta de anúncios, e todos os Business Managers acessíveis (",e.jsx("code",{children:"owned_pages"})," + ",e.jsx("code",{children:"client_pages"}),"). Se nenhuma página apareceu mas você sabe o ID, use a inserção manual acima."]})]})]})}function SN(){const{user:a}=Sa(),{toast:r}=st(),[l,n]=d.useState({...bc}),[u,f]=d.useState(null),[j,p]=d.useState(!1),[g,w]=d.useState(null),[y,F]=d.useState(""),[c,m]=d.useState("all"),[$,D]=d.useState("all"),[A,o]=d.useState("list"),[L,v]=d.useState(null),I=50,[de,me]=d.useState(I);d.useEffect(()=>{me(I),v(null)},[y,c,$]);const[ne,Z]=d.useState("");d.useEffect(()=>{const t=setTimeout(()=>Z(y.trim()),400);return()=>clearTimeout(t)},[y]);const S=ne.length>=2,[re,_]=d.useState(""),[ee,h]=d.useState("all"),[te,M]=d.useState(""),[ae,ye]=d.useState(null),[Me,se]=d.useState(!1),[Ne,ie]=d.useState("all"),[X,B]=d.useState("all"),[ge,ut]=d.useState("all"),[at,$t]=d.useState("all"),[pa,Ms]=d.useState(0),[fe,sa]=d.useState(null),[Ha,Aa]=d.useState(!1),[Tn,ki]=d.useState(!1),[le,aa]=d.useState("metrics"),[Pa,Ji]=d.useState(null),[Kt,R]=d.useState("services"),[Ee,ds]=d.useState(30),[Yi,Yt]=d.useState(30),[Xa,Ar]=d.useState(null),[Ci,k]=d.useState(null),[q,V]=d.useState(null),[ce,he]=d.useState(null),[ke,xt]=d.useState(""),[At,Zt]=d.useState(""),[os,Ta]=d.useState(""),[Ps,Zi]=d.useState(""),[Ns,Mc]=d.useState({}),[Pr,Ih]=d.useState({}
2),[Lc,zc]=d.useState(null),[td,qc]=d.useState(null),[sd,Rh]=d.useState(null),[ad,Fh]=d.useState(null),[ia,En]=d.useState(null),[_c,Oc]=d.useState(!1),[id,Tr]=d.useState(""),[Ts,Ja]=d.useState(null),[Bc,Uc]=d.useState(!1);d.useEffect(()=>{L&&!(L in Ns)&&N("GET",`/api/admin/users/${L}/credits`).then(t=>t.json()).then(t=>Mc(s=>({...s,[L]:t.balance??0}))).catch(()=>{})},[L]);const Dh=async t=>{zc(t);try{const i=await(await N("POST",`/api/admin/users/${t}/magic-link`)).json();Ih(x=>({...x,[t]:{link:i.magicLink,expiresAt:i.expiresAt}})),await navigator.clipboard.writeText(i.magicLink),r({title:"Link mágico gerado e copiado!",description:"Válido por 10 minutos. Envie ao cliente."})}catch(s){r({title:"Erro ao gerar link",description:s.message,variant:"destructive"})}finally{zc(null)}},Mh=async t=>{qc(t);try{const s=await N("POST",`/api/admin/users/${t}/dossie-to-woovi`);if(!s.ok){const x=await s.json().catch(()=>({}));throw new Error(x.error||`Erro ${s.status}`)}const i=await s.json();r({title:"✅ Dossiê enviado para a Woovi!",description:i.message||"Evidência submetida com sucesso para a disputa MED."})}catch(s){r({title:"Falha ao enviar para Woovi",description:s.message||"Erro desconhecido. Verifique a aba MED no admin.",variant:"destructive"})}finally{qc(null)}},Kc=async(t,s,i,x)=>{x(t),r({description:i==="dossie-zip"?"Montando dossiê dividido (ZIP)... pode levar alguns minutos.":"Gerando dossiê... pode levar alguns minutos."});try{const C=await N("GET",`/api/admin/users/${t}/${i}`,void 0,{timeoutMs:9e5});if(!C.ok){const Oe=await C.json().catch(()=>({}));throw new Error(Oe.message||Oe.error||`Erro ${C.status}`)}const P=await C.blob(),H=(s||"cliente").replace(/[^a-zA-Z0-9À-ÿ\s]/g,"").replace(/\s+/g,"_").substring(0,50),Q=new Date().toISOString().split("T")[0].replace(/-/g,""),G=i==="dossie-zip"?"zip":"pdf",ue=i==="dossie-zip"?"_dividido":"",Te=window.URL.createObjectURL(P),Y=document.createElement("a");Y.href=Te,Y.download=`DOSSIE_${H}_${Q}${ue}.${G}`,document.body.appendChild(Y),Y.click(),Y.remove(),window.URL.revokeObjectURL(Te),r({title:"✅ Dossiê pronto",description:"O download foi iniciado."})}catch(C){r({title:"Falha ao gerar dossiê",description:C.message||"Erro desconhecido. Tente novamente em instantes.",variant:"destructive"})}finally{x(null)}},{data:rd}=z({queryKey:["/api/admin/course/access"],staleTime:3e4}),Lh=new Set((rd?.betaUsers||[]).map(t=>t.id)),nd=W({mutationFn:async({userId:t,email:s,grant:i})=>i?(await N("POST","/api/admin/course/access/beta-users",{email:s})).json():(await N("DELETE",`/api/admin/course/access/beta-users/${t}`)).json(),onSuccess:(t,s)=>{K.invalidateQueries({queryKey:["/api/admin/course/access"]}),r({title:s.grant?"Acesso ao Curso liberado!":"Acesso ao Curso removido",description:s.grant?"O cliente já pode ver o painel CURSOS no menu.":"O cliente não verá mais o painel CURSOS."})},onError:t=>{r({title:"Erro ao alterar acesso ao Curso",description:t?.message||"Falha desconhecida",variant:"destructive"})}}),{data:Gc}=z({queryKey:["/api/sabhia-pay/admin/access"],staleTime:3e4}),zh=new Set((Gc?.betaUsers||[]).map(t=>t.id)),ld=W({mutationFn:async({userId:t,email:s,grant:i})=>i?(await N("POST","/api/sabhia-pay/admin/access/beta-users",{email:s})).json():(await N("DELETE",`/api/sabhia-pay/admin/access/beta-users/${t}`)).json(),onSuccess:(t,s)=>{K.invalidateQueries({queryKey:["/api/sabhia-pay/admin/access"]}),r({title:s.grant?"Acesso ao Sábhia Pay liberado!":"Acesso ao 
2Sábhia Pay removido",description:s.grant?"O cliente já pode acessar o painel Sábhia Pay.":"O cliente não terá mais acesso ao painel Sábhia Pay."})},onError:t=>{r({title:"Erro ao alterar acesso ao Sábhia Pay",description:t?.message||"Falha desconhecida",variant:"destructive"})}}),qh=async(t,s)=>{if(s.trim()){Uc(!0);try{const x=await(await N("GET",`/api/admin/users?search=${encodeURIComponent(s.trim())}`)).json(),P=(x.users||x||[]).find(H=>H.email===s.trim());P?P.id===t.id?(r({title:"Mesma conta",description:"Não é possível mesclar uma conta com ela mesma.",variant:"destructive"}),Ja(null)):Ja({sourceUser:t,targetUser:P}):(r({title:"Conta não encontrada",description:`Nenhuma conta com email "${s.trim()}" foi encontrada.`,variant:"destructive"}),Ja(null))}catch(i){r({title:"Erro ao buscar conta",description:i.message,variant:"destructive"})}finally{Uc(!1)}}},_h=async()=>{if(!(!ia||!Ts)){Oc(!0);try{const s=await(await N("POST","/api/support/migrate/link-email",{phoneUserId:Ts.sourceUser.id,targetEmail:Ts.targetUser.email})).json();s.success?(r({title:"Contas mescladas com sucesso!",description:`Todos os dados foram transferidos para a conta ${Ts.targetUser.email}.`}),En(null),Ja(null),Tr(""),K.invalidateQueries({queryKey:["/api/admin/users"]})):r({title:"Erro na mesclagem",description:s.message||"Falha desconhecida",variant:"destructive"})}catch(t){r({title:"Erro ao mesclar contas",description:t.message,variant:"destructive"})}finally{Oc(!1)}}},dd=W({mutationFn:async({userId:t,amount:s,reason:i})=>(await N("POST",`/api/admin/users/${t}/credits`,{amount:s,reason:i})).json(),onSuccess:(t,s)=>{Mc(i=>({...i,[s.userId]:t.balance})),V(null),Ta(""),Zi(""),r({title:"Créditos adicionados!",description:`${s.amount.toLocaleString("pt-BR")} créditos (R$ ${(s.amount/100).toFixed(2).replace(".",",")}) foram adicionados com sucesso.`})},onError:t=>{r({title:"Erro ao adicionar créditos",description:t.message,variant:"destructive"})}}),od=W({mutationFn:async t=>(await N("POST",`/api/admin/books/${t}/retry-generation`)).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/users"]}),r({title:t.recovered?"Livro recuperado!":"Geração retomada!",description:t.message})},onError:t=>{r({title:"Erro ao retomar geração",description:t.message,variant:"destructive"})}}),cd=W({mutationFn:async t=>(await N("POST",`/api/admin/books/${t}/generate-from-plan`)).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/users"]}),r({title:t.alreadyRunning?"Já está gerando":"Geração iniciada!",description:t.message})},onError:t=>{r({title:"Erro ao gerar texto",description:t.message,variant:"destructive"})}}),xd=W({mutationFn:async t=>(await N("POST",`/api/admin/books/${t}/grant-access`)).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/users"]}),r({title:t.alreadyGranted?"Acesso já liberado":"Acesso liberado!",description:t.message})},onError:t=>{r({title:"Erro ao liberar acesso",description:t.message,variant:"destructive"})}}),pe=!!a&&a.role==="admin",{data:Pt,isLoading:Oh,error:Bh,refetch:Uh}=z({queryKey:["/api/admin/metrics"],enabled:pe,staleTime:300*1e3}),{data:fs}=z({queryKey:["/api/admin/checkout-health"],enabled:pe,staleTime:300*1e3}),{data:ra,refetch:Kh}=z({queryKey:["/api/admin/orphan-order-recovery/stats"],enabled:pe,staleTime:300*1e3}),[Vc,Qc]=d.useState(!1),{data:ws}=z({queryKey:["/api/admin/pulse"],enabled:pe,staleTime:60*1e3,refetchInterval:90*1e3}),{data:md}=z({queryKey:["/api/admin/daily-sales"],enabled:pe,staleTime:600*1e3});d.useMemo(()=>md?md.map(t=>({...t,revenue:Math.round(t.revenue*100)/100,revenueGross:Math.round((t.revenueGross??t.revenue)*100)/100,label:new Date(t.date+"T12:00:00").toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})})):[],[md]);const{data:Si,isLoading:Wc}=z({queryKey:["/api/admin/users"],enabled:pe&&le==="users",staleTime:300*1e3}),{data:Hc,isFetching:Xc,isError:Gh,refetch:Vh}=z({queryKey:["/api/admin/users","search",ne],queryFn:async()=>(await N("GET",`/api/admin/users?search=${encodeURIComponent(ne)}`)).json(),enabled:pe&&le==="users"&&S,staleTime:3e4,retry:1,placeholderData:t=>t}),{data:Jc,isLoading:Qh}=z({queryKey:["/api/admin/services"],enabled:pe&&(le==="orders"||le==="services"),staleTime:600*1e3}),{data:cs,isLoading:Wh}=z({queryKey:["/api/admin/orders"],enabled:pe&&le==="orders",staleTime:300*1e3}),{data:Hh}=z({queryKey:["/api/settings/book_generation_price"],enabled:pe}),{data:Gs}=z({queryKey:["/api/admin/free-plan-ip-guard"],enabled:pe&&le==="settings"}),[Yc,Zc]=d.useState("5");d.useEffect(()=>{Gs?.limit&&Zc(String(Gs.limit))},[Gs?.limit]);const{data:Es}=z({queryKey:["/api/admin/webhook-info"],enabled:pe&&le==="webhooks"}),{data:In}=z({queryKey:["/api/admin/webhook-events"],enabled:pe&&le==="webhooks",refetchInterval:le==="webhooks"?1e4:!1}),hd=[{key:"otp",label:"Código de Acesso",description:"Autenticação por email e WhatsApp",icon:"🔐",variables:[{tag:"{{code}}",label:"Código OTP"},{tag:"{{magic_link}}",label:"Link mágico"},{tag:"{{app_name}}",label:"Nome da app"},{tag:"{{logo_url}}",label:"URL da logo"}]}
2,{key:"bookplan",label:"Plano do Livro",description:"Enviado após conversa no chat",icon:"📖",variables:[{tag:"{{book_title}}",label:"Título do livro"},{tag:"{{book_subtitle}}",label:"Subtítulo do livro"},{tag:"{{book_summary}}",label:"Resumo do livro"},{tag:"{{magic_link}}",label:"Link mágico"},{tag:"{{author_name}}",label:"Nome do autor"},{tag:"{{app_name}}",label:"Nome da app"},{tag:"{{logo_url}}",label:"URL da logo"}]},{key:"welcome",label:"Boas-vindas",description:"Email automático 15min após registro",icon:"👋",variables:[{tag:"{{author_name}}",label:"Nome do autor"},{tag:"{{magic_link}}",label:"Link mágico"},{tag:"{{app_name}}",label:"Nome da app"},{tag:"{{logo_url}}",label:"URL da logo"}]},{key:"pipeline_ready",label:"Livro Pronto",description:"Notificação quando serviço fica pronto",icon:"🎉",variables:[{tag:"{{user_name}}",label:"Nome do autor"},{tag:"{{book_title}}",label:"Título do livro"},{tag:"{{book_subtitle}}",label:"Subtítulo do livro"},{tag:"{{service_label}}",label:"Tipo do serviço (Livro, Capa, etc.)"},{tag:"{{magic_link}}",label:"Link mágico do livro"},{tag:"{{user_email}}",label:"Email do cliente"},{tag:"{{user_phone}}",label:"Telefone do cliente"},{tag:"{{total_amount}}",label:"Valor total do pedido"},{tag:"{{order_date}}",label:"Data do pedido"},{tag:"{{app_name}}",label:"Nome da app"}]},{key:"store_published",label:"Livro Publicado",description:"WhatsApp quando a página de vendas entrar no ar",icon:"🏪",variables:[{tag:"{{author_name}}",label:"Nome do autor"},{tag:"{{book_title}}",label:"Título do livro"},{tag:"{{sales_url}}",label:"URL pública da página de vendas"}]}],[Is,Xh]=d.useState("otp"),{data:Ls,refetch:Zb}=z({queryKey:["/api/admin/notification-templates",Is],queryFn:async()=>{const t=await fetch(`/api/admin/notification-templates/${Is}`,{credentials:"include"});if(!t.ok)throw new Error("Failed to load");return t.json()},enabled:pe&&le==="notifications"}),[Tt,Ya]=d.useState({emailSubject:"",emailTemplate:"",appName:"",metaTemplateName:"",metaTemplateLanguage:"pt_BR",metaComponents:"[]"}),[ua,ex]=d.useState([]),[pd,tx]=d.useState(!1),[na,$i]=d.useState(null),[Rn,Za]=d.useState({});d.useEffect(()=>{if(Ls&&(Ya({emailSubject:Ls.emailSubject,emailTemplate:Ls.emailTemplate,appName:Ls.appName,metaTemplateName:Ls.metaTemplateName||"",metaTemplateLanguage:Ls.metaTemplateLanguage||"pt_BR",metaComponents:Ls.metaComponents||"[]"}),$i(null),Za({}),Ls.metaTemplateName&&ua.length>0)){const t=ua.find(s=>s.name===Ls.metaTemplateName);if(t){$i(t);const s={};t.components?.forEach(i=>{if(i.type==="BUTTONS"&&i.buttons)i.buttons.forEach((x,C)=>{x.type==="URL"&&x.url?.match(/\{\{(\d+)\}\}/g)&&(s[`button_url_${C}`]="")});else if(i.text){const x=i.text.match(/\{\{(\d+)\}\}/g);x&&x.forEach(C=>{const P=C.replace(/[{}]/g,"");s[`${i.type.toLowerCase()}_${P}`]=""})}});try{const i=JSON.parse(Ls.metaComponents||"[]");Array.isArray(i)&&i.forEach(x=>{if(x.type==="button"&&x.sub_type==="url"){const C=`button_url_${x.index||"0"}`;x.parameters?.[0]?.text&&s[C]!==void 0&&(s[C]=x.parameters[0].text)}else x.parameters&&x.parameters.forEach((C,P)=>{const H=`${x.type}_${P+1}`;C.text&&s[H]!==void 0&&(s[H]=C.text)})})}catch{}Za(s)}}},[Ls,Is,ua]);const{data:ej=[]}=z({queryKey:["/api/admin/marketing-templates"],enabled:pe}),{data:tj=[]}=z({queryKey:["/api/admin/marketing-funnels"],enabled:pe}),{data:sj=[]}=z({queryKey:["/api/admin/notification-queue"],enabled:pe}),{data:aj=[]}=z({queryKey:["/api/admin/notification-logs"],enabled:pe}),{data:ij}=z({queryKey:["/api/admin/marketing-variables"],enabled:pe}),{data:ei,isLoading:Jh}=z({queryKey:["/api/admin/ai-usage"],enabled:pe&&le==="costs"&&Kt==="users"}),{data:es,isLoading:Yh}=z({queryKey:["/api/admin/ai-service-costs",Ee],queryFn:()=>fetch(`/api/admin/ai-service-costs?days=${Ee}`,{credentials:"include"}).then(t=>t.json()),enabled:pe&&le==="costs"&&(Kt==="services"||Kt==="workers")}),{data:zs,isLoading:Zh,refetch:ep}=z({queryKey:["/api/admin/workers/status"],queryFn:()=>fetch("/api/admin/workers/status",{credentials:"include"}).then(t=>t.json()),enabled:pe&&le==="costs"&&Kt==="workers"}),{data:xs,isLoading:tp,error:sx}=z({queryKey:["/api/admin/generation-quality",Yi],queryFn:async()=>{const t=await fetch(`/api/admin/generation-quality?days=${Yi}`,{credentials:"include"});if(!t.ok)throw new Error(`Falha ao carregar qualidade da geração (HTTP ${t.status})`);return t.json()},enabled:pe&&le==="costs"&&Kt==="quality"}),{data:Ea,isLoading:sp}=z({queryKey:["/api/admin/author-health"],enabled:pe&&le==="author-health",refetchInterval:le==="author-health"?3e4:!1}),{data:ax=[],isLoading:ap}=z({queryKey:["/api/admin/daily-emails"],enabled:pe&&le==="daily-emails",refetchInterval:le==="daily-emails"?3e4:!1}),{data:qs,refetch:ip}=z({queryKey:["/api/admin/daily-emails/stats"],enabled:pe&&le==="daily-emails"}),{data:it}=z({queryKey:["/api/admin/daily-emails/analytics"],enabled:pe&&le==="daily-emails",refetchInterval:le==="daily-emails"?3e4:!1}),{data:Lt}=z({queryKey:["/api/admin/daily-emails/diagnostics"],enabled:pe&&le==="daily-emails",refetchInterval:le==="daily-emails"?15e3:!1}),{data:rj}=z({queryKey:["/api/admin/publishing/overview"],queryFn:()=>N("GET","/api/admin/publishing/overview").then(t=>t.json()),enabled:pe&&le==="integrations"}),{data:nj}=z({queryKey:["/api/publishing/tasks"],queryFn:()=>N("GET","/api/publishing/tasks").then(t=>t.json()),enabled:pe&&le==="integrations"}),{data:lj}=z({queryKey:["/api/admin/publishing/subscriptions"],queryFn:()=>N("GET","/api/admin/publishing/subscriptions").then(t=>t.json()),enabled:pe&&le==="integrations"}),{data:dj}=z({queryKey:["/api/admin/publishing/withdrawals"],queryFn:()=>N("GET","/api/admin/publishing/withdrawals").then(t=>t.json()),enabled:pe&&le==="integrations"}),{data:ix=[],isLoading:oj}=z({queryKey:["/api/admin/publishing/manual-queue"],queryFn:()=>N("GET","/api/admin/publishing/manual-queue").then(t=>t.json()),enabled:pe&&le==="integrations"}),{data:cj,isLoading:xj}=z({queryKey:["/api/admin/platforms"],enabled:pe}),[mj,hj]=d.useState({}
2),[pj,uj]=d.useState(""),[gj,bj]=d.useState(null),[jj,vj]=d.useState(!1),[Nj,fj]=d.useState(!1),[Vs,rp]=d.useState(null),[rx,nx]=d.useState(!1),[wj,lx]=d.useState(!1),[Er,dx]=d.useState(null),[np,Fn]=d.useState(!1),[Ir,yj]=d.useState(null),[Ft,ti]=d.useState({name:"",slug:"",emoji:"📚",description:"",type:"manual",status:"active",storeCount:1,displayOrder:0,logoUrl:""}),{data:lp,refetch:ox,isLoading:dp}=z({queryKey:[`/api/admin/books/${Vs}/publishing-metadata`],enabled:pe&&!!Vs}),[Dn,op]=d.useState(""),[si,cp]=d.useState(""),[cx,xx]=d.useState(!1),[mx,hx]=d.useState(!1),[Qs,ud]=d.useState(null),[ms,gd]=d.useState(null),[bd,xp]=d.useState(""),[gt,px]=d.useState(null),[mp,jd]=d.useState(!1),[ux,gx]=d.useState(!1),[Ai,hp]=d.useState(""),[bx,jx]=d.useState(!1),[vx,Nx]=d.useState(!1),[fx,wx]=d.useState("08:00"),[yx,kx]=d.useState("11:00"),[Cx,Sx]=d.useState(!1),[vd,Nd]=d.useState(!1),[fd,pp]=d.useState(null),[Et,la]=d.useState({name:"",channel:"email",subject:"",htmlContent:"",textContent:"",whatsappTemplateName:"",whatsappTemplateLanguage:"pt_BR",whatsappComponents:"[]",variables:[],category:"marketing",active:!0}),[Rr,up]=d.useState([]),[$x,Ax]=d.useState(!1),[er,gp]=d.useState(null),[Mn,Px]=d.useState({}),[kj,bp]=d.useState(!1),[Tx,jp]=d.useState(null),[Cj,Sj]=d.useState({name:"",description:"",triggerEvent:"book_plan_completed",active:!0,steps:[]}),[Ex,$j]=d.useState(null),[Aj,Pj]=d.useState(!1),[Pi,vp]=d.useState("all"),[Np,tr]=d.useState(!1),[fp,Ln]=d.useState(!1),[Gt,Ti]=d.useState({headline:"",primaryText:"",description:"",callToAction:"LEARN_MORE",format:"feed_vertical",angle:"manual",targetAudience:"geral"}),[wd,yd]=d.useState(null),[kd,Cd]=d.useState(null),[wp,zn]=d.useState(!1),[It,Sd]=d.use
2State([]),[Ia,sr]=d.useState([{headline:"",primaryText:"",description:""}]),[ar,$d]=d.useState({callToAction:"LEARN_MORE",format:"feed_vertical",targetAudience:"geral"}),[yp,Ad]=d.useState(null),[Ve,Ws]=d.useState({mode:"standard",conceptIdea:"",angle:"transformacao",targetAudience:"geral",format:"feed_square",style:"moderno",overlayText:"",includeOverlay:!1,overlayMode:"auto",count:1}),[oe,ys]=d.useState(null),[qn,ir]=d.useState(new Set),[Ei,Pd]=d.useState(new Set),[Dt,Ix]=d.useState(null),[kp,_n]=d.useState(null),[Td,Ed]=d.useState(""),[Rx,ai]=d.useState(null),[Cp,Id]=d.useState(!1),[Fx,On]=d.useState(""),[Rd,Dx]=d.useState("detail"),[Vt,Bn]=d.useState(null),[Sp,Un]=d.useState(null),[Mx,Fd]=d.useState(!1),[Qe,Fr]=d.useState("creatives"),[Dd,$p]=d.useState(!1),[Md,Ap]=d.useState("all"),[Lx,Pp]=d.useState(null),[Le,bt]=d.useState(null),[ii,rr]=d.useState(null),[Tp,Ep]=d.useState(null),[nr,zx]=d.useState(""),qx=d.useRef(null),[Ii,Ip]=d.useState("overview"),[Dr,Rp]=d.useState("campaign"),[_x,Fp]=d.useState([]),[lr,Kn]=d.useState(!1),[_e,zt]=d.useState({campaignName:"",dailyBudget:"50",destinationUrl:"https://sabhia.ai/chat",countries:"BR",ageMin:"25",ageMax:"65",status:"ACTIVE"}),[hs,Ox]=d.useState("new"),[dr,Ld]=d.useState(""),[or,Gn]=d.use
2State(""),[ga,Ri]=d.useState([]),[ks,Mr]=d.useState(new Set),[Fi,Lr]=d.useState(!1),[zr,Bx]=d.useState(null),[ts,zd]=d.useState(null),[ba,qr]=d.useState(""),[ri,cr]=d.useState(""),[Ux,_r]=d.useState(!1),[Vn,Or]=d.useState(!1),[Kx,Br]=d.useState(""),[Qn,Ur]=d.useState(""),[Cs,qd]=d.useState(!0),[da,Wn]=d.useState("auto"),[Qt,Gx]=d.useState("new"),[ja,Vx]=d.useState(""),[_d,Qx]=d.useState(""),[Od,Wx]=d.useState("all"),[Bd,Hx]=d.useState("advantage_plus"),[xr,Xx]=d.useState("LOWEST_COST_WITHOUT_CAP"),[Ud,Jx]=d.useState(""),[Kd,Dp]=d.useState(""),[Yx,Zx]=d.useState("PURCHASE"),[Tj,Mp]=d.useState(!0),[Gd,Lp]=d.useState(!1),[Hn,Vd]=d.useState({loading:!1}),[Xn,Kr]=d.useState(!1),[em,tm]=d.useState(!1),[Jn,zp]=d.useState(null),[Qd,sm]=d.useState({accessToken:"",adAccountId:"",pixelId:"",pageId:"",appSecret:"",gaTrackingId:"",instagramAccountId:""}),[qp,Yn]=d.useState(!1),[_s,Di]=d.useState({name:"",condition:"roas_above",action:"increase_budget",threshold:"2",windowDays:"3",maxAdjustmentPct:"30"}),[va,_p]=d.useState("7d"),[Gr,am]=d.useState(null),[im,rm]=d.useState(!1),{data:Ra,isLoading:Op}=z({queryKey:["/api/admin/ad-creatives",Pi],queryFn:async()=>{const t=Pi!=="all"&&Pi!=="matrix"?`?status=${Pi}`:"",s=await N("GET",`/api/admin/ad-creatives${t}`).then(i=>i.json());return Pi==="matrix"?s.filter(i=>i.testGroup):s},enabled:pe&&le==="ad-creatives"}),{data:Rs}=z({queryKey:["/api/admin/ads/anomalies"],enabled:pe&&le==="ad-creatives",refetchInterval:6e4}),{data:wt,isLoading:Bp}=z({queryKey:["/api/admin/ads/matrix-performance",Gr],queryFn:()=>N("GET",`/api/admin/ads/matrix-performance/${Gr}`).then(t=>t.json()),enabled:!!Gr}),Up=W({mutationFn:t=>N("POST",`/api/admin/ads/anomalies/${t}/acknowledge`),onSuccess:()=>K.invalidateQueries({queryKey:["/api/admin/ads/anomalies"]})}),Wd=d.useRef(0);d.useEffect(()=>{if(Rs){if(Rs.length>Wd.current&&Wd.current>0){const t=Rs[0];t&&r({title:t.title,description:t.message?.substring(0,120),variant:t.severity==="critical"?"destructive":"default"})}Wd.current=Rs.length}},[Rs]);const[Fs,mr]=d.useState(null),Zn=d.useRef(null),el=d.useRef(null),nm=d.useRef(null),Fa=d.useRef(0),tl=d.useRef([]),sl=d.useRef(!1),Hd=d.useCallback(()=>{if(sl.current||tl.current.length===0)return;sl.current=!0;const t=tl.current.shift();nm.current?.(t)},[]),ni=d.useCallback(()=>{el.current=null,Fa.current=0,Zn.current&&(clearInterval(Zn.current),Zn.current=null)},[]),Kp=d.useCallback((t,s)=>{ni(),el.current=t,Fa.current=0,tl.current=[],sl.current=!1;const i=new Set;mr({jobId:t,total:s,completed:0,creatives:[],status:"processing"}),Zn.current=setInterval(async()=>{if(el.current===t)try{const x=await fetch(`/api/admin/ad-creatives/job/${t}`,{credentials:"include"});if(el.current!==t)return;if(x.status===404){Fa.current++,Fa.current>=5&&(ni(),ai(null),mr(null),K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),r({title:"Geração concluída",description:"O servidor foi reiniciado durante o processo. Verifique os criativos salvos."}));return}if(!x.ok){Fa.current++,Fa.current>=5&&(ni(),ai(null),mr(null),K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),r({title:"Erro ao verificar progresso",description:"Verifique se os criativos foram salvos na lista.",variant:"destructive"}));return}Fa.current=0;const C=await x.json();mr({jobId:t,total:C.total,completed:C.completed,creatives:C.creatives||[],status:C.status}),ai(`Gerando ${Math.min(C.completed+1,C.total)}/${C.total}...`);for(const P of C.creatives||[])P.id&&!P.imageUrl&&!i.has(P.id)&&(i.add(P.id),tl.current.push(P.id),Hd());(C.status==="completed"||C.status==="error")&&(ni(),ai(null),K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),C.status==="completed"&&C.creatives?.length>0?(ys(C.creatives[0]),r({title:`${C.creatives.length} criativos gerados!`,description:"Gerando imagens automaticamente..."})):C.status==="error"&&r({title:"Erro na geração",description:C.error||"Erro desconhecido",variant:"destructive"}),setTimeout(()=>mr(null),2e3))}catch{Fa.current++,Fa.current>=5&&(ni(),ai(null),mr(null),K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}
2),r({title:"Conexão perdida",description:"A geração pode ter continuado. Verifique a lista de criativos.",variant:"destructive"}))}},3e3)},[ni,K,r,Hd]);d.useEffect(()=>()=>ni(),[ni]);const Xd=W({mutationFn:async t=>(ai(t.count&&t.count>1?`Gerando 1/${t.count}...`:null),(await N("POST","/api/admin/ad-creatives/generate",t)).json()),onSuccess:t=>{if(t.jobId){tr(!1),Kp(t.jobId,t.total);return}if(ai(null),K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),tr(!1),Array.isArray(t)){t.length>0&&ys(t[0]),r({title:`${t.length} criativos gerados!`,description:"Gerando imagens automaticamente..."});for(const s of t)s.id&&!s.imageUrl&&Qr.mutate(s.id)}else ys(t),r({title:"Criativo gerado!",description:"Gerando imagem automaticamente..."}),t.id&&!t.imageUrl&&Qr.mutate(t.id)},onError:t=>{ai(null),r({title:"Erro ao gerar criativo",description:t.message,variant:"destructive"})}}),Jd=W({mutationFn:async t=>{const s=await fetch("/api/admin/ad-creatives/manual",{method:"POST",body:t,credentials:"include"});if(!s.ok){const i=await s.json();throw new Error(i.message||"Erro ao criar criativo")}return s.json()},onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),Ln(!1),ys(t),Ti({headline:"",primaryText:"",description:"",callToAction:"LEARN_MORE",format:"feed_vertical",angle:"manual",targetAudience:"geral"}),yd(null),Cd(null),r({title:"Criativo criado!",description:"Seu criativo manual foi adicionado com sucesso."})},onError:t=>{r({title:"Erro ao criar criativo",description:t.message,variant:"destructive"})}});W({mutationFn:async t=>(await N("POST","/api/admin/ad-creatives/matrix-publish",t)).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),r({title:`${t.totalPublished} anúncios publicados!`,description:t.structure})},onError:t=>{r({title:"Erro ao publicar matriz",description:t.message,variant:"destructive"})}});const Vr=W({mutationFn:async t=>{const s=await fetch("/api/admin/ad-creatives/bulk-matrix",{method:"POST",body:t,credentials:"include"});if(!s.ok){const i=await s.json();throw new Error(i.message||"Erro ao criar matriz")}return s.json()},onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),zn(!1),Sd([]),sr([{headline:"",primaryText:"",description:""}]),Ad(null),r({title:`${t.creatives.length} criativos aprovados!`,description:`Matriz ${t.matrix} — Abrindo publicação...`});const s=new Set(t.creatives.map(Te=>Te.id));Mr(s);const i=new Set(t.creatives.map(Te=>Te.imageUrl)),x=new Set(t.creatives.map(Te=>Te.headline)),C=t.testType||(i.size>1&&x.size>1?"both":i.size>1?"image":"text"),P=C==="image"?i.size:C==="text"?x.size:i.size,H=Math.ceil(t.creatives.length/Math.max(P,1)),Q=t.creatives[0],G=Q?.targetAudience==="religiosos"?"Religiosos":Q?.targetAudience==="empreendedores"?"Empreend":Q?.targetAudience==="coaches"?"Coaches":Q?.targetAudience==="professores"?"Professores":Q?.targetAudience==="saude"?"Saúde":Q?.targetAudience==="autores_iniciantes"?"Iniciantes":"Geral",ue=new Date().toISOString().split("T")[0];zt(Te=>({...Te,campaignName:`[SABHIA] Matrix A/B | ${G} | ${P}sets×${H}ads | ${ue}`,dailyBudget:String(Math.max(10,Math.round(50/Math.max(P,1))))})),Wn(C==="both"?"auto":C==="image"?"image":C==="text"?"text":"single"),Ri([]),qr(""),cr(""),Gx("new"),setTimeout(()=>Lr(!0),300)},onError:t=>{Ad(null),r({title:"Erro ao criar matriz",description:t.message,variant:"destructive"})}}),lm=W({mutationFn:async t=>(await N("POST",`/api/admin/ad-creatives/${t}/duplicate`)).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),ys(t),r({title:"Criativo duplicado!",description:"Cópia criada como rascunho."})}}),al=W({mutationFn:async({id:t,field:s,value:i})=>(await N("PATCH",`/api/admin/ad-creatives/${t}`,{[s]:i})).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),ys(t),_n(null)}}),Qr=W({mutationFn:async t=>(ir(i=>new Set(i).add(t)),(await N("POST",`/api/admin/ad-creatives/${t}/generate-image`)).json()),onSuccess:t=>{ir(s=>{const i=new Set(s);return i.delete(t.id),i}),K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),ys(s=>!s||s.id===t.id?t:s),r({title:"Imagem gerada!",description:"A imagem do anúncio está pronta."})},onError:(t,s)=>{ir(i=>{const x=new Set(i);return x.delete(s),x}
2),r({title:"Erro ao gerar imagem",description:t.message,variant:"destructive"})},onSettled:()=>{sl.current=!1,setTimeout(()=>Hd(),2e3)}});nm.current=t=>Qr.mutate(t);const Yd=W({mutationFn:async t=>(await N("POST",`/api/admin/ad-creatives/${t}/regenerate-text`)).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),ys(t),r({title:"Texto regenerado!"})},onError:t=>{r({title:"Erro",description:t.message,variant:"destructive"})}}),Wr=W({mutationFn:async({id:t,imageDirection:s})=>{ir(C=>new Set(C).add(t));const i={};return s?.trim()&&(i.imageDirection=s.trim()),(await N("POST",`/api/admin/ad-creatives/${t}/regenerate-image`,Object.keys(i).length>0?i:void 0)).json()},onSuccess:t=>{ir(s=>{const i=new Set(s);return i.delete(t.id),i}),K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),ys(t),Id(!1),On(""),r({title:"Imagem regenerada!"})},onError:t=>{ir(new Set),r({title:"Erro",description:t.message,variant:"destructive"})}}),Gp=W({mutationFn:async t=>(Fd(!0),Un(t),(await N("POST",`/api/admin/ad-creatives/${t}/evaluate-compliance`)).json()),onSuccess:t=>{Fd(!1),t.evaluation&&Bn(t.evaluation)},onError:t=>{Fd(!1),Bn(null),Un(null),r({title:"Erro na avaliação",description:t.message,variant:"destructive"})}}),il=W({mutationFn:async({id:t,issues:s})=>(await N("POST",`/api/admin/ad-creatives/${t}/regenerate-compliant`,{issues:s})).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),ys(t),Bn(null),Un(null),r({title:"Texto regenerado dentro das políticas!"})},onError:t=>{r({title:"Erro ao regenerar",description:t.message,variant:"destructive"})}}),Vp=d.useCallback(t=>{let s=0;const i=30,x=setInterval(async()=>{s++;try{const C=await fetch(`/api/admin/ads/creatives/${t}/variations/status`,{credentials:"include"});if(C.ok){const P=await C.json();(!P.inProgress||s>=i)&&(clearInterval(x),Pd(H=>{const Q=new Set(H);return Q.delete(t),Q}),K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),P.childCount>0?r({title:`${P.childCount} variações criadas!`,description:"Novas variações prontas para revisão."}):s>=i&&r({title:"Geração demorou mais que o esperado",description:"Atualize a página para verificar."}))}}catch{}},1e4)},[K,r]),Zd=W({mutationFn:async t=>(Pd(i=>new Set(i).add(t)),(await N("POST",`/api/admin/ads/creatives/${t}/variations`)).json()),onSuccess:(t,s)=>{r({title:"Gerando variações...",description:"5 variações sendo criadas. Você será notificado quando terminar."}),Vp(s)},onError:(t,s)=>{Pd(i=>{const x=new Set(i);return x.delete(s),x}),r({title:"Erro ao gerar variações",variant:"destructive"})}}),Qp=W({mutationFn:async t=>{await N("DELETE",`/api/admin/ad-creatives/${t}`)},onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),ys(null),r({title:"Criativo excluído"})}}),dm=W({mutationFn:async({id:t,status:s})=>(await N("PATCH",`/api/admin/ad-creatives/${t}`,{status:s})).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),ys(t),r({title:"Status atualizado"})}}),{data:rl}=z({queryKey:["/api/admin/traffic-manager/config"],queryFn:()=>N("GET","/api/admin/traffic-manager/config").then(t=>t.json()).catch(()=>null),enabled:pe&&le==="ad-creatives"}),{data:Da,isLoading:Ej}=z({queryKey:["/api/admin/meta-config"],queryFn:()=>N("GET","/api/admin/meta-config").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="config"});d.useEffect(()=>{Da&&sm(t=>({accessToken:t.accessToken||Da.accessToken||"",adAccountId:t.adAccountId||Da.adAccountId||"",pixelId:t.pixelId||Da.pixelId||"",pageId:t.pageId||Da.pageId||"",appSecret:t.appSecret||Da.appSecret||"",gaTrackingId:t.gaTrackingId||Da.gaTrackingId||"",instagramAccountId:t.instagramAccountId||Da.instagramAccountId||""}))},[Da]);const{data:om,isLoading:Ij}=z({queryKey:["/api/admin/campaigns"],queryFn:()=>N("GET","/api/admin/campaigns").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&(Qe==="campaigns"||Qe==="performance")}),{data:hr}=z({queryKey:["/api/admin/meta-audiences"],queryFn:()=>N("GET","/api/admin/meta-audiences").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&(lr||Fi),staleTime:6e4}),{data:nl=[]}=z({queryKey:["/api/admin/meta-configs"],queryFn:()=>N("GET","/api/admin/meta-configs").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&(lr||Fi),staleTime:6e4}),{data:ll,isLoading:cm,error:xm,refetch:mm}=z({queryKey:["/api/admin/meta-config/list-pages",ba||"default"],queryFn:async()=>{const t=await N("GET",`/api/admin/meta-config/list-pages${ba?`?accountId=${ba}`:""}`);if(!t.ok){const s=await t.json().catch(()=>({}));throw new Error(s?.message||`HTTP ${t.status}`)}return t.json()},enabled:pe&&le==="ad-creatives"&&(lr||Fi),staleTime:6e4,retry:!1});d.useEffect(()=>{cr(""),Or(!1),Br(""),Ur(""),_r(!1)},[ba]);const{data:Nt,isLoading:Wp,refetch:dl}=z({queryKey:["/api/admin/ads-config/preflight"],queryFn:()=>N("GET","/api/admin/ads-config/preflight").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&(lr||Fi),staleTime:3e4}),{data:ol}=z({queryKey:["/api/admin/campaigns","for-publish"],queryFn:()=>N("GET","/api/admin/campaigns").then(t=>t.json()),enabled:pe&&Fi&&(Qt==="existing_campaign"||Qt==="existing_adset"),staleTime:3e4}),{data:hm}=z({queryKey:["/api/admin/ad-sets",ja],queryFn:()=>N("GET",`/api/admin/ad-sets?campaignId=${encodeURIComponent(ja)}`).then(t=>t.json()),enabled:pe&&Fi&&Qt==="existing_adset"&&!!ja,staleTime:3e4}),{data:pm}=z({queryKey:["/api/admin/ads/tree"],queryFn:()=>N("GET","/api/admin/ads/tree").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&lr,staleTime:3e4}),{data:qt,isLoading:Hp}=z({queryKey:["/api/admin/performance",va],queryFn:()=>{const t=new Date,s=va==="7d"?7:va==="14d"?14:va==="30d"?30:365,i=new Date(t.getTime()-s*864e5).toISOString().split("T")[0];return N("GET",`/api/admin/performance?startDate=${i}`).then(x=>x.json())},enabled:pe&&le==="ad-creatives"&&Qe==="performance"}),{data:um=[]}=z({queryKey:["/api/admin/performance/attribution",va],queryFn:()=>{const t=new Date,s=va==="7d"?7:va==="14d"?14:va==="30d"?30:365,i=new Date(t.getTime()-s*864e5).toISOString().split("T")[0];return N("GET",`/api/admin/performance/attribution?startDate=${i}`).then(x=>x.json())},enabled:pe&&le==="ad-creatives"&&Qe==="performance"}),{data:Hr}=z({queryKey:["/api/admin/performance/ltv"],queryFn:()=>N("GET","/api/admin/performance/ltv").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="performance"&&Ii==="ltv"}),{data:Xp=[]}=z({queryKey:["/api/admin/tracking-events"],queryFn:()=>N("GET","/api/admin/tracking-events?limit=100").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="performance"}),{data:gm=[],isLoading:Jp}=z({queryKey:["/api/admin/meta-audiences"],queryFn:()=>N("GET","/api/admin/meta-audiences").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="audiences"}),eo=W({mutationFn:t=>N("POST","/api/admin/meta-audiences",t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/meta-audiences"]}
2),r({title:"Audiência criada!"})},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})}),bm=W({mutationFn:({id:t,ratio:s})=>N("POST",`/api/admin/meta-audiences/${t}/lookalike`,{ratio:s}).then(i=>i.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/meta-audiences"]}),r({title:"Lookalike criado!"})},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})}),Yp=W({mutationFn:t=>N("DELETE",`/api/admin/meta-audiences/${t}`),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/meta-audiences"]}),r({title:"Audiência removida"})}}),{data:to,isLoading:Zp,refetch:e0}=z({queryKey:["/api/admin/smart-audiences-preview"],queryFn:()=>N("GET","/api/admin/smart-audiences-preview").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="audiences"}),[Xr,so]=d.useState([]),[t0,jm]=d.useState(null),ao=W({mutationFn:t=>N("POST","/api/admin/meta-audiences/smart",{segments:t}).then(s=>s.json()),onSuccess:t=>{jm(t.results||[]),K.invalidateQueries({queryKey:["/api/admin/meta-audiences"]}),r({title:"Audiências inteligentes criadas!",description:`${(t.results||[]).filter(s=>s.audienceId).length} audiências enviadas ao Meta`})},onError:t=>r({title:"Erro ao criar audiências",description:t.message,variant:"destructive"})}),{data:cl}=z({queryKey:["/api/admin/optimizer/status"],queryFn:()=>N("GET","/api/admin/optimizer/status").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="optimizer"}),{data:io}=z({queryKey:["/api/admin/optimizer/rules"],queryFn:()=>N("GET","/api/admin/optimizer/rules").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="optimizer"}),{data:ro}=z({queryKey:["/api/admin/optimizer/actions"],queryFn:()=>N("GET","/api/admin/optimizer/actions?limit=20").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&(Qe==="optimizer"||Qe==="campaigns")}),{data:Ue,refetch:vm}=z({queryKey:["/api/admin/traffic-manager/status"],queryFn:()=>N("GET","/api/admin/traffic-manager/status").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="ia-gestor",refetchInterval:le==="ad-creatives"&&Qe==="ia-gestor"?3e4:!1}),{data:no,refetch:Nm}=z({queryKey:["/api/admin/traffic-manager/config"],queryFn:()=>N("GET","/api/admin/traffic-manager/config").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="ia-gestor"});d.useEffect(()=>{no&&!Le&&bt(no)},[no]);const{data:Jr}=z({queryKey:["/api/admin/traffic-manager/insights/winners"],queryFn:()=>N("GET","/api/admin/traffic-manager/insights/winners").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="ia-gestor"}),{data:We}=z({queryKey:["/api/admin/traffic-manager/funnel-counts"],queryFn:()=>N("GET","/api/admin/traffic-manager/funnel-counts").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="ia-gestor",refetchInterval:le==="ad-creatives"&&Qe==="ia-gestor"?6e4:!1}),{data:lo,refetch:s0}=z({queryKey:["/api/admin/traffic-manager/log"],queryFn:()=>N("GET","/api/admin/traffic-manager/log").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="ia-gestor",refetchInterval:le==="ad-creatives"&&Qe==="ia-gestor"?15e3:!1}),{data:xl}=z({queryKey:["/api/admin/traffic-manager/ab-tests"],queryFn:()=>N("GET","/api/admin/traffic-manager/ab-tests").then(t=>t.json()),enabled:pe&&le==="ad-creatives"&&Qe==="ia-gestor",refetchInterval:le==="ad-creatives"&&Qe==="ia-gestor"?3e4:!1}),fm=W({mutationFn:t=>N("POST","/api/admin/traffic-manager/toggle",{enabled:t}).then(s=>s.json()),onSuccess:t=>{vm(),Nm(),r({title:t?.isEnabled?"IA Gestor ativado!":"IA Gestor desativado!"})},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})}),oo=W({mutationFn:()=>N("POST","/api/admin/traffic-manager/run-now").then(t=>t.json()),onSuccess:()=>{vm(),s0(),r({title:"Ciclo iniciado!",description:"Análise e geração em andamento."})},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})}),co=W({mutationFn:t=>N("PUT","/api/admin/traffic-manager/config",t).then(s=>s.json()),onSuccess:()=>{Nm(),r({title:"Configuração salva!"})},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})}),{data:xo}=z({queryKey:["/api/admin/orchestration/config"],queryFn:()=>N("GET","/api/admin/orchestration/config").then(t=>t.json()).catch(()=>null),staleTime:3e4,enabled:pe&&le==="orchestration"});d.useEffect(()=>{xo&&!ii&&rr(xo)},[xo]);const{data:a0}=z({queryKey:["/api/admin/orchestration/status"],queryFn:()=>N("GET","/api/admin/orchestration/status").then(t=>t.json()).catch(()=>null),enabled:pe&&le==="orchestration",refetchInterval:le==="orchestration"?6e4:!1}),{data:ml}=z({queryKey:["/api/admin/orchestration/reports"],queryFn:()=>N("GET","/api/admin/orchestration/reports?limit=10").then(t=>t.json()).catch(()=>[]),enabled:pe&&le==="orchestration",refetchInterval:le==="orchestration"?6e4:!1}),{data:li,refetch:mo,isLoading:i0}=z({queryKey:["/api/admin/chat-variant-stats"],queryFn:async()=>(await N("GET","/api/admin/chat-variant-stats")).json(),enabled:pe&&le==="chat-ab",refetchInterval:le==="chat-ab"?3e4:!1}
2),[r0,pr]=d.useState(!1),[hl,pl]=d.useState(null),[Ss,Ma]=d.useState({name:"",description:"",weight:50,isActive:!0,config:'{"chatPage": "chat"}'}),ho=W({mutationFn:async t=>(await N("POST","/api/admin/chat-variants",t)).json(),onSuccess:()=>{pr(!1),pl(null),Ma({name:"",description:"",weight:50,isActive:!0,config:'{"chatPage": "chat"}'}),mo(),r({title:"Variante do chat criada!"})},onError:t=>r({title:"Erro ao criar variante",description:t.message,variant:"destructive"})}),ul=W({mutationFn:async({id:t,data:s})=>(await N("PUT",`/api/admin/chat-variants/${t}`,s)).json(),onSuccess:()=>{pr(!1),pl(null),Ma({name:"",description:"",weight:50,isActive:!0,config:'{"chatPage": "chat"}'}),mo(),r({title:"Variante do chat atualizada!"})},onError:t=>r({title:"Erro ao atualizar variante",description:t.message,variant:"destructive"})}),n0=W({mutationFn:async t=>(await N("DELETE",`/api/admin/chat-variants/${t}`)).json(),onSuccess:()=>{mo(),r({title:"Variante do chat excluída!"})},onError:t=>r({title:"Erro ao excluir variante",description:t.message,variant:"destructive"})}
2),[gl,l0]=d.useState("all"),[bl,d0]=d.useState("all"),[Ke,wm]=d.useState(null),[o0,ym]=d.useState(!1),{data:km=[],isLoading:Cm}=z({queryKey:["/api/admin/checkout-sessions",gl,bl],queryFn:async()=>{const t=new URLSearchParams;gl!=="all"&&t.set("status",gl),bl!=="all"&&t.set("variant",bl),t.set("limit","200");const s=await fetch(`/api/admin/checkout-sessions?${t}`,{credentials:"include"});if(!s.ok)throw new Error("Failed");return s.json()},enabled:pe&&le==="checkouts",refetchInterval:le==="checkouts"?3e4:!1}),{data:ps}=z({queryKey:["/api/admin/checkout-metrics"],enabled:pe&&le==="checkouts",refetchInterval:le==="checkouts"?3e4:!1}),c0=async t=>{ym(!0);try{const i=await(await N("GET",`/api/admin/checkout-sessions/${t}`)).json();wm(i)}catch{r({title:"Erro ao carregar detalhes",variant:"destructive"})}finally{ym(!1)}},{data:Mi,refetch:Sm}=z({queryKey:["/api/admin/checkout-variant-stats"],queryFn:async()=>(await(await N("GET","/api/admin/checkout-variant-stats")).json()).variants||[],enabled:pe&&le==="checkout-ab",refetchInterval:le==="checkout-ab"?3e4:!1}),{data:ur}=z({queryKey:["/api/admin/checkout-variant-stats","significance"],queryFn:async()=>(await(await N("GET","/api/admin/checkout-variant-stats")).json()).significance||{significant:!1,pValue:null,message:""},enabled:pe&&le==="checkout-ab"}),[x0,gr]=d.useState(!1),[jl,vl]=d.useState(null),[Ds,Na]=d.useState({name:"",weight:50,isActive:!0,config:"{}"}),po=W({mutationFn:async t=>(await N("POST","/api/admin/checkout-variants",t)).json(),onSuccess:()=>{gr(!1),vl(null),Na({name:"",weight:50,isActive:!0,config:"{}"}),Sm(),K.invalidateQueries({queryKey:["/api/admin/checkout-variant-stats"]}),r({title:"Variante criada!"})},onError:t=>r({title:"Erro ao criar variante",description:t.message,variant:"destructive"})}),Nl=W({mutationFn:async({id:t,data:s})=>(await N("PUT",`/api/admin/checkout-variants/${t}`,s)).json(),onSuccess:()=>{gr(!1),vl(null),Na({name:"",weight:50,isActive:!0,config:"{}"}),Sm(),K.invalidateQueries({queryKey:["/api/admin/checkout-variant-stats"]}),r({title:"Variante atualizada!"})},onError:t=>r({title:"Erro ao atualizar variante",description:t.message,variant:"destructive"})}),{data:ss}=z({queryKey:["/api/admin/plan-landing-variant-stats"],queryFn:async()=>(await N("GET","/api/admin/plan-landing-variant-stats")).json(),enabled:pe&&le==="plan-landing-ab",refetchInterval:le==="plan-landing-ab"?3e4:!1}),{data:Yr,refetch:$m}=z({queryKey:["/api/admin/ceo-chat/history"],queryFn:()=>N("GET","/api/admin/ceo-chat/history").then(t=>t.json()).catch(()=>[]),enabled:pe&&le==="orchestration"});d.useEffect(()=>{qx.current?.scrollIntoView({behavior:"smooth"})},[Yr]);const Li=W({mutationFn:t=>N("POST","/api/admin/ceo-chat/message",{message:t}).then(s=>s.json()),onSuccess:()=>{$m(),zx("")},onError:t=>r({title:"Erro ao enviar mensagem",description:t.message,variant:"destructive"})}),Am=W({mutationFn:()=>N("DELETE","/api/admin/ceo-chat/history").then(t=>t.json()),onSuccess:()=>{$m(),r({title:"Conversa limpa!"})}}),uo=W({mutationFn:t=>N("PUT","/api/admin/orchestration/config",t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/orchestration/config"]}),K.invalidateQueries({queryKey:["/api/admin/orchestration/status"]}),r({title:"Configuração de orquestração salva!"})},onError:t=>r({title:"Erro ao salvar",description:t.message,variant:"destructive"})}),go=W({mutationFn:t=>N("PUT","/api/admin/meta-config",t).then(s=>s.json()),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/meta-config"]}),t.connectionTest?t.connectionTest.success?r({title:"Configuração salva!",description:`Conexão OK — Conta: ${t.connectionTest.accountName} (${t.connectionTest.currency})`}):r({title:"Configuração salva, mas conexão falhou",description:t.connectionTest.error||"Verifique as permissões do token.",variant:"destructive"}):r({title:"Configuração salva!"})},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})});W({mutationFn:()=>N("POST","/api/admin/meta-config/test").then(t=>t.json()),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/meta-config"]}),t.success?r({title:"Conexão OK!",description:`Conta: ${t.accountName} (${t.currency})`}):t.warnings?.length>0?r({title:"Conexão parcial",description:t.error||t.warnings[0],variant:"destructive"}):r({title:"Erro na conexão",description:t.error,variant:"destructive"})}});const bo=W({mutationFn:t=>N("POST",`/api/admin/ad-creatives/${t.creativeId}/publish`,t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),K.invalidateQueries({queryKey:["/api/admin/campaigns"]}),K.invalidateQueries({queryKey:["/api/admin/ads/tree"]}),Kn(!1),Ri([]),r({title:"Publicado na Meta!",description:"Anúncio criado com sucesso.",action:e.jsx(Om,{altText:"Ver Performance",onClick:()=>Fr("performance"),children:"Ver Performance"})})},onError:t=>{const s=t.message||"Erro interno",i=s.toLowerCase(),x=i.includes("certificação")||i.includes("nondiscrimination")||i.includes("non-discrimination")||i.includes("cert_error");x&&Kr(!0),r({title:x?"Token Meta precisa ser atualizado":"Erro ao publicar",description:x?"A certificação de não discriminação não está sendo reconhecida. Se você já aceitou a certificação, atualize o Access Token em Admin > Meta Ads > Configuração com um token gerado APÓS a certificação.":s,variant:"destructive",duration:x?2e4:5e3})}}),La=d.useRef(null),zi=d.useRef(!1),fl=d.useCallback(()=>{zi.current=!1,La.current&&(clearTimeout(La.current),La.current=null),Bx(null),zd(null)},[]),jo=d.useCallback(t=>
2{fl(),K.invalidateQueries({queryKey:["/api/admin/ad-creatives"]}),K.invalidateQueries({queryKey:["/api/admin/campaigns"]}),K.invalidateQueries({queryKey:["/api/admin/ads/tree"]}),Lr(!1),Mr(new Set),Ri([]),Kr(!1);const s=t.totalPublished||0,i=t.totalErrors||0,x=t.adSets?.length||0,C=t.preflightWarnings?.length||0;let P=`${x} conjunto(s) de anúncios criados com ${s} anúncios.`;if(i>0){const H=(t.adSets||[]).flatMap(Q=>Q.errors||[]);P+=` ${i} falharam: ${H.map(Q=>Q.error).slice(0,3).join("; ")}`}C>0&&(P+=` (${C} ignorado(s) no pré-check)`),r({title:i>0?`${s} publicado(s), ${i} com erro`:`${s} anúncio(s) publicados em ${x} conjuntos!`,description:P,variant:i>0?"destructive":"default",action:e.jsx(Om,{altText:"Ver Campanhas",onClick:()=>Fr("campaigns"),children:"Ver Campanhas"})})},[fl,K,r,Fr]),Zr=d.useCallback(t=>{fl();const s=t.toLowerCase(),i=s.includes("certificação")||s.includes("nondiscrimination")||s.includes("non-discrimination")||s.includes("cert_error");i&&Kr(!0),r({title:i?"Token Meta precisa ser atualizado":"Erro ao publicar em lote",description:i?"A certificação de não discriminação não está sendo reconhecida. Se você já aceitou a certificação, atualize o Access Token em Admin > Meta Ads > Configuração com um token gerado APÓS a certificação.":t,variant:"destructive",duration:i?2e4:5e3})},[fl,r]),m0=d.useCallback(t=>{zi.current&&(zi.current=!1,La.current&&clearTimeout(La.current)),Bx(t),zd({current:0,total:0,phase:"Iniciando publicação...",adSetsCreated:0,adSetsTotal:0}),zi.current=!0;let s=0;const i=async()=>{if(zi.current){try{const x=await fetch(`/api/admin/ad-creatives/publish-job/${t}`,{credentials:"include"});if(x.ok){s=0;const C=await x.json();if(zd(C.progress),C.status==="complete"){jo(C.result);return}else if(C.status==="error"){Zr(C.error||"Erro desconhecido");return}}else if(s++,x.status===404||s>=10){Zr(x.status===404?"Job de publicação não encontrado. O servidor pode ter reiniciado.":"Conexão perdida com o servidor. Verifique o status no Meta Ads Manager.");return}}catch{if(s++,s>=10){Zr("Conexão perdida com o servidor. Verifique o status no Meta Ads Manager.");return}}zi.current&&(La.current=setTimeout(i,2e3))}};La.current=setTimeout(i,1e3)},[jo,Zr]);d.useEffect(()=>()=>{zi.current=!1,La.current&&clearTimeout(La.current)},[]);const vo=W({mutationFn:t=>N("POST","/api/admin/ad-creatives/smart-publish",t).then(s=>s.json()),onSuccess:t=>{t.jobId?m0(t.jobId):jo(t)},onError:t=>{Zr(t.message||"Erro interno")}}),No=W({mutationFn:()=>N("POST","/api/admin/performance/sync").then(t=>t.json()),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/performance"]}),K.invalidateQueries({queryKey:["/api/admin/campaign-snapshots-all"]}),r({title:"Sincronizado!",description:t.details||t.message})},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})}),Pm=W({mutationFn:t=>N("POST","/api/admin/optimizer/toggle",t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/optimizer/status"]}),r({title:"Optimizer atualizado!"})}}),fo=W({mutationFn:t=>N("POST","/api/admin/optimizer/rules",t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/optimizer/rules"]}),Yn(!1),r({title:"Regra criada!"})},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})}),h0=W({mutationFn:({id:t,isActive:s})=>N("PATCH",`/api/admin/optimizer/rules/${t}`,{isActive:s}).then(i=>i.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/optimizer/rules"]})}}),p0=W({mutationFn:t=>N("DELETE",`/api/admin/optimizer/rules/${t}`),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/optimizer/rules"]}),r({title:"Regra excluída"})}}),wo=W({mutationFn:()=>N("POST","/api/admin/optimizer/run").then(t=>t.json()),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/optimizer/actions"]}),r({title:"Optimizer executado",description:`${t.evaluated} regras, ${t.actionsCount} ações`})}}),[wl,u0]=d.useState("all"),[us,yo]=d.useState(null),[yl,en]=d.useState(!1),[tn,g0]=d.useState(""),[sn,b0]=d.useState(""),ko=d.useRef(null);d.useEffect(()=>{function t(s){ko.current&&!ko.current.contains(s.target)&&en(!1)}if(yl)return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[yl]);const[Co,kl]=d.useState([]),[j0,Cl]=d.useState(!1),[oa,Rj]=d.useState(null),[v0,So]=d.use
2State(!1),[N0,$o]=d.useState(!1),[ca,an]=d.useState({credentialType:"api_key",credentialKey:"",credentialValue:"",environment:"sandbox"}),[xa,rn]=d.useState({supportedFormats:[],royaltyRate:.7,sabhiaCommission:.05,apiDocUrl:"",authMethod:"api_key"}),[Fj,Dj]=d.useState(null),[f0,Ao]=d.useState(!1),[Po,Tm]=d.useState(""),{data:Sl}=z({queryKey:["/api/admin/support/conversations",wl],queryFn:()=>{const t=wl!=="all"?`?status=${wl}`:"";return N("GET",`/api/admin/support/conversations${t}`).then(s=>s.json())},enabled:pe&&le==="support",refetchInterval:le==="support"?1e4:!1}),{data:Hs}=z({queryKey:["/api/admin/support/conversations",us],queryFn:()=>N("GET",`/api/admin/support/conversations/${us}`).then(t=>t.json()),enabled:pe&&le==="support"&&!!us,refetchInterval:le==="support"&&us?5e3:!1}),[di,w0]=d.useState("chat"),[$l,To]=d.useState(null),[ma,qi]=d.useState({title:"",content:"",category:"geral"}),[Os,Eo]=d.useState(null),[Io,Em]=d.useState(""),[Ro,Fo]=d.useState([]),[Do,Im]=d.useState(""),[nn,Rm]=d.useState(!1),[Mo,y0]=d.useState(!1),Lo=d.useRef(null),{data:zo}=z({queryKey:["/api/settings/ai_email_enabled"],queryFn:()=>N("GET","/api/settings/ai_email_enabled").then(t=>t.json()).catch(()=>({value:"true"})),enabled:pe&&le==="support"&&di==="email"}),{data:Al,isLoading:k0}=z({queryKey:["/api/admin/support/knowledge-base"],queryFn:()=>N("GET","/api/admin/support/knowledge-base").then(t=>t.json()),enabled:pe&&le==="support"&&di==="kb"}),qo=W({mutationFn:t=>N("POST","/api/admin/support/knowledge-base",t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/support/knowledge-base"]}),qi({title:"",content:"",category:"geral"}),r({title:"Entrada criada com sucesso!"})},onError:t=>r({title:"Erro ao criar",description:t.message,variant:"destructive"})}),_o=W({mutationFn:t=>N("PUT",`/api/admin/support/knowledge-base/${t.id}`,t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/support/knowledge-base"]}),To(null),qi({title:"",content:"",category:"geral"}),r({title:"Entrada atualizada!"})},onError:t=>r({title:"Erro ao atualizar",description:t.message,variant:"destructive"})}),C0=W({mutationFn:t=>N("DELETE",`/api/admin/support/knowledge-base/${t}`).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/support/knowledge-base"]}),r({title:"Entrada removida!"})},onError:t=>r({title:"Erro ao remover",description:t.message,variant:"destructive"})}),S0=W({mutationFn:t=>N("PUT",`/api/admin/support/knowledge-base/${t.id}`,{isActive:t.isActive}).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/support/knowledge-base"]})}}),$0=W({mutationFn:t=>N("PUT","/api/admin/settings/ai_email_enabled",{value:t?"true":"false"}),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/settings/ai_email_enabled"]}),r({title:"IA Email atualizada!"})}}),{data:Oo}=z({queryKey:["/api/admin/email-conversations"],queryFn:()=>N("GET","/api/admin/email-conversations").then(t=>t.json()),enabled:pe&&le==="support"&&di==="email",refetchInterval:15e3}),{data:oi}=z({queryKey:["/api/admin/email-conversations",Os,"messages"],queryFn:()=>N("GET",`/api/admin/email-conversations/${Os}/messages`).then(t=>t.json()),enabled:pe&&le==="support"&&di==="email"&&!!Os,refetchInterval:1e4}),Bo=W({mutationFn:t=>N("POST",`/api/admin/email-conversations/${t.id}/reply`,{body:t.body}).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/email-conversations"]}),K.invalidateQueries({queryKey:["/api/admin/email-conversations",Os,"messages"]}),Em(""),r({title:"Email enviado!"})},onError:t=>r({title:"Erro ao enviar",description:t.message,variant:"destructive"})}),Uo=W({mutationFn:t=>N("PATCH",`/api/admin/email-conversations/${t.id}/status`,{status:t.status}).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/email-conversations"]}),K.invalidateQueries({queryKey:["/api/admin/email-conversations",Os,"messages"]}),r({title:"Status atualizado!"})},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})}),{data:Mj}=z({queryKey:["/api/admin/marketing-funnels/"+Ex+"/analytics"],enabled:pe&&!!Ex}),A0=W({mutationFn:t=>N("POST","/api/admin/platforms",t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/platforms"]}
2),r({title:"Plataforma criada!"}),Fn(!1)}}),P0=W({mutationFn:({id:t,data:s})=>N("PATCH",`/api/admin/platforms/${t}`,s).then(i=>i.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/platforms"]}),r({title:"Plataforma atualizada!"}),Fn(!1)}});W({mutationFn:t=>N("DELETE",`/api/admin/platforms/${t}`),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/platforms"]}),r({title:"Plataforma removida!"})}});const{data:Lj,isLoading:zj}=z({queryKey:["/api/admin/integrations/overview"],enabled:pe&&le==="integrations"}),{data:Ko}=z({queryKey:["/api/admin/platforms",oa?.id,"credentials"],queryFn:()=>oa?N("GET",`/api/admin/platforms/${oa.id}/credentials`).then(t=>t.json()):null,enabled:pe&&!!oa}),Go=W({mutationFn:t=>N("POST",`/api/admin/platforms/${oa?.id}/credentials`,t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/platforms",oa?.id,"credentials"]}),K.invalidateQueries({queryKey:["/api/admin/integrations/overview"]}),So(!1),an({credentialType:"api_key",credentialKey:"",credentialValue:"",environment:"sandbox"}),r({title:"Credencial salva com sucesso!"})},onError:t=>r({title:"Erro ao salvar credencial",description:t.message,variant:"destructive"})}),T0=W({mutationFn:t=>N("DELETE",`/api/admin/platforms/${oa?.id}/credentials/${t}`),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/platforms",oa?.id,"credentials"]}),K.invalidateQueries({queryKey:["/api/admin/integrations/overview"]}),r({title:"Credencial removida!"})}}),Vo=W({mutationFn:t=>N("PUT",`/api/admin/platforms/${oa?.id}/config`,t).then(s=>s.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/integrations/overview"]}),$o(!1),r({title:"Configuração atualizada!"})},onError:t=>r({title:"Erro ao atualizar",description:t.message,variant:"destructive"})}),Qo=W({mutationFn:t=>N("POST","/api/admin/sales/import",t).then(s=>s.json()),onSuccess:t=>
2{r({title:"Importação concluída!",description:`${t.imported} registros importados, ${t.skipped} ignorados`}),Ao(!1),Tm(""),K.invalidateQueries({queryKey:["/api/admin/integrations/overview"]})},onError:t=>r({title:"Erro na importação",description:t.message,variant:"destructive"})}),Wo=W({mutationFn:async t=>{fd?await N("PUT",`/api/admin/marketing-templates/${fd.id}`,t):await N("POST","/api/admin/marketing-templates",t)},onSuccess:()=>{r({title:"Template salvo!"}),K.invalidateQueries({queryKey:["/api/admin/marketing-templates"]}),Nd(!1),pp(null)},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})});W({mutationFn:async t=>{await N("DELETE",`/api/admin/marketing-templates/${t}`)},onSuccess:()=>{r({title:"Template removido!"}),K.invalidateQueries({queryKey:["/api/admin/marketing-templates"]})}}),W({mutationFn:async t=>{Tx?await N("PUT",`/api/admin/marketing-funnels/${Tx.id}`,t):await N("POST","/api/admin/marketing-funnels",t)},onSuccess:()=>{r({title:"Funil salvo!"}),K.invalidateQueries({queryKey:["/api/admin/marketing-funnels"]}),bp(!1),jp(null)},onError:t=>r({title:"Erro",description:t.message,variant:"destructive"})}),W({mutationFn:async t=>{await N("DELETE",`/api/admin/marketing-funnels/${t}`)},onSuccess:()=>{r({title:"Funil removido!"}),K.invalidateQueries({queryKey:["/api/admin/marketing-funnels"]})}});const Fm=async()=>{Ax(!0);try{const s=await(await N("GET","/api/admin/whatsapp-templates")).json();up(s.templates||[])}catch(t){r({title:"Erro ao buscar templates",description:t.message,variant:"destructive"})}finally{Ax(!1)}},E0=t=>{gp(t),la(i=>({...i,whatsappTemplateName:t.name,whatsappTemplateLanguage:t.language}));const s={};t.components?.forEach(i=>{if(i.text){const x=i.text.match(/\{\{(\d+)\}\}/g);x&&x.forEach(C=>{const P=C.replace(/[{}]/g,""),H=`${i.type.toLowerCase()}_${P}`;s[H]=""})}}),Px(s)},I0=()=>{if(!er)return[];const t=[];return er.components?.forEach(s=>{if(!s.text)return;const i=s.text.match(/\{\{(\d+)\}\}/g);if(!i||i.length===0)return;const x=i.map(C=>{const P=C.replace(/[{}]/g,""),H=`${s.type.toLowerCase()}_${P}`;return{type:"text",text:Mn[H]||""}});t.push({type:s.type.toLowerCase(),parameters:x})}),t},Dm=async()=>{tx(!0);try{const i=(await(await N("GET","/api/admin/whatsapp-templates")).json()).templates||[];if(ex(i),Tt.metaTemplateName&&i.length>0){const x=i.find(C=>C.name===Tt.metaTemplateName);if(x){$i(x);const C={};x.components?.forEach(P=>{if(P.type==="BUTTONS"&&P.buttons)P.buttons.forEach((H,Q)=>{H.type==="URL"&&H.url&&H.url.match(/\{\{(\d+)\}\}/g)&&(C[`button_url_${Q}`]="")});else if(P.text){const H=P.text.match(/\{\{(\d+)\}\}/g);H&&H.forEach(Q=>{const G=Q.replace(/[{}]/g,""),ue=`${P.type.toLowerCase()}_${G}`;C[ue]=""})}});try{const P=JSON.parse(Tt.metaComponents||"[]");Array.isArray(P)&&P.forEach(H=>{if(H.type==="button"&&H.sub_type==="url"){const Q=`button_url_${H.index||"0"}`;H.parameters?.[0]?.text&&C[Q]!==void 0&&(C[Q]=H.parameters[0].text)}else H.parameters&&H.parameters.forEach((Q,G)=>{const ue=`${H.type}_${G+1}`;Q.text&&C[ue]!==void 0&&(C[ue]=Q.text)})})}catch{}Za(C)}}}catch(t){r({title:"Erro ao buscar templates",description:t.message,variant:"destructive"})}finally{tx(!1)}};d.useEffect(()=>{le==="notifications"&&ua.length===0&&Ls&&Dm()},[le,Ls]),d.useEffect(()=>{qs&&(wx(qs.windowStart||"08:00"),kx(qs.windowEnd||"11:00"))},[qs]),d.useEffect(()=>{vd&&Et.channel==="whatsapp"&&Rr.length===0&&Fm()},[vd,Et.channel]);const R0=t=>{$i(t),Ya(i=>({...i,metaTemplateName:t.name,metaTemplateLanguage:t.language}));const s={};t.components?.forEach(i=>{if(i.type==="BUTTONS"&&i.buttons)i.buttons.forEach((x,C)=>{if(x.type==="URL"&&x.url){const P=x.url.match(/\{\{(\d+)\}\}/g);P&&P.forEach(H=>{const Q=`button_url_${C}`;s[Q]=""})}});else if(i.text){const x=i.text.match(/\{\{(\d+)\}\}/g);x&&x.forEach(C=>{const P=C.replace(/[{}]/g,""),H=`${i.type.toLowerCase()}_${P}`;s[H]=""})}}),Is==="store_published"&&Object.entries({body_1:"{{author_name}}",body_2:"{{book_title}}",body_3:"{{sales_url}}"}).forEach(([x,C])=>{Object.prototype.hasOwnProperty.call(s,x)&&(s[x]=C)}),Za(s)},F0=()=>{if(!na)return[];const t=[];return na.components?.forEach(s=>{if(s.type==="BUTTONS"&&s.buttons)s.buttons.forEach((i,x)=>
2{if(i.type==="URL"&&i.url&&i.url.match(/\{\{(\d+)\}\}/g)){const P=`button_url_${x}`;t.push({type:"button",sub_type:"url",index:String(x),parameters:[{type:"text",text:Rn[P]||""}]})}});else if(s.text){const i=s.text.match(/\{\{(\d+)\}\}/g);if(!i||i.length===0)return;const x=i.map(C=>{const P=C.replace(/[{}]/g,""),H=`${s.type.toLowerCase()}_${P}`;return{type:"text",text:Rn[H]||""}});t.push({type:s.type.toLowerCase(),parameters:x})}}),t},Ho=W({mutationFn:async t=>{await N("POST","/api/admin/services",t)},onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/services"]}),n({...bc}),p(!1),r({title:"Serviço criado com sucesso!"})},onError:t=>r({title:"Erro ao criar serviço",description:t.message,variant:"destructive"})}),Pl=W({mutationFn:async({id:t,data:s})=>{await N("PATCH",`/api/admin/services/${t}`,s)},onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/services"]}),f(null),r({title:"Serviço atualizado!"})},onError:t=>r({title:"Erro ao atualizar",description:t.message,variant:"destructive"})}),Xo=W({mutationFn:async t=>{await N("DELETE",`/api/admin/services/${t}`)},onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/services"]}),w(null),r({title:"Serviço removido!"})},onError:t=>r({title:"Erro ao remover",description:t.message,variant:"destructive"})}),Jo=W({mutationFn:async t=>{await N("PUT","/api/admin/settings/book_generation_price",{value:t})},onSuccess:()=>{K.invalidateQueries({queryKey:["/api/settings/book_generation_price"]}),r({title:"Preço atualizado!"})}}),ln=W({mutationFn:async t=>(await N("PUT","/api/admin/free-plan-ip-guard",t)).json(),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/free-plan-ip-guard"]}),r({title:"Limite de planejamentos atualizado!"})},onError:t=>r({title:"Não foi possível atualizar",description:t.message,variant:"destructive"})}),Yo=W({mutationFn:async({id:t,role:s})=>{await N("PATCH",`/api/admin/users/${t}/role`,{role:s})},onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/users"]}),r({title:"Papel atualizado!"})},onError:t=>{r({title:"Não foi possível alterar o papel",description:t?.message||"Tente novamente.",variant:"destructive"})}}),Tl=W({mutationFn:async({id:t,multiplier:s,maxPerUser:i})=>(await N("PATCH",`/api/admin/users/${t}/support-credit-limits`,{multiplier:s,maxPerUser:i})).json(),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/users"]}),r({title:"Limite de crédito do agente atualizado."})},onError:t=>r({title:"Erro ao atualizar",description:t.message,variant:"destructive"})}),[D0,M0]=d.useState({}),L0=W({mutationFn:async({id:t,status:s})=>{await N("PATCH",`/api/admin/orders/${t}/status`,{status:s})},onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/orders"]}),K.invalidateQueries({queryKey:["/api/admin/metrics"]}
2),r({title:"Status do pedido atualizado!"})},onError:t=>r({title:"Erro ao atualizar",description:t.message,variant:"destructive"})}),Zo=W({mutationFn:async()=>(await N("POST","/api/admin/orders/reattribute")).json(),onSuccess:t=>{K.invalidateQueries({queryKey:["/api/admin/orders"]}),K.invalidateQueries({queryKey:["/api/admin/users"]}),r({title:"Reatribuição concluída",description:`${t.updated} de ${t.total} pedidos atualizados com dados de tráfego.`})},onError:t=>r({title:"Erro na reatribuição",description:t.message,variant:"destructive"})}),z0=async t=>{Aa(!0);try{const i=await(await N("GET",`/api/admin/orders/${t}/details`)).json();sa(i)}catch{r({title:"Erro ao buscar detalhes",variant:"destructive"})}finally{Aa(!1)}},br=W({mutationFn:async t=>{await N("PUT",`/api/admin/notification-templates/${Is}`,t)},onSuccess:()=>{r({title:"Templates salvos com sucesso!"}),K.invalidateQueries({queryKey:["/api/admin/notification-templates"]}),K.invalidateQueries({queryKey:["/api/admin/notification-templates",Is]})},onError:t=>r({title:"Erro ao salvar",description:t.message,variant:"destructive"})}),q0=async t=>{try{await navigator.clipboard.writeText(t),ki(!0),r({title:"URL copiada!"}),setTimeout(()=>ki(!1),3e3)}catch{r({title:"Erro ao copiar",variant:"destructive"})}},_0={plan_generation:"Planejamento",plan_edit:"Edição de Plano",outline_generation:"Estrutura",chapter_writing:"Escrita de Capítulo",chapter_summarization:"Resumo de Capítulo",chapter_summary:"Resumo de Capítulo",preface:"Prefácio",closing_message:"Mensagem do Autor",bibliography:"Bibliografia",bibliography_regeneration:"Regen. Bibliografia",chat:"Chat IA",conversation_chat:"Chat Conversação",cover_prompt_generation:"Prompt de Capa",cover_image_generation:"Imagem de Capa",cover_edit:"Edição de Capa",cover_chat_adjustment:"Ajuste de Capa (Chat)",illustration_prompt:"Prompt de Ilustração",illustration_generation:"Geração de Ilustração",illustration_positions:"Posições de Ilustração",background_generation:"Background do Livro",translation_title:"Tradução (Título)",translation_subtitle:"Tradução (Subtítulo)",translation_synopsis:"Tradução (Sinopse)",translation_chapter:"Tradução (Capítulo)",translation_chapter_title:"Tradução (Título Cap.)",translation_chapter_summary:"Tradução (Resumo Cap.)",chapter_outline:"Outline Capítulo",publishing_metadata:"Metadados de Publicação",sales_description:"Descrição de Vendas"},El=t=>{const s=t.firstTouch;if(!s)return{key:"organic",label:"Orgânico",color:"text-white/40 border-white/10"};const i=(s.utmSource||"").toLowerCase(),x=(s.landingPage||"").toLowerCase(),C=(s.referrer||"").toLowerCase();return i.includes("facebook")||i.includes("fb")||i==="ig"?{key:"facebook",label:"Facebook Ads",color:"text-blue-400 border-blue-500/30"}:i.includes("google")?{key:"google",label:"Google",color:"text-red-400 border-red-500/30"}:C.includes("/blog")||x.includes("/blog")?{key:"blog",label:"Blog",color:"text-orange-400 border-orange-500/30"}:x.includes("/chat")?{key:"chat",label:"Chat",color:"text-violet-400 border-violet-500/30"}:x.includes("/create-my-book")?{key:"create",label:"Criar Livro",color:"text-pink-400 border-pink-500/30"}:i?{key:"other",label:i,color:"text-cyan-400 border-cyan-500/30"}:C?{key:"referral",label:"Referral",color:"text-teal-400 border-teal-500/30"}:{key:"organic",label:"Orgânico",color:"text-white/40 border-white/10"}},ci=(S?Hc:Si)?.filter(t=>{if(c!=="all"){const i=El(t);if(c==="paid"&&i.key!=="facebook"&&i.key!=="google")return!1;if(c!=="paid"&&i.key!==c)return!1}if($!=="all"){const i=t.role||"user";if($==="user"&&i!=="user")return!1;if($!=="user"&&i!==$)return!1}if(S||!y)return!0;const s=y.toLowerCase();return t.email.toLowerCase().includes(s)||(t.name||"").toLowerCase().includes(s)}),Mm=d.useMemo(()=>{if(!cs)return[];const t=new Set;return cs.forEach(s=>{s.utmSource&&t.add(s.utmSource)}),Array.from(t).sort()},[cs]),Lm=d.useMemo(()=>{if(!cs)return[];const t=new Set;return cs.forEach(s=>{s.utmMedium&&t.add(s.utmMedium)}),Array.from(t).sort()},[cs]),zm=d.useMemo(()=>{if(!cs)return[];const t=new Set;return cs.forEach(s=>{s.utmCampaign&&t.add(s.utmCampaign)}),Array.from(t).sort()}
2,[cs]),qm=d.useMemo(()=>{if(!cs)return[];const t=new Set;return cs.forEach(s=>{s.chatFlowName&&t.add(s.chatFlowName)}),Array.from(t).sort()},[cs]),za=cs?.filter(t=>{if(ee!=="all"&&t.status!==ee||Ne!=="all"&&(t.utmSource||"")!==Ne||X!=="all"&&(t.utmMedium||"")!==X||ge!=="all"&&(t.utmCampaign||"")!==ge||at!=="all"&&(t.chatFlowName||"")!==at)return!1;if(!re)return!0;const s=re.toLowerCase();return t.id.toLowerCase().includes(s)||(t.userEmail||"").toLowerCase().includes(s)||(t.userName||"").toLowerCase().includes(s)||(t.bookTitle||"").toLowerCase().includes(s)||(t.serviceName||"").toLowerCase().includes(s)}),ec=200,dn=Math.max(1,Math.ceil((za?.length||0)/ec)),on=Math.min(pa,dn-1),O0=za?.slice(on*ec,(on+1)*ec);d.useEffect(()=>{Ms(0)},[re,ee,Ne,X,ge,at]);const B0=t=>{f(t),n({title:t.title,description:t.description||"",longDescription:t.longDescription||"",price:t.price,type:t.type,iconName:t.iconName||"Palette",recurring:t.recurring||!1,active:t.active!==!1,displayLocation:t.displayLocation||"services_tab",executionType:t.executionType||"ai",category:t.category||"outro",sortOrder:t.sortOrder||0,estimatedDays:t.estimatedDays||0,availableForManualSale:t.availableForManualSale||!1,allowOfferInChat:t.allowOfferInChat||!1,defaultDiscountPct:t.defaultDiscountPct||0,extraFieldsConfig:t.extraFieldsConfig||null})},U0=gc.find(t=>t.value===l.iconName)?.icon||Zs;function K0(){if(!Vs)return null;const t=(Array.isArray(ix)?ix:[]).find(Q=>(Q.book?.id||Q.tasks?.[0]?.bookId)===Vs),s=t?.book||{};t?.tasks;const i=lp,x=(Q,G)=>{navigator.clipboard.writeText(Q),dx(G),r({title:"Copiado!"}),setTimeout(()=>dx(null),2e3)},C=async()=>{nx(!0);try{await N("POST",`/api/admin/books/${Vs}/publishing-metadata/generate`);const Q=async(G=0)=>{if(G>60)throw new Error("Tempo limite excedido");await new Promise(Y=>setTimeout(Y,3e3));const Te=await(await N("GET",`/api/books/${Vs}/publishing-metadata/status`)).json();if(Te.status!=="done"){if(Te.status==="generating")return Q(G+1);if(!(G>3))return Q(G+1)}};await Q(),await ox(),r({title:"Metadados gerados com sucesso!"})}catch(Q){r({title:"Erro ao gerar",description:Q.message,variant:"destructive"})}finally{nx(!1)}},P=async(Q,G)=>{lx(!0);try{await N("PATCH",`/api/admin/books/${Vs}/publishing-metadata`,{[Q]:G}),await ox(),r({title:"Salvo!"})}catch(ue){r({title:"Erro ao salvar",description:ue.message,variant:"destructive"})}finally{lx(!1)}},H=({text:Q,field:G})=>e.jsx(b,{variant:"ghost",size:"sm",className:"h-6 px-2 text-[10px] text-muted-foreground hover:text-white",onClick:()=>x(Q,G),"data-testid":`btn-copy-${G}`,children:Er===G?e.jsx(be,{className:"w-3 h-3 text-emerald-400"}):e.jsx(ha,{className:"w-3 h-3"})});return e.jsx(Je,{open:!!Vs,onOpenChange:Q=>!Q&&rp(null),children:e.jsxs(Ye,{className:"max-w-[900px] max-h-[90vh] overflow-y-auto bg-[#0d1f1a] border-white/10",children:[e.jsx(Ze,{children:e.jsxs(et,{className:"flex items-center gap-3 text-lg",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-blue-400/20 to-cyan-600/20 flex items-center justify-center",children:e.jsx(tt,{className:"w-5 h-5 text-blue-400"})}),e.jsxs("div",{children:[e.jsx("span",{className:"text-white",children:"Detalhes de Publicação"}),e.jsx("p",{className:"text-xs text-muted-foreground font-normal mt-0.5",children:s.title||"Sem título"})]})]})}),e.jsxs("div",{className:"flex items-center justify-between bg-gradient-to-r from-blue-500/10 to-cyan-500/10 border border-blue-500/20 rounded-xl p-4",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-blue-400"})," Gerar Metadados com IA"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:i?.generatedAt?`Gerado em ${new Date(i.generatedAt).toLocaleDateString("pt-BR")}`:"Gere todos os campos automaticamente com inteligência artificial"})]}),e.jsx(b,{onClick:C,disabled:rx,className:"bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600 text-white","data-testid":"btn-generate-metadata",children:rx?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 mr-2 animate-spin"})," Gerando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"w-4 h-4 mr-2"})," ",i?.generatedAt?"Regenerar":"Gerar com IA"]})})]}),dp?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2 border-b border-white/10 pb-2",children:[e.jsx(ot,{className:"w-4 h-4 text-emerald-400"})," Informações Básicas"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Título do Livro"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("p",{className:"text-sm text-white font-medium",children:s.title||"—"}),s.title&&e.jsx(H,{text:s.title,field:"title"})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Subtítulo"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("p",{className:"text-sm text-white",children:s.subtitle||"—"}),s.subtitle&&e.jsx(H,{text:s.subtitle,field:"subtitle"})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Nome do Autor"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsxs("p",{className:"text-sm text-white",children:[i?.authorFirstName||""," ",i?.authorLastName||s.author||"—"]}),(i?.authorFirstName||s.author)&&e.jsx(H,{text:`${i?.authorFirstName||""} ${i?.authorLastName||s.author||""}`,field:"author"})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Editora"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("p",{className:"text-sm text-white",children:i?.publisherName||"SÁBHIA"}),e.jsx(H,{text:i?.publisherName||"SÁBHIA",field:"publisher"})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Idioma"}),e.jsx("p",{className:"text-sm text-white mt-1",children:s.language==="pt"?"Português":s.language==="en"?"English":s.language==="es"?"Español":s.language||"—"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Gênero"}),e.jsx("p",{className:"text-sm text-white mt-1",children:s.genre||"—"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"ISBN"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("p",{className:"text-sm text-white",children:i?.isbn||"Não atribuído"}),i?.isbn&&e.jsx(H,{text:i.isbn,field:"isbn"})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Conteúdo Gerado por IA"}),e.jsx("p",{className:"text-sm text-white mt-1",children:i?.aiContentDisclosure?"Sim":"Não"})]})]})]}),i?.tagline&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2 border-b border-white/10 pb-2",children:[e.jsx(wn,{className:"w-4 h-4 text-yellow-400"})," Frase de Destaque (Tagline)"]}),e.jsxs("div",{className:"bg-gradient-to-r from-yellow-500/10 to-amber-500/10 border border-yellow-500/20 rounded-lg p-3 flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-white font-medium italic",children:['"',i.tagline,'"']}),e.jsx(H,{text:i.tagline,field:"tagline"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2 border-b border-white/10 pb-2 flex-1",children:[e.jsx(tt,{className:"w-4 h-4 text-blue-400"})," Descrição Comercial (Amazon KDP)"]}
2),i?.kdpDescription&&e.jsx(H,{text:i.kdpDescription,field:"kdpDescription"})]}),i?.kdpDescription?e.jsxs("div",{className:"bg-white/[0.03] border border-white/10 rounded-lg p-4",children:[e.jsx("div",{className:"text-sm text-white/90 leading-relaxed prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:i.kdpDescription}}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-3 text-right",children:[i.kdpDescription.replace(/<[^>]+>/g,"").length," / 4000 caracteres"]})]}):e.jsx("p",{className:"text-xs text-muted-foreground italic",children:'Clique em "Gerar com IA" para criar a descrição comercial'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2 border-b border-white/10 pb-2 flex-1",children:[e.jsx(ot,{className:"w-4 h-4 text-purple-400"})," Sinopse Editorial"]}),i?.editorialSynopsis&&e.jsx(H,{text:i.editorialSynopsis,field:"editorialSynopsis"})]}),i?.editorialSynopsis?e.jsx("div",{className:"bg-white/[0.03] border border-white/10 rounded-lg p-4",children:e.jsx("p",{className:"text-sm text-white/90 leading-relaxed",children:i.editorialSynopsis})}):e.jsx("p",{className:"text-xs text-muted-foreground italic",children:'Clique em "Gerar com IA" para criar a sinopse editorial'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2 border-b border-white/10 pb-2 flex-1",children:[e.jsx(St,{className:"w-4 h-4 text-cyan-400"})," Palavras-chave (7 Keywords SEO)"]}),i?.keywords&&i.keywords?.length>0&&e.jsx(b,{variant:"ghost",size:"sm",className:"h-6 px-2 text-[10px] text-muted-foreground hover:text-white",onClick:()=>x(i.keywords.join(", "),"allKeywords"),"data-testid":"btn-copy-all-keywords",children:Er==="allKeywords"?e.jsx(be,{className:"w-3 h-3 text-emerald-400"}):e.jsxs(e.Fragment,{children:[e.jsx(ha,{className:"w-3 h-3 mr-1"})," Copiar todas"]})})]}),i?.keywords&&i.keywords?.length>0?e.jsx("div",{className:"flex flex-wrap gap-2",children:i.keywords.map((Q,G)=>e.jsxs("div",{className:"flex items-center gap-1 bg-cyan-500/10 border border-cyan-500/20 rounded-lg px-3 py-1.5 group cursor-pointer hover:bg-cyan-500/20 transition-colors",onClick:()=>x(Q,`kw-${G}`),"data-testid":`keyword-${G}`,children:[e.jsx("span",{className:"text-xs text-cyan-300",children:Q}),Er===`kw-${G}`?e.jsx(be,{className:"w-3 h-3 text-emerald-400"}):e.jsx(ha,{className:"w-3 h-3 text-cyan-400/50 group-hover:text-cyan-400 transition-colors"})]},G))}):e.jsx("p",{className:"text-xs text-muted-foreground italic",children:'Clique em "Gerar com IA" para criar palavras-chave'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2 border-b border-white/10 pb-2 flex-1",children:[e.jsx(Zs,{className:"w-4 h-4 text-orange-400"})," Categorias Amazon KDP"]}),i?.bisacCategories&&i.bisacCategories?.length>0&&e.jsx(b,{variant:"ghost",size:"sm",className:"h-6 px-2 text-[10px] text-muted-foreground hover:text-white",onClick:()=>x(i.bisacCategories.join(`
3`),"allCategories"),"data-testid":"btn-copy-all-categories",children:Er==="allCategories"?e.jsx(be,{className:"w-3 h-3 text-emerald-400"}):e.jsxs(e.Fragment,{children:[e.jsx(ha,{className:"w-3 h-3 mr-1"})," Copiar todas"]})})]}),i?.bisacCategories&&i.bisacCategories?.length>0?e.jsx("div",{className:"space-y-1.5",children:i.bisacCategories.map((Q,G)=>e.jsxs("div",{className:"flex items-center justify-between bg-orange-500/10 border border-orange-500/20 rounded-lg px-3 py-2 group cursor-pointer hover:bg-orange-500/20 transition-colors",onClick:()=>x(Q,`cat-${G}`),"data-testid":`category-${G}`,children:[e.jsxs("span",{className:"text-xs text-orange-300",children:[G+1,". ",Q]}),Er===`cat-${G}`?e.jsx(be,{className:"w-3 h-3 text-emerald-400"}):e.jsx(ha,{className:"w-3 h-3 text-orange-400/50 group-hover:text-orange-400 transition-colors"})]},G))}):e.jsx("p",{className:"text-xs text-muted-foreground italic",children:'Clique em "Gerar com IA" para gerar categorias Amazon KDP'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2 border-b border-white/10 pb-2",children:[e.jsx(Re,{className:"w-4 h-4 text-pink-400"})," Público-alvo"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-white/[0.03] border border-white/10 rounded-lg p-3",children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Idade Mínima"}),e.jsx("p",{className:"text-sm text-white mt-1",children:i?.ageRangeMin!=null?`${i.ageRangeMin} anos`:"—"})]}),e.jsxs("div",{className:"bg-white/[0.03] border border-white/10 rounded-lg p-3",children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Idade Máxima"}),e.jsx("p",{className:"text-sm text-white mt-1",children:i?.ageRangeMax!=null?`${i.ageRangeMax} anos`:"—"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2 border-b border-white/10 pb-2",children:[e.jsx(Rt,{className:"w-4 h-4 text-emerald-400"})," Downloads"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:`/api/admin/books/${Vs}
3/epub`,className:"inline-flex items-center gap-1.5 text-xs bg-emerald-500/10 border border-emerald-500/20 rounded-lg px-3 py-2 text-emerald-400 hover:bg-emerald-500/20 transition-colors","data-testid":"btn-download-epub-details",children:[e.jsx(Rt,{className:"w-3.5 h-3.5"})," Baixar EPUB"]}),s.coverImage&&e.jsxs("a",{href:`/api/admin/books/${Vs}/cover.jpg`,className:"inline-flex items-center gap-1.5 text-xs bg-purple-500/10 border border-purple-500/20 rounded-lg px-3 py-2 text-purple-400 hover:bg-purple-500/20 transition-colors","data-testid":"btn-download-cover-details",children:[e.jsx(Rt,{className:"w-3.5 h-3.5"})," Capa JPG (KDP)"]}),e.jsxs("a",{href:`/api/admin/books/${Vs}/pdf`,className:"inline-flex items-center gap-1.5 text-xs bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2 text-blue-400 hover:bg-blue-500/20 transition-colors","data-testid":"btn-download-pdf-details",children:[e.jsx(Rt,{className:"w-3.5 h-3.5"})," Baixar PDF"]}),e.jsxs("a",{href:`/api/admin/books/${Vs}/docx`,className:"inline-flex items-center gap-1.5 text-xs bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2 text-amber-400 hover:bg-amber-500/20 transition-colors","data-testid":"btn-download-docx-details",children:[e.jsx(Rt,{className:"w-3.5 h-3.5"})," Baixar DOCX"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2 border-b border-white/10 pb-2",children:[e.jsx(pt,{className:"w-4 h-4 text-teal-400"})," URLs de Publicação nas Plataformas"]}),e.jsx("div",{className:"space-y-2",children:[{key:"amazonUrl",label:"Amazon KDP",placeholder:"https://amazon.com/dp/B0..."},{key:"appleUrl",label:"Apple Books",placeholder:"https://books.apple.com/book/..."},{key:"googlePlayUrl",label:"Google Play",placeholder:"https://play.google.com/store/books/..."},{key:"koboUrl",label:"Kobo",placeholder:"https://www.kobo.com/ebook/..."},{key:"barnesNobleUrl",label:"Barnes & Noble",placeholder:"https://www.barnesandnoble.com/w/..."},{key:"streetlibUrl",label:"StreetLib",placeholder:"https://www.streetlib.com/..."},{key:"luluUrl",label:"Lulu",placeholder:"https://www.lulu.com/..."},{key:"publishdriveUrl",label:"PublishDrive",placeholder:"https://publishdrive.com/..."}].map(Q=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"text-xs text-muted-foreground w-28 shrink-0",children:Q.label}),e.jsx(J,{placeholder:Q.placeholder,defaultValue:i?.[Q.key]||"",className:"h-8 text-xs bg-white/5 border-white/10 flex-1",onBlur:G=>{const ue=G.target.value.trim();ue!==(i?.[Q.key]||"")&&P(Q.key,ue||null)},"data-testid":`input-platform-url-${Q.key}`}),i?.[Q.key]&&e.jsx("a",{href:i[Q.key],target:"_blank",rel:"noopener noreferrer",className:"shrink-0",children:e.jsx(vs,{className:"w-3.5 h-3.5 text-muted-foreground hover:text-white"})})]},Q.key))})]})]})]})})}return e.jsxs(X0,{children:[e.jsxs("div",{className:"p-3 md:p-8 max-w-7xl mx-auto space-y-6 overflow-x-hidden",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl md:text-3xl font-heading font-bold text-white mb-1","data-testid":"text-admin-title",children:"Painel de Gestão"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gerencie produtos, vendas, clientes e configurações da plataforma."})]}),e.jsx(Ku,{}),e.jsx(Bu,{}),e.jsxs(Vm,{value:le,onValueChange:t=>aa(t),children:[e.jsxs(Qm,{className:"bg-white/5 border border-white/10 flex-wrap h-auto gap-1 p-1",children:[e.jsxs(we,{value:"metrics",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(ft,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Dashboard"]}),e.jsxs(we,{value:"bi",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Ie,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," BI"]}),e.jsxs(we,{value:"meta-tracking",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(jt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Meta"]}),e.jsxs(we,{value:"orders",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Jt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Vendas"]}),e.jsxs(we,{value:"users",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Re,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Clientes"]}),e.jsxs(we,{value:"leitores",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-leitores",onClick:()=>{window.location.href="/admin/leitores"},children:[e.jsx(ot,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Leitores"]}),e.jsxs(we,{value:"books",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(ot,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Livros"]}),e.jsxs(we,{value:"settings",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(qa,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Config"]}),e.jsxs(we,{value:"webhooks",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(pt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Webhooks"]}),e.jsxs(we,{value:"notifications",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Nn,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Notificações"]}),e.jsxs(we,{value:"costs",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Ht,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Custos IA"]}),e.jsxs(we,{value:"daily-emails",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Ge,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Emails"]}
3),e.jsxs(we,{value:"ad-creatives",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Xt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Tráfego"]}),e.jsxs(we,{value:"support",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Ut,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Suporte"]}),e.jsxs(we,{value:"blog",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(tt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Blog"]}),e.jsxs(we,{value:"origins",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(lt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Origens"]}),e.jsxs(we,{value:"sales-attribution",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx($r,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Atribuição"]}),e.jsxs(we,{value:"orchestration",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Ot,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Orquestração"]}),e.jsxs(we,{value:"growth",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Ie,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Crescimento"]}),e.jsxs(we,{value:"chat-ab",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Il,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Chat A/B"]}),e.jsxs(we,{value:"chat-builder",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-chat-builder",onClick:()=>{window.location.href="/admin/chat-builder"},children:[e.jsx(Ut,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Construtor"]}),e.jsxs(we,{value:"leads-crm",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-leads-crm",onClick:()=>{window.location.href="/admin/leads"},children:[e.jsx(Re,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Leads CRM"]}),e.jsxs(we,{value:"clientes-fundadores",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-clientes-fundadores",onClick:()=>{window.location.href="/admin/clientes-fundadores"},children:[e.jsx(J0,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Fundadores"]}),e.jsxs(we,{value:"ai-optimization",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-ai-optimization",onClick:()=>{window.location.href="/admin/ai-optimization"},children:[e.jsx(qe,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Otimização IA"]}),e.jsxs(we,{value:"bundle-delivery",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-bundle-delivery",onClick:()=>{window.location.href="/admin/bundle-delivery"},children:[e.jsx(Zs,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Pacotes"]}),e.jsxs(we,{value:"meta-tracking-health",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-meta-tracking-health",onClick:()=>{window.location.href="/admin/meta-tracking-health"},children:[e.jsx(jt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Tracking Meta"]}),e.jsxs(we,{value:"meta-relatorios",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-meta-relatorios",onClick:()=>{window.location.href="/admin/meta-relatorios"},children:[e.jsx(ft,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Relatórios Meta"]}),e.jsxs(we,{value:"contabilizacao",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-contabilizacao",onClick:()=>{window.location.href="/admin/contabilizacao"},children:[e.jsx(nt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Contabilização"]}),e.jsxs(we,{value:"custos-apis",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-custos-apis",onClick:()=>{window.location.href="/admin/custos-apis"},children:[e.jsx(nt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Custos APIs"]}),e.jsxs(we,{value:"funil-landing",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-funil-landing",onClick:()=>{window.location.href="/admin/funil-landing"},children:[e.jsx(Ie,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Funil Landing"]}),e.jsxs(we,{value:"landingpages",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-landingpages",onClick:()=>{window.location.href="/admin/landingpages"},children:[e.jsx(pt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Hub LPs"]}),e.jsxs(we,{value:"funil-conversao",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-funil-conversao",onClick:()=>{window.location.href="/admin/funil-conversao"},children:[e.jsx(qe,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Funil Conversão"]}),e.jsxs(we,{value:"plan-followup",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-plan-followup",onClick:()=>{window.location.href="/admin/plan-followup"},children:[e.jsx(qe,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Recuperação Planos"]}),e.jsxs(we,{value:"upsell-stats",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-upsell-stats",onClick:()=>{window.location.href="/admin/upsell-stats"},children:[e.jsx(Ge,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Upsell Pós-Compra"]}),e.jsxs(we,{value:"audiobook-access",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-audiobook-access",onClick:()=>{window.location.href="/admin/audiobook-access"},children:[e.jsx(Y0,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Audiobook"]}
3),e.jsxs(we,{value:"launch-plan-access",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-launch-plan-access",onClick:()=>{window.location.href="/admin/launch-plan-access"},children:[e.jsx(Z0,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Acesso Plano Lanç."]}),e.jsxs(we,{value:"isbn-access",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-isbn-access",onClick:()=>{window.location.href="/admin/isbn-access"},children:[e.jsx(ju,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Acesso ISBN"]}),e.jsxs(we,{value:"loja-sabhia",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-loja-sabhia",onClick:()=>{window.location.href="/admin/loja/visao-geral"},children:[e.jsx(Gl,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Loja Sábhia"]}),e.jsxs(we,{value:"sales-funnels",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-sales-funnels",onClick:()=>{window.location.href="/admin/sales-funnels"},children:[e.jsx(Ka,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Funis de Venda"]}),e.jsxs(we,{value:"checkouts",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Bt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Checkouts"]}),e.jsxs(we,{value:"recovery",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(xe,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Recuperação"]}),e.jsxs(we,{value:"checkout-ab",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(ka,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," A/B Checkout"]}),e.jsxs(we,{value:"plan-landing-ab",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-plan-landing-ab",children:[e.jsx(Oi,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Hub vs Editor"]}),e.jsxs(we,{value:"margin",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(nt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Margem"]}),e.jsxs(we,{value:"social-media",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(ls,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Social"]}),e.jsxs(we,{value:"author-health",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Xm,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Saúde"]}),e.jsxs(we,{value:"disputes",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Ks,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Disputas"]}),e.jsxs(we,{value:"influencers",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(Vi,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Influencers"]}),e.jsxs(we,{value:"author-prospector",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-author-prospector",children:[e.jsx(qe,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Prospecção Autores"]}),e.jsxs(we,{value:"ebook-funnel",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5",children:[e.jsx(ot,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Funil"]}),e.jsxs(we,{value:"ops",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-ops",children:[e.jsx(jt,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Ops"]}),e.jsxs(we,{value:"digiwork-webhooks",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-digiwork-webhooks",onClick:()=>{window.location.href="/admin/digiwork-webhooks"},children:[e.jsx(vu,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Webhooks DigiWork"]}),e.jsxs(we,{value:"greenn-webhooks",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-greenn-webhooks",onClick:()=>{window.location.href="/admin/webhooks-greenn"},children:[e.jsx(Ka,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Webhooks Greenn"]}),e.jsxs(we,{value:"servicos-humanos",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-servicos-humanos",onClick:()=>{window.location.href="/admin/servicos-humanos"},children:[e.jsx(Zs,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Serv. Humanos"]}),e.jsxs(we,{value:"educa",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-educa",onClick:()=>{window.location.href="/admin/educa"},children:[e.jsx(Bm,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Educa"]}
3),e.jsxs(we,{value:"quality",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-quality",children:[e.jsx(Ks,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Qualidade"]}),e.jsxs(we,{value:"interview-popup",className:"gap-1 text-[9px] md:text-xs whitespace-nowrap px-2 py-1 md:px-3 md:py-1.5","data-testid":"tab-interview-popup",children:[e.jsx(Us,{className:"w-3 h-3 md:w-3.5 md:h-3.5"})," Entrevista Vale"]})]}),e.jsx(Be,{value:"interview-popup",className:"mt-6",children:e.jsx(zb,{})}),e.jsx(Be,{value:"bi",className:"mt-6",children:e.jsx(Qg,{})}),e.jsx(Be,{value:"meta-tracking",className:"mt-6",children:e.jsx(Sb,{})}),e.jsxs(Be,{value:"metrics",className:"mt-6 space-y-6",children:[ws&&(()=>{const t=Q=>`R$ ${Q.toLocaleString("pt-BR",{minimumFractionDigits:0,maximumFractionDigits:0})}`,s=(Q,G)=>G>0?Q/G:null,i=Q=>Q===null?"text-white/40":Q>=.85?"text-emerald-400":Q>=.55?"text-amber-400":"text-red-400",x=ws.lastSaleMinutesAgo,C=x===null?"bg-white/30":x<=90?"bg-emerald-400":x<=240?"bg-amber-400":"bg-red-400",P=x===null?"sem venda registrada":x<60?`última venda há ${x} min`:`última venda há ${Math.floor(x/60)}h${x%60?` ${x%60}min`:""}`,H=[{key:"orders",icon:Jt,label:"Pedidos pagos",today:ws.paidOrders.today,avg:ws.paidOrders.avgAtThisHour,fmt:Q=>`${Q}`},{key:"revenue",icon:nt,label:"Receita (real)",today:ws.revenue.today,avg:ws.revenue.avgAtThisHour,fmt:t},{key:"plans",icon:ot,label:"Planos prontos",today:ws.plansReady.today,avg:ws.plansReady.avgAtThisHour,fmt:Q=>`${Q}`},{key:"signups",icon:Re,label:"Cadastros",today:ws.signups.today,avg:ws.signups.avgAtThisHour,fmt:Q=>`${Q}`}];return e.jsxs("div",{className:"relative overflow-hidden rounded-2xl border border-amber-500/25 bg-gradient-to-br from-black via-zinc-950 to-black p-5 sm:p-6 shadow-[0_0_40px_-12px_rgba(245,158,11,0.25)]","data-testid":"section-pulse",children:[e.jsx("div",{className:"absolute -top-24 -right-24 w-64 h-64 rounded-full bg-amber-500/10 blur-3xl pointer-events-none"}),e.jsxs("div",{className:"relative flex items-center gap-2.5 mb-1",children:[e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:`animate-ping absolute inline-flex h-full w-full rounded-full opacity-60 ${C}`}),e.jsx("span",{className:`relative inline-flex rounded-full h-2.5 w-2.5 ${C}`})]}),e.jsx("h3",{className:"text-base sm:text-lg font-bold tracking-tight bg-gradient-to-r from-amber-200 via-amber-400 to-amber-200 bg-clip-text text-transparent",children:"Pulso do Negócio · agora"}),e.jsx("span",{className:"ml-auto text-[11px] text-amber-300/70 font-medium","data-testid":"text-pulse-alive",children:P})]}),e.jsxs("p",{className:"relative text-[11px] text-white/45 mb-4",children:["Hoje (parcial) comparado com a ",e.jsx("span",{className:"text-white/70",children:"média dos últimos 7 dias no MESMO horário"})," — então um dia em andamento nunca parece queda."]}),e.jsx("div",{className:"relative grid grid-cols-2 lg:grid-cols-4 gap-3",children:H.map(Q=>{const G=s(Q.today,Q.avg),ue=G===null?null:Math.round(G*100),Te=Q.icon;return e.jsxs("div",{className:"rounded-xl border border-amber-500/15 bg-white/[0.03] p-4","data-testid":`pulse-tile-${Q.key}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-amber-300/60 mb-2",children:[e.jsx(Te,{className:"w-3.5 h-3.5"})," ",Q.label]}),e.jsx("div",{className:"text-2xl font-extrabold text-white leading-none","data-testid":`pulse-today-${Q.key}`,children:Q.fmt(Q.today)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-1",children:[e.jsxs("span",{className:"text-[10px] text-white/40",children:["méd. ",Q.fmt(Math.round(Q.avg))]}),ue===null?e.jsx("span",{className:"text-[10px] text-white/30",children:"—"}):e.jsxs("span",{className:`text-[11px] font-bold ${i(G)}`,"data-testid":`pulse-pace-${Q.key}`,children:[ue>=100?"▲":"▼"," ",ue,"%"]})]})]},Q.key)})}),e.jsxs("div",{className:"relative mt-4 grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-xl border border-amber-500/15 bg-white/[0.03] p-4 flex items-center gap-3","data-testid":"pulse-conversion",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-500/10 flex items-center justify-center shrink-0",children:e.jsx(Ie,{className:"w-4 h-4 text-amber-400"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-amber-300/60",children:"Conversão real · 7 dias"}),e.jsxs("div",{className:"text-lg font-bold text-white",children:[ws.conversion7d.rate===null?"—":`${ws.conversion7d.rate}%`,e.jsxs("span",{className:"ml-2 text-[11px] font-normal text-white/40",children:[ws.conversion7d.payers,"/",ws.conversion7d.planners," autores"]})]}),e.jsx("div",{className:"text-[10px] text-white/35",children:"planejou → pagou (per-usuário, orgânico). A verdade — não o 0% do card Stripe-only abaixo."})]})]}),e.jsxs("div",{className:"rounded-xl border border-amber-500/15 bg-white/[0.03] p-4 flex items-center gap-3","data-testid":"pulse-plans-created",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-500/10 flex items-center justify-center shrink-0",children:e.jsx(He,{className:"w-4 h-4 text-amber-400"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-amber-300/60",children:"Planos criados hoje"}),e.jsx("div",{className:"text-lg font-bold text-white",children:ws.plansCreated.today}),e.jsxs("div",{className:"text-[10px] text-white/35",children:["intenção de topo de funil (",P,")"]})]})]})]})]})})(),Oh&&e.jsx("div",{className:"flex items-center justify-center py-20","data-testid":"metrics-loading",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx(xe,{className:"w-8 h-8 animate-spin text-teal-400"}),e.jsx("p",{className:"text-gray-400 text-sm",children:"Carregando métricas..."})]})}),Bh&&!Pt&&e.jsx("div",{className:"flex items-center justify-center py-20","data-testid":"metrics-error",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-12 h-12 rounded-xl bg-red-500/10 border border-red-500/20 flex items-center justify-center",children:e.jsx(Ce,{className:"w-6 h-6 text-red-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white/80 font-medium text-sm",children:"Não foi possível carregar as métricas"}),e.jsx("p",{className:"text-white/40 text-xs mt-1",children:"Verifique sua conexão e tente novamente"})]}),e.jsxs("button",{onClick:()=>Uh(),className:"inline-flex items-center gap-2 px-4 py-2 bg-teal-600/20 hover:bg-teal-600/30 border border-teal-500/30 rounded-lg text-sm text-teal-400 transition-colors","data-testid":"button-retry-metrics",children:[e.jsx(xe,{className:"w-3.5 h-3.5"}),"Tentar novamente"]})]})}),Pt&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3",children:[e.jsx(kt,{icon:Re,label:"Clientes",value:Pt?.totalUsers??0,"data-testid":"metric-total-users"}),e.jsx(kt,{icon:ot,label:"Livros",value:Pt?.totalBooks??0,sub:`${Pt?.paidBooks??0} pagos`,"data-testid":"metric-total-books"}),e.jsx(kt,{icon:nt,label:"Receita Líquida",value:`R$ ${(Pt?.totalRevenue??0).toFixed(2)}`,color:"text-emerald-400",sub:"descontadas taxas","data-testid":"metric-total-revenue"}),e.jsx(kt,{icon:Jt,label:"Vendas Pagas",value:Pt?.paidOrdersCount??0,sub:`${Pt?.confirmedOrders??0} confirmadas total`,"data-testid":"metric-total-orders"}
3),e.jsx(kt,{icon:ns,label:"Pendentes",value:Pt?.pendingOrders??0,color:"text-amber-400","data-testid":"metric-pending-orders"}),e.jsx(kt,{icon:He,label:"Em Progresso",value:Pt?.booksInProgress??0,"data-testid":"metric-books-in-progress"}),e.jsx(kt,{icon:is,label:"Concluídos",value:Pt?.booksCompleted??0,color:"text-emerald-400","data-testid":"metric-books-completed"}),e.jsx(kt,{icon:Ie,label:"Conversão",value:Pt?.totalBooks?`${((Pt?.paidBooks??0)/Pt.totalBooks*100).toFixed(0)}%`:"0%",sub:"planejados → pagos","data-testid":"metric-conversion"})]}),e.jsx(Hu,{}),fs&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"section-checkout-health",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-teal-400"})," Saúde do Checkout",e.jsx("span",{className:"text-[10px] text-white/40 font-normal ml-auto",children:"últimos 30 dias"})]}),e.jsxs("p",{className:"text-[11px] text-amber-300/70 -mt-2 flex items-start gap-1.5","data-testid":"text-checkout-caveat",children:[e.jsx(Ce,{className:"w-3.5 h-3.5 shrink-0 mt-px"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Só Stripe (cartão)."})," Estas sessões NÃO incluem PIX (gateway Woovi) — por isso Conversão/PIX podem aparecer baixos ou 0%. Para a conversão real do negócio, veja o card ",e.jsx("strong",{children:"Pulso do Negócio"})," no topo."]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"Sessões"}),e.jsx("p",{className:"text-lg font-bold text-white","data-testid":"text-checkout-total-sessions",children:fs.totalSessions})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"Conversão"}),e.jsxs("p",{className:`text-lg font-bold ${fs.conversionRate>=10?"text-emerald-400":fs.conversionRate>=5?"text-amber-400":"text-red-400"}`,"data-testid":"text-checkout-conversion-rate",children:[fs.conversionRate,"%"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"PIX"}),e.jsxs("p",{className:"text-lg font-bold text-teal-400","data-testid":"text-checkout-pix-rate",children:[fs.pixSuccessRate,"%"]}),e.jsxs("p",{className:"text-[9px] text-white/30",children:[fs.pixPaid,"/",fs.pixSessions]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"Cartão"}),e.jsxs("p",{className:"text-lg font-bold text-blue-400","data-testid":"text-checkout-card-rate",children:[fs.cardSuccessRate,"%"]}),e.jsxs("p",{className:"text-[9px] text-white/30",children:[fs.cardPaid,"/",fs.cardSessions]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"Cancelamentos"}),e.jsx("p",{className:"text-lg font-bold text-red-400","data-testid":"text-checkout-cancelled",children:fs.cancelledOrders})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"Média Tentativas"}),e.jsx("p",{className:"text-lg font-bold text-violet-400","data-testid":"text-checkout-avg-attempts",children:fs.avgAttemptsBeforePurchase})]})]}),Object.keys(fs.cancellationBreakdown).length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-white/50 font-medium",children:"Motivos de cancelamento"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(fs.cancellationBreakdown).map(([t,s])=>{const x={method_switch:{label:"Troca de método",color:"bg-blue-500/20 text-blue-400 border-blue-500/30"}
3,bump_change:{label:"Alterou itens",color:"bg-amber-500/20 text-amber-400 border-amber-500/30"},superseded:{label:"Novo pedido",color:"bg-violet-500/20 text-violet-400 border-violet-500/30"},expired:{label:"Expirado",color:"bg-orange-500/20 text-orange-400 border-orange-500/30"},unknown:{label:"Sem motivo (legado)",color:"bg-white/10 text-white/50 border-white/10"}}[t]||{label:t,color:"bg-white/10 text-white/50 border-white/10"};return e.jsxs("span",{className:`px-2.5 py-1 rounded-full text-[11px] font-medium border ${x.color}`,"data-testid":`badge-cancel-reason-${t}`,children:[x.label,": ",s]},t)})})]})]}),ra&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"section-orphan-order-recovery",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4 text-teal-400"})," Recuperação de Pedidos Órfãos",e.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full ml-2 ${ra.masterEnabled&&ra.workerToggleEnabled?"bg-emerald-500/20 text-emerald-300":"bg-red-500/20 text-red-300"}`,children:ra.masterEnabled?ra.workerToggleEnabled?"Ativo":"Pausado (toggle)":"Desligado (env)"}),e.jsxs("button",{onClick:async()=>{Qc(!0);try{await fetch("/api/admin/orphan-order-recovery/run-now",{method:"POST",credentials:"include"}),await Kh()}catch(t){console.error("Run orphan recovery error:",t)}Qc(!1)},disabled:Vc,className:"ml-auto inline-flex items-center gap-1.5 px-2.5 py-1 bg-teal-600/20 hover:bg-teal-600/30 border border-teal-500/30 rounded-lg text-[11px] text-teal-400 transition-colors disabled:opacity-50","data-testid":"button-run-orphan-recovery",children:[Vc?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),"Rodar agora"]})]}),e.jsx("p",{className:"text-[11px] text-white/40 -mt-2",children:"Pedidos PIX/cartão sem checkout_session correspondente (Task #327) — preço integral, sem desconto, com split treatment/controle."}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"Elegíveis agora"}),e.jsx("p",{className:"text-lg font-bold text-white","data-testid":"text-orphan-eligible-now",children:ra.eligibleNow})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"Processados"}),e.jsx("p",{className:"text-lg font-bold text-white","data-testid":"text-orphan-total-processed",children:ra.totalProcessed})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"Enviados"}),e.jsx("p",{className:"text-lg font-bold text-emerald-400","data-testid":"text-orphan-total-sent",children:ra.totalSent}),e.jsxs("p",{className:"text-[9px] text-white/30",children:[ra.totalPixSent," PIX / ",ra.totalCardSent," cartão"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/50 uppercase tracking-wider mb-1",children:"Controle"}),e.jsx("p",{className:"text-lg font-bold text-violet-400","data-testid":"text-orphan-total-control",children:ra.totalControl})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"section-revenue-by-service",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4 text-primary"})," Receita por Produto",e.jsx("span",{className:"ml-auto text-[10px] text-white/40 font-normal",title:"Apenas pedidos pagos com dinheiro real (PIX/cartão). Compras feitas com saldo de créditos não entram aqui — o cash já foi contado quando o pacote de créditos foi vendido.",children:"PIX/cartão"})]}),Pt?.revenueByService&&Pt.revenueByService.length>0?e.jsx("div",{className:"space-y-3",children:Pt.revenueByService.map((t,s)=>{const i=Math.max(...Pt.revenueByService.map(C=>C.revenue)),x=i>0?t.revenue/i*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-white/80",children:t.name}),e.jsxs("span",{className:"text-white font-medium",children:["R$ ",t.revenue.toFixed(2)," ",e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",t.count,"x)"]})]})]}),e.jsx("div",{className:"h-1.5 bg-white/5 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-primary to-primary/60 rounded-full transition-all",style:{width:`${x}%`}})})]},s)})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma venda registrada ainda."})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"section-recent-orders",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(ns,{className:"w-4 h-4 text-primary"})," Vendas Recentes"]}),Pt?.recentOrders&&Pt.recentOrders.length>0?e.jsx("div",{className:"space-y-2 max-h-[300px] overflow-y-auto",children:Pt.recentOrders.map(t=>e.jsxs("div",{className:"flex items-center justify-between py-2.5 border-b border-white/5 last:border-0",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"text-sm text-white truncate",children:t.serviceName||t.label||t.type}),t.paymentMethod==="pix"?e.jsx("span",{title:"PIX",children:e.jsx(Oa,{className:"w-3.5 h-3.5 text-teal-400 shrink-0"})}):t.paymentMethod==="card"||t.paymentMethod==="credit_card"?e.jsx("span",{title:"Cartão",children:e.jsx(Bt,{className:"w-3.5 h-3.5 text-blue-400 shrink-0"})}):t.paymentMethod==="credits"?e.jsx("span",{title:"Créditos",className:"shrink-0",children:e.jsx(ic,{size:"sm"})}):t.paymentMethod==="beta"?e.jsx("span",{title:"Beta",className:"text-[9px] text-amber-400/70 font-medium shrink-0",children:"BETA"}):null]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:t.userEmail}),e.jsx("span",{className:"text-[10px] text-white/30",children:"·"}),e.jsxs("p",{className:"text-[10px] text-white/40 shrink-0",children:[t.createdAt?new Date(t.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}):""," ",t.createdAt?new Date(t.createdAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):""]})]})]}),e.jsx("div",{className:"flex items-center gap-2 shrink-0 ml-3",children:t.paymentMethod==="credits"||t.paymentMethod==="beta"?e.jsxs(e.Fragment,{children:[t.paymentMethod==="credits"&&e.jsxs("span",{className:"text-xs text-amber-400/70 font-medium",children:[Math.round(t.amount*100)," créditos"]}),e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium border bg-white/5 text-white/50 border-white/10",children:t.paymentMethod==="beta"?"Beta":"Créditos"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-sm font-medium text-white",children:["R$ ",t.amount.toFixed(2)]}),e.jsx(Gi,{status:t.status})]})})]},t.id))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma venda ainda."})]})]})]}),e.jsxs(Be,{value:"services",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:"Produtos e Serviços"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cadastre todos os produtos que serão oferecidos aos clientes."})]}),e.jsxs(b,{onClick:()=>{f(null),n({...bc}),p(!0)},"data-testid":"button-new-service",className:"gap-2",children:[e.jsx(_t,{className:"w-4 h-4"})," Novo Produto"]})]}),Qh?e.jsx("div",{className:"p-12 text-center",children:e.jsx(T,{className:"w-6 h-6 animate-spin mx-auto text-primary"})}):e.jsxs("div",{className:"grid gap-3",children:[Jc?.map(t=>{const s=gc.find(i=>i.value===t.iconName)?.icon||Zs;return e.jsxs("div",{className:`bg-white/5 border rounded-xl p-4 flex items-center gap-4 transition-all hover:bg-white/[0.07] ${t.active?"border-white/10":"border-red-500/20 opacity-60"}`,"data-testid":`card-service-${t.id}`,children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center shrink-0 ${t.active?"bg-primary/10":"bg-white/5"}`,children:e.jsx(s,{className:`w-5 h-5 ${t.active?"text-primary":"text-muted-foreground"}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"text-white font-medium text-sm",children:t.title}),t.recurring&&e.jsx(E,{variant:"outline",className:"text-[10px] border-primary/30 text-primary",children:"Recorrente"}),t.executionType&&e.jsx(E,{variant:"outline",className:`text-[10px] ${t.executionType==="ai"?"border-blue-500/30 text-blue-400":t.executionType==="human"?"border-amber-500/30 text-amber-400":"border-purple-500/30 text-purple-400"}`,children:hh.find(i=>i.value===t.executionType)?.label||t.executionType}),t.displayLocation&&t.displayLocation!=="services_tab"&&e.jsx(E,{variant:"outline",className:"text-[10px] border-white/10 text-muted-foreground",children:mh.find(i=>
3i.value===t.displayLocation)?.label||t.displayLocation}),t.availableForManualSale&&e.jsxs(E,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-300 gap-1",children:[e.jsx(qe,{className:"w-2.5 h-2.5"})," Venda no chat",t.defaultDiscountPct>0?` · ${t.defaultDiscountPct}% off`:""]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:t.description})]}),e.jsxs("div",{className:"text-right shrink-0 space-y-1",children:[e.jsxs("p",{className:"text-white font-semibold text-sm",children:["R$ ",t.price.toFixed(2),t.recurring?"/mês":""]}),t.estimatedDays>0&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[t.estimatedDays," dias"]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(b,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-white",onClick:()=>B0(t),"data-testid":`button-edit-service-${t.id}`,children:e.jsx(Yl,{className:"w-3.5 h-3.5"})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-white",onClick:()=>Pl.mutate({id:t.id,data:{active:!t.active}}),"data-testid":`button-toggle-service-${t.id}`,children:t.active?e.jsx(ht,{className:"w-3.5 h-3.5"}):e.jsx(Hl,{className:"w-3.5 h-3.5"})}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-red-400",onClick:()=>w(t.id),"data-testid":`button-delete-service-${t.id}`,children:e.jsx(As,{className:"w-3.5 h-3.5"})})]})]},t.id)}),Jc?.length===0&&e.jsxs("div",{className:"p-12 text-center text-muted-foreground",children:[e.jsx(Zs,{className:"w-8 h-8 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum produto cadastrado."})]})]}),e.jsx(Je,{open:j||!!u,onOpenChange:t=>{t||(p(!1),f(null))},children:e.jsxs(Ye,{className:"bg-[#0a1628] border-white/10 max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsx(et,{className:"text-white",children:u?"Editar Produto":"Novo Produto"}),e.jsx(mt,{className:"text-muted-foreground",children:u?"Atualize as informações do produto.":"Preencha os dados do novo produto/serviço."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 py-4",children:[e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Título *"}),e.jsx(J,{value:l.title,onChange:t=>n({...l,title:t.target.value}),className:"bg-black/20 border-white/10",placeholder:"Ex: Revisão Ortográfica","data-testid":"input-service-title"})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Descrição curta"}),e.jsx(J,{value:l.description,onChange:t=>n({...l,description:t.target.value}),className:"bg-black/20 border-white/10",placeholder:"Aparece na listagem"})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Descrição detalhada"}),e.jsx($s,{value:l.longDescription,onChange:t=>n({...l,longDescription:t.target.value}),className:"bg-black/20 border-white/10 min-h-[80px]",placeholder:"Descrição completa para a página do produto"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Preço (R$) *"}),e.jsx(J,{type:"number",step:"0.01",value:l.price,onChange:t=>n({...l,price:parseFloat(t.target.value)||0}),className:"bg-black/20 border-white/10","data-testid":"input-service-price"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Prazo estimado (dias)"}),e.jsx(J,{type:"number",value:l.estimatedDays,onChange:t=>n({...l,estimatedDays:parseInt(t.target.value)||0}),className:"bg-black/20 border-white/10"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Categoria"}),e.jsxs(Se,{value:l.category,onValueChange:t=>n({...l,category:t}),children:[e.jsx($e,{className:"bg-black/20 border-white/10",children:e.jsx(Ae,{})}),e.jsx(Pe,{className:"bg-[#0a1628] border-white/10",children:qb.map(t=>e.jsx(U,{value:t.value,children:t.label},t.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Tipo técnico"}
3),e.jsx(J,{value:l.type,onChange:t=>n({...l,type:t.target.value}),className:"bg-black/20 border-white/10",placeholder:"design, review, translation..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Onde exibir"}),e.jsxs(Se,{value:l.displayLocation,onValueChange:t=>n({...l,displayLocation:t}),children:[e.jsx($e,{className:"bg-black/20 border-white/10",children:e.jsx(Ae,{})}),e.jsx(Pe,{className:"bg-[#0a1628] border-white/10",children:mh.map(t=>e.jsx(U,{value:t.value,children:t.label},t.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Execução"}),e.jsxs(Se,{value:l.executionType,onValueChange:t=>n({...l,executionType:t}),children:[e.jsx($e,{className:"bg-black/20 border-white/10",children:e.jsx(Ae,{})}),e.jsx(Pe,{className:"bg-[#0a1628] border-white/10",children:hh.map(t=>e.jsx(U,{value:t.value,children:t.label},t.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Ícone"}),e.jsxs(Se,{value:l.iconName,onValueChange:t=>n({...l,iconName:t}),children:[e.jsx($e,{className:"bg-black/20 border-white/10",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U0,{className:"w-4 h-4"}),e.jsx(Ae,{})]})}),e.jsx(Pe,{className:"bg-[#0a1628] border-white/10",children:gc.map(t=>{const s=t.icon;return e.jsx(U,{value:t.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s,{className:"w-4 h-4"})," ",t.label]})},t.value)})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Ordem de exibição"}),e.jsx(J,{type:"number",value:l.sortOrder,onChange:t=>n({...l,sortOrder:parseInt(t.target.value)||0}),className:"bg-black/20 border-white/10"})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(O,{className:"text-white text-xs",children:"Campos extras (JSON)"}),e.jsx($s,{value:typeof l.extraFieldsConfig=="string"?l.extraFieldsConfig:l.extraFieldsConfig?JSON.stringify(l.extraFieldsConfig,null,2):"",onChange:t=>{try{const s=t.target.value?JSON.parse(t.target.value):null;n({...l,extraFieldsConfig:s})}catch{n({...l,extraFieldsConfig:t.target.value})}},className:"bg-black/20 border-white/10 min-h-[60px] font-mono text-xs",placeholder:'Ex: [{"field": "idioma", "type": "select", "options": ["Inglês", "Espanhol"]}]',"data-testid":"input-service-extra-fields"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Configuração JSON para campos adicionais no formulário de compra."})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-4",children:[e.jsx(rt,{checked:l.recurring,onCheckedChange:t=>n({...l,recurring:t})}),e.jsx(O,{className:"text-white text-xs",children:"Cobrança recorrente (assinatura)"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-4",children:[e.jsx(rt,{checked:l.active,onCheckedChange:t=>n({...l,active:t})}),e.jsx(O,{className:"text-white text-xs",children:"Produto ativo (visível)"})]}),e.jsxs("div",{className:"mt-2 rounded-xl border border-amber-500/25 bg-amber-950/10 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-amber-300 text-xs font-semibold",children:[e.jsx(qe,{className:"w-3.5 h-3.5"})," Venda pela equipe de suporte (chat)"]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs(O,{className:"text-white/80 text-xs leading-snug",children:["Liberar para venda no chat",e.jsx("span",{className:"block text-[10px] text-white/45 font-normal",children:"O suporte pode oferecer este serviço no chat da Central e ganha comissão na venda."})]}),e.jsx(rt,{checked:l.availableForManualSale,onCheckedChange:t=>n({...l,availableForManualSale:t}),"data-testid":"switch-manual-sale"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs(O,{className:"text-white/80 text-xs leading-snug",children:["Permitir em ofertas combinadas",e.jsx("span",{className:"block text-[10px] text-white/45 font-normal",children:"Pode ser incluído junto com outros serviços num pacote único."})]}),e.jsx(rt,{checked:l.allowOfferInChat,onCheckedChange:t=>n({...l,allowOfferInChat:t}),disabled:!l.availableForManualSale,"data-testid":"switch-allow-combo"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(O,{className:"text-white/80 text-xs",children:"Desconto sugerido (%)"}),e.jsx(J,{type:"number",min:0,max:50,value:l.defaultDiscountPct,onChange:t=>n({...l,defaultDiscountPct:Math.max(0,Math.min(50,parseInt(t.target.value)||0))}),className:"bg-black/20 border-white/10 w-28",disabled:!l.availableForManualSale,"data-testid":"input-default-discount"}),e.jsx("p",{className:"text-[10px] text-white/45",children:"Vem pré-preenchido no chat (o agente pode ajustar). Desconto máximo permitido: 50%."})]})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>{p(!1),f(null)},className:"border-white/10",children:"Cancelar"}),e.jsxs(b,{onClick:()=>{u?Pl.mutate({id:u.id,data:l}):Ho.mutate(l)},disabled:Ho.isPending||Pl.isPending||!l.title,"data-testid":"button-save-service",children:[(Ho.isPending||Pl.isPending)&&e.jsx(T,{className:"w-4 h-4 mr-2 animate-spin"}),u?"Salvar":"Criar Produto"]})]})]})}),e.jsx(Je,{open:!!g,onOpenChange:()=>w(null),children:e.jsxs(Ye,{className:"bg-[#0a1628] border-white/10 max-w-sm",children:[e.jsxs(Ze,{children:[e.jsx(et,{className:"text-white",children:"Confirmar exclusão"}),e.jsx(mt,{className:"text-muted-foreground",children:"Tem certeza que deseja remover este produto? Esta ação não pode ser desfeita."})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>w(null),className:"border-white/10",children:"Cancelar"}),e.jsxs(b,{variant:"destructive",onClick:()=>g&&Xo.mutate(g),disabled:Xo.isPending,children:[Xo.isPending&&e.jsx(T,{className:"w-4 h-4 mr-2 animate-spin"}),"Remover"]})]})]})})]}),e.jsxs(Be,{value:"orders",className:"mt-6 space-y-4",children:[e.jsx(Cg,{}),e.jsx(ag,{}),e.jsx(rg,{}),e.jsx($g,{}),e.jsx(Tg,{}),e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:"Vendas e Pedidos"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controle todos os pagamentos e status."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("div",{className:"relative w-full sm:w-auto",children:[e.jsx(St,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(J,{value:re,onChange:t=>_(t.target.value),placeholder:"Buscar por cliente, livro...",className:"bg-black/20 border-white/10 pl-9 w-full sm:w-[220px] h-9 text-xs","data-testid":"input-order-search"})]}),e.jsxs(Se,{value:ee,onValueChange:h,children:[e.jsx($e,{className:"bg-black/20 border-white/10 w-[140px] h-9 text-xs","data-testid":"select-order-status-filter",children:e.jsx(Ae,{placeholder:"Status"})}),e.jsxs(Pe,{className:"bg-[#0a1628] border-white/10",children:[e.jsx(U,{value:"all",children:"Todos"}),e.jsx(U,{value:"pending",children:"Pendentes"}),e.jsx(U,{value:"confirmed",children:"Confirmados"}),e.jsx(U,{value:"completed",children:"Concluídos"}),e.jsx(U,{value:"cancelled",children:"Cancelados"})]})]}),Mm.length>0&&e.jsxs(Se,{value:Ne,onValueChange:ie,children:[e.jsx($e,{className:"bg-black/20 border-white/10 w-[130px] h-9 text-xs","data-testid":"select-utm-source-filter",children:e.jsx(Ae,{placeholder:"Source"})}),e.jsxs(Pe,{className:"bg-[#0a1628] border-white/10 max-h-[250px]",children:[e.jsx(U,{value:"all",children:"Source: Todos"}),Mm.map(t=>e.jsx(U,{value:t,children:t},t))]})]}),Lm.length>0&&e.jsxs(Se,{value:X,onValueChange:B,children:[e.jsx($e,{className:"bg-black/20 border-white/10 w-[130px] h-9 text-xs","data-testid":"select-utm-medium-filter",children:e.jsx(Ae,{placeholder:"Medium"})}),e.jsxs(Pe,{className:"bg-[#0a1628] border-white/10 max-h-[250px]",children:[e.jsx(U,{value:"all",children:"Medium: Todos"}),Lm.map(t=>e.jsx(U,{value:t,children:t},t))]})]}),zm.length>0&&e.jsxs(Se,{value:ge,onValueChange:ut,children:[e.jsx($e,{className:"bg-black/20 border-white/10 w-[160px] h-9 text-xs","data-testid":"select-utm-campaign-filter",children:e.jsx(Ae,{placeholder:"Campaign"})}),e.jsxs(Pe,{className:"bg-[#0a1628] border-white/10 max-h-[250px]",children:[e.jsx(U,{value:"all",children:"Campaign: Todos"}),zm.map(t=>e.jsx(U,{value:t,children:t},t))]})]}),qm.length>0&&e.jsxs(Se,{value:at,onValueChange:$t,children:[e.jsx($e,{className:"bg-black/20 border-white/10 w-[160px] h-9 text-xs","data-testid":"select-chat-flow-filter",children:e.jsx(Ae,{placeholder:"Chat Flow"})}),e.jsxs(Pe,{className:"bg-[#0a1628] border-white/10 max-h-[250px]",children:[e.jsx(U,{value:"all",children:"Chat: Todos"}),qm.map(t=>e.jsx(U,{value:t,children:t},t))]})]}),e.jsxs(b,{variant:"outline",size:"sm",className:"h-9 text-xs border-green-500/20 text-green-400 hover:bg-green-500/10",onClick:()=>{const t=new URLSearchParams;ee!=="all"&&t.set("status",ee),Ne!=="all"&&t.set("utmSource",Ne),X!=="all"&&t.set("utmMedium",X),ge!=="all"&&t.set("utmCampaign",ge),re&&t.set("search",re);const s=document.createElement("a");s.href=`/api/admin/orders/export-csv${t.toString()?`?${t.toString()}`:""}`,s.download="",document.body.appendChild(s),s.click(),document.body.removeChild(s)},"data-testid":"button-export-orders-csv",children:[e.jsx(Rt,{className:"w-3 h-3 mr-1"}),"Exportar CSV"]}),e.jsxs(b,{variant:"outline",size:"sm",className:"h-9 text-xs border-cyan-500/20 text-cyan-400 hover:bg-cyan-500/10",onClick:()=>Zo.mutate(),disabled:Zo.isPending,"data-testid":"button-reattribute-orders",children:[Zo.isPending?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(xe,{className:"w-3 h-3 mr-1"}),"Reatribuir Tráfego"]})]})]}),Wh?e.jsx("div",{className:"p-12 text-center",children:e.jsx(T,{className:"w-6 h-6 animate-spin mx-auto text-primary"})}):e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-white/5",children:e.jsxs("tr",{className:"text-muted-foreground text-left text-xs uppercase tracking-wider",children:[e.jsx("th",{className:"p-3 pl-4",children:"Pedido"}),e.jsx("th",{className:"p-3",children:"Cliente"}),e.jsx("th",{className:"p-3",children:"Produto"}),e.jsx("th",{className:"p-3",children:"Origem"}),e.jsx("th",{className:"p-3",children:"Tráfego"}),e.jsx("th",{className:"p-3",children:"Pagamento"}),e.jsx("th",{className:"p-3",children:"Valor"}),e.jsx("th",{className:"p-3",children:"Custo IA"}),e.jsx("th",{className:"p-3",children:"Status"}),e.jsx("th",{className:"p-3",children:"Data"}),e.jsx("th",{className:"p-3 pr-4",children:"Ações"})]})}),e.jsx("tbody",{children:O0?.map(t=>e.jsxs("tr",{className:"border-t border-white/5 text-white hover:bg-white/[0.03] transition-colors","data-testid":`row-order-${t.id}`,children:[e.jsx("td",{className:"p-3 pl-4",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.id.slice(0,8)})}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-white",children:t.userName||"-"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t.userEmail})]})}),e.jsx("td",{className:"p-3 text-xs",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:t.serviceName||t.label||t.type}),t.isBundleSubOrder&&e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full inline-flex items-center gap-1 w-fit bg-emerald-500/15 text-emerald-300 border border-emerald-500/20",title:`Item entregue como parte do pacote ${t.parentOrderId?`#${t.parentOrderId.slice(0,8)}`:""}`,"data-testid":`badge-bundle-delivery-${t.id}`,children:"📦 Entrega de pacote"})]})}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full inline-flex items-center gap-1 w-fit ${t.source==="chat"||t.source==="chat_inline_checkout"?"bg-violet-500/20 text-violet-400":"bg-teal-500/20 text-teal-400"}`,"data-testid":`badge-source-${t.id}`,children:t.source==="chat"||t.source==="chat_inline_checkout"?"Chat":"Landing"}),t.chatFlowName&&e.jsx("span",{className:"text-[10px] text-violet-300/70 truncate max-w-[120px]",title:t.chatFlowName,"data-testid":`text-flow-${t.id}`,children:t.chatFlowName})]})}),e.jsx("td",{className:"p-3 max-w-[160px]",children:(()=>{const s=t.utmSource||"",i=t.utmCampaign||"",x=t.utmMedium||"",C=t.utmContent||"",P=t.source||"",H=t.referrerPage||"";if(s||i){const Q={chat_ai:{label:"Chat IA",color:"text-violet-400"},blog:{label:"Blog",color:"text-orange-400"},landing:{label:"Landing",color:"text-teal-400"},seo:{label:"SEO",color:"text-green-400"},recovery:{label:"Recuperação",color:"text-amber-400"},email_sequence:{label:"Email",color:"text-pink-400"},referral:{label:"Indicação",color:"text-emerald-400"},instagram:{label:"Instagram",color:"text-fuchsia-400"},facebook:{label:"Facebook Ads",color:"text-blue-400"},fb:{label:"Facebook Ads",color:"text-blue-400"},google:{label:"Google",color:"text-red-400"}},G=s.toLowerCase(),ue=Q[G]||(G.includes("facebook")||G.includes("fb")||G==="ig"?Q.facebook:G.includes("google")?Q.google:null);return e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:`text-xs font-medium truncate ${ue?.color||"text-cyan-400"}`,children:ue?.label||s}),i&&e.jsx("p",{className:"text-[10px] text-white/50 truncate",title:i,children:i}),C&&e.jsx("p",{className:"text-[10px] text-white/30 truncate",title:C,children:C}),!i&&x&&e.jsx("p",{className:"text-[10px] text-white/30 truncate",children:x})]})}return P==="chat"?e.jsx("span",{className:"text-xs text-violet-400/70",children:"Chat Funnel"}):H.includes("/book")?e.jsx("span",{className:"text-xs text-teal-400/70",children:"Dashboard"}):H.includes("/capas")||H.includes("/ilustrar")?e.jsx("span",{className:"text-xs text-teal-400/70",children:"Dashboard"}):e.jsx("span",{className:"text-xs text-white/30",children:"Orgânico"})})()}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-1",children:[t.paymentMethod==="pix"?e.jsx(Oa,{className:"w-3 h-3 text-primary"}):t.paymentMethod==="credit_card"||t.paymentMethod==="card"?e.jsx(Bt,{className:"w-3 h-3 text-blue-400"}):t.paymentMethod==="credits"?e.jsx(ic,{size:"sm"}):null,e.jsx("span",{className:"text-xs text-muted-foreground",children:t.paymentMethod==="pix"?"PIX":t.paymentMethod==="credit_card"||t.paymentMethod==="card"?"Cartão":t.paymentMethod==="credits"?"Créditos":t.paymentMethod==="beta"?"Beta":t.paymentMethod||"-"})]})}),e.jsx("td",{className:"p-3 font-medium text-xs",children:t.isBundleSubOrder?e.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":`value-bundle-${t.id}`,children:[e.jsx("span",{className:"text-emerald-300/90 text-[11px] font-semibold",children:"Incluso no pacote"}),t.parentOrderId&&e.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono",children:["#",t.parentOrderId.slice(0,8)]})]}):e.jsxs("span",{"data-testid":`value-amount-${t.id}`,children:["R$ ",t.amount.toFixed(2)]})}),e.jsx("td",{className:"p-3","data-testid":`text-ai-cost-${t.id}`,children:t.aiCost&&t.aiCost.callCount>0?e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-medium text-amber-400",children:["R$ ",t.aiCost.costBRL.toFixed(4)]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[t.aiCost.totalTokens?.toLocaleStr
3ing()," tok"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"-"})}),e.jsx("td",{className:"p-3",children:e.jsx(Gi,{status:t.status})}),e.jsx("td",{className:"p-3 text-xs text-muted-foreground whitespace-nowrap",children:t.createdAt?new Date(t.createdAt).toLocaleDateString("pt-BR"):"-"}),e.jsx("td",{className:"p-3 pr-4",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-white",onClick:()=>z0(t.id),"data-testid":`button-view-order-${t.id}`,children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),t.status==="pending"&&(t.paymentMethod==="card"||t.paymentMethod==="credit_card")&&e.jsxs(b,{variant:"ghost",size:"sm",className:"h-7 text-[10px] text-amber-400 hover:text-amber-300 hover:bg-amber-500/10",onClick:async()=>{try{const i=await(await N("POST",`/api/admin/orders/${t.id}/verify-stripe`)).json();i.confirmed?(r({description:`Pagamento confirmado! Status Stripe: ${i.stripeStatus}`}),K.invalidateQueries({queryKey:["/api/admin/orders"]})):r({description:`Stripe: ${i.message}`,variant:"destructive"})}catch{r({description:"Erro ao verificar no Stripe",variant:"destructive"})}},"data-testid":`button-verify-stripe-${t.id}`,children:[e.jsx(as,{className:"w-3 h-3 mr-1"}),"Verificar Stripe"]}),t.status==="pending"&&e.jsxs(b,{variant:"ghost",size:"sm",className:"h-7 text-[10px] text-emerald-400 hover:text-emerald-300 hover:bg-emerald-500/10",onClick:async()=>{if(confirm(`Confirmar e gerar o serviço "${t.type}" para este pedido?`))try{const i=await(await N("POST",`/api/admin/orders/${t.id}/fulfill`)).json();i.fulfilled?(r({description:i.message}),K.invalidateQueries({queryKey:["/api/admin/orders"]})):i.already?r({description:i.message}):r({description:i.message||"Erro ao gerar serviço",variant:"destructive"})}catch{r({description:"Erro ao gerar serviço",variant:"destructive"})}},"data-testid":`button-fulfill-order-${t.id}`,children:[e.jsx(He,{className:"w-3 h-3 mr-1"}),"Gerar Serviço"]}),e.jsxs(Se,{onValueChange:s=>L0.mutate({id:t.id,status:s}),children:[e.jsx($e,{className:"bg-transparent border-white/10 h-7 w-[100px] text-[11px]","data-testid":`select-order-status-${t.id}`,children:e.jsx(Ae,{placeholder:"Alterar"})}),e.jsxs(Pe,{className:"bg-[#0a1628] border-white/10",children:[e.jsx(U,{value:"confirmed",children:"Confirmar"}),e.jsx(U,{value:"completed",children:"Concluir"}),e.jsx(U,{value:"cancelled",children:"Cancelar"}),e.jsx(U,{value:"refunded",children:"Reembolsar"})]})]})]})})]},t.id))})]})}),za?.length===0&&e.jsxs("div",{className:"p-12 text-center text-muted-foreground",children:[e.jsx(Jt,{className:"w-8 h-8 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum pedido encontrado."})]}),za&&za.length>0&&(()=>{const t=za.filter(i=>i.isBundleSubOrder).length,s=za.filter(i=>!i.isBundleSubOrder).reduce((i,x)=>i+x.amount,0);return e.jsxs("div",{className:"p-3 border-t border-white/5 flex items-center justify-between text-xs text-muted-foreground flex-wrap gap-2",children:[e.jsxs("span",{"data-testid":"text-orders-count",children:[za.length," pedido",za.length!==1?"s":"",t>0&&e.jsxs("span",{className:"ml-2 text-emerald-300/70",children:["(",t," entrega",t!==1?"s":""," de pacote)"]})]}),dn>1&&e.jsxs("div",{className:"flex items-center gap-2","data-testid":"orders-pagination",children:[e.jsxs(b,{variant:"outline",size:"sm",className:"h-7 text-xs border-white/10",disabled:on===0,onClick:()=>Ms(i=>Math.max(0,i-1)),"data-testid":"button-orders-prev",children:[e.jsx(eu,{className:"w-3 h-3 mr-1"}),"Anterior"]}),e.jsxs("span",{className:"text-[11px]","data-testid":"text-orders-page",children:["Página ",on+1," de ",dn]}),e.jsxs(b,{variant:"outline",size:"sm",className:"h-7 text-xs border-white/10",disabled:on>=dn-1,onClick:()=>Ms(i=>Math.min(dn-1,i+1)),"data-testid":"button-orders-next",children:["Próxima",e.jsx(ya,{className:"w-3 h-3 ml-1"})]})]}),e.jsxs("span",{"data-testid":"text-orders-total",children:["Total: R$ ",s.toFixed(2)]})]})})()]}),e.jsx(Je,{open:!!fe,onOpenChange:t=>{t||sa(null)},children:e.jsxs(Ye,{className:"bg-[#0a1628] border-white/10 max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"text-white flex items-center gap-2",children:[e.jsx(Jt,{className:"w-5 h-5 text-primary"}),"Detalhes do Pedido"]}),e.jsxs(mt,{className:"text-muted-foreground",children:[fe?.id?.slice(0,8)," — ",fe?.label||fe?.type]})]}),Ha?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(T,{className:"w-8 h-8 animate-spin text-primary"})}):fe&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-white/5 rounded-xl p-3 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Valor"}),e.jsxs("p",{className:"text-lg font-bold text-emerald-400",children:["R$ ",(fe.amount||0).toFixed(2)]})]}),e.jsxs("div",{className:"bg-white/5 rounded-xl p-3 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custo IA"}),e.jsxs("p",{className:"text-lg font-bold text-amber-400",children:["R$ ",fe.aiCost?.costBRL?.toFixed(4)||"0.0000"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-xl p-3 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Lucro"}),e.jsxs("p",{className:"text-lg font-bold text-white",children:["R$ ",((fe.amount||0)-(fe.aiCost?.costBRL||0)).toFixed(2)]})]}),e.jsxs("div",{className:"bg-white/5 rounded-xl p-3 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status"}),e.jsx(Gi,{status:fe.status})]})]}),e.jsxs("div",{className:"bg-white/5 rounded-xl p-4 space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Informações"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Cliente:"})," ",e.jsx("span",{className:"text-white ml-1",children:fe.userName||fe.userEmail})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Email:"})," ",e.jsx("span",{className:"text-white ml-1",children:fe.userEmail})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Livro:"})," ",e.jsx("span",{className:"text-white ml-1",children:fe.bookTitle||"-"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Pagamento:"})," ",e.jsx("span",{className:"text-white ml-1",children:fe.paymentMethod==="pix"?"PIX":fe.paymentMethod==="card"||fe.paymentMethod==="credit_card"?"Cartão":fe.paymentMethod==="beta"?"Beta":fe.paymentMethod||"-"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Tipo:"})," ",e.jsx("span",{className:"text-white ml-1",children:fe.label||fe.type})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Data:"})," ",e.jsx("span",{className:"text-white ml-1",children:fe.createdAt?new Date(fe.createdAt).toLocaleDateString("pt-BR"):"-"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Origem:"})," ",e.jsx("span",{className:"text-cyan-300 ml-1",children:fe.utmSource?`${fe.utmSource}${fe.utmMedium?` / ${fe.utmMedium}`:""}`:fe.source==="chat"?"Chat Funnel":fe.referrerPage?.includes("/book")?"Dashboard":"Orgânico"})]}),fe.utmCampaign&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Campanha:"})," ",e.jsx("span",{className:"text-cyan-300 ml-1",children:fe.utmCampaign})]}),fe.utmContent&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Conteúdo:"})," ",e.jsx("span",{className:"text-cyan-300 ml-1",children:fe.utmContent})]}),fe.utmTerm&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Termo:"})," ",e.jsx("span",{className:"text-cyan-300 ml-1",children:fe.utmTerm})]})]})]}),fe.assets?.covers?.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Va,{className:"w-3.5 h-3.5"})," Capas Geradas (",fe.assets.covers.length,")"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:fe.assets.covers.map(t=>e.jsxs("div",{className:"group relative rounded-xl overflow-hidden border border-white/10 hover:border-primary/30 transition-all",children:[e.jsx(vc,{src:t.imageUrl,alt:"Capa",widths:[160,200,240,320],sizes:"(max-width: 768px) 45vw, 200px",className:"w-full aspect-[3/4] object-cover"}),e.jsxs("div",{className:"absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2",children:[e.jsx("a",{href:t.imageUrl,target:"_blank",rel:"noopener noreferrer",className:"p-2 bg-white/10 rounded-lg hover:bg-white/20 transition-colors",children:e.jsx(ht,{className:"w-4 h-4 text-white"})}),e.jsx("a",{href:t.imageUrl,download:!0,className:"p-2 bg-white/10 rounded-lg hover:bg-white/20 transition-colors",children:e.jsx(Rt,{className:"w-4 h-4 text-white"})})]}),t.selected&&e.jsx(E,{className:"absolute top-2 right-2 bg-primary/80 text-white text-[10px]",children:"Selecionada"})]},t.id))})]}),fe.assets?.illustrations?.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(qe,{className:"w-3.5 h-3.5"})," Ilustrações Geradas (",fe.assets.illustrations.length,")"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:fe.assets.illustrations.map(t=>e.jsxs("div",{className:"group relative rounded-xl overflow-hidden border border-white/10 hover:border-primary/30 transition-all",children:[e.jsx("img",{src:t.imageUrl,alt:"Ilustração",className:"w-full aspect-square object-cover"}),e.jsxs("div",{className:"absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2",children:[e.jsx("a",{href:t.imageUrl,target:"_blank",rel:"noopener noreferrer",className:"p-2 bg-white/10 rounded-lg hover:bg-white/20 transition-colors",children:e.jsx(ht,{className:"w-4 h-4 text-white"})}),e.jsx("a",{href:t.imageUrl,download:!0,className:"p-2 bg-white/10 rounded-lg hover:bg-white/20 transition-colors",children:e.jsx(Rt,{className:"w-4 h-4 text-white"})})]}),t.style&&e.jsx(E,{className:"absolute top-2 left-2 bg-black/60 text-white/80 text-[10px]",children:t.style})]},t.id))})]}),fe.assets?.chapters?.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(tt,{className:"w-3.5 h-3.5"})," Capítulos do Livro (",fe.assets.chapters.length,")"]}),e.jsx("div",{className:"space-y-2 max-h-[300px] overflow-y-auto",children:fe.assets.chapters.map((t,s)=>e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground w-6 text-center",children:s+1}),e.jsx("span",{className:"text-sm text-white truncate",children:t.title})]}),e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:t.content?e.jsx(E,{className:"bg-emerald-500/10 text-emerald-400 border-emerald-500/20 text-[10px]",children:"Escrito"}):e.jsx(E,{className:"bg-amber-500/10 text-amber-400 border-amber-500/20 text-[10px]",children:"Pendente"})})]},t.id))})]}),fe.assets?.marketingMaterials?.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Xt,{className:"w-3.5 h-3.5"})," Materiais de Divulgação (",fe.assets.marketingMaterials.length,")"]}),e.jsx("div",{className:"space-y-2 max-h-[300px] overflow-y-auto",children:fe.assets.marketingMaterials.map(t=>e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(E,{className:"bg-primary/10 text-primary border-primary/20 text-[10px]",children:t.contentType}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:t.createdAt?new Date(t.createdAt).toLocaleDateString("pt-BR"):""})]}),e.jsx("p",{className:"text-xs text-white/80 line-clamp-3 whitespace-pre-wrap",children:typeof t.content=="string"?t.content.slice(0,200)+(t.content.length>200?"...":""):JSON.stringify(t.content).slice(0,200)})]},t.id))})]}),fe.assets?.translations?.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(fn,{className:"w-3.5 h-3.5"})," Traduções (",fe.assets.translations.length,")"]}),e.jsx("div",{className:"space-y-2",children:fe.assets.translations.map(t=>e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-white",children:t.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.language||"Tradução"})]}),e.jsx(E,{className:"bg-emerald-500/10 text-emerald-400 border-emerald-500/20 text-[10px]",children:t.status})]},t.id))})]}),!fe.assets?.covers?.length&&!fe.assets?.illustrations?.length&&!fe.assets?.chapters?.length&&!fe.assets?.marketingMaterials?.length&&!fe.assets?.translations?.length&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Zs,{className:"w-8 h-8 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum conteúdo gerado encontrado para este pedido."})]})]})]})})]}),e.jsxs(Be,{value:"books",className:"mt-6 space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between flex-wrap gap-3",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:"Livros"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pesquise e gerencie todos os livros da plataforma."})]})}),e.jsx(cb,{})]}),e.jsxs(Be,{value:"users",className:"mt-6 space-y-4",children:[e.jsx("div",{className:"inline-flex rounded-lg border border-white/10 overflow-hidden","data-testid":"clientes-view-switcher",children:[{key:"list",label:"Lista"},{key:"export",label:"Exportar"}].map(t=>e.jsx("button",{onClick:()=>o(t.key),className:`px-4 py-1.5 text-xs font-medium transition-all ${A===t.key?"bg-primary/15 text-primary":"text-white/40 hover:text-white/70"}`,"data-testid":`button-clientes-view-${t.key}`,children:t.label==="Exportar"?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Rt,{className:"w-3.5 h-3.5"}),t.label]}):t.label},t.key))}),A==="export"&&e.jsx(Ng,{users:Si,loading:Wc,getUserSource:El}),A==="list"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:"Clientes"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Veja todos os clientes, seus livros e compras."})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto",children:[e.jsx(kg,{}),e.jsxs("div",{className:"relative flex-1 sm:w-auto",children:[e.jsx(St,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(J,{value:y,onChange:t=>F(t.target.value),placeholder:"Buscar por email ou nome...",className:"bg-black/20 border-white/10 pl-9 pr-8 w-full sm:w-[260px] h-9 text-xs","data-testid":"input-user-search"}),Xc&&e.jsx(T,{className:"w-3.5 h-3.5 animate-spin absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground","data-testid":"loader-user-search"})]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5","data-testid":"user-source-filters",children:[{key:"all",label:"Todos",color:"text-white/60 border-white/10"},{key:"paid",label:"Tráfego Pago",color:"text-teal-400 border-teal-500/30"},{key:"facebook",label:"Facebook Ads",color:"text-blue-400 border-blue-500/30"},{key:"google",label:"Google",color:"text-red-400 border-red-50
30/30"},{key:"blog",label:"Blog",color:"text-orange-400 border-orange-500/30"},{key:"chat",label:"Chat",color:"text-violet-400 border-violet-500/30"},{key:"create",label:"Criar Livro",color:"text-pink-400 border-pink-500/30"},{key:"organic",label:"Orgânico",color:"text-white/40 border-white/10"}].map(t=>e.jsxs("button",{onClick:()=>m(t.key),className:`px-2.5 py-1 rounded-full text-[10px] font-medium border transition-all ${c===t.key?`${t.color} bg-white/10`:"text-white/30 border-transparent hover:border-white/10 hover:text-white/50"}`,"data-testid":`filter-source-${t.key}`,children:[t.label,t.key!=="all"&&Si&&e.jsx("span",{className:"ml-1 text-white/20",children:Si.filter(s=>{const i=El(s);return t.key==="paid"?i.key==="facebook"||i.key==="google":i.key===t.key}).length})]},t.key))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5","data-testid":"user-role-filters",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-white/30 mr-1",children:"Papel:"}),[{key:"all",label:"Todos",color:"text-white/60 border-white/10"},{key:"user",label:"Usuário",color:"text-white/70 border-white/20"},{key:"support",label:"Suporte",color:"text-orange-400 border-orange-500/30"},{key:"admin",label:"Admin",color:"text-primary border-primary/30"},{key:"openclaw",label:"Publicador",color:"text-blue-400 border-blue-500/30"}].map(t=>e.jsxs("button",{onClick:()=>D(t.key),className:`px-2.5 py-1 rounded-full text-[10px] font-medium border transition-all ${$===t.key?`${t.color} bg-white/10`:"text-white/30 border-transparent hover:border-white/10 hover:text-white/50"}`,"data-testid":`filter-role-${t.key}`,children:[t.label,t.key!=="all"&&Si&&e.jsx("span",{className:"ml-1 text-white/20",children:Si.filter(s=>(s.role||"user")===t.key).length})]},t.key))]}),S&&Gh?e.jsxs("div",{className:"p-12 text-center space-y-3",children:[e.jsx("p",{className:"text-sm text-red-400",children:"Falha na busca de clientes."}),e.jsx(b,{size:"sm",variant:"outline",onClick:()=>Vh(),"data-testid":"button-retry-user-search",children:"Tentar novamente"})]}):(S?Xc&&!Hc:Wc)?e.jsx("div",{className:"p-12 text-center",children:e.jsx(T,{className:"w-6 h-6 animate-spin mx-auto text-primary"})}):e.jsxs("div",{className:"space-y-2",children:[ci?.length===0&&e.jsxs("div",{className:"p-12 text-center text-sm text-muted-foreground","data-testid":"text-no-users-found",children:["Nenhum cliente encontrado",S?` para "${ne}"`:"","."]}),ci?.slice(0,de).map(t=>e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden","data-testid":`card-user-${t.id}`,children:[e.jsxs("div",{className:"p-4 flex items-center gap-4 cursor-pointer hover:bg-white/[0.03] transition-colors",onClick:()=>v(L===t.id?null:t.id),children:[e.jsx("div",{className:"w-9 h-9 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"text-xs font-bold text-primary",children:t.name?t.name.split(" ").map(s=>s[0]).join("").slice(0,2).toUpperCase():t.email.slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-white truncate max-w-[150px] sm:max-w-none",children:t.name||t.email}),e.jsx(E,{variant:"outline",className:`text-[10px] shrink-0 ${t.role==="admin"?"border-primary/30 text-primary":t.role==="openclaw"?"border-blue-500/30 text-blue-400":t.role==="support"?"border-orange-500/30 text-orange-400":"border-white/10 text-muted-foreground"}`,children:t.role==="openclaw"?"Publicador":t.role==="support"?"Suporte":t.role}),(()=>{const s=El(t);return e.jsx(E,{variant:"outline",className:`text-[9px] shrink-0 ${s.color}`,children:s.label})})(),t.primaryChannel&&e.jsx(E,{variant:"outline",className:`text-[9px] shrink-0 ${t.primaryChannel==="chat"?"border-violet-500/30 text-violet-400":"border-teal-500/30 text-teal-400"}`,children:t.primaryChannel==="chat"?"Chat":"Landing"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:t.email})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3 shrink-0 flex-wrap",children:[[{val:t.booksCount,label:"livros",color:"text-white"}
3,{val:t.activity?.plans||0,label:"planej.",color:"text-blue-400"},{val:t.activity?.covers||0,label:"capas",color:"text-purple-400"},{val:t.activity?.illustrations||0,label:"ilustr.",color:"text-pink-400"},{val:t.activity?.marketingMaterials||0,label:"divulg.",color:"text-orange-400"},{val:t.activity?.publications||0,label:"public.",color:"text-teal-400"},{val:t.activity?.translations||0,label:"trad.",color:"text-cyan-400"}].filter(s=>s.val>0).map(s=>e.jsxs("div",{className:"text-center min-w-[40px]",children:[e.jsx("p",{className:`text-sm font-bold ${s.color}`,children:s.val}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:s.label})]},s.label)),e.jsxs("div",{className:"text-center min-w-[60px]",title:"Apenas PIX/cartão. Pedidos pagos com créditos não contam (cash já entrou no pacote original)",children:[e.jsxs("p",{className:"text-sm font-bold text-emerald-400",children:["R$ ",t.totalSpent.toFixed(2)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"cash · PIX/cartão"})]}),e.jsxs("div",{className:"text-center min-w-[60px]",children:[e.jsxs("p",{className:"text-sm font-bold text-amber-400","data-testid":`text-ai-cost-user-${t.id}`,children:["R$ ",t.totalAiCostBRL?.toFixed(4)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"custo IA"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(b,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-white",title:"Alterar papel",onClick:s=>{s.stopPropagation(),he({userId:t.id,userName:t.name||t.email,currentRole:t.role}),xt(""),Zt("")},"data-testid":`button-toggle-role-${t.id}`,children:e.jsx(as,{className:"w-3.5 h-3.5"})}),L===t.id?e.jsx(ta,{className:"w-4 h-4 text-muted-foreground"}):e.jsx(Ct,{className:"w-4 h-4 text-muted-foreground"})]})]}),L===t.id&&e.jsxs("div",{className:"border-t border-white/5 p-4 space-y-5 bg-black/10",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ge,{className:"w-3 h-3"})," ",t.email]}),t.phone&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ul,{className:"w-3 h-3"})," ",t.phone]}),e.jsxs("span",{children:["Cadastro: ",t.createdAt?new Date(t.createdAt).toLocaleDateString("pt-BR"):"-"]})]}),e.jsxs("div",{className:"sm:hidden flex items-center gap-3 flex-wrap mb-3",children:[[{val:t.booksCount,label:"livros",color:"text-white"},{val:t.activity?.plans||0,label:"planej.",color:"text-blue-400"},{val:t.activity?.covers||0,label:"capas",color:"text-purple-400"},{val:t.activity?.illustrations||0,label:"ilustr.",color:"text-pink-400"},{val:t.activity?.marketingMaterials||0,label:"divulg.",color:"text-orange-400"},{val:t.activity?.publications||0,label:"public.",color:"text-teal-400"},{val:t.activity?.translations||0,label:"trad.",color:"text-cyan-400"}].filter(s=>s.val>0).map(s=>e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:`text-sm font-bold ${s.color}`,children:s.val}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:s.label})]},s.label)),e.jsxs("div",{className:"text-center",title:"Apenas PIX/cartão. Pedidos pagos com créditos não contam.",children:[e.jsxs("p",{className:"text-sm font-bold text-emerald-400",children:["R$ ",t.totalSpent.toFixed(2)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"cash · PIX/cartão"})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-sm font-bold text-amber-400",children:["R$ ",t.totalAiCostBRL?.toFixed(4)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"custo IA"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-amber-500/5 border border-amber-500/10",children:[e.jsx(jc,{className:"w-5 h-5 text-amber-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Créditos: "}),e.jsx("span",{className:"text-sm font-bold text-amber-400","data-testid":`text-credits-${t.id}
3`,children:Ns[t.id]!==void 0?`${Ns[t.id].toLocaleString("pt-BR")} (R$ ${(Ns[t.id]/100).toFixed(2).replace(".",",")})`:"..."})]}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-8 text-xs border-amber-500/20 text-amber-400 hover:bg-amber-500/10",onClick:s=>{s.stopPropagation(),V({userId:t.id,userName:t.name||t.email})},"data-testid":`button-add-credits-${t.id}`,children:[e.jsx(_t,{className:"w-3 h-3 mr-1"})," Adicionar Créditos"]})]}),(()=>{const s=t.role==="admin",i=rd?.mode==="all",x=Lh.has(t.id),C=rd?.flagEnabled===!1,P=s||!C&&(i||x),H=nd.isPending&&nd.variables?.userId===t.id;return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-indigo-500/5 border border-indigo-500/10","data-testid":`course-access-${t.id}`,children:[e.jsx(Bm,{className:"w-5 h-5 text-indigo-400"}),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-medium text-white",children:"Painel CURSOS"}),P?e.jsx(E,{variant:"outline",className:"text-[9px] border-emerald-500/40 text-emerald-300",children:"acesso liberado"}):e.jsx(E,{variant:"outline",className:"text-[9px] border-white/10 text-muted-foreground",children:"sem acesso"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground leading-snug mt-0.5",children:s?"Admin sempre tem acesso ao painel de cursos.":C?"Feature DESLIGADA globalmente — ative ENABLE_COURSE_GENERATOR para o cliente ver o painel. A liberação abaixo fica pré-configurada.":i?"Liberado para TODOS (modo global ativo).":"Libere ou remova o acesso deste cliente ao painel de cursos."})]}),!s&&!i&&e.jsx(b,{size:"sm",variant:"outline",disabled:H,className:x?"h-8 text-xs border-red-500/20 text-red-400 hover:bg-red-500/10":"h-8 text-xs border-indigo-500/20 text-indigo-400 hover:bg-indigo-500/10",onClick:Q=>{Q.stopPropagation(),nd.mutate({userId:t.id,email:t.email,grant:!x})},"data-testid":`button-toggle-course-${t.id}`,children:H?e.jsx(T,{className:"w-3 h-3 animate-spin"}):x?e.jsx(e.Fragment,{children:"Remover acesso"}):e.jsxs(e.Fragment,{children:[e.jsx(_t,{className:"w-3 h-3 mr-1"})," Liberar acesso"]})})]})})(),(()=>{const s=t.role==="admin",i=Gc?.mode==="all",x=zh.has(t.id),C=s||i||x,P=ld.isPending&&ld.variables?.userId===t.id;return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-violet-500/5 border border-violet-500/10","data-testid":`sabhia-pay-access-${t.id}`,children:[e.jsx(Bt,{className:"w-5 h-5 text-violet-400"}),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-medium text-white",children:"Sábhia Pay"}),C?e.jsx(E,{variant:"outline",className:"text-[9px] border-emerald-500/40 text-emerald-300",children:"acesso liberado"}):e.jsx(E,{variant:"outline",className:"text-[9px] border-white/10 text-muted-foreground",children:"sem acesso"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground leading-snug mt-0.5",children:s?"Admin sempre tem acesso ao Sábhia Pay.":i?"Liberado para TODOS (modo global ativo).":"Libere ou remova o acesso deste cliente ao painel Sábhia Pay."})]}),!s&&!i&&e.jsx(b,{size:"sm",variant:"outline",disabled:P,className:x?"h-8 text-xs border-red-500/20 text-red-400 hover:bg-red-500/10":"h-8 text-xs border-violet-500/20 text-violet-400 hover:bg-violet-500/10",onClick:H=>{H.stopPropagation(),ld.mutate({userId:t.id,email:t.email,grant:!x})},"data-testid":`button-toggle-sabhia-pay-${t.id}`,children:P?e.jsx(T,{className:"w-3 h-3 animate-spin"}):x?e.jsx(e.Fragment,{children:"Remover acesso"}):e.jsxs(e.Fragment,{children:[e.jsx(_t,{className:"w-3 h-3 mr-1"})," Liberar acesso"]})})]})})(),(t.role==="support"||t.role==="admin")&&(()=>{const s=t.supportCreditMultiplier!==null&&t.supportCreditMultiplier!==void 0?Number(t.supportCreditMultiplier):null,i=t.supportCreditMaxPerUser??null,x=D0[t.id]||{multiplier:s!==null?String(s):"",maxPerUser:i!==null?String(i):""},C=Y=>M0(Oe=>({...Oe,[t.id]:{...x,...Y}})),P=x.multiplier.trim()===""?null:Number(x.multiplier.replace(",",".")),H=x.maxPerUser.trim()===""?null:parseInt(x.maxPerUser.replace(/\D/g,""),10),Q=P===null||Number.isFinite(P)&&P>0&&P<=100,G=H===null||Number.isFinite(H)&&H>0&&H<=1e7,ue=P!==s||H!==i,Te=Tl.isPending&&Tl.variables?.id===t.id;return e.jsxs("div",{className:"p-3 rounded-lg bg-orange-500/5 border border-orange-500/10 space-y-3","data-testid":`support-credit-limits-${t.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Um,{className:"w-4 h-4 text-orange-400"}),e.jsx("span",{className:"text-sm font-medium text-white",children:"Limite de crédito do agente"}),s!==null||i!==null?e.jsx(E,{variant:"outline",className:"text-[9px] border-orange-500/40 text-orange-300",children:"override ativo"}):e.jsx(E,{variant:"outline",className:"text-[9px] border-white/10 text-muted-foreground",children:"padrão (2× gasto)"})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground leading-snug",children:["Padrão: agente pode liberar até ",e.jsx("strong",{children:"2× o que o cliente pagou em PIX/cartão"})," (mín 1.000 créditos de cortesia). Aqui você ajusta SÓ esse agente: ",e.jsx("strong",{children:"multiplicador"})," sobe para 3×/5× etc, e/ou ",e.jsx("strong",{children:"cap absoluto"})," garante que o agente sempre pode liberar até X créditos por cliente, independente do gasto. Limites NUNCA reduzem o padrão — só aumentam."]}),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("label",{className:"text-[10px] text-muted-foreground",children:"Multiplicador (vazio = padrão 2×)"}),e.jsx(J,{type:"number",step:"0.5",min:0,max:100,value:x.multiplier,onCh
3ange:Y=>C({multiplier:Y.target.value}),placeholder:"ex: 3",className:`h-8 text-xs bg-black/30 border-white/10 ${Q?"":"border-red-500/50"}`,"data-testid":`input-support-mult-${t.id}`})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Cap absoluto / cliente (créditos, vazio = sem cap)"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(J,{type:"number",min:0,max:1e7,value:x.maxPerUser,onChange:Y=>C({maxPerUser:Y.target.value}),placeholder:"ex: 100000",className:`h-8 text-xs bg-black/30 border-white/10 ${G?"":"border-red-500/50"}`,"data-testid":`input-support-cap-${t.id}`}),[5e4,1e5,2e5,3e5].map(Y=>e.jsxs(b,{type:"button",size:"sm",variant:"outline",className:"h-8 px-2 text-[10px] border-orange-500/20 text-orange-400 hover:bg-orange-500/10",onClick:()=>C({maxPerUser:String(Y)}),"data-testid":`button-support-cap-preset-${t.id}-${Y}`,children:[Y/1e3,"k"]},Y))]})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-1",children:[(s!==null||i!==null)&&e.jsx(b,{size:"sm",variant:"outline",className:"h-8 text-xs border-white/10 text-muted-foreground hover:text-white",onClick:()=>{C({multiplier:"",maxPerUser:""}),Tl.mutate({id:t.id,multiplier:null,maxPerUser:null})},disabled:Te,"data-testid":`button-support-limits-reset-${t.id}`,children:"Voltar pro padrão"}),e.jsx(b,{size:"sm",className:"h-8 text-xs bg-orange-600 hover:bg-orange-700 text-white",disabled:!ue||!Q||!G||Te,onClick:()=>Tl.mutate({id:t.id,multiplier:P,maxPerUser:H}),"data-testid":`button-support-limits-save-${t.id}`,children:Te?e.jsx(T,{className:"w-3 h-3 animate-spin"}):"Salvar"})]})]})})(),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-teal-500/5 border border-teal-500/10",children:[e.jsx(Ka,{className:"w-5 h-5 text-teal-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Link Mágico"}),e.jsx("p",{className:"text-[11px] text-white/40",children:"Gera um link de acesso direto válido por 10 minutos"}),Pr[t.id]&&e.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[e.jsx("input",{readOnly:!0,value:Pr[t.id].link,className:"flex-1 text-[11px] bg-black/30 border border-white/10 rounded px-2 py-1 text-teal-300 font-mono truncate",onClick:s=>{s.target.select(),navigator.clipboard.writeText(Pr[t.id].link),r({title:"Link copiado!"})},"data-testid":`input-magic-link-${t.id}`}),e.jsxs("span",{className:"text-[10px] text-white/30 flex-shrink-0",children:["Expira ",new Date(Pr[t.id].expiresAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})]})]})]}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-8 text-xs border-teal-500/20 text-teal-400 hover:bg-teal-500/10",onClick:s=>{s.stopPropagation(),Dh(t.id)},disabled:Lc===t.id,"data-testid":`button-magic-link-${t.id}`,children:[Lc===t.id?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(Ka,{className:"w-3 h-3 mr-1"}),Pr[t.id]?"Gerar Novo":"Gerar Link"]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"flex-1 flex items-center gap-3 p-3 rounded-lg bg-violet-500/5 border border-violet-500/10",children:[e.jsx(Ut,{className:"w-5 h-5 text-violet-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Iniciar Conversa"}),e.jsx("p",{className:"text-[11px] text-white/40",children:"Enviar mensagem direta ao cliente via chat"})]}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-8 text-xs border-violet-500/20 text-violet-400 hover:bg-violet-500/10",onClick:async s=>{s.stopPropagation();try{(await(await N("POST","/api/admin/support/conversations/start",{userId:t.id})).json()).conversationId&&r({description:"Conversa iniciada! Acesse a aba Suporte IA para continuar."})}catch{r({description:"Erro ao iniciar conversa",variant:"destructive"})}},"data-testid":`button-start-chat-${t.id}`,children:[e.jsx(Ut,{className:"w-3 h-3 mr-1"}),"Iniciar Chat"]})]}),e.jsxs("div",{className:"flex-1 flex items-center gap-3 p-3 rounded-lg bg-amber-500/5 border border-amber-500/10",children:[e.jsx(tt,{className:"w-5 h-5 text-amber-400 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Dossiê do Cliente"}),e.jsx("p",{className:"text-[11px] text-white/40",children:"Documento completo com tudo entregue"})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(b,{size:"sm",variant:"outline",className:"h-8 text-xs border-amber-500/20 text-amber-400 hover:bg-amber-500/10",disabled:sd===t.id,onClick:s=>{s.stopPropagation(),Kc(t.id,t.name,"dossie",Rh)},"data-testid":`button-dossie-${t.id}`,children:[sd===t.id?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(tt,{className:"w-3 h-3 mr-1"}),sd===t.id?"Gerando...":"Gerar Dossiê"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-8 text-xs border-amber-500/20 text-amber-400 hover:bg-amber-500/10",disabled:ad===t.id,onClick:s=>{s.stopPropagation(),Kc(t.id,t.name,"dossie-zip",Fh)},"data-testid":`button-dossie-zip-${t.id}`,title:"Baixar o dossiê dividido em PDFs pequenos (ZIP) — ideal pro limite de tamanho da Woovi",children:[ad===t.id?e.jsx(T,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(tt,{className:"w-3 h-3 mr-1"}),ad===t.id?"Montando...":"ZIP dividido"]}),e.jsxs(b,{size:"sm",className:"h-8 text-xs bg-cyan-600 hover:bg-cyan-700 text-white gap-1",disabled:td===t.id,onClick:s=>{s.stopPropagation(),Mh(t.id)},"data-testid":`button-dossie-woovi-${t.id}`,title:"Gerar dossiê e enviar como evidência para a disputa MED ativa na Woovi",children:[td===t.id?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(ct,{className:"w-3 h-3"}),td===t.id?"Enviando...":"Enviar Woovi"]})]})]})]}),t.email?.includes("@sabhia.temp")&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-orange-500/5 border border-orange-500/10",children:[e.jsx(Oi,{className:"w-5 h-5 text-orange-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-white",children:"Mesclar com Conta Email"}),e.jsx("p",{className:"text-[11px] text-white/40",children:"Transferir livros e dados desta conta temporária para uma conta com email real"})]}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-8 text-xs border-orange-500/20 text-orange-400 hover:bg-orange-500/10",onClick:s=>{s.stopPropagation(),En({sourceUser:t,targetEmail:""}),Tr(t.notificationEmail||""),Ja(null)},"data-testid":`button-merge-accounts-${t.id}`,children:[e.jsx(Oi,{className:"w-3 h-3 mr-1"}),"Mesclar Contas"]})]}),e.jsx(Wb,{userId:t.id,isExpanded:L===t.id}),e.jsxs("div",{className:"bg-gradient-to-r from-white/[0.03] to-transparent roun
3ded-xl border border-white/10 p-5",children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-4 flex items-center gap-2",children:[e.jsx(nt,{className:"w-3.5 h-3.5"})," Relatório Financeiro"]}),(()=>{const s=new Set(["pix","card","credit_card"]),i=t.orders.filter(ze=>ze.status==="confirmed"||ze.status==="completed"),x=i.filter(ze=>s.has(String(ze.paymentMethod||""))),C=i.filter(ze=>ze.paymentMethod==="credits"),P=x.reduce((ze,Wt)=>ze+Wt.amount,0),H=C.reduce((ze,Wt)=>ze+Wt.amount,0),Q=t.totalAiCostBRL||0,G=P-Q,ue=P>0?G/P*100:0,Te=x.length,Y=t.orders.filter(ze=>ze.status==="pending").length,Oe=Te>0?P/Te:0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsxs("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:["Faturamento ",e.jsx("span",{className:"text-emerald-400/50",children:"· PIX/cartão"})]}),e.jsxs("p",{className:"text-lg font-bold text-emerald-400","data-testid":`text-revenue-${t.id}`,children:["R$ ",P.toFixed(2)]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Te," pedido",Te!==1?"s":""," pago",Te!==1?"s":""]}),H>0&&e.jsx("div",{className:"mt-1.5 inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-amber-500/10 border border-amber-500/20","data-testid":`badge-credits-revenue-${t.id}`,children:e.jsxs("span",{className:"text-[9px] text-amber-400/90",children:["+ R$ ",H.toFixed(2)," em créditos"]})})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Custo IA"}),e.jsxs("p",{className:"text-lg font-bold text-amber-400","data-testid":`text-cost-${t.id}`,children:["R$ ",Q.toFixed(4)]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[t.orders.reduce((ze,Wt)=>ze+(Wt.aiCalls||0),0)," chamadas"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Saldo Líquido"}),e.jsxs("p",{className:`text-lg font-bold ${G>=0?"text-emerald-400":"text-red-400"}`,"data-testid":`text-net-${t.id}`,children:["R$ ",G.toFixed(2)]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Margem: ",ue.toFixed(1),"%"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Ticket Médio"}),e.jsxs("p",{className:"text-lg font-bold text-white","data-testid":`text-avg-${t.id}`,children:["R$ ",Oe.toFixed(2)]}),Y>0&&e.jsxs("p",{className:"text-[10px] text-amber-400",children:[Y," pendente",Y!==1?"s":""]})]})]}),t.orders.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-2",children:["Receita por Tipo de Serviço ",e.jsx("span",{className:"text-emerald-400/50 normal-case",children:"(PIX/cartão — créditos não contam)"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(()=>{const ze={};return x.forEach(Wt=>{const Xs=Wt.type;ze[Xs]||(ze[Xs]={revenue:0,count:0,label:Wt.label||Wt.type}),ze[Xs].revenue+=Wt.amount,ze[Xs].count+=1}),Object.entries(ze).map(([Wt,Xs])=>e.jsxs("div",{className:"bg-white/5 rounded-lg px-3 py-1.5 flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] text-white",children:Xs.label}),e.jsxs("span",{className:"text-[10px] text-emerald-400 font-medium",children:["R$ ",Xs.revenue.toFixed(2)]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",Xs.count,"x)"]})]},Wt))})()})]})]})})()]}),e.jsxs("div",{className:"bg-gradient-to-r from-white/[0.03] to-transparent rounded-xl border border-white/10 p-5",children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-4 flex items-center gap-2",children:[e.jsx(jt,{className:"w-3.5 h-3.5"})," Resumo de Atividades"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-7 gap-3","data-testid":`section-activities-${t.id}`,children:[{icon:ot,label:"Planejamentos",value:t.activity?.plans||
30,color:"text-blue-400",bg:"bg-blue-500/10"},{icon:tt,label:"Livros Gerados",value:t.activity?.booksGenerated||0,color:"text-emerald-400",bg:"bg-emerald-500/10"},{icon:Va,label:"Capas Criadas",value:t.activity?.covers||0,color:"text-purple-400",bg:"bg-purple-500/10"},{icon:qe,label:"Ilustrações",value:t.activity?.illustrations||0,color:"text-pink-400",bg:"bg-pink-500/10"},{icon:Xt,label:"Divulgações",value:t.activity?.marketingMaterials||0,color:"text-orange-400",bg:"bg-orange-500/10"},{icon:Zs,label:"Publicações",value:t.activity?.publications||0,color:"text-teal-400",bg:"bg-teal-500/10"},{icon:fn,label:"Traduções",value:t.activity?.translations||0,color:"text-cyan-400",bg:"bg-cyan-500/10"}].map(s=>e.jsxs("div",{className:`rounded-lg p-3 text-center space-y-1.5 ${s.value>0?"bg-white/5":"bg-white/[0.02] opacity-50"}`,"data-testid":`text-activity-${s.label.toLowerCase().replace(/\s+/g,"-")}-${t.id}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full ${s.value>0?s.bg:"bg-white/5"} flex items-center justify-center mx-auto`,children:e.jsx(s.icon,{className:`w-4 h-4 ${s.value>0?s.color:"text-muted-foreground"}`})}),e.jsx("p",{className:`text-sm font-bold ${s.value>0?"text-white":"text-muted-foreground"}`,children:s.value}),e.jsx("p",{className:"text-[10px] text-muted-foreground leading-tight",children:s.label})]},s.label))})]}),t.aiCostByCategory&&Object.entries(t.aiCostByCategory).some(([,s])=>s.callCount>0)&&e.jsxs("div",{className:"bg-gradient-to-r from-white/[0.03] to-transparent rounded-xl border border-white/10 p-5",children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-4 flex items-center gap-2",children:[e.jsx(Ht,{className:"w-3.5 h-3.5"})," Custo IA por Serviço"]}),e.jsx("div",{className:"grid gap-2","data-testid":`section-ai-cost-category-${t.id}`,children:Object.entries(t.aiCostByCategory).filter(([,s])=>s.callCount>0).sort((s,i)=>i[1].costBRL-s[1].costBRL).map(([s,i])=>e.jsxs("div",{className:"flex items-center justify-between bg-white/5 rounded-lg px-3 py-2",children:[e.jsx("span",{className:"text-xs text-white",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-xs font-medium text-amber-400",children:["R$ ",i.costBRL.toFixed(4)]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[i.callCount," chamada",i.callCount!==1?"s":""]})]})]},s))})]}),t.books.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Livros"}),e.jsx("div",{className:"grid gap-3",children:t.books.map(s=>e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-2","data-testid":`card-book-detail-${s.id}`,children:[e.jsxs("div",{className:"flex items-start gap-3",children:[s.coverImage?e.jsx(vc,{src:s.coverImage,alt:s.title,widths:[96,128,160],sizes:"48px",className:"w-12 h-16 rounded object-cover shrink-0 border border-white/10"}):e.jsx("div",{className:"w-12 h-16 rounded bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:e.jsx(ot,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-white truncate",children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(Gi,{status:s.status}),(s.status==="error"||s.status==="needs_review")&&e.jsxs("button",{onClick:i=>{i.stopPropagation(),od.mutate(s.id)},disabled:od.isPending,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium bg-amber-500/20 text-amber-400 border border-amber-500/30 hover:bg-amber-500/30 transition-colors disabled:opacity-50","data-testid":`btn-retry-book-${s.id}`,title:s.status==="needs_review"?"Retoma a geração além da pausa de revisão de qualidade, usando os capítulos já escritos":void 0,children:[od.isPending?e.jsx(T,{className:"w-2.5 h-2.5 animate-spin"}):e.jsx(xe,{className:"w-2.5 h-2.5"}),"Retomar Geração"]}),s.planStatus==="ready"&&!s.isPaid&&(s.chaptersWritten??0)===0&&s.status!=="generating"&&s.status!=="writing"&&s.status!=="completed"&&e.jsxs("button",{onClick:i=>{i.stopPropagation(),window.confirm(`Gerar o TEXTO completo de "${s.title}" agora, como se tivesse sido pago?
4
5Isso consome IA e escreve todos os capítulos do plano. Use só para livros que você mesmo quer gerar.`)&&cd.mutate(s.id)},disabled:cd.isPending,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium bg-violet-500/20 text-violet-300 border border-violet-500/30 hover:bg-violet-500/30 transition-colors disabled:opacity-50","data-testid":`btn-generate-from-plan-${s.id}`,children:[cd.isPending?e.jsx(T,{className:"w-2.5 h-2.5 animate-spin"}):e.jsx(qe,{className:"w-2.5 h-2.5"}),"Gerar Texto do Livro"]}),!s.isPaid&&(s.chaptersWritten??0)>0&&e.jsxs("button",{onClick:i=>{i.stopPropagation(),window.confirm(`Liberar o acesso de "${s.title}" como cortesia (como se tivesse sido pago)?
6
7O texto já está escrito. Isso remove a cobrança e o seletor de plano, libera a aba de escrita e os downloads para o cliente. NÃO gera nova cobrança nem conta como receita.`)&&xd.mutate(s.id)},disabled:xd.isPending,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 hover:bg-emerald-500/30 transition-colors disabled:opacity-50","data-testid":`btn-grant-access-${s.id}`,children:[xd.isPending?e.jsx(T,{className:"w-2.5 h-2.5 animate-spin"}):e.jsx(be,{className:"w-2.5 h-2.5"}),"Liberar Acesso (Cortesia)"]}),s.isPaid&&e.jsx(E,{variant:"outline",className:"text-[10px] border-emerald-500/30 text-emerald-400",children:"Pago"}),s.planStatus&&e.jsx(E,{variant:"outline",className:"text-[10px] border-blue-500/30 text-blue-400",children:s.planStatus}),s.publicationReady&&e.jsxs(E,{variant:"outline",className:"text-[10px] border-teal-500/30 text-teal-400",children:[e.jsx(Zs,{className:"w-2.5 h-2.5 mr-1"}),"Pronto p/ Publicação"]})]}),s.createdAt&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:["Criado: ",new Date(s.createdAt).toLocaleDateString("pt-BR")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap text-[10px]",children:[e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground","data-testid":`text-chapter
7s-${s.id}`,children:[e.jsx(tt,{className:"w-3 h-3"})," ",s.chaptersWritten,"/",s.chapterCount," capítulos"]}),s.coverCount>0&&e.jsxs("span",{className:"flex items-center gap-1 text-purple-400","data-testid":`text-covers-${s.id}`,children:[e.jsx(Va,{className:"w-3 h-3"})," ",s.coverCount," ",s.coverCount===1?"capa":"capas"]}),s.illustrationCount>0&&e.jsxs("span",{className:"flex items-center gap-1 text-pink-400","data-testid":`text-illustrations-${s.id}`,children:[e.jsx(qe,{className:"w-3 h-3"})," ",s.illustrationCount," ",s.illustrationCount===1?"ilustração":"ilustrações"]}),s.translationCount>0&&e.jsxs("span",{className:"flex items-center gap-1 text-cyan-400","data-testid":`text-translations-${s.id}`,children:[e.jsx(fn,{className:"w-3 h-3"})," ",s.translationCount," ",s.translationCount===1?"tradução":"traduções"]}),(s.marketingCount||0)>0&&e.jsxs("span",{className:"flex items-center gap-1 text-orange-400","data-testid":`text-marketing-${s.id}`,children:[e.jsx(Xt,{className:"w-3 h-3"})," ",s.marketingCount," divulgaç",s.marketingCount===1?"ão":"ões"]}),(s.planVersionCount||0)>0&&e.jsxs("span",{className:"flex items-center gap-1 text-blue-400","data-testid":`text-plan-versions-${s.id}`,children:[e.jsx(ot,{className:"w-3 h-3"})," ",s.planVersionCount," ",s.planVersionCount===1?"versão":"versões"," do plano"]})]}),e.jsx(tu,{bookId:s.id,title:s.title,coverImage:s.coverImage})]},s.id))})]}),t.orders.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Pedidos"}),e.jsx("div",{className:"grid gap-2",children:t.orders.map(s=>e.jsxs("div",{className:"flex items-center justify-between bg-white/5 rounded-lg px-3 py-2","data-testid":`card-order-${s.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-mono text-muted-foreground",children:s.id.slice(0,8)}),e.jsx("span",{className:"text-xs text-white",children:s.label||s.type}),s.paymentMethod&&e.jsxs(E,{variant:"outline",className:`text-[10px] ${s.paymentMethod==="pix"?"border-green-500/30 text-green-400":s.paymentMethod==="card"?"border-blue-500/30 text-blue-400":s.paymentMethod==="credits"?"border-amber-500/30 text-amber-400":"border-white/10 text-muted-foreground"}`,children:[s.paymentMethod==="pix"&&e.jsx(Oa,{className:"w-2.5 h-2.5 mr-1"}),s.paymentMethod==="card"&&e.jsx(Bt,{className:"w-2.5 h-2.5 mr-1"}),s.paymentMethod==="credits"&&e.jsx("span",{className:"mr-1 inline-flex",children:e.jsx(ic,{size:"sm"})}),s.paymentMethod==="credits"?"CRÉDITOS":s.paymentMethod.toUpperCase()]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs font-medium text-white",children:["R$ ",s.amount.toFixed(2)]}),s.aiCostBRL>0&&e.jsxs("span",{className:"text-[10px] text-amber-400 font-mono","data-testid":`text-ai-cost-order-${s.id}`,children:["IA: R$ ",s.aiCostBRL.toFixed(4)]}),e.jsx(Gi,{status:s.status}),e.jsx(Gb,{userId:t.id,orderId:s.id,orderStatus:s.status}),e.jsx(lg,{orderId:s.id,orderStatus:s.status,orderAmount:s.amount,orderLabel:s.label||s.type,customerName:t.name||t.email||"Cliente",refundedAt:s.refundedAt,refundProtocol:s.refundProtocol,refundGateway:s.refundGateway}),s.createdAt&&e.jsx("span",{className:"text-[10px] text-muted-foreground hidden sm:inline",children:new Date(s.createdAt).toLocaleDateString("pt-BR")})]})]},s.id))})]}),e.jsx(mg,{userId:t.id,customerName:t.name||t.email||"Cliente"}),t.books.length===0&&t.orders.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Nenhum livro ou pedido."})]})]},t.id)),ci&&ci.length>0&&e.jsxs("div",{className:"flex flex-col items-center gap-2 pt-3","data-testid":"users-pagination",children:[e.jsxs("p",{className:"text-xs text-muted-foreground","data-testid":"text-users-shown",children:["Mostrando ",Math.min(de,ci.length)," de ",ci.length," clientes"]}),ci.length>de&&e.jsxs(b,{variant:"outline",size:"sm",className:"h-9 text-xs border-white/10 text-white/70 hover:text-white",onClick:()=>me(t=>t+I),"data-testid":"button-load-more-users",children:[e.jsx(Ct,{className:"w-4 h-4 mr-1.5"}),"Carregar mais ",Math.min(I,ci.length-de)]})]})]})]})]}),e.jsxs(Be,{value:"settings",className:"mt-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:"Configurações"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Preç
7os, gateways e configurações gerais."})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"section-book-search",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-primary"})," Buscar Livro (todos os usuários)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Pesquise por título ou autor em todos os livros da plataforma. Use para encontrar livros "perdidos" de usuários.'}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(J,{placeholder:"Título ou autor...",value:te,onChange:t=>M(t.target.value),onKeyDown:t=>{if(t.key==="Enter"){const s=te.trim();s.length>=2&&(se(!0),fetch(`/api/admin/books/search?q=${encodeURIComponent(s)}`).then(i=>i.json()).then(i=>ye(i)).catch(()=>ye([])).finally(()=>se(!1)))}},className:"bg-black/20 border-white/10","data-testid":"input-admin-book-search"}),e.jsx(b,{variant:"outline",onClick:()=>{const t=te.trim();t.length>=2&&(se(!0),fetch(`/api/admin/books/search?q=${encodeURIComponent(t)}`).then(s=>s.json()).then(s=>ye(s)).catch(()=>ye([])).finally(()=>se(!1)))},disabled:Me,"data-testid":"button-admin-book-search",children:Me?e.jsx(T,{className:"w-4 h-4 animate-spin"}):e.jsx(St,{className:"w-4 h-4"})})]}),ae!==null&&e.jsx("div",{className:"space-y-2",children:ae.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nenhum livro encontrado."}):ae.map(t=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-black/20 rounded-lg border border-white/10",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-white font-medium truncate","data-testid":`text-book-title-${t.id}`,children:t.title}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[t.author," · ",t.userEmail," · ",t.status]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 ml-3",children:[e.jsx("button",{onClick:()=>navigator.clipboard.writeText(t.id),className:"text-[10px] px-2 py-1 bg-white/10 rounded hover:bg-white/20 text-white","data-testid":`button-copy-id-${t.id}`,children:"Copiar ID"}),e.jsx("button",{onClick:async()=>{const s=prompt("Email do usuário destino:");if(s)try{const i=await fetch(`/api/admin/books/${t.id}/reassign`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetUserId:s})}),x=await i.json();if(alert(x.message||x.error||"Erro"),i.ok){const C=te.trim();C.length>=2&&fetch(`/api/admin/books/search?q=${encodeURIComponent(C)}`).then(P=>P.json()).then(P=>ye(P))}}catch{alert("Erro de conexão")}},className:"text-[10px] px-2 py-1 bg-orange-500/20 rounded hover:bg-orange-500/30 text-orange-400","data-testid":`button-reassign-${t.id}`,children:"Transferir"})]})]},t.id))})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"section-free-plan-ip-guard",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4 text-primary"})," Limite de planejamentos gratuitos"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Controla quantos planejamentos gratuitos um mesmo IP pode iniciar em 24 horas."})]}),e.jsx(rt,{checked:Gs?.enabled??!1,disabled:!Gs||ln.isPending,onCheckedChange:t=>ln.mutate({enabled:t,limit:Gs?.limit||5}),"data-testid":"switch-free-plan-ip-guard"})]}),e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(O,{htmlFor:"free-plan-ip-limit",className:"text-xs text-white/80",children:"Planejamentos por IP em 24 horas"}),e.jsx(J,{id:"free-plan-ip-limit",type:"number",min:"1",max:"100",step:"1",value:Yc,onChange:t=>Zc(t.target.value),disabled:!Gs?.enabled,className:"bg-black/20 border-white/10","data-testid":"input-free-plan-ip-limit"})]}),e.jsxs(b,{onClick:()=>ln.mutate({enabled:Gs?.enabled??!1,limit:Math.max(1,Math.min(100,Number(Yc)||5))}),disabled:!Gs?.enabled||ln.isPending,"data-testid":"button-save-free-plan-ip-limit",children:[ln.isPending&&e.jsx(T,{className:"w-4 h-4 mr-2 animate-spin"}),"Salvar"]})]}),e.jsx("p",{className:`text-xs ${Gs?.enabled?"text-amber-300/80":"text-emerald-300/80"}`,children:Gs?.enabled?`Limitação ativa: até ${Gs.limit} planejamentos por IP.`:"Limitação desativada: novos planejamentos não serão bloqueados por IP."})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"section-price-sett
7ings",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4 text-primary"})," Preço da Geração de Livro"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Valor cobrado quando o cliente manda gerar o livro completo após o planejamento."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(J,{type:"number",step:"0.01",defaultValue:Hh?.value||"49.99",id:"book-price-input",className:"bg-black/20 border-white/10","data-testid":"input-book-price"}),e.jsxs(b,{onClick:()=>{const t=document.getElementById("book-price-input");Jo.mutate(t.value)},disabled:Jo.isPending,"data-testid":"button-update-price",children:[Jo.isPending&&e.jsx(T,{className:"w-4 h-4 mr-2 animate-spin"}),"Salvar"]})]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"section-gateway-status",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-primary"})," Gateways de Pagamento"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg border ${Es?.hasWooviAppId?"bg-emerald-500/5 border-emerald-500/20":"bg-red-500/5 border-red-500/20"}`,children:[e.jsx(Oa,{className:"w-5 h-5 text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-white font-medium",children:"PIX (Woovi/OpenPix)"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Pagamentos via PIX"})]}),Es?.hasWooviAppId?e.jsx(E,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-[10px]",children:"Ativo"}):e.jsx(E,{className:"bg-red-500/20 text-red-400 border-red-500/30 text-[10px]",children:"Inativo"})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-emerald-500/5 border-emerald-500/20",children:[e.jsx(Bt,{className:"w-5 h-5 text-blue-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-white font-medium",children:"Stripe (Cartão)"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Cartão de crédito"})]}),e.jsx(E,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-[10px]",children:"Ativo"})]})]})]})]})]}),e.jsxs(Be,{value:"webhooks",className:"mt-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:"Integrações e Webhooks"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Configure e monitore as integrações externas."})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-green-500/10 flex items-center justify-center",children:e.jsx(pt,{className:"w-5 h-5 text-green-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-white font-semibold text-sm",children:"Webhook PIX (Woovi/OpenPix)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Configure esta URL no painel da Woovi"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground font-medium uppercase tracking-wider",children:"URL do Webhook"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex-1 bg-black/30 border border-white/10 rounded-lg px-4 py-2.5 font-mono text-xs text-green-400 overflow-x-auto","data-testid":"text-webhook-url",children:Es?.webhookUrl||"Carregando..."}),e.jsx(b,{variant:"outline",size:"icon",className:"h-10 w-10 shrink-0 border-white/10 hover:bg-white/10",onClick:()=>Es?.webhookUrl&&q0(Es.webhookUrl),"data-testid":"button-copy-webhook-url",children:e.jsx(ha,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:`flex items-center gap-2 p-3 rounded-lg border ${Es?.hasWooviAppId?"bg-green-500/5 border-green-500/20":"bg-red-500/5 border-red-500/20"}`,children:[Es?.hasWooviAppId?e.jsx(be,{className:"w-4 h-4 text-green-400"}):e.jsx(dt,{className:"w-4 h-4 text-red-400"}),e.jsxs("span",{className:`text-xs ${Es?.hasWooviAppId?"text-green-400":"text-red-400"}`,children:["WOOVI_APP_ID ",Es?.hasWooviAppId?"configurado":"não configurado"]})]}),e.jsxs("div",{className:`flex items-center gap-2 p-3 rounded-lg border ${Es?.hasWebhookSecret?"bg-green-500/5 border-green-500/20":"bg-
7amber-500/5 border-amber-500/20"}`,children:[Es?.hasWebhookSecret?e.jsx(be,{className:"w-4 h-4 text-green-400"}):e.jsx(Ce,{className:"w-4 h-4 text-amber-400"}),e.jsxs("span",{className:`text-xs ${Es?.hasWebhookSecret?"text-green-400":"text-amber-400"}`,children:["WOOVI_WEBHOOK_SECRET ",Es?.hasWebhookSecret?"configurado":"(opcional)"]})]})]}),e.jsxs("div",{className:"bg-black/20 border border-white/5 rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary text-xs font-semibold",children:[e.jsx(js,{className:"w-3.5 h-3.5"}),"Instruções para configurar no Woovi"]}),e.jsxs("ol",{className:"text-xs text-muted-foreground space-y-1.5 list-decimal list-inside",children:[e.jsxs("li",{children:["Acesse o painel Woovi → ",e.jsx("span",{className:"text-white",children:"Configurações → Webhooks"})]}),e.jsxs("li",{children:["Crie um novo webhook com o nome ",e.jsx("span",{className:"text-white",children:'"Sábhia Books"'})]}),e.jsxs("li",{children:["Evento: ",e.jsx("span",{className:"text-green-400 font-mono text-[11px]",children:Es?.instructions?.event||"OPENPIX:CHARGE_COMPLETED"})]}),e.jsx("li",{children:"Cole a URL acima no campo URL"}),e.jsx("li",{children:"Ative o webhook e salve"})]})]})]}),e.jsx(Ob,{}),e.jsx(Bb,{}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-white/5 flex items-center justify-between",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:["Eventos Recebidos",e.jsx(E,{variant:"outline",className:"text-[10px] border-white/10 text-muted-foreground",children:In?.length||0})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Atualiza a cada 10s"})]}),In&&In.length>0?e.jsx("div",{className:"divide-y divide-white/5 max-h-[400px] overflow-y-auto",children:In.map(t=>e.jsxs("div",{className:"p-3 hover:bg-white/5 transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[t.status==="processed"?e.jsx(be,{className:"w-3.5 h-3.5 text-green-400"}):t.status==="error"||t.status==="rejected"?e.jsx(dt,{className:"w-3.5 h-3.5 text-red-400"}):t.status==="skipped"?e.jsx(Ce,{className:"w-3.5 h-3.5 text-amber-400"}):e.jsx(ns,{className:"w-3.5 h-3.5 text-blue-400"}),e.jsx("span",{className:"text-xs text-white font-medium",children:t.event}),e.jsx(E,{variant:"outline",className:`text-[10px] ${t.status==="processed"?"border-green-500/30 text-green-400":t.status==="error"||t.status==="rejected"?"border-red-500/30 text-red-400":t.status==="skipped"?"border-amber-500/30 text-amber-400":"border-blue-500/30 text-blue-400"}`,children:t.status})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:t.createdAt?new Date(t.createdAt).toLocaleString("pt-BR"):"-"})]}),t.correlationId&&e.jsxs("p",{className:"text-[10px] text-muted-foreground font-mono ml-5",children:["Order: ",t.correlationId.slice(0,12),"..."]}),t.errorMessage&&e.jsx("p",{className:"text-[10px] text-red-400/80 ml-5 mt-0.5",children:t.errorMessage})]},t.id))}):e.jsxs("div",{className:"p-8 text-center text-muted-foreground",children:[e.jsx(pt,{className:"w-8 h-8 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum evento recebido ainda."})]})]})]}),e.jsxs(Be,{value:"notifications",className:"mt-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:"Notificações"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Selecione a notificação que deseja configurar e edite os templates de email e WhatsApp."})]}),(()=>{const t=hd.find(i=>i.key===Is)||hd[0],s=Is==="store_published";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3","data-testid":"notif-type-selector",children:hd.map(i=>e.jsx("button",{onClick:()=>{Xh(i.key),$i(null),Za({}),ex([])},className:`text-left rounded-xl p-4 border transition-all ${Is===i.key?"bg-teal-500/10 border-teal-500/40 ring-1 ring-teal-500/30":"bg-white/[0.03] border-white/10 hover:bg-white/[0.06] hover:border-white/20"}`,"data-testid":`notif-type-card-${i.key}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:i.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:`text-sm font-semibold ${Is===i.key?"text-teal-300":"text-white"}`,children:i.label}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:i.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[i.key!=="store_published"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400 border border-blue-500/20",children:"📧 Email"}),e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-green-500/10 text-green-400 border border-green-500/20",children:"📱 WhatsApp"})]})]}),Is===i.key&&e.jsx(be,{className:"w-4 h-4 text-teal-400 shrink-0 mt-0.5"})]})},i.key))}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(O,{className:"text-white text-xs",children:"Nome da Aplicação"}),e.jsx(J,{value:Tt.appName,onChange:i=>Ya(x=>({...x,appName:i.target.value})),placeholder:"Minha App",className:"bg-black/20 border-white/10 max-w-md","data-testid":"input-notif-app-name"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[!s&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(Nn,{className:"w-4 h-4 text-primary"})," Template de E-mail — ",t.label]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(O,{className:"text-white text-xs",children:"Assu
7nto do Email"}),e.jsx(J,{value:Tt.emailSubject,onChange:i=>Ya(x=>({...x,emailSubject:i.target.value})),placeholder:"Assunto do email...",className:"bg-black/20 border-white/10","data-testid":"input-notif-email-subject"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(O,{className:"text-white text-xs",children:"Template HTML"}),e.jsx($s,{value:Tt.emailTemplate,onChange:i=>Ya(x=>({...x,emailTemplate:i.target.value})),rows:12,placeholder:Is==="welcome"?"Vazio = email gerado por IA automaticamente":"HTML do email... (vazio = template padrão do sistema)",className:"bg-black/20 border-white/10 font-mono text-xs","data-testid":"input-notif-email-template"})]}),e.jsxs("div",{className:"bg-black/20 border border-white/10 rounded-lg p-3 space-y-1.5",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground font-medium uppercase tracking-wider",children:"Variáveis disponíveis"}),t.variables.map(i=>e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[11px] font-mono bg-primary/10 text-primary",children:i.tag}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:i.label})]},i.tag))]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{variant:"outline",size:"sm",className:"border-white/10 text-muted-foreground hover:text-white",onClick:()=>Ya(i=>({...i,emailSubject:"",emailTemplate:""})),"data-testid":"button-notif-email-reset",children:"Restaurar Padrão"}),e.jsxs(b,{size:"sm",onClick:()=>br.mutate(Tt),disabled:br.isPending,"data-testid":"button-notif-email-save",children:[br.isPending&&e.jsx(T,{className:"w-3.5 h-3.5 animate-spin mr-1.5"}),"Salvar"]})]})]}),e.jsxs("div",{className:`bg-white/5 border border-white/10 rounded-xl p-5 space-y-4 ${s?"lg:col-span-2":""}`,children:[e.jsxs("h3",{className:"text-white font-semibold text-sm flex items-center gap-2",children:[e.jsx(Ul,{className:"w-4 h-4 text-green-400"})," Template de WhatsApp — ",t.label]}),e.jsxs("div",{className:"bg-green-500/5 border border-green-500/20 rounded-xl p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-green-400 font-semibold flex items-center gap-2",children:[e.jsx(qe,{className:"w-3.5 h-3.5"}),"Template Meta (API Oficial)"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"h-7 text-[10px] border-green-500/30 text-green-400 hover:bg-green-500/10",onClick:Dm,disabled:pd,"data-testid":"button-fetch-notif-meta-templates",children:[pd?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(xe,{className:"w-3 h-3 mr-1"}),ua.length>0?"Atualizar":"Buscar Templates"]})]}),pd&&ua.length===0&&e.jsxs("div",{className:"flex items-center justify-center py-4 text-xs text-white/40",children:[e.jsx(T,{className:"w-4 h-4 animate-spin mr-2"}),"Carregando templates da Meta..."]}),ua.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-xs text-white/60",children:"Selecionar Template"}),e.jsxs(Se,{value:Tt.metaTemplateName||"__none__",onValueChange:i=>{if(i==="__none__"){$i(null),Za({}),Ya(C=>({...C,metaTemplateName:"",metaTemplateLanguage:"pt_BR",metaComponents:"[]"}));return}const x=ua.find(C=>C.name===i);x&&R0(x)},children:[e.jsx($e,{className:"h-9 text-xs bg-black/20 border-white/10","data-testid":"select-notif-meta-template",children:e.jsx(Ae,{placeholder:"Escolha um template aprovado..."})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"__none__",children:"Nenhum (usar texto simples)"}),ua.map(i=>e.jsxs(U,{value:i.name,children:[i.name," (",i.language,") — ",i.category?.toLowerCase()]},`${i.name}-${i.language}`))]})]})]}),na&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-[#0b141a] rounded-xl p-4 space-y-2 border border-white/5",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-green-400/60 font-semibold mb-2",children:"Prévia do Template"}),e.jsx("div",{className:"bg-[#005c4b] rounded-lg rounded-tl-none p-3 max-w-[85%] space-y-1.5",children:na.components?.map((i,x)=>i.type==="HEADER"&&i.format==="TEXT"?e.jsx("p",{className:"text-[13px] font-bold text-white",children:i.text},x):i.type==="HEADER"&&i.format!=="TEXT"?e.jsxs("div",{className:"text-[10px] text-white/50 italic",children:["[",i.format,": mídia]"]},x):i.type==="BODY"?e.jsx("p",{className:"text-[13px] text-white/90 whitespace-pre-wrap",children:i.text},x):i.type==="FOOTER"?e.jsx("p",{className:"text-[11px] text-white/40 mt-1",children:i.text},x):null)}),na.components?.filter(i=>i.type==="BUTTONS").map((i,x)=>e.jsx("div",{className:"space-y-1 mt-1",children:i.buttons?.map((C,P)=>e.jsx("div",{className:"bg-[#1b2b32] rounded-lg text-center py-2 text-[12px] text-[#53bdeb]",children:C.text},P))},`btn-${x}`))]}),Object.keys(Rn).length>0&&e.jsxs("div",{className:"space-y-2.5",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40 font-semibold",children:"Mapeamento de Variáveis"}),e.jsx("p",{className:"text-[10px] text-white/30",children:"Defina o que será enviado em cada variável do template Meta."}),Object.entries(Rn).map(([i,x])=>{const C=i.split("_"),P=C.pop(),H=C.join("_");return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-xs font-mono text-green-400 w-28 shrink-0",children:[H.toUpperCase()," ",`{{${P}}}`]}),e.jsxs(Se,{value:x||"__empty__",onValueChange:Q=>Za(G=>({...G,[i]:Q==="__empty__"?"":Q})),children:[e.jsx($e,{className:"flex-1 h-8 text-xs bg-black/20 border-white/10","data-testid":`select-notif-var-${i}`,children:e.jsx(Ae,{placeholder:"Selecione..."})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"__empty__",children:"— Não mapeado —"}),t.variables.map(Q=>e.jsx(U,{value:Q.tag,children:Q.label},Q.tag))]})]})]},i)})]})]}),!na&&Tt.metaTemplateName&&ua.length>0&&e.jsxs("div",{className:"text-xs text-amber-400/80 flex items-center gap-2 bg-amber-500/5 rounded-lg p-2.5 border border-amber-500/10",children:[e.jsx(Ce,{className:"w-3.5 h-3.5 shrink-0"}),'Template "',Tt.metaTemplateName,'" salvo mas não encontrado na lista da Meta.']}),Tt.metaTemplateName&&na&&e.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-white/40 bg-black/10 rounded-lg p-2",children:[e.jsx(be,{className:"w-3 h-3 text-green-400"}),"Template ativo: ",e.jsx("span",{className:"font-mono text-green-400",children:Tt.metaTemplateName})," (",Tt.metaTemplateLanguage,")"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{variant:"outline",size:"sm",className:"border-white/10 text-muted-foreground hover:text-white",onClick:()=>{$i(null),Za({}),Ya(i=>({...i,metaTemplateName:"",metaTemplateLanguage:"pt_BR",metaComponents:"[]"}))},"data-testid":"button-notif-whatsapp-reset",children:"Restaurar Padrão"}),e.jsxs(b,{size:"sm",onClick:()=>{const i=F0(),x={...Tt,metaComponents:JSON.stringify(i)};br.mutate(x)},disabled:br.isPending,"data-testid":"button-notif-whatsapp-save",children:[br.isPending&&e.jsx(T,{className:"w-3.5 h-3.5 animate-spin mr-1.5"}),"Salvar"]})]})]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4",children:[e.jsxs("h3",{className:"text-white font-semibold text-sm",children:["Preview — ",t.label]}),e.jsxs(Vm,{defaultValue:s?"preview-whatsapp":"preview-email",children:[e.jsxs(Qm,{className:"bg-white/5 border border-white/10 h-auto gap-1 p-1",children:[!s&&e.jsx(we,{value:"preview-email",className:"text-xs",children:"Preview Email"}),e.jsx(we,{value:"preview-whatsapp",className:"text-xs",children:"Preview WhatsApp"})]}),!s&&e.jsx(Be,{value:"preview-email",className:"mt-4",children:Tt.emailTemplate?e.jsx("div",{className:"bg-white rounded-lg p-4 text-black text-sm overflow-auto max-h-[400px]",dangerouslySetInnerHTML:{__html:t.variables.reduce((i,x)=>i.replace(new RegExp(x.tag.replace(/[{}]/g,"\\$&"),"g"),x.tag==="{{code}}"?"123456":x.tag==="{{magic_link}}"?"https://sabhia.ai/api/auth/magic/sample-token":x.tag==="{{app_name}}"?Tt.appName||"SÁBHIA BOOKS":x.tag==="{{logo_url}}"?"/logo.webp":x.tag==="{{book_title}}"?"Meu Livro Incrível":x.tag==="{{book_subtitle}}"?"Uma história fascinante":x.tag==="{{book_summary}}"?"Este é um resumo do livro gerado pela IA...":x.tag==="{{author_name}}"?"João Silva":x.tag),Tt.emailTemplate)},"data-testid":"preview-email-content"}):e.jsx("div",{className:"bg-black/20 border border-white/10 rounded-lg p-6 text-center text-muted-foreground text-sm","data-testid":"preview-email-empty",children:Is==="welcome"?"Template vazio — o email será gerado automaticamente por IA.":"Template de email vazio — será usado o template padrão do sistema."})}),e.jsx(Be,{value:"preview-whatsapp",className:"mt-4",children:e.jsx("div",{className:"bg-[#0b141a] border border-white/10 rounded-lg p-4 space-y-3",children:na?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(be,{className:"w-4 h-4 text-green-400"}),e.jsx("span",{className:"text-sm text-green-400 font-medium",children:"Template Meta Configurado"})]}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-white/40",children:"Nome:"}),e.jsx("span",{className:"font-mono text-[#e9edef]",children:Tt.metaTemplateName})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-white/40",children:"Idioma:"}),e.jsx("span",{className:"font-mono text-[#e9edef]",children:Tt.metaTemplateLanguage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-white/40",children:"Status:"}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${na.status==="APPROVED"?"bg-green-500/20 text-green-400":"bg-yellow-500/20 text-yellow-400"}`,children:na.status})]})]}),na.components?.filter(i=>i.type==="BODY").map((i,x)=>e.jsxs("div",{className:"mt-3 p-3 bg-black/30 rounded-lg border border-white/5",children:[e.jsx("p",{className:"text-[10px] text-white/30 uppercase mb-1",children:"Prévia do corpo"}),e.jsx("p",{className:"text-sm text-[#e9edef] whitespace-pre-wrap",children:i.text})]},x))]}):Tt.metaTemplateName?e.jsxs("div",{className:"text-center py-6",children:[e.jsx(Ce,{className:"w-8 h-8 text-amber-400/60 mx-auto mb-2"}),e.jsxs("p",{className:"text-sm text-[#e9edef]",children:['Template "',Tt.metaTemplateName,'" configurado']}),e.jsx("p",{className:"text-xs text-white/40 mt-1",children:'Clique em "Atualizar" para carregar a prévia do template.'})]}):e.jsxs("div",{className:"text-center py-6",children:[e.jsx(Qa,{className:"w-8 h-8 text-white/20 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-white/40",children:"Nenhum template Meta selecionado."}),e.jsx("p",{className:"text-xs text-white/30 mt-1",children:"Selecione um template acima para configurar o envio via WhatsApp."})]})})})]},Is)]})]})})(),e.jsxs("div",{className:"bg-white/[0.02] border border-white/10 rounded-xl p-6 space-y-6",children:[e.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[e.jsx(jt,{className:"w-5 h-5 text-cyan-400"})," Diagnóstico de Comunicação"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teste o envio de email e WhatsApp para verificar se tudo está funcionando corretamente."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white/[0.03] border border-white/10 rounded-xl p-4 space-y-3",children:[e.jsxs("h4",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4 text-blue-400"})," Teste de Email"]}),e.jsx(J,{placeholder:"[email protected]",value:Dn,onChange:t=>op(t.target.value),className:"h-9 text-sm bg-white/5 border-white/10","data-testid":"input-test-email"}),e.jsx(b,{onClick:async()=>
7{if(Dn){xx(!0),ud(null);try{const s=await(await N("POST","/api/admin/test-email",{email:Dn})).json();ud(s)}catch(t){ud({success:!1,error:t.message})}finally{xx(!1)}}},disabled:cx||!Dn,className:"w-full h-9 text-sm bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600 text-white","data-testid":"btn-test-email",children:cx?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 mr-2 animate-spin"})," Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ct,{className:"w-4 h-4 mr-2"})," Enviar Email de Teste"]})}),Qs&&e.jsxs("div",{className:`rounded-lg p-3 text-xs ${Qs.success?"bg-emerald-500/10 border border-emerald-500/20 text-emerald-300":"bg-red-500/10 border border-red-500/20 text-red-300"}`,"data-testid":"email-test-result",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[Qs.success?e.jsx(be,{className:"w-4 h-4"}):e.jsx(dt,{className:"w-4 h-4"}),e.jsx("span",{className:"font-semibold",children:Qs.success?"Enviado com sucesso!":"Falha no envio"})]}),Qs.provider&&e.jsxs("p",{children:["Provedor: ",Qs.provider]}),Qs.fromEmail&&e.jsxs("p",{children:["Remetente: ",Qs.fromEmail]}),Qs.elapsed&&e.jsxs("p",{children:["Tempo: ",Qs.elapsed]}),Qs.error&&e.jsx("p",{className:"text-red-400 mt-1",children:Qs.error})]})]}),e.jsxs("div",{className:"bg-white/[0.03] border border-white/10 rounded-xl p-4 space-y-3",children:[e.jsxs("h4",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Qa,{className:"w-4 h-4 text-emerald-400"})," Teste de WhatsApp"]}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"+55"}),e.jsx(J,{placeholder:"(21) 99999-9999",value:si,onChange:t=>cp(t.target.value.replace(/\D/g,"")),className:"h-9 text-sm bg-white/5 border-white/10 pl-10","data-testid":"input-test-phone"})]}),e.jsx(b,{onClick:async()=>{if(!(!si||si.length<10)){hx(!0),gd(null);try{const t=si.startsWith("55")?si:`55${si}`,i=await(await N("POST","/api/admin/test-whatsapp",{phone:t})).json();gd(i)}catch(t){gd({success:!1,error:t.message})}finally{hx(!1)}}},disabled:mx||!si||si.length<10,className:"w-full h-9 text-sm bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-600 hover:to-teal-600 text-white","data-testid":"btn-test-whatsapp",children:mx?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 mr-2 animate-spin"})," Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ct,{className:"w-4 h-4 mr-2"})," Enviar WhatsApp de Teste"]})}),ms&&e.jsxs("div",{className:`rounded-lg p-3 text-xs ${ms.success?"bg-emerald-500/10 border border-emerald-500/20 text-emerald-300":"bg-red-500/10 border border-red-500/20 text-red-300"}`,"data-testid":"whatsapp-test-result",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[ms.success?e.jsx(be,{className:"w-4 h-4"}):e.jsx(dt,{className:"w-4 h-4"}),e.jsx("span",{className:"font-semibold",children:ms.success?"Enviado com sucesso!":"Falha no envio"})]}),ms.templateName&&e.jsxs("p",{children:["Template: ",ms.templateName]}),ms.templateLanguage&&e.jsxs("p",{children:["Idioma: ",ms.templateLanguage]}),ms.phoneNumberId&&e.jsxs("p",{children:["Phone Number ID: ",ms.phoneNumberId]}),ms.accessToken&&e.jsxs("p",{children:["Access Token: ",ms.accessToken]}),ms.elapsed&&e.jsxs("p",{children:["Tempo: ",ms.elapsed]}),ms.error&&e.jsx("p",{className:"text-red-400 mt-1",children:ms.error})]})]})]})]})]}),e.jsxs(Be,{value:"costs",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsxs("button",{onClick:()=>R("services"),className:`px-4 py-2 rounded-lg text-xs font-medium transition-colors ${Kt==="services"?"bg-violet-500/20 text-violet-300 border border-violet-500/30":"bg-white/5 text-muted-foreground border border-white/10 hover:bg-white/10"}`,"data-testid":"btn-cost-subtab-services",children:[e.jsx(Ht,{className:"w-3.5 h-3.5 inline mr-1.5"}),"Serviços & APIs"]}),e.jsxs("button",{onClick:()=>R("users"),className:`px-4 py-2 rounded-lg text-xs font-medium transition-colors ${Kt==="users"?"bg-violet-500/20 text-violet-300 border border-violet-500/30":"bg-white/5 text-muted-foreground border border-white/10 hover:bg-white/10"}`,"data-testid":"btn-cost-subtab-users",children:[e.jsx(Re,{className:"w-3.5 h-3.5 inline mr-1.5"}),"Por Cliente"]}),e.jsxs("button",{onClick:()=>R("workers"),className:`px-4 py-2 rounded-lg text-xs font-medium transition-colors ${Kt==="workers"?"bg-violet-500/20 text-violet-300 border border-violet-500/30":"bg-white/5 text-muted-foreground border border-white/10 hover:bg-white/10"}`,"data-testid":"btn-cost-subtab-workers",children:[e.jsx(qa,{className:"w-3.5 h-3.5 inline mr-1.5"}),"Workers"]}),e.jsxs("button",{onClick:()=>R("quality"),className:`px-4 py-2 rounded-lg text-xs font-medium transition-colors ${Kt==="quality"?"bg-violet-500/20 text-violet-300 border border-violet-500/30":"bg-white/5 text-muted-foreground border border-white/10 hover:bg-white/10"}`,"data-testid":"btn-cost-subtab-quality",children:[e.jsx(Ce,{className:"w-3.5 h-3.5 inline mr-1.5"}),"Qualidade da Geração"]})]}),Kt==="services"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Período:"}),[7,30,90].map(t=>e.jsxs("button",{onClick:()=>ds(t),className:`px-3 py-1 rounded-md text-xs font-medium transition-colors ${Ee===t?"bg-violet-500/20 text-violet-300 border border-violet-500/30":"bg-white/5 text-muted-foreground border border-white/10 hover:bg-white/10"}`,"data-testid":`btn-cost-period-${t}`,children:[t,"d"]},t))]}),Yh?e.jsx("div",{className:"p-12 text-center",children:e.jsx(T,{className:"w-6 h-6 animate-spin mx-auto text-primary"})}):es?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-violet-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Chamadas"})]}),e.jsx("p",{className:"text-xl font-bold text-white","data-testid":"metric-svc-total-calls",children:es.totals?.calls?.toLocaleStr
7ing()??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(He,{className:"w-4 h-4 text-amber-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Tokens"})]}),e.jsx("p",{className:"text-xl font-bold text-white","data-testid":"metric-svc-total-tokens",children:es.totals?.totalTokens?.toLocaleString()??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(nt,{className:"w-4 h-4 text-red-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Custo (R$)"})]}),e.jsxs("p",{className:"text-xl font-bold text-red-400","data-testid":"metric-svc-total-cost-brl",children:["R$ ",es.totals?.costBRL?.toFixed(2)??"0.00"]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(nt,{className:"w-4 h-4 text-blue-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Custo (USD)"})]}),e.jsxs("p",{className:"text-xl font-bold text-blue-400","data-testid":"metric-svc-total-cost-usd",children:["$ ",es.totals?.costUSD?.toFixed(4)??"0.0000"]})]})]}),Object.keys(es.byApiSource||{}).length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-3",children:"Por Fonte de API"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:Object.entries(es.byApiSource||{}).map(([t,s])=>{const i={replit:"Replit Integration",backup:"Chave Backup (Gemini)",tts:"TTS (Google)"},x={replit:"text-violet-400",backup:"text-amber-400",tts:"text-cyan-400"},C={replit:"border-violet-500/30",backup:"border-amber-500/30",tts:"border-cyan-500/30"};return e.jsxs("div",{className:`bg-white/5 border ${C[t]||"border-white/10"} rounded-xl p-4`,"data-testid":`card-api-source-${t}`,children:[e.jsx("p",{className:`text-xs font-medium ${x[t]||"text-white"} mb-1`,children:i[t]||t}),e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-white",children:s.calls?.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"chamadas"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-amber-400",children:s.tokens?.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"tokens"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-bold text-red-400",children:["R$ ",s.costBRL?.toFixed(2)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"custo"})]})]})]},t)})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-3",children:"Custo por Serviço"}),e.jsxs("div",{className:"space-y-2",children:[(es.services||[]).map(t=>{const s={"user-facing":"Operações do Usuário",agentFramework:"Agente IA",agentEngine:"Motor do Agente",emailAiResponder:"Respostas Email IA",recoveryEmails:"Emails de Recuperação",checkoutDripWorker:"Drip de Checkout",influencerWorker:"Busca de Influencers",supportChat:"Chat de Suporte",analyticsIntelligence:"Inteligência Analytics",instagramService:"Conteúdo Instagram",socialMediaService:"Redes Sociais",emailSequenceWorker:"Sequências de Email",blogWorker:"Blog & SEO",dailyEmailGenerator:"Email Diário",checkoutPipeline:"Pipeline de Checkout",trafficManager:"Gerente de Tráfego",coverGenerator:"Gerador de Capas",illustrationGenerator:"Gerador de Ilustrações"},i={replit:"bg-violet-500/20 text-violet-300",backup:"bg-amber-500/20 text-amber-300",tts:"bg-cyan-500/20 text-cyan-300"},x=es.totals?.costBRL>0?t.costBRL/es.totals.costBRL*100:0;return e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden","data-testid":`card-service-cost-${t.service}`,children:[e.jsxs("div",{className:"p-4 flex items-center gap-4 cursor-pointer hover:bg-white/[0.03] transition-colors",onClick:()=>Ar(Xa===t.service?null:t.service),children:[e.jsx("div",{className:"w-9 h-9 rounded-full bg-violet-500/10 flex items-center justify-center shrink-0",children:e.jsx(Ht,{className:"w-4 h-4 text-violet-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-white truncate",children:s[t.service]||t.service}),e.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full ${i[t.apiSource]||"bg-white/10 text-white/60"}`,children:t.apiSource||"replit"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx("div",{className:"flex-1 h-1.5 bg-white/5 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-violet-500 to-red-500 rounded-full",style:{width:`${Math.min(x,100)}%`}})}),e.jsxs("span",{className:"text-[10px] text-muted-foreground shrink-0",children:[x.toFixed(1),"%"]})]})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-6 shrink-0 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-violet-400",children:t.calls?.toLocaleStr
7ing()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"chamadas"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-amber-400",children:t.totalTokens?.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"tokens"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-bold text-red-400","data-testid":`text-svc-cost-${t.service}`,children:["R$ ",t.costBRL?.toFixed(4)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"custo"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-bold text-blue-400",children:["$ ",t.costUSD?.toFixed(4)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"USD"})]})]}),Xa===t.service?e.jsx(ta,{className:"w-4 h-4 text-muted-foreground shrink-0"}):e.jsx(Ct,{className:"w-4 h-4 text-muted-foreground shrink-0"})]}),Xa===t.service&&e.jsxs("div",{className:"border-t border-white/5 p-4 space-y-3 bg-black/10",children:[e.jsxs("div",{className:"sm:hidden flex flex-wrap items-center gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-violet-400",children:t.calls?.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"chamadas"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-amber-400",children:t.totalTokens?.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"tokens"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-bold text-red-400",children:["R$ ",t.costBRL?.toFixed(4)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"custo"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-bold text-blue-400",children:["$ ",t.costUSD?.toFixed(4)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"USD"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg px-3 py-2",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Entrada"}),e.jsxs("p",{className:"font-bold text-blue-400",children:[t.inputTokens?.toLocaleString()," tok"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg px-3 py-2",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saída"}),e.jsxs("p",{className:"font-bold text-emerald-400",children:[t.outputTokens?.toLocaleString()," tok"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg px-3 py-2",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Usuários"}),e.jsx("p",{className:"font-bold text-white",children:t.uniqueUsers})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg px-3 py-2",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Última chamada"}),e.jsx("p",{className:"font-bold text-white",children:t.lastCall?new Date(t.lastCall).toLocaleDateString("pt-BR"):"—"})]})]}),Object.keys(t.models||{}).length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-2",children:"Por Modelo"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:Object.entries(t.models||{}).sort(([,C],[,P])=>P.costUSD-C.costUSD).map(([C,P])=>e.jsxs("div",{className:"bg-white/5 rounded-lg px-3 py-2 flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-white font-mono truncate",children:C}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsxs("span",{className:"text-[10px] text-violet-400",children:[P.calls,"x"]}),e.jsxs("span",{className:"text-[10px] text-amber-400",children:[(P.inputTokens+P.outputTokens).toLocaleString()," tok"]}),e.jsxs("span",{className:"text-[10px] text-red-400",children:["$ ",P.costUSD?.toFixed(4)]})]})]},C))})]})]})]},t.service)}),(!es.services||es.services.length===0)&&e.jsxs("div",{className:"text-center py-12 text-muted-foreground text-sm",children:[e.jsx(Ht,{className:"w-8 h-8 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:"Nenhum uso de IA registrado neste período."})]})]})]}),es.usdBrlRate&&e.jsxs("p",{className:"text-[10px] text-muted-foreground text-right",children:["Câmbio USD/BRL: ",es.usdBrlRate?.toFixed(2)," · Período: ",es.days," dias"]})]}):null]}),Kt==="users"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 ga
7p-3",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ht,{className:"w-4 h-4 text-violet-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Chamadas IA"})]}),e.jsx("p",{className:"text-xl font-bold text-white","data-testid":"metric-ai-total-calls",children:ei?.totals?.totalCalls?.toLocaleString()??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(He,{className:"w-4 h-4 text-amber-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Tokens Totais"})]}),e.jsx("p",{className:"text-xl font-bold text-white","data-testid":"metric-ai-total-tokens",children:ei?.totals?.totalTokens?.toLocaleString()??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ie,{className:"w-4 h-4 text-blue-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Tokens Entrada"})]}),e.jsx("p",{className:"text-xl font-bold text-white","data-testid":"metric-ai-input-tokens",children:ei?.totals?.totalInputTokens?.toLocaleString()??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Tokens Saída"})]}),e.jsx("p",{className:"text-xl font-bold text-white","data-testid":"metric-ai-output-tokens",children:ei?.totals?.totalOutputTokens?.toLocaleString()??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(nt,{className:"w-4 h-4 text-red-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Custo Total (R$)"})]}),e.jsxs("p",{className:"text-xl font-bold text-red-400","data-testid":"metric-ai-total-cost",children:["R$ ",ei?.totals?.totalCostBRL?.toFixed(4)??"0.0000"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Uso de IA por cliente — clique para expandir e ver detalhes por livro e tipo de operação."}),Jh?e.jsx("div",{className:"p-12 text-center",children:e.jsx(T,{className:"w-6 h-6 animate-spin mx-auto text-primary"})}):e.jsxs("div",{className:"space-y-2",children:[(ei?.users||[]).map(t=>e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden","data-testid":`card-cost-user-${t.userId}`,children:[e.jsxs("div",{className:"p-4 flex items-center gap-4 cursor-pointer hover:bg-white/[0.03] transition-colors",onClick:()=>Ji(Pa===t.userId?null:t.userId),children:[e.jsx("div",{className:"w-9 h-9 rounded-full bg-violet-500/10 flex items-center justify-center shrink-0",children:e.jsx(Ht,{className:"w-4 h-4 text-violet-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-white truncate",children:t.userName||t.userEmail}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:t.userEmail})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-6 shrink-0 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-violet-400",children:t.totalCalls}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"chamadas"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-amber-400",children:t.totalTokens?.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"tokens"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-white",children:t.booksCount}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"livros"})]}),e.jsxs("div",{title:"Apenas PIX/cartão. Pedidos pagos com créditos não contam.",children:[e.jsxs("p",{className:"text-sm font-bold text-emerald-400",children:["R$ ",t.totalSpent?.toFixed(2)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"receita · cash"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-bold text-red-400","data-testid":`text-cost-user-${t.userId}`,children:["R$ ",t.totalCostBRL?.toFixed(4)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"custo IA"})]})]}),Pa===t.userId?e.jsx(ta,{className:"w-4 h-4 text-muted-foreground shrink-0"}):e.jsx(Ct,{className:"w-4 h-4 text-muted-foreground shrink-0"})]}),Pa===t.userId&&e.jsxs("div",{className:"border-t border-white/5 p-4 space-y-4 bg-black/10",children:[e.jsxs("div",{className:"sm:hidden flex items-center gap-6 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-violet-400",children:t.totalCalls}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"chamadas"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-amber-400",children:t.totalTokens?.toLocaleStr
7ing()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"tokens"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-white",children:t.booksCount}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"livros"})]}),e.jsxs("div",{title:"Apenas PIX/cartão",children:[e.jsxs("p",{className:"text-sm font-bold text-emerald-400",children:["R$ ",t.totalSpent?.toFixed(2)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"receita · cash"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-bold text-red-400",children:["R$ ",t.totalCostBRL?.toFixed(4)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"custo IA"})]})]}),Object.keys(t.operationBreakdown||{}).length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Por Tipo de Operação"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2",children:Object.entries(t.operationBreakdown||{}).sort(([,s],[,i])=>i.tokens-s.tokens).map(([s,i])=>e.jsxs("div",{className:"bg-white/5 rounded-lg px-3 py-2",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:_0[s]||s}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsxs("span",{className:"text-xs font-bold text-white",children:[i.calls,"x"]}),e.jsxs("span",{className:"text-[10px] text-amber-400",children:[i.tokens?.toLocaleString()," tok"]}),e.jsxs("span",{className:"text-[10px] text-red-400","data-testid":`text-cost-op-${s}`,children:["R$ ",i.costBRL?.toFixed(4)]})]})]},s))})]}),Object.keys(t.bookBreakdown||{}).length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Por Livro"}),e.jsx("div",{className:"grid gap-2",children:Object.entries(t.bookBreakdown||{}).sort(([,s],[,i])=>i.tokens-s.tokens).map(([s,i])=>e.jsxs("div",{className:"flex items-center justify-between bg-white/5 rounded-lg px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ot,{className:"w-3.5 h-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-xs text-white truncate",children:i.title})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsxs("span",{className:"text-xs text-violet-400",children:[i.calls," chamadas"]}),e.jsxs("span",{className:"text-xs text-amber-400 font-medium",children:[i.tokens?.toLocaleString()," tokens"]}),e.jsxs("span",{className:"text-xs text-red-400 font-medium","data-testid":`text-cost-book-${s}`,children:["R$ ",i.costBRL?.toFixed(4)]})]})]},s))})]})]})]},t.userId)),(!ei?.users||ei.users.length===0)&&e.jsxs("div",{className:"text-center py-12 text-muted-foreground text-sm",children:[e.jsx(Ht,{className:"w-8 h-8 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:"Nenhum uso de IA registrado ainda."}),e.jsx("p",{className:"text-xs mt-1",children:"Os dados aparecerão conforme os clientes utilizarem a plataforma."})]})]})]}),Kt==="workers"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"bg-gradient-to-r from-violet-500/10 to-purple-500/10 border border-violet-500/20 rounded-xl p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-violet-500/20 flex items-center justify-center",children:e.jsx(qa,{className:"w-5 h-5 text-violet-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Central de Workers IA"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controle todos os serviços de IA que rodam em segundo plano. Ative ou desative cada um individualmente."})]})]}),zs?.workers&&(()=>{const t=zs.workers.filter(i=>i.category==="background"),s=t.filter(i=>i.enabled).length;return e.jsxs("div",{className:"flex items-center gap-4 mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400"}),e.jsxs("span",{className:"text-xs text-emerald-400 font-medium",children:[s," ativos"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-red-400"}),e.jsxs("span",{className:"text-xs text-red-400 font-medium",children:[t.length-s," desativados"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400"}),e.jsxs("span",{className:"text-xs text-blue-400 font-medium",children:[zs.workers.filter(i=>i.category==="on-demand").length," sob demanda"]})]})]})})(),zs?.dailyEmailAiBudget&&e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2","data-testid":"daily-email-ai-budget",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/10 p-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Limite diário"}),e.jsx("p",{className:"mt-1 text-lg font-semibold text-white",children:zs.dailyEmailAiBudget.limit.toLocaleStr
7ing()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/10 p-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Usado"}),e.jsx("p",{className:"mt-1 text-lg font-semibold text-amber-400",children:zs.dailyEmailAiBudget.used.toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/10 p-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Restante"}),e.jsx("p",{className:"mt-1 text-lg font-semibold text-emerald-400",children:zs.dailyEmailAiBudget.remaining.toLocaleString()})]}),e.jsxs("p",{className:"col-span-3 text-[10px] text-muted-foreground",children:["Geração global de e-mails diários · dia BRT ",zs.dailyEmailAiBudget.dayBrt]})]})]}),Zh?e.jsx("div",{className:"p-12 text-center",children:e.jsx(T,{className:"w-6 h-6 animate-spin mx-auto text-primary"})}):zs?.workers?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-3 flex items-center gap-2",children:[e.jsx(Ht,{className:"w-3.5 h-3.5"})," Workers de Fundo (",zs.workers.filter(t=>t.category==="background").length,")"]}),e.jsx("div",{className:"space-y-2",children:zs.workers.filter(t=>t.category==="background").map(t=>{const s=es?.services?.find(i=>i.service===t.name);return e.jsx("div",{className:`border rounded-xl overflow-hidden transition-all ${t.enabled?"bg-white/5 border-white/10":"bg-red-500/5 border-red-500/15"}`,"data-testid":`worker-card-${t.name}`,children:e.jsxs("div",{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-xl flex items-center justify-center shrink-0 ${t.enabled?"bg-emerald-500/10":"bg-red-500/10"}`,children:t.enabled?e.jsx(He,{className:"w-5 h-5 text-emerald-400"}):e.jsx(dt,{className:"w-5 h-5 text-red-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[e.jsx("p",{className:"text-sm font-medium text-white",children:t.label}),e.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full ${t.enabled?"bg-emerald-500/20 text-emerald-300":"bg-red-500/20 text-red-300"}`,children:t.enabled?"Ativo":"Desativado"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),s&&e.jsxs("div",{className:"flex items-center gap-3 mt-1.5",children:[e.jsxs("span",{className:"text-[10px] text-violet-400",children:[s.calls?.toLocaleString()," chamadas"]}),e.jsxs("span",{className:"text-[10px] text-amber-400",children:[s.totalTokens?.toLocaleString()," tokens"]}),e.jsxs("span",{className:"text-[10px] text-red-400",children:["R$ ",s.costBRL?.toFixed(4)]})]})]}),e.jsxs("button",{onClick:async()=>{k(t.name);try{await fetch("/api/admin/workers/toggle",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workerName:t.name,enabled:!t.enabled})}),await ep()}catch(i){console.error("Toggle worker error:",i)}k(null)},disabled:Ci===t.name,className:`relative shrink-0 w-12 h-7 rounded-full transition-colors duration-200 cursor-pointer ${t.enabled?"bg-emerald-500":"bg-white/20"} ${Ci===t.name?"opacity-50":""}`,"data-testid":`toggle-worker-${t.name}`,children:[e.jsx("div",{className:`absolute top-1 w-5 h-5 rounded-full bg-white shadow-md transition-transform duration-200 ${t.enabled?"translate-x-6":"translate-x-1"}`}),Ci===t.name&&e.jsx(T,{className:"w-3 h-3 animate-spin absolute top-2 left-4 text-white"})]})]})},t.name)})})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-3 flex items-center gap-2",children:[e.jsx(He,{className:"w-3.5 h-3.5"})," Serviços Sob Demanda (",zs.workers.filter(t=>t.category==="on-demand").length,")"]}),e.jsx("p",{className:"text-[10px] text-muted-foreground mb-2",children:"Estes serviços são acionados por ações do cliente e não podem ser desativados."}),e.jsx("div",{className:"space-y-2",children:zs.workers.filter(t=>t.category==="on-demand").map(t=>{const s=es?.services?.find(i=>i.service===t.name);return e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4 flex items-center gap-4","data-testid":`worker-card-${t.name}`,children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-500/10 flex items-center justify-center shrink-0",children:e.jsx(He,{className:"w-5 h-5 text-blue-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[e.jsx("p",{className:"text-sm font-medium text-white",children:t.label}),e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-blue-500/20 text-blue-300",children:"Sob demanda"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),s&&e.jsxs("div",{className:"flex items-center gap-3 mt-1.5",children:[e.jsxs("span",{className:"text-[10px] text-violet-400",children:[s.calls?.toLocaleStr
7ing()," chamadas"]}),e.jsxs("span",{className:"text-[10px] text-amber-400",children:[s.totalTokens?.toLocaleString()," tokens"]}),e.jsxs("span",{className:"text-[10px] text-red-400",children:["R$ ",s.costBRL?.toFixed(4)]})]})]}),e.jsx("div",{className:"shrink-0 w-12 h-7 rounded-full bg-blue-500/30 relative cursor-not-allowed",children:e.jsx("div",{className:"absolute top-1 translate-x-6 w-5 h-5 rounded-full bg-blue-400 shadow-md"})})]},t.name)})})]})]}):null]}),Kt==="quality"&&e.jsxs("div",{className:"space-y-6","data-testid":"section-generation-quality",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Período:"}),[7,30,90].map(t=>e.jsxs("button",{onClick:()=>Yt(t),className:`px-3 py-1 rounded-md text-xs font-medium transition-colors ${Yi===t?"bg-violet-500/20 text-violet-300 border border-violet-500/30":"bg-white/5 text-muted-foreground border border-white/10 hover:bg-white/10"}`,"data-testid":`btn-quality-period-${t}`,children:[t,"d"]},t))]}),tp?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-violet-400"})}):sx?e.jsx("div",{className:"text-center py-12 text-sm text-red-300","data-testid":"text-quality-error",children:sx.message||"Erro ao carregar dados."}):xs?(()=>{const t=xs.totals?.totalBooks??0,s=xs.totals?.flaggedFallback??0,i=t>0?Number((s/t*100).toFixed(2)):0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5",children:[e.jsxs("div",{className:"text-xs text-muted-foreground mb-1",children:["Livros gerados (",xs.days,"d)"]}),e.jsx("div",{className:"text-2xl font-bold text-white","data-testid":"text-quality-total-books",children:t})]}),e.jsxs("div",{className:"bg-amber-500/10 border border-amber-500/20 rounded-xl p-5",children:[e.jsx("div",{className:"text-xs text-amber-300 mb-1",children:"Em fallback"}),e.jsxs("div",{className:"text-2xl font-bold text-amber-300","data-testid":"text-quality-fallback-percent",children:[i,"%"]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-1",children:[s," de ",t," livros"]})]}),e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-xl p-5",children:[e.jsx("div",{className:"text-xs text-red-300 mb-1",children:"Reembolso (fallback)"}),e.jsxs("div",{className:"text-2xl font-bold text-red-300","data-testid":"text-quality-fallback-refund-rate",children:[xs.refunds?.fallbackRefundRate??0,"%"]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-1",children:[xs.refunds?.fallbackRefundedBooks??0," reembolsados"]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Reembolso (baseline)"}),e.jsxs("div",{className:"text-2xl font-bold text-white","data-testid":"text-quality-baseline-refund-rate",children:[xs.refunds?.baselineRefundRate??0,"%"]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-1",children:[xs.refunds?.totalRefundedBooks??0," de ",xs.totals?.totalBooks??0," no total"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Livros sinalizados (fallback OU desvio)"}),e.jsx("div",{className:"text-lg font-semibold text-white mt-1","data-testid":"text-quality-flagged-books",children:xs.totals?.flaggedBooks??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Apenas desvio de plano"}),e.jsx("div",{className:"text-lg font-semibold text-white mt-1","data-testid":"text-quality-deviation-only",children:xs.totals?.flaggedPlanDeviation??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Reembolso entre sinalizados"}),e.jsxs("div",{className:"text-lg font-semibold text-white mt-1","data-testid":"text-quality-flagged-refund-rate",children:[xs.refunds?.flaggedRefundRate??0,"% ",e.jsxs("span",{className:"text-xs text-muted-foreground font-normal",children:["(",xs.refunds?.flaggedRefundedBooks??0,")"]})]})]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-3 border-b border-white/10 flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Livros afetados"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[xs.sampleBooks?.length??0," mostrados"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs","data-testid":"table-quality-books",children:[e.jsx("thead",{className:"bg-white/5",children:e.jsxs("tr",{className:"text-left text-muted-foreground",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"ID"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Título"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Usuário"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Data"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Fallback"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Desvio"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Reembolso"})]})}),e.jsx("tbody",{children:(xs.sampleBooks||[]).length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-8 text-center text-muted-foreground",children:"Nenhum livro afetado no período."})}):xs.sampleBooks.map(x=>e.jsxs("tr",{className:"border-t border-white/5 hover:bg-white/5","data-testid":`row-quality-book-${x.id}`,children:[e.jsx("td",{className:"px-4 py-2 font-mono text-[10px] text-muted-foreground",children:String(x.id).slice(0,8)}),e.jsx("td",{className:"px-4 py-2 text-white",children:x.title||"—"}),e.jsx("td",{className:"px-4 py-2 font-mono text-[10px] text-muted-foreground",children:x.userId?String(x.userId).slice(0,8):"—"}),e.jsx("td",{className:"px-4 py-2 text-muted-foreground",children:x.createdAt?new Date(x.createdAt).toLocaleStr
7ing("pt-BR"):"—"}),e.jsx("td",{className:"px-4 py-2",children:x.fallbackUsed?e.jsx("span",{className:"px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 text-[10px] font-medium",children:"SIM"}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"px-4 py-2",children:x.planDeviation?e.jsx("span",{className:"px-2 py-0.5 rounded bg-orange-500/20 text-orange-300 text-[10px] font-medium",children:"SIM"}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"px-4 py-2",children:x.refunded?e.jsx("span",{className:"px-2 py-0.5 rounded bg-red-500/20 text-red-300 text-[10px] font-medium",children:"REEMBOLSADO"}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})]},x.id))})]})})]})]})})():e.jsx("div",{className:"text-center py-12 text-sm text-muted-foreground",children:"Sem dados disponíveis."})]})]}),e.jsxs(Be,{value:"daily-emails",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"daily-email-control-bar",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ge,{className:"w-5 h-5 text-teal-400"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Sistema de Email Diário"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Email inteligente e personalizado para cada autor"})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${qs?.enabled?"bg-emerald-400 animate-pulse":"bg-red-400"}`}),e.jsx("span",{className:"text-xs text-muted-foreground",children:qs?.enabled?"Ativo":"Inativo"})]}),e.jsx(rt,{checked:qs?.enabled||!1,onCheckedChange:async t=>{try{await N("POST","/api/admin/daily-emails/toggle",{enabled:t}),K.invalidateQueries({queryKey:["/api/admin/daily-emails/stats"]}),r({title:t?"Email diário ativado!":"Email diário desativado"})}catch(s){r({title:"Erro",description:s.message,variant:"destructive"})}},"data-testid":"toggle-daily-email"})]})]}),e.jsxs("div",{className:"flex items-end gap-3 flex-wrap",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Janela de envio (BRT)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{type:"time",value:fx,onChange:t=>wx(t.target.value),className:"bg-black/20 border-white/10 w-28 text-xs","data-testid":"input-daily-window-start"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"até"}),e.jsx(J,{type:"time",value:yx,onChange:t=>kx(t.target.value),className:"bg-black/20 border-white/10 w-28 text-xs","data-testid":"input-daily-window-end"})]})]}),e.jsx(b,{size:"sm",variant:"outline",disabled:Cx,onClick:async()=>{Sx(!0);try{await N("PUT","/api/admin/daily-emails/settings",{windowStart:fx,windowEnd:yx}),ip(),r({title:"Configurações salvas!"})}catch(t){r({title:"Erro",description:t.message,variant:"destructive"})}finally{Sx(!1)}},"data-testid":"btn-save-daily-settings",children:Cx?e.jsx(T,{className:"w-3 h-3 animate-spin"}):"Salvar"})]})]}),Lt&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"daily-email-diagnostics",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(jt,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Diagnóstico do Sistema"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground ml-auto",children:[Lt.currentTimeBRT," BRT"]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3",children:[{label:"Sistema",ok:Lt.enabled,okText:"Ativado",failText:"Desativado"},{label:"Resend",ok:Lt.resendConfigured,okText:"Configurado",failText:"Não configurado"},{label:"Janela de Envio",ok:Lt.inSendingWindow,okText:`Dentro (${Lt.windowStart}–${Lt.windowEnd})`,failText:`Fora (${Lt.windowStart}–${Lt.windowEnd})`},{label:"Usuários Elegíveis",ok:Lt.eligibleUsers>0,okText:`${Lt.eligibleUsers} usuários`,failText:"Nenhum"},{label:"Último Envio",ok:!!Lt.lastSentAt,okText:Lt.lastSentAt?new Date(Lt.lastSentAt).toLocaleStr
7ing("pt-BR",{timeZone:"America/Sao_Paulo"}):"—",failText:"Nunca enviado"},{label:"URL Tracking",ok:!!Lt.publicBaseUrl,okText:Lt.publicBaseUrl?.replace("https://",""),failText:"Não configurada"}].map((t,s)=>e.jsxs("div",{className:"flex items-start gap-2 p-2 rounded-lg bg-black/20",children:[t.ok?e.jsx(be,{className:"w-3.5 h-3.5 text-emerald-400 shrink-0 mt-0.5"}):e.jsx(Ce,{className:"w-3.5 h-3.5 text-red-400 shrink-0 mt-0.5"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:t.label}),e.jsx("p",{className:`text-xs font-medium truncate ${t.ok?"text-emerald-400":"text-red-400"}`,children:t.ok?t.okText:t.failText})]})]},s))}),!Lt.enabled&&e.jsxs("p",{className:"text-xs text-amber-400/80 mt-3 flex items-center gap-1.5",children:[e.jsx(js,{className:"w-3.5 h-3.5 shrink-0"}),"O sistema está desativado. Ative o toggle acima para começar a enviar emails diários."]}),Lt.enabled&&!Lt.resendConfigured&&e.jsxs("p",{className:"text-xs text-red-400/80 mt-3 flex items-center gap-1.5",children:[e.jsx(Ce,{className:"w-3.5 h-3.5 shrink-0"}),"O Resend não está configurado. Os emails não serão enviados. Verifique a integração Resend."]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3",children:[e.jsx(kt,{icon:ct,label:"Enviados Hoje",value:qs?.sentToday??0,color:"text-emerald-400","data-testid":"metric-daily-sent-today"}),e.jsx(kt,{icon:Ge,label:"Total Hoje",value:qs?.totalToday??0,"data-testid":"metric-daily-total-today"}),e.jsx(kt,{icon:jt,label:"Esta Semana",value:qs?.totalWeek??0,"data-testid":"metric-daily-total-week"}),e.jsx(kt,{icon:Ie,label:"Este Mês",value:qs?.totalMonth??0,"data-testid":"metric-daily-total-month"}),e.jsx(kt,{icon:dt,label:"Falharam Hoje",value:qs?.failedToday??0,color:"text-red-400","data-testid":"metric-daily-failed-today"}),e.jsx(kt,{icon:ns,label:"Pulados Hoje",value:qs?.skippedToday??0,color:"text-amber-400","data-testid":"metric-daily-skipped-today"})]}),it&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3",children:[e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-open-rate",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ht,{className:"w-4 h-4 text-blue-400"}),e.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Taxa Abertura"})]}),e.jsxs("p",{className:"text-2xl font-bold text-blue-400",children:[it.month.sent>0?(it.month.opened/it.month.sent*100).toFixed(1):"0.0","%"]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:[it.month.opened,"/",it.month.sent," abertos (mês)"]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-click-rate",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Jl,{className:"w-4 h-4 text-purple-400"}),e.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Taxa Cliques"})]}),e.jsxs("p",{className:"text-2xl font-bold text-purple-400",children:[it.month.opened>0?(it.month.clicked/it.month.opened*100).toFixed(1):"0.0","%"]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:[it.month.clicked,"/",it.month.opened," clicados (mês)"]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-conversions",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(lt,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Conversões"})]}),e.jsx("p",{className:"text-2xl font-bold text-emerald-400",children:it.month.converted}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:["R$ ",it.month.revenue.toFixed(2)," receita (mês)"]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-ai-cost",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ht,{className:"w-4 h-4 text-amber-400"}),e.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Custo IA"})]}),e.jsxs("p",{className:"text-2xl font-bold text-amber-400",children:["R$ ",it.month.aiCost.toFixed(2)]}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:it.month.sent>0?`R$ ${(it.month.aiCost/it.month.sent).toFixed(4)}/email`:"—"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-roi",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"ROI"})]}),e.jsx("p",{className:`text-2xl font-bold ${it.month.aiCost>0&&it.month.revenue>it.month.aiCost?"text-emerald-400":"text-muted-foreground"}`,children:it.month.aiCost>0?`${((it.month.revenue-it.month.aiCost)/it.month.aiCost*100).toFixed(0)}%`:"—"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:it.month.revenue>0?`R$ ${(it.month.revenue-it.month.aiCost).toFixed(2)} lucro`:"sem receita ainda"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4","data-testid":"metric-today-engagement",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(qe,{className:"w-4 h-4 text-teal-400"}),e.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Hoje"})]}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Abertos"}),e.jsx("span",{className:"text-white font-medium",children:it.today.opened})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cliques"}),e.jsx("span",{className:"text-white font-medium",children:it.today.clicked})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Conversões"}),e.jsx("span",{className:"text-white font-medium",children:it.today.converted})]})]})]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-3","data-testid":"daily-email-test-send",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(He,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Testar / Pré-visualizar Email"})]}),e.jsxs("div",{className:"flex items-end gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-[200px] space-y-1",children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Selecionar usuário"}),e.jsxs(Se,{value:Ai,onValueChange:hp,children:[e.jsx($e,{className:"bg-black/20 border-white/10","data-testid":"select-daily-test-user",children:e.jsx(Ae,{placeholder:"Escolha um usuário..."})}),e.jsx(Pe,{children:(Si||[]).filter(t=>t.email&&!t.email.includes("@sabhia.temp")&&t.role!=="admin").slice(0,50).map(t=>e.jsxs(U,{value:t.id,children:[t.name||t.email," (",t.email,")"]},t.id))})]})]}),e.jsxs(b,{size:"sm",variant:"outline",disabled:!Ai||ux,onClick:async()=>{gx(!0);try{const s=await(await N("POST","/api/admin/daily-emails/preview",{userId:Ai})).json();px(s),jd(!0)}catch(t){r({title:"Erro ao gerar preview",description:t.message,variant:"destructive"})}finally{gx(!1)}},"data-testid":"btn-daily-preview",children:[ux?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(ht,{className:"w-3 h-3 mr-1"}),"Preview"]}),e.jsxs(b,{size:"sm",disabled:!Ai||bx,onClick:async()=>{jx(!0);try{const s=await(await N("POST",`/api/admin/daily-emails/send-now/${Ai}`)).json();s.success?(r({title:"Email enviado com sucesso!"}),K.invalidateQueries({queryKey:["/api/admin/daily-emails"]}),K.invalidateQueries({queryKey:["/api/admin/daily-emails/stats"]})):r({title:"Falha",description:s.error||"Erro desconhecido",variant:"destructive"})}catch(t){r({title:"Erro",description:t.message,variant:"destructive"})}finally{jx(!1)}},className:"bg-teal-600 hover:bg-teal-700","data-testid":"btn-daily-send-now",children:[bx?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(ct,{className:"w-3 h-3 mr-1"}),"Enviar Agora"]}),e.jsxs(b,{size:"sm",variant:"outline",disabled:!Ai||vx,onClick:async()=>{Nx(!0);try{const s=await(await N("POST",`/api/admin/daily-emails/send-welcome/${Ai}`)).json();s.success?(r({title:"Email de boas-vindas enviado!"}),K.invalidateQueries({queryKey:["/api/admin/daily-emails"]}),K.invalidateQueries({queryKey:["/api/admin/daily-emails/stats"]})):r({title:"Falha",description:s.error||"Erro desconhecido",variant:"destructive"})}catch(t){r({title:"Erro",description:t.message,variant:"destructive"})}finally{Nx(!1)}},className:"border-amber-500/30 text-amber-400 hover:bg-amber-500/10","data-testid":"btn-daily-send-welcome",children:[vx?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(Ge,{className:"w-3 h-3 mr-1"}),"Testar Boas-vindas"]})]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-3","data-testid":"daily-email-history",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Histórico de Emails"})]}),e.jsxs("div",{className:"relative",children:[e.jsx(St,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground"}),e.jsx(J,{value:bd,onChange:t=>xp(t.target.value),placeholder:"Buscar por nome ou email...",className:"bg-black/20 border-white/10 pl-8 w-56 text-xs","data-testid":"input-daily-email-search"})]})]}),ap?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-left text-muted-foreground",children:[e.jsx("th",{className:"py-2 px-2",children:"Data"}),e.jsx("th",{className:"py-2 px-2",children:"Usuário"}
7),e.jsx("th",{className:"py-2 px-2",children:"Assunto"}),e.jsx("th",{className:"py-2 px-2",children:"Foco"}),e.jsx("th",{className:"py-2 px-2",children:"Engajamento"}),e.jsx("th",{className:"py-2 px-2",children:"Custo IA"}),e.jsx("th",{className:"py-2 px-2",children:"Status"}),e.jsx("th",{className:"py-2 px-2",children:"Ações"})]})}),e.jsxs("tbody",{children:[ax.filter(t=>{if(!bd)return!0;const s=bd.toLowerCase();return(t.userName||"").toLowerCase().includes(s)||(t.userEmail||"").toLowerCase().includes(s)||(t.subject||"").toLowerCase().includes(s)}).slice(0,100).map(t=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/[0.03]","data-testid":`row-daily-email-${t.id}`,children:[e.jsx("td",{className:"py-2 px-2 whitespace-nowrap text-muted-foreground",children:t.sentAt?new Date(t.sentAt).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"—"}),e.jsxs("td",{className:"py-2 px-2",children:[e.jsx("div",{className:"font-medium text-white",children:t.userName}),e.jsx("div",{className:"text-muted-foreground text-[10px]",children:t.userEmail})]}),e.jsx("td",{className:"py-2 px-2 max-w-[200px] truncate text-white/80",children:t.subject||"—"}),e.jsx("td",{className:"py-2 px-2",children:t.focusArea==="welcome"?e.jsx(E,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-400 bg-amber-500/10",children:"Boas-vindas"}):t.focusArea?e.jsx(E,{variant:"outline",className:"text-[10px] border-teal-500/30 text-teal-400",children:t.focusArea}):"—"}),e.jsx("td",{className:"py-2 px-2",children:t.status==="sent"?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{title:t.openedAt?`Aberto em ${new Date(t.openedAt).toLocaleString("pt-BR")}${t.sentAt?` (${(()=>{try{const s=Math.round((new Date(t.openedAt).getTime()-new Date(t.sentAt).getTime())/6e4);return isNaN(s)||s<0?"":s<60?`${s}min`:`${Math.round(s/60)}h`}catch{return""}})()} após envio)`:""}`:"Não aberto",children:e.jsx(ht,{className:`w-3.5 h-3.5 ${t.openedAt?"text-blue-400":"text-white/15"}`})}),e.jsx("span",{title:t.clickedAt?`Clicou: ${t.clickedCta||"CTA"} em ${new Date(t.clickedAt).toLocaleString("pt-BR")}`:"Sem clique",children:e.jsx(Jl,{className:`w-3.5 h-3.5 ${t.clickedAt?"text-purple-400":"text-white/15"}`})}),t.clickedCta&&e.jsx("span",{className:"text-[10px] text-purple-400/70 max-w-[60px] truncate",title:t.clickedCta,children:t.clickedCta}),e.jsx("span",{title:t.conversionOrderId?`Conversão: R$ ${parseFloat(t.conversionAmount||0).toFixed(2)}`:"Sem conversão",children:e.jsx(nt,{className:`w-3.5 h-3.5 ${t.conversionOrderId?"text-emerald-400":"text-white/15"}`})}),t.conversionAmount&&parseFloat(t.conversionAmount)>0&&e.jsxs("span",{className:"text-[10px] text-emerald-400 font-medium ml-0.5",children:["R$",parseFloat(t.conversionAmount).toFixed(0)]})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 px-2",children:t.aiCost?e.jsxs("span",{className:"text-[10px] text-amber-400/70",children:["R$",parseFloat(t.aiCost).toFixed(4)]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 px-2",children:[e.jsx(Gi,{status:t.status}),t.skipReason&&e.jsxs("span",{className:"text-[10px] text-muted-foreground ml-1",children:["(",{account_too_new:"Conta muito recente",no_valid_email:"Email inválido",unsubscribed:"Cancelou inscrição",dormant_90d:"Inativo há 90+ dias",too_recent:"Diário já enviado hoje",admin_user:"Administrador",internal_staff:"Equipe interna",global_throttle:"Outro email enviado há pouco",unknown:"Motivo não identificado"}[t.skipReason]||t.skipReason,")"]})]}),e.jsx("td",{className:"py-2 px-2",children:t.status==="sent"&&e.jsxs(b,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px]",onClick:async()=>{try{const i=await(await N("GET",`/api/admin/daily-emails/${t.id}`)).json();px({subject:i.subject,htmlContent:i.htmlContent,focusArea:i.focusArea,snapshot:i.contextSnapshot,userName:i.userName,ctaLinks:i.ctaLinks,aiCost:i.aiCost,aiTokensUsed:i.aiTokensUsed,openedAt:i.openedAt,clickedAt:i.clickedAt,clickedCta:i.clickedCta,conversionOrderId:i.conversionOrderId,conversionAmount:i.conversionAmount}),jd(!0)}catch(s){r({title:"Erro",description:s.message,variant:"destructive"})}},"data-testid":`btn-preview-daily-${t.id}`,children:[e.jsx(ht,{className:"w-3 h-3 mr-1"})," Ver"]})})]},t.id)),ax.length===0&&e.jsx("tr",{children:e.jsxs("td",{colSpan:8,className:"py-8 text-center text-muted-foreground",children:[e.jsx(Ge,{className:"w-8 h-8 mx-auto mb-2 opacity-30"}
7),e.jsx("p",{children:"Nenhum email diário enviado ainda."})]})})]})]})})]})]}),e.jsx(Je,{open:mp,onOpenChange:jd,children:e.jsxs(Ye,{className:"max-w-3xl max-h-[85vh] overflow-y-auto bg-[#111114] border-white/10",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"text-white flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4 text-teal-400"}),"Preview do Email Diário"]}),gt&&e.jsxs(mt,{className:"text-muted-foreground text-xs",children:[gt.userName&&e.jsxs("span",{className:"mr-3",children:["Para: ",gt.userName]}),gt.focusArea&&e.jsx(E,{variant:"outline",className:"text-[10px] border-teal-500/30 text-teal-400 mr-2",children:gt.focusArea})]})]}),gt&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-black/30 rounded-lg p-3",children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Assunto"}),e.jsx("p",{className:"text-sm text-white font-medium mt-1","data-testid":"text-daily-preview-subject",children:gt.subject})]}),gt.focus&&e.jsxs("div",{className:"bg-black/30 rounded-lg p-3 space-y-2",children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Dados do Focus Engine"}),e.jsxs("div",{className:"text-xs text-white/70 space-y-1",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Foco principal:"})," ",gt.focus.primaryFocus]}),gt.focus.primaryBookTitle&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Livro:"})," ",gt.focus.primaryBookTitle]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Urgência:"})," ",gt.focus.urgencyLevel]}),gt.focus.secondaryActions?.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"CTAs secundários:"})," ",gt.focus.secondaryActions.map(t=>t.label).join(", ")]})]})]}),gt.snapshot&&e.jsxs("div",{className:"bg-black/30 rounded-lg p-3 space-y-2",children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Snapshot do Autor"}),e.jsxs("div",{className:"text-xs text-white/70 space-y-1",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Nome:"})," ",gt.snapshot.user?.name," ",gt.snapshot.user?.hasRealName===!1&&e.jsx("span",{className:"text-amber-400/70 text-[10px] ml-1",children:"(nome desconhecido)"})]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Livros:"})," ",gt.snapshot.summary?.totalBooks??0]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Gerados:"})," ",gt.snapshot.summary?.booksGenerated??0]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Total gasto:"})," R$",(gt.snapshot.summary?.totalSpent??0).toFixed(2)]}),gt.snapshot.summary?.servicesNeverPurchased?.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Nunca usou:"})," ",gt.snapshot.summary.servicesNeverPurchased.join(", ")]})]})]}),gt.ctaLinks&&gt.ctaLinks.length>0&&e.jsxs("div",{className:"bg-black/30 rounded-lg p-3 space-y-2",children:[e.jsxs(O,{className:"text-xs text-muted-foreground",children:["CTAs (",gt.ctaLinks.length,")"]}),e.jsx("div",{className:"space-y-1",children:gt.ctaLinks.map((t,s)=>e.jsxs("div",{className:"text-xs text-white/70 flex items-center gap-2",children:[e.jsx(vs,{className:"w-3 h-3 text-teal-400 flex-shrink-0"}),e.jsx("span",{children:t.label}),e.jsxs("span",{className:"text-muted-foreground",children:["→ ",t.targetService]})]},s))})]}),e.jsxs("div",{className:"border border-white/10 rounded-lg overflow-hidden",children:[e.jsx("div",{className:"bg-black/40 px-3 py-2 flex items-center justify-between",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"HTML Preview"})}),e.jsx("div",{className:"bg-white",children:e.jsx("iframe",{srcDoc:gt.htmlContent||"<p>Sem conteúdo</p>",className:"w-full border-0",style:{minHeight:400},title:"Email Preview",sandbox:"allow-same-origin","data-testid":"iframe-daily-preview"})})]})]})]})}),e.jsxs(Be,{value:"ad-creatives",className:"mt-6 space-y-6",children:[e.jsx(Ig,{}),e.jsx("div",{className:"flex items-center gap-2 border-b border-white/10 pb-3 mb-4 overflow-x-auto",children:[{val:"creatives",label:"Criativos",icon:e.jsx(Xt,{className:"w-3.5 h-3.5"})},{val:"campaigns",label:"Campanhas",icon:e.jsx(lt,{className:"w-3.5 h-3.5"})},{val:"performance",label:"Performance",icon:e.jsx(ft,{className:"w-3.5 h-3.5"})},{val:"audiences",label:"Audiências",icon:e.jsx(Re,{className:"w-3.5 h-3.5"})},{val:"optimizer",label:"Optimizer",icon:e.jsx(Ht,{className:"w-3.5 h-3.5"})},{val:"ia-gestor",label:"IA Gestor",icon:e.jsx(Qi,{className:"w-3.5 h-3.5"})},{val:"intelligence",label:"Inteligência",icon:e.jsx(jn,{className:"w-3.5 h-3.5"})},{val:"multiplicador",label:"Multiplicador",icon:e.jsx(Ie,{className:"w-3.5 h-3.5"})},{val:"instagram",label:"Instagram",icon:e.jsx(ls,{className:"w-3.5 h-3.5"})},{val:"config",label:"Meta Config",icon:e.jsx(Pn,{className:"w-3.5 h-3.5"})}].map(t=>e.jsxs("button",{onClick:()=>Fr(t.val),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors whitespace-nowrap ${Qe===t.val?"bg-teal-600/20 text-teal-400 border border-teal-500/30":"text-white/50 hover:text-white/80 border border-transparent"}`,"data-testid":`subtab-${t.val}`,children:[t.icon," ",t.label]},t.val))}),Qe==="creatives"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white",children:"Gerador de Criativos"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Gere anúncios persuasivos para Meta Ads com IA"})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>rm(!im),className:`relative p-2 rounded-lg border transition-colors ${Rs&&Rs.length>0?"border-amber-500/30 bg-amber-500/10 text-amber-400 hover:bg-amber-500/20":"border-white/10 bg-white/[0.02] text-white/40 hover:bg-white/[0.05]"}`,"data-testid":"btn-anomaly-bell",children:[e.jsx(Nn,{className:"w-4 h-4"}),Rs&&Rs.length>0&&e.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 rounded-full bg-amber-500 text-[9px] font-bold text-black flex items-center justify-center","data-testid":"text-anomaly-count",children:Rs.length>9?"9+":Rs.length})]}),im&&e.jsxs("div",{className:"absolute right-0 top-full mt-2 w-80 bg-[#1a1a2e] border border-white/10 rounded-xl shadow-2xl z-50 overflow-hidden","data-testid":"anomaly-dropdown",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/5 flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-amber-400"}),"Alertas Proativos"]}),e.jsx("button",{onClick:()=>rm(!1),className:"text-white/40 hover:text-white/70",children:e.jsx(ea,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"max-h-80 overflow-y-auto",children:!Rs||Rs.length===0?e.jsxs("div",{className:"px-4 py-8 text-center",children:[e.jsx(be,{className:"w-8 h-8 text-emerald-400 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-white/60",children:"Tudo funcionando perfeitamente"}),e.jsx("p",{className:"text-xs text-white/30 mt-1",children:"Nenhuma anomalia detectada"})]}):Rs.map(t=>e.jsx("div",{className:"px-4 py-3 border-b border-white/5 hover:bg-white/[0.02] transition-colors","data-testid":`anomaly-item-${t.id}`,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:"flex items-center gap-2 mb-1",children:[e.jsx(E,{variant:"outline",className:`text-[9px] ${t.severity==="critical"?"text-red-400 border-red-500/30":t.severity==="high"?"text-amber-400 border-amber-500/30":t.severity==="warning"?"text-amber-300 border-amber-400/30":"text-blue-400 border-blue-500/30"}`,children:t.severity==="critical"?"Crítico":t.severity==="high"?"Alto":t.severity==="warning"?"Atenção":"Info"}),e.jsx("span",{className:"text-xs text-white/30",children:new Date(t.createdAt).toLocaleStr
7ing("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})})]}),e.jsx("p",{className:"text-xs font-medium text-white/80 truncate",children:t.title}),e.jsx("p",{className:"text-[10px] text-white/40 mt-0.5 line-clamp-2",children:t.message})]}),e.jsx("button",{onClick:s=>{s.stopPropagation(),Up.mutate(t.id)},className:"shrink-0 p-1 rounded hover:bg-white/10 text-white/30 hover:text-emerald-400 transition-colors",title:"Marcar como visto","data-testid":`btn-ack-anomaly-${t.id}`,children:e.jsx(Ua,{className:"w-3.5 h-3.5"})})]})},t.id))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex gap-1",children:[{val:"all",label:"Todos"},{val:"draft",label:"Rascunho"},{val:"generated",label:"Gerados"},{val:"approved",label:"Aprovados"},{val:"archived",label:"Arquivados"},{val:"matrix",label:"📊 Matrizes"}].map(({val:t,label:s})=>e.jsx("button",{onClick:()=>vp(t),className:`px-3 py-1 rounded-full text-xs font-medium transition-colors ${Pi===t?"bg-teal-500/20 text-teal-400 border border-teal-500/30":"bg-white/5 text-white/60 border border-white/10 hover:bg-white/10"}`,"data-testid":`filter-ad-${t}`,children:s},t))}),e.jsx(b,{size:"sm",variant:"outline",asChild:!0,className:"border-amber-500/30 hover:bg-amber-500/10 text-amber-300 gap-1.5","data-testid":"btn-champion-studio",children:e.jsxs("a",{href:"/admin/criativos/campeao",children:[e.jsx(_i,{className:"w-3.5 h-3.5"})," Modo Campeão"]})}),e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>zn(!0),className:"border-violet-500/30 hover:bg-violet-500/10 text-violet-300 gap-1.5","data-testid":"btn-bulk-matrix",children:[e.jsx(Ot,{className:"w-3.5 h-3.5"})," Matriz de Testes"]}),e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>Ln(!0),className:"border-white/20 hover:bg-white/10 gap-1.5","data-testid":"btn-manual-upload",children:[e.jsx(rc,{className:"w-3.5 h-3.5"})," Upload Manual"]}),e.jsxs(b,{size:"sm",onClick:()=>tr(!0),className:"bg-teal-600 hover:bg-teal-700 gap-1.5","data-testid":"btn-new-creative",children:[e.jsx(qe,{className:"w-3.5 h-3.5"})," Gerar Novo Criativo"]})]})]}),Dt&&e.jsxs("div",{className:"border border-amber-500/30 rounded-xl bg-gradient-to-r from-amber-500/10 via-orange-500/5 to-amber-500/10 p-4 space-y-3","data-testid":"winner-audience-banner",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-amber-500/20 flex items-center justify-center",children:e.jsx(_i,{className:"w-4 h-4 text-amber-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-amber-400",children:"Variações do Campeão"}),e.jsxs("p",{className:"text-[11px] text-white/60 truncate max-w-[400px]",children:['"',Dt.sourceHeadline,'"']})]})]}),e.jsx("button",{onClick:()=>Ix(null),className:"text-white/30 hover:text-white/60 transition-colors p-1","data-testid":"btn-close-audience-banner",children:e.jsx(ea,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-2.5",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"ROAS Original"}),e.jsxs("p",{className:"text-sm font-bold text-emerald-400",children:[Dt.roas,"x"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-2.5",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"CPA Original"}),e.jsxs("p",{className:"text-sm font-bold text-white",children:["R$ ",Dt.cpa]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-2.5",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Conversões"}),e.jsx("p",{className:"text-sm font-bold text-sky-400",children:Dt.conversions})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-2.5",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Campanha"}),e.jsx("p",{className:"text-[11px] font-medium text-white truncate",children:Dt.campaignName})]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-2",children:[e.jsxs("p",{className:"text-[10px] font-bold text-amber-400 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Re,{className:"w-3 h-3"})," Público Comprador (usar na nova campanha)"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-1 text-[11px]",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-white/40",children:"País:"}),e.jsx("span",{className:"text-white font-medium",children:Dt.countries})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-white/40",children:"Idade:"}),e.jsxs("span",{className:"text-white font-medium",children:[Dt.ageMin,"–",Dt.ageMax," anos"]})]}),Dt.genders&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-white/40",children:"Gênero:"}),e.jsx("span",{className:"text-white font-medium",children:Dt.genders})]}),Dt.interests&&e.jsxs("div",{className:"flex justify-between col-span-2",children:[e.jsx("span",{className:"text-white/40",children:"Interesses:"}),e.jsx("span",{className:"text-white font-medium truncate max-w-[300px]",children:Dt.interests})]}),Dt.sourceAudience&&e.jsxs("div",{className:"flex justify-between col-span-2",children:[e.jsx("span",{className:"text-white/40",children:"Público-alvo:"}),e.jsx("span",{className:"text-white font-medium truncate max-w-[300px]",children:Dt.sourceAudience})]}),Dt.sourceAngle&&e.jsxs("div",{className:"flex justify-between col-span-2",children:[e.jsx("span",{className:"text-white/40",children:"Ângulo:"}),e.jsx("span",{className:"text-white font-medium truncate max-w-[300px]",children:Dt.sourceAngle})]}),e.jsxs("div",{className:"flex justify-between col-span-2",children:[e.jsx("span",{className:"text-white/40",children:"Conjunto:"}),e.jsx("span",{className:"text-white font-medium truncate max-w-[300px]",children:Dt.adSetName})]})]})]}),Dt.sourceHeadline&&Ei.size>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-amber-400",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}),e.jsxs("span",{className:"font-medium",children:['Gerando 5 variações baseadas em "',Dt.sourceHeadline,'"...']})]})]}),Fs&&e.jsxs("div",{className:"border border-teal-500/30 rounded-xl bg-teal-500/5 p-4 space-y-3","data-testid":"batch-progress",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{className:`w-4 h-4 text-teal-400 ${Fs.status==="processing"?"animate-spin":""}`}),e.jsx("span",{className:"text-sm font-medium text-white",children:Fs.status==="completed"?`${Fs.creatives.length} criativos gerados!`:`Gerando criativos... ${Fs.completed}/${Fs.total}`})]}),Fs.status==="completed"&&e.jsx("span",{className:"text-xs text-teal-400 font-medium",children:"Gerando imagens..."})]}),e.jsx("div",{className:"w-full bg-white/10 rounded-full h-2 overflow-hidden",children:e.jsx("div",{className:"bg-teal-500 h-full rounded-full transition-all duration-500 ease-out",style:{width:`${Fs.completed/Fs.total*100}%`}})}),Fs.creatives.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Fs.creatives.map((t,s)=>e.jsxs("div",{className:"flex items-center gap-1.5 bg-white/5 border border-white/10 rounded-lg px-2.5 py-1.5 text-xs",children:[e.jsx(be,{className:"w-3 h-3 text-teal-400"}),e.jsx("span",{className:"text-white/80 truncate max-w-[200px]",children:t.headline||`Criativo ${s+1}`})]},t.id||s)),Fs.status==="processing"&&Fs.completed<Fs.total&&e.jsxs("div",{className:"flex items-center gap-1.5 bg-white/5 border border-white/10 rounded-lg px-2.5 py-1.5 text-xs",children:[e.jsx(T,{className:"w-3 h-3 text-white/40 animate-spin"}),e.jsx("span",{className:"text-white/40",children:"Gerando..."})]})]})]}),oe&&e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] overflow-hidden","data-testid":"creative-preview",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"font-semibold text-white text-sm",children:"Preview do Criativo"}),e.jsx(E,{variant:"outline",className:oe.status==="approved"?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":oe.status==="generated"?"bg-blue-500/20 text-blue-400 border-blue-500/30":oe.status==="archived"?"bg-white/10 text-white/40 border-white/10":"bg-amber-500/20 text-amber-400 border-amber-500/30",children:oe.status==="draft"?"Rascunho":oe.status==="generated"?"Gerado":oe.status==="approved"?"Aprovado":"Arquivado"}),oe.overlayText&&e.jsx(E,{variant:"outline",className:"text-[10px] border-teal-500/30 text-teal-400",children:"Texto na imagem"}),oe.lastError&&e.jsx(E,{variant:"outline",className:"text-[10px] bg-red-500/20 text-red-400 border-red-500/30",children:"Erro na publicação"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex bg-white/5 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>Dx("detail"),className:`px-2.5 py-1 rounded-md text-[10px] font-medium transition-colors ${Rd==="detail"?"bg-teal-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":"btn-preview-detail",children:"Detalhes"}),e.jsx("button",{onClick:()=>Dx("instagram"),className:`px-2.5 py-1 rounded-md text-[10px] font-medium transition-colors ${Rd==="instagram"?"bg-teal-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":"btn-preview-instagram",children:"Instagram"})]}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>{ys(null),_n(null)},className:"text-white/60 hover:text-white",children:e.jsx(ea,{className:"w-4 h-4"})})]})]}),Rd==="instagram"?e.jsx("div",{className:"flex justify-center p-8 bg-black/30",children:e.jsxs("div",{className:"w-[380px] bg-black rounded-2xl overflow-hidden shadow-2xl border border-white/10",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-gradient-to-br from-teal-500 to-teal-700 flex items-center justify-center text-white text-[10px] font-bold",children:"S"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-white text-xs font-semibold",children:"sabhiabooks"}),e.jsx("p",{className:"text-white/40 text-[10px]",children:"Patrocinado"})]}),e.jsx(Su,{className:"w-4 h-4 text-white/40"})]}),e.jsx("div",{className:`bg-neutral-800 ${oe.format==="feed_square"?"aspect-square":oe.format==="feed_vertical"?"aspect-[4/5]":"aspect-[9/16]"}`,children:oe.imageUrl?e.jsx("img",{src:oe.imageUrl,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Xt,{className:"w-12 h-12 text-white/10"})})}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ah,{className:"w-5 h-5 text-white"}),e.jsx(Ut,{className:"w-5 h-5 text-white"}),e.jsx(ct,{className:"w-5 h-5 text-white"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-white text-xs font-bold",children:oe.headline}),e.jsx(E,{className:"bg-teal-600 text-white text-[9px] px-2 py-0.5",children:oe.callToAction})]}),e.jsxs("p",{className:"text-white/80 text-[11px] leading-relaxed",children:[e.jsx("span",{className:"font-semibold text-white",children:"sabhiabooks "}),oe.primaryText.length>120?oe.primaryText.substring(0,120)+"... ":oe.primaryText,oe.primaryText.length>120&&e.jsx("span",{className:"text-white/40",children:"mais"})]}),e.jsx("p",{className:"text-white/40 text-[10px]",children:oe.description})]})]})}):e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-0",children:[e.jsx("div",{className:"p-6 flex flex-col items-center justify-center border-r border-white/10 bg-black/20 min-h-[400px]",children:oe.imageUrl?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:oe.imageUrl,alt:"Ad creative",className:"max-w-full max-h-[500px] rounded-lg shadow-2xl","data-testid":"img-creative-preview"}),e.jsxs("div",{className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2 rounded-lg",children:[e.jsxs(b,{size:"sm",variant:"outline",className:"border-white/30 text-white text-xs gap-1",onClick:()=>{const t=document.createElement("a");t.href=oe.imageUrl,t.download=`sabhia-ad-${oe.id}.jpg`,t.click()},"data-testid":"btn-download-image",children:[e.jsx(Rt,{className:"w-3 h-3"})," Baixar"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"border-white/30 text-white text-xs gap-1",disabled:Wr.isPending,onClick:()=>{Id(!0),On("")},"data-testid":"btn-regenerate-image",children:[Wr.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"})," Nova Imagem"]})]}),Cp&&e.jsxs("div",{className:"absolute bottom-4 left-4 right-4 bg-[#1a1a1c] border border-white/15 rounded-lg p-3 shadow-xl",style:{animation:"waFadeIn .2s ease"},children:[e.jsx("textarea",{value:Fx,onChange:t=>On(t.target.value),placeholder:"Descreva como quer a imagem (opcional)... Ex: mulher segurando um livro, fundo rosa, iluminação suave...",className:"w-full bg-black/30 border border-white/10 rounded-md px-3 py-2 text-xs text-white placeholder:text-white/30 resize-none focus:outline-none focus:ring-1 focus:ring-teal-500/50",rows:2,maxLength:500,"data-testid":"textarea-image-direction"}),e.jsxs("div",{className:"flex justify-end gap-2 mt-2",children:[e.jsx(b,{size:"sm",variant:"ghost",className:"text-white/60 text-xs h-7 px-3",onClick:()=>{Id(!1),On("")},children:"Cancelar"}),e.jsxs(b,{size:"sm",className:"bg-teal-600 hover:bg-teal-700 text-xs h-7 px-3 gap-1",disabled:Wr.isPending,onClick:()=>Wr.mutate({id:oe.id,imageDirection:Fx}),"data-testid":"btn-confirm-regenerate-image",children:[Wr.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(qe,{className:"w-3 h-3"})," Gerar"]})]})]})]}):e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"w-24 h-24 rounded-2xl bg-white/5 border border-dashed border-white/20 flex items-center justify-center mx-auto",children:e.jsx(Xt,{className:"w-10 h-10 text-white/20"})}),e.jsx("p",{className:"text-white/40 text-sm",children:"Imagem ainda não gerada"}),e.jsx(b,{size:"sm",className:"bg-teal-600 hover:bg-teal-700 gap-1.5",disabled:qn.has(oe.id),onClick:()=>Qr.mutate(oe.id),"data-testid":"btn-generate-image",children:qn.has(oe.id)?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"})," Gerando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"w-3.5 h-3.5"})," Gerar Imagem"]})})]})}),e.jsxs("div",{className:"p-6 space-y-4",children:[[{field:"headline",label:"Headline",limit:40,multiline:!1},{field:"primaryText",label:"Texto Principal",limit:500,multiline:!0},{field:"description",label:"Descrição",limit:30,multiline:!1}].map(({field:t,label:s,limit:i,multiline:x})=>{const C=oe[t]||"",P=C.length,H=P/i,Q=H>1?"text-red-400":H>.85?"text-amber-400":"text-white/30",G=kp===t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] uppercase tracking-wider text-white/40 font-medium",children:s}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[H>1&&!G&&e.jsx("button",{onClick:ue=>{ue.stopPropagation(),al.mutate({id:oe.id,field:t,value:C.slice(0,i)})},className:"text-[9px] px-1.5 py-0.5 rounded bg-red-500/20 text-red-300 hover:bg-red-500/30 transition-colors border border-red-500/20","data-testid":`btn-truncate-${t}`,children:"Truncar"}),e.jsxs("span",{className:`text-[10px] font-mono ${Q}`,children:[P,"/",i]})]})]}),G?e.jsxs("div",{className:"space-y-1",children:[x?e.jsx("textarea",{value:Td,onChange:ue=>Ed(ue.target.value),className:"w-full bg-white/5 border border-teal-500/30 rounded-lg p-2 text-sm text-white resize-none focus:outline-none focus:ring-1 focus:ring-teal-500/50",rows:4,autoF
7ocus:!0,"data-testid":`input-edit-${t}`}):e.jsx("input",{value:Td,onChange:ue=>Ed(ue.target.value),className:"w-full bg-white/5 border border-teal-500/30 rounded-lg px-2 py-1.5 text-sm text-white focus:outline-none focus:ring-1 focus:ring-teal-500/50",autoFocus:!0,"data-testid":`input-edit-${t}`}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(b,{size:"sm",className:"text-[10px] h-6 bg-teal-600 hover:bg-teal-700 px-2",disabled:al.isPending,onClick:()=>al.mutate({id:oe.id,field:t,value:Td}),children:al.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):"Salvar"}),e.jsx(b,{size:"sm",variant:"ghost",className:"text-[10px] h-6 text-white/50 px-2",onClick:()=>_n(null),children:"Cancelar"})]})]}):e.jsx("div",{className:"group/edit cursor-pointer",onClick:()=>{_n(t),Ed(C)},children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx("p",{className:`${t==="headline"?"text-lg font-bold text-white":t==="primaryText"?"text-sm text-white/80 whitespace-pre-wrap leading-relaxed":"text-xs text-white/60"} flex-1`,"data-testid":`text-creative-${t}`,children:C}),e.jsx(Yl,{className:"w-3 h-3 text-white/20 group-hover/edit:text-teal-400 shrink-0 mt-1 transition-colors"})]})})]},t)}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] uppercase tracking-wider text-white/40 font-medium",children:"CTA"}),e.jsx(E,{className:"mt-1 bg-teal-600/20 text-teal-400 border-teal-500/30 block w-fit",children:oe.callToAction})]}),oe.overlayText&&e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[10px] uppercase tracking-wider text-white/40 font-medium",children:"Texto na Imagem"}),e.jsxs("p",{className:"text-xs text-teal-400/80 mt-1 italic",children:['"',oe.overlayText,'"']})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(E,{variant:"outline",className:"text-[10px] border-white/10 text-white/50",children:oe.angle==="transformacao"?"🎯 Transformação":oe.angle==="preco"?"💰 Preço":oe.angle==="tecnologia"?"⚡ Tecnologia":oe.angle==="prova_social"?"📊 Prova Social":oe.angle==="urgencia"?"🔥 Urgência":oe.angle==="autoridade"?"🌟 Autoridade":oe.angle==="curiosidade"?"❓ Curiosidade":oe.angle==="antes_depois"?"🔄 Antes/Depois":oe.angle==="contrario"?"🔀 Contrário":oe.angle==="paradoxo"?"🧩 Paradoxo":oe.angle==="pop_quiz"?"🎲 Pop Quiz":oe.angle==="curiosidade_especifica"?"🔍 Curiosidade Específica":oe.angle==="conspiracao"?"🕵️ Conspiração":oe.angle==="teaser_mecanismo"?"⚙️ Teaser Mecanismo":oe.angle==="truque"?"🎩 Truque":oe.angle==="receita_estranha"?"🧪 Receita Estranha":"🔄 Antes/Depois"}),e.jsx(E,{variant:"outline",className:"text-[10px] border-white/10 text-white/50",children:oe.format==="feed_square"?"⬜ 1:1":oe.format==="feed_vertical"?"📱 4:5":"📲 9:16"}),e.jsx(E,{variant:"outline",className:"text-[10px] border-white/10 text-white/50",children:oe.targetAudience==="autores_iniciantes"?"✍️ Iniciantes":oe.targetAudience==="empreendedores"?"💼 Empreendedores":oe.targetAudience==="coaches"?"🎓 Coaches":oe.targetAudience==="religiosos"?"⛪ Religiosos":oe.targetAudience==="professores"?"📚 Professores":oe.targetAudience==="saude"?"🏥 Saúde":"🌐 Geral"})]}),Vt&&Sp===oe.id&&e.jsxs("div",{className:`rounded-lg border p-3 space-y-2 ${Vt.status==="APROVADO"?"bg-emerald-500/10 border-emerald-500/20":Vt.status==="ATENÇÃO"?"bg-amber-500/10 border-amber-500/20":"bg-red-500/10 border-red-500/20"}`,"data-testid":"compliance-result",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Vt.status==="APROVADO"?e.jsx(be,{className:"w-4 h-4 text-emerald-400"}):Vt.status==="ATENÇÃO"?e.jsx(Ce,{className:"w-4 h-4 text-amber-400"}):e.jsx(dt,{className:"w-4 h-4 text-red-400"}),e.jsx("span",{className:`text-sm font-bold ${Vt.status==="APROVADO"?"text-emerald-400":Vt.status==="ATENÇÃO"?"text-amber-400":"text-red-400"}`,children:Vt.status}),e.jsxs("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded ${Vt.score>=80?"bg-emerald-500/20 text-emerald-300":Vt.score>=50?"bg-amber-500/20 text-amber-300":"bg-red-500/20 text-red-300"}`,children:[Vt.score,"/100"]})]}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-5 w-5 p-0 text-white/30 hover:text-white/60",onClick:()=>{Bn(null),Un(null)},"data-testid":"btn-close-compliance",children:e.jsx(ea,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-[11px] text-white/70",children:Vt.summary}),Vt.issues?.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-semibold text-white/50 uppercase tracking-wider",children:"Problemas encontrados"}),Vt.issues.map((t,s)=>e.jsxs("div",{className:`rounded-md p-2 text-[11px] ${t.severity==="alta"?"bg-red-500/15 border border-red-500/20":t.severity==="média"?"bg-amber-500/15 border border-amber-500/20":"bg-blue-500/10 border border-blue-500/20"}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx(E,{variant:"outline",className:`text-[8px] px-1 py-0 ${t.severity==="alta"?"border-red-500/30 text-red-400":t.severity==="média"?"border-amber-500/30 text-amber-400":"border-blue-500/30 text-blue-400"}`,children:t.severity}),e.jsx("span",{className:"text-white/60 font-medium",children:t.category})]}),e.jsx("p",{className:"text-white/80",children:t.description}),e.jsxs("p",{className:"text-teal-400/80 mt-0.5",children:["Sugestão: ",t.suggestion]})]},s))]}),Vt.strengths?.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[10px] font-semibold text-white/50 uppercase tracking-wider",children:"Pontos fortes"}),Vt.strengths.map((t,s)=>e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-emerald-400/80",children:[e.jsx(is,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{children:t})]},s))]}),Vt.status!=="APROVADO"&&e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsxs(b,{size:"sm",className:"w-full text-xs gap-1.5 bg-gradient-to-r from-violet-600 to-teal-600 hover:from-violet-500 hover:to-teal-500 text-white font-semibold",disabled:il.isPending,onClick:()=>il.mutate({id:oe.id,issues:Vt.issues||[]}),"data-testid":"btn-regenerate-compliant",children:[il.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(xe,{className:"w-3.5 h-3.5"}),il.isPending?"Regenerando...":"Regenerar dentro das políticas"]}),e.jsx("p",{className:"text-[9px] text-white/40 text-center mt-1",children:"A IA vai reescrever o texto corrigindo todos os problemas acima"})]})]}),e.jsxs("div",{className:"border-t border-white/10 pt-4 flex flex-wrap gap-2",children:[oe.lastError&&e.jsxs("div",{className:"w-full mb-2 p-2.5 rounded-lg bg-red-500/10 border border-red-500/20",children:[e.jsx("p",{className:"text-[10px] text-red-400 font-semibold mb-1",children:"Erro na última publicação:"}),e.jsx("p",{className:"text-[10px] text-red-300/80 break-words",children:oe.lastError})]}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-violet-500/30 text-violet-400 hover:bg-violet-500/10",disabled:Mx,onClick:()=>Gp.mutate(oe.id),"data-testid":"btn-evaluate-compliance",children:[Mx?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(as,{className:"w-3 h-3"})," Avaliar Compliance"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-white/10 text-white/70 hover:text-white",onClick:()=>{const t=`📋 HEADLINE:
8${oe.headline}
9
10📝 TEXTO PRINCIPAL:
11${oe.primaryText}
12
13📌 DESCRIÇÃO:
14${oe.description}
15
16🔗 CTA: ${oe.callToAction}`;navigator.clipboard.writeText(t),r({title:"Copiado para Meta Ads!"})},"data-testid":"btn-copy-meta",children:[e.jsx(ha,{className:"w-3 h-3"})," Copiar para Meta Ads"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-white/10 text-white/70 hover:text-white",disabled:Yd.isPending,onClick:()=>Yd.mutate(oe.id),"data-testid":"btn-regenerate-text",children:[Yd.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"})," Regenerar Texto"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-white/10 text-white/70 hover:text-white",onClick:()=>lm.mutate(oe.id),disabled:lm.isPending,"data-testid":"btn-duplicate",children:[e.jsx(ha,{className:"w-3 h-3"})," Duplicar"]}),!oe.imageUrl&&e.jsxs(b,{size:"sm",className:"text-xs gap-1 bg-teal-600 hover:bg-teal-700",disabled:qn.has(oe.id),onClick:()=>Qr.mutate(oe.id),children:[qn.has(oe.id)?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(qe,{className:"w-3 h-3"})," Gerar Imagem"]}),oe.status!=="approved"&&e.jsxs(b,{size:"sm",className:"text-xs gap-1 bg-emerald-600 hover:bg-emerald-700",onClick:()=>dm.mutate({id:oe.id,status:"approved"}),"data-testid":"btn-approve",children:[e.jsx(be,{className:"w-3 h-3"})," Aprovar"]}),(oe.status==="approved"||oe.lastError&&oe.imageUrl)&&oe.imageUrl&&e.jsx(b,{size:"sm",className:`text-xs gap-1 ${oe.lastError?"bg-orange-600 hover:bg-orange-700":"bg-blue-600 hover:bg-blue-700"}`,onClick:()=>{const t=rl,s=oe.angle||"geral",i=oe.targetAudience||"geral",x=new Date().toISOString().split("T")[0].replace(/-/g,""),C=`[SABHIA] ${s} | ${i} | M${Date.now().toString().slice(-4)} | ${x}`,H=(t?.targetUrl||"https://sabhia.ai/chat").replace("sabhia.com","sabhia.ai");zt({campaignName:C,dailyBudget:t?.defaultTestBudget?String(t.defaultTestBudget/100):"10",destinationUrl:H,countries:t?.targetCountries||"BR",ageMin:t?.targetAgeMin?String(t.targetAgeMin):"25",ageMax:t?.targetAgeMax?String(t.targetAgeMax):"65",status:"ACTIVE"}),qd(!1),Ox("new"),Ld(""),Gn(""),Ri([]),qr(""),Kn(!0)},"data-testid":"btn-publish-meta",children:oe.lastError?e.jsxs(e.Fragment,{children:[e.jsx(xe,{className:"w-3 h-3"})," Republicar na Meta"]}):e.jsxs(e.Fragment,{children:[e.jsx(vs,{className:"w-3 h-3"})," Publicar na Meta"]})}),oe.status!=="archived"&&e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-white/10 text-white/50",onClick:()=>dm.mutate({id:oe.id,status:"archived"}),"data-testid":"btn-archive",children:[e.jsx(Hl,{className:"w-3 h-3"})," Arquivar"]}),e.jsx(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-teal-500/30 text-teal-400 hover:bg-teal-500/10",disabled:Ei.has(oe.id),onClick:()=>Zd.mutate(oe.id),"data-testid":"btn-variations-detail",children:Ei.has(oe.id)?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-3 h-3 animate-spin"})," Gerando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"w-3 h-3"})," Criar Variações"]})}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:()=>{confirm("Excluir este criativo?")&&Qp.mutate(oe.id)},"data-testid":"btn-delete-creative",children:[e.jsx(As,{className:"w-3 h-3"})," Excluir"]})]})]})]})]}),Op?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-teal-500"})}):Ra?.length?Pi==="matrix"&&Ra?.length>0?(()=>{const t=Ra.reduce((s,i)=>{const x=i.testGroup||"sem-grupo";return s[x]||(s[x]=[]),s[x].push(i),s},{});return e.jsx("div",{className:"space-y-6",children:Object.entries(t).map(([s,i])=>{const x=[...new Set(i.map(H=>H.imageUrl))].length,C=[...new Set(i.map(H=>H.headline))].length,P=i[0]?.testVariable||"both";return i.every(H=>(H.status==="approved"||H.status==="generated")&&H.imageUrl),e.jsxs("div",{className:"border border-violet-500/20 rounded-xl overflow-hidden bg-violet-500/[0.02]","data-testid":`matrix-group-${s.substring(0,8)}`,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-violet-500/10 border-b border-violet-500/20",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ot,{className:"w-4 h-4 text-violet-400"}),e.jsxs("div",{children:[e.jsxs("span",{className:"text-sm font-semibold text-white",children:["Matriz ",s.substring(0,8)]}),e.jsxs("span",{className:"text-xs text-white/40 ml-2",children:[x," img × ",C," txt = ",i.length," criativos"]})]}),e.jsx(E,{variant:"outline",className:`text-[10px] ${P==="image"?"text-violet-300 border-violet-500/30":P==="text"?"text-blue-300 border-blue-500/30":"text-teal-300 border-teal-500/30"}`,children:P==="image"?"Teste de Imagem":P==="text"?"Teste de Texto":"Teste Completo"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(b,{size:"sm",variant:"outline",className:"border-teal-500/30 text-teal-300 hover:bg-teal-500/20 gap-1.5 h-7 text-xs",onClick:()=>am(s),"data-testid":`btn-perf-matrix-${s.substring(0,8)}`,children:[e.jsx(ft,{className:"w-3 h-3"})," Performance"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"border-violet-500/30 text-violet-300 hover:bg-violet-500/20 gap-1.5 h-7 text-xs",onClick:()=>
16{i.forEach(H=>{Mr(Q=>{const G=new Set(Q);return G.add(H.id),G})})},"data-testid":`btn-select-matrix-${s.substring(0,8)}`,children:[e.jsx(Ua,{className:"w-3 h-3"})," Selecionar Todos"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 p-4",children:i.map(H=>{const Q=ks.has(H.id);return e.jsxs("div",{onClick:()=>ys(H),className:`border rounded-lg overflow-hidden cursor-pointer transition-all hover:border-violet-500/40 ${oe?.id===H.id?"border-violet-500/50 ring-1 ring-violet-500/20":Q?"border-blue-500/50 ring-1 ring-blue-500/20":"border-white/10"} bg-white/[0.02]`,"data-testid":`matrix-card-${H.id}`,children:[e.jsxs("div",{className:"aspect-video bg-black/30 relative overflow-hidden",children:[H.imageUrl&&e.jsx("img",{src:H.imageUrl,alt:"",className:"w-full h-full object-cover"}),e.jsx(E,{variant:"outline",className:"absolute top-1 right-1 text-[9px] backdrop-blur-sm bg-black/50 text-white/70 border-white/20",children:H.status==="published"?"Publicado":H.status==="approved"?"Aprovado":"Gerado"})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"text-xs font-medium text-white truncate",children:H.headline}),e.jsx("p",{className:"text-[10px] text-white/40 mt-0.5 line-clamp-1",children:H.primaryText})]})]},H.id)})})]},s)})})})():e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ra.map(t=>{const s=ks.has(t.id),i=t.status==="approved"&&t.imageUrl;return e.jsxs("div",{onClick:()=>ys(t),className:`border rounded-xl overflow-hidden cursor-pointer transition-all hover:border-teal-500/40 hover:shadow-lg hover:shadow-teal-500/5 ${oe?.id===t.id?"border-teal-500/50 ring-1 ring-teal-500/20":s?"border-blue-500/50 ring-1 ring-blue-500/20":"border-white/10"} bg-white/[0.02]`,"data-testid":`card-creative-${t.id}`,children:[e.jsxs("div",{className:"aspect-video bg-black/30 relative overflow-hidden",children:[t.imageUrl?e.jsx("img",{src:t.imageUrl,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Xt,{className:"w-8 h-8 text-white/10"})}),i&&e.jsx("button",{className:`absolute top-2 left-2 w-6 h-6 rounded-md border-2 flex items-center justify-center transition-all z-10 ${s?"bg-blue-500 border-blue-400":"bg-black/40 border-white/30 hover:border-white/60"}`,onClick:x=>{x.stopPropagation(),Mr(C=>{const P=new Set(C);return P.has(t.id)?P.delete(t.id):P.add(t.id),P})},"data-testid":`checkbox-creative-${t.id}`,children:s&&e.jsx(Ua,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[e.jsx(E,{variant:"outline",className:`text-[10px] backdrop-blur-sm ${t.status==="published"?"bg-blue-500/30 text-blue-300 border-blue-500/40":t.status==="approved"?"bg-emerald-500/30 text-emerald-300 border-emerald-500/40":t.status==="generated"?"bg-blue-500/30 text-blue-300 border-blue-500/40":t.status==="archived"?"bg-white/20 text-white/50 border-white/20":"bg-amber-500/30 text-amber-300 border-amber-500/40"}`,children:t.status==="draft"?"Rascunho":t.status==="generated"?"Gerado":t.status==="approved"?"Aprovado":t.status==="published"?"Publicado":"Arquivado"}),t.lastError&&e.jsx(E,{variant:"outline",className:"text-[10px] backdrop-blur-sm bg-red-500/30 text-red-300 border-red-500/40",title:t.lastError,children:"Erro"})]}),e.jsxs("div",{className:"absolute bottom-2 left-2 flex gap-1",children:[e.jsx(E,{variant:"outline",className:"text-[9px] backdrop-blur-sm bg-black/40 text-white/70 border-white/20",children:t.angle==="transformacao"?"🎯":t.angle==="preco"?"💰":t.angle==="tecnologia"?"⚡":t.angle==="prova_social"?"📊":t.angle==="urgencia"?"🔥":t.angle==="autoridade"?"🌟":t.angle==="curiosidade"?"❓":t.angle==="contrario"?"🔀":t.angle==="paradoxo"?"🧩":t.angle==="pop_quiz"?"🎲":t.angle==="curiosidade_especifica"?"🔍":t.angle==="conspiracao"?"🕵️":t.angle==="teaser_mecanismo"?"⚙️":t.angle==="truque"?"🎩":t.angle==="receita_estranha"?"🧪":"🔄"}),e.jsx(E,{variant:"outline",className:"text-[9px] backdrop-blur-sm bg-black/40 text-white/70 border-white/20",children:t.format==="feed_square"?"1:1":t.format==="feed_vertical"?"4:5":"9:16"})]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-sm font-semibold text-white truncate",children:t.headline}),e.jsx("p",{className:"text-xs text-white/50 mt-1 line-clamp-2",children:t.primaryText}),t.parentCreativeId&&e.jsx("p",{className:"text-[10px] text-teal-400/70 mt-1 truncate","data-testid":`text-variation-of-${t.id}`,children:"Variação de criativo anterior"}),t.testGroup&&e.jsxs("p",{className:"text-[10px] text-violet-400/70 mt-1 flex items-center gap-1","data-testid":`text-matrix-group-${t.id}`,children:[e.jsx(Ot,{className:"w-3 h-3"})," Matriz ",t.testGroup.substring(0,8)," • ",t.testVariable==="image"?"Teste de Imagem":t.testVariable==="text"?"Teste de Texto":"Teste Completo"]}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-[10px] text-white/30",children:t.createdAt?new Date(t.createdAt).toLocaleDateString("pt-BR"):""}),e.jsxs("button",{className:`flex items-center gap-1 text-[10px] px-2 py-1 rounded-md transition-all ${Ei.has(t.id)?"bg-teal-500/20 text-teal-400 cursor-wait":"bg-white/5 text-white/40 hover:bg-teal-500/20 hover:text-teal-400"}`,disabled:Ei.has(t.id),onClick:x=>{x.stopPropagation(),Zd.mutate(t.id)},title:"Criar 5 variações deste criativo","data-testid":`btn-variations-${t.id}`,children:[Ei.has(t.id)?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(qe,{className:"w-3 h-3"}),Ei.has(t.id)?"Gerando...":"Variações"]})]})]})]},t.id)})}):e.jsxs("div",{className:"text-center py-16 border border-dashed border-white/10 rounded-xl",children:[e.jsx(Xt,{className:"w-12 h-12 text-white/10 mx-auto mb-3"}),e.jsx("p",{className:"text-white/40 text-sm mb-4",children:"Nenhum criativo gerado ainda"}),e.jsxs(b,{size:"sm",onClick:()=>tr(!0),className:"bg-teal-600 hover:bg-teal-700 gap-1.5",children:[e.jsx(qe,{className:"w-3.5 h-3.5"})," Gerar Primeiro Criativo"]})]}),ks.size>0&&e.jsxs("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-[#1a1a2e] border border-violet-500/30 rounded-xl px-5 py-3 flex items-center gap-4 shadow-xl shadow-violet-500/10","data-testid":"batch-publish-bar",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-violet-500/20 flex items-center justify-center",children:e.jsx(Ot,{className:"w-4 h-4 text-violet-400"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-semibold text-white",children:[ks.size," criativo(s) selecionado(s)"]}),e.jsx("p",{className:"text-[10px] text-white/40",children:(()=>{const s=Array.from(ks).map(C=>Ra?.find(P=>
16P.id===C)).filter(Boolean),i=new Set(s.map(C=>C?.imageUrl)),x=new Set(s.map(C=>C?.headline));return i.size>1&&x.size>1?`Matriz ${i.size} imagens × ${x.size} textos — será separado inteligentemente`:i.size>1?`${i.size} imagens com mesmo texto — teste de imagem`:x.size>1?`${x.size} textos com mesma imagem — teste de texto`:"Mesmo criativo selecionado"})()})]})]}),e.jsx(b,{size:"sm",variant:"outline",className:"text-xs border-white/20 text-white/60 hover:text-white",onClick:()=>Mr(new Set),"data-testid":"btn-clear-selection",children:"Limpar"}),e.jsxs(b,{size:"sm",className:"bg-violet-600 hover:bg-violet-700 text-xs gap-1.5",onClick:()=>{const t=Array.from(ks)[0],s=Ra?.find(i=>i.id===t);if(s){const i=s.targetAudience==="religiosos"?"Religiosos":s.targetAudience==="empreendedores"?"Empreend":s.targetAudience==="coaches"?"Coaches":s.targetAudience==="professores"?"Professores":s.targetAudience==="saude"?"Saúde":s.targetAudience==="autores_iniciantes"?"Iniciantes":"Geral",x=s.angle==="transformacao"?"Transformação":s.angle==="preco"?"Preço":s.angle==="tecnologia"?"Tech":s.angle==="prova_social"?"Social":s.angle==="urgencia"?"Urgência":s.angle==="autoridade"?"Autoridade":s.angle==="curiosidade"?"Curiosidade":s.angle==="antes_depois"?"A/B":s.angle==="contrario"?"Contrário":s.angle==="paradoxo"?"Paradoxo":s.angle==="pop_quiz"?"PopQuiz":s.angle==="curiosidade_especifica"?"CurEspec":s.angle==="conspiracao"?"Conspiração":s.angle==="teaser_mecanismo"?"Teaser":s.angle==="truque"?"Truque":s.angle==="receita_estranha"?"ReceitaEstr":"A/B",C=new Date().toISOString().split("T")[0],P=Array.from(ks),H=P.map(Y=>Ra?.find(Oe=>Oe.id===Y)).filter(Boolean),Q=new Set(H.map(Y=>Y?.imageUrl)),G=new Set(H.map(Y=>Y?.headline)),ue=Q.size>1?Q.size:G.size,Te=Math.ceil(P.length/Math.max(ue,1));zt(Y=>({...Y,campaignName:`[SABHIA] Matrix ${x} | ${i} | ${ue}sets×${Te}ads | ${C}`,dailyBudget:String(Math.max(10,Math.round(50/Math.max(ue,1))))})),Wn(Q.size>1&&G.size>1?"auto":Q.size>1?"image":G.size>1?"text":"single")}Ri([]),qr(""),Lr(!0)},"data-testid":"btn-batch-publish",children:[e.jsx(vs,{className:"w-3.5 h-3.5"})," Publicar ",ks.size," na Meta"]})]})]}),Qe==="campaigns"&&e.jsx(Jb,{onCreateFromWinner:(t,s)=>{Ix(s),Zd.mutate(t),Fr("creatives")}}),Qe==="performance"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white",children:"Dashboard de Performance"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tracking avançado com funil, atribuição e comparativo A/B"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5",children:["7d","14d","30d","all"].map(t=>e.jsx("button",{onClick:()=>_p(t),className:`px-2.5 py-1 rounded-md text-[10px] font-medium transition-colors ${va===t?"bg-teal-600 text-white":"text-white/50 hover:text-white/80"}`,children:t==="all"?"Tudo":t},t))}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-white/10",onClick:()=>No.mutate(),disabled:No.isPending,children:[No.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"})," Sync"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-white/10",onClick:()=>{window.open(`/api/admin/performance/export?format=csv&period=${va}`,"_blank")},"data-testid":"btn-export-csv",children:[e.jsx(Rt,{className:"w-3 h-3"})," CSV"]})]})]}),e.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5 w-fit",children:[{val:"overview",label:"Visão Geral"},{val:"funnel",label:"Funil"},{val:"attribution",label:"Atribuição UTM"},{val:"ltv",label:"LTV"},{val:"ab",label:"A/B Comparativo"}].map(t=>e.jsx("button",{onClick:()=>Ip(t.val),className:`px-3 py-1 rounded-md text-[10px] font-medium transition-colors ${Ii===t.val?"bg-teal-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":`perfview-${t.val}`,children:t.label},t.val))}),Hp?e.jsx("div",{className:"flex justify-center p-12",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-teal-400"})}):e.jsxs(e.Fragment,{children:[Ii==="overview"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 ga
16p-3",children:[{label:"Investimento",value:`R$ ${((qt?.spend||0)/100).toFixed(2)}`,color:"text-white"},{label:"Receita",value:`R$ ${((qt?.revenue||0)/100).toFixed(2)}`,color:"text-emerald-400"},{label:"ROAS",value:`${qt?.roas||"0"}x`,color:parseFloat(qt?.roas||"0")>=2?"text-emerald-400":parseFloat(qt?.roas||"0")>=1?"text-amber-400":"text-red-400"},{label:"CPA",value:`R$ ${((qt?.cpa||0)/100).toFixed(2)}`,color:"text-white"},{label:"Conversões",value:String(qt?.conversions||0),color:"text-teal-400"}].map((t,s)=>e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 text-center",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40 mb-1",children:t.label}),e.jsx("p",{className:`text-xl font-bold ${t.color}`,"data-testid":`perf-${t.label.toLowerCase()}`,children:t.value})]},s))}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:[{label:"Impressões",value:(qt?.impressions||0).toLocaleString("pt-BR")},{label:"Cliques",value:(qt?.clicks||0).toLocaleString("pt-BR")},{label:"CTR",value:`${qt?.ctr||"0"}%`}].map((t,s)=>e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-3 text-center",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-white/40 mb-1",children:t.label}),e.jsx("p",{className:"text-lg font-semibold text-white",children:t.value})]},s))}),qt?.byDate&&Object.keys(qt.byDate).length>0&&e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-white mb-3",children:"Investimento vs Receita por dia"}),e.jsx("div",{className:"space-y-1.5",children:Object.entries(qt.byDate).sort().map(([t,s])=>{const i=Math.max(...Object.values(qt.byDate).flatMap(x=>[x.spend,x.revenue]));return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[10px] text-white/40 w-20 shrink-0",children:new Date(t).toLocaleDateString("pt-BR",{day:"2-digit",month:"short"})}),e.jsxs("div",{className:"flex-1 flex gap-1 items-center",children:[e.jsx("div",{className:"h-3 bg-red-500/40 rounded",style:{width:`${i>0?s.spend/i*100:0}%`},title:`Gasto: R$${(s.spend/100).toFixed(2)}`}),e.jsx("div",{className:"h-3 bg-emerald-500/40 rounded",style:{width:`${i>0?s.revenue/i*100:0}%`},title:`Receita: R$${(s.revenue/100).toFixed(2)}`})]}),e.jsxs("span",{className:"text-[10px] text-white/60 w-24 text-right",children:["R$ ",(s.spend/100).toFixed(0)," / R$ ",(s.revenue/100).toFixed(0)]})]},t)})}),e.jsxs("div",{className:"flex gap-4 mt-2 text-[10px] text-white/30",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-red-500/40 rounded"})," Investimento"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-emerald-500/40 rounded"})," Receita"]})]})]}),(()=>{const t=(cs||[]).filter(s=>s.status==="confirmed"||s.status==="completed").sort((s,i)=>new Date(i.createdAt||0).getTime()-new Date(s.createdAt||0).getTime()).slice(0,10);return t.length===0?null:e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-white mb-3","data-testid":"text-recent-conversions-title",children:"Últimas Conversões"}),e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:t.map(s=>e.jsxs("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg bg-white/[0.02] border border-white/5","data-testid":`conversion-row-${s.id}`,children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-emerald-500/15 flex items-center justify-center flex-shrink-0",children:e.jsx(is,{className:"w-4 h-4 text-emerald-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs text-white font-medium truncate",children:s.label||s.type}),e.jsxs("p",{className:"text-[10px] text-white/40 truncate",children:[s.userName||s.userEmail||"Cliente",s.bookTitle?` — ${s.bookTitle}`:""]})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsxs("p",{className:"text-xs font-bold text-emerald-400",children:["R$ ",s.amount.toFixed(2)]}),e.jsx("p",{className:"text-[10px] text-white/30",children:s.createdAt?new Date(s.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}):""})]})]},s.id))})]})})(),(!qt||qt.spend===0&&qt.impressions===0)&&(!cs||cs.filter(t=>t.status==="confirmed"||t.status==="completed").length===0)&&e.jsxs("div",{className:"border border-dashed border-white/10 rounded-xl p-8 text-center",children:[e.jsx(ft,{className:"w-10 h-10 text-white/10 mx-auto mb-3"}),e.jsx("p",{className:"text-white/40 text-sm",children:"Sem dados de performance ainda"}),e.jsx("p",{className:"text-white/25 text-xs mt-1",children:"Publique anúncios e sincronize para ver métricas"})]})]}),Ii==="funnel"&&(()=>{const t={};
16Xp.forEach(x=>{t[x.eventName]=(t[x.eventName]||0)+1});const s=[{name:"Impressões",count:qt?.impressions||0,color:"bg-slate-500"},{name:"Cliques",count:qt?.clicks||0,color:"bg-blue-500"},{name:"PageView",count:t.PageView||0,color:"bg-indigo-500"},{name:"ViewContent",count:t.ViewContent||0,color:"bg-violet-500"},{name:"CustomizeProduct",count:t.CustomizeProduct||0,color:"bg-purple-500"},{name:"InitiateCheckout",count:t.InitiateCheckout||0,color:"bg-amber-500"},{name:"Purchase",count:t.Purchase||0,color:"bg-emerald-500"}],i=Math.max(...s.map(x=>x.count),1);return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Funil de Conversão Completo"}),e.jsx("div",{className:"space-y-2",children:s.map((x,C)=>{const P=C>0?s[C-1].count:x.count,H=P>0?(x.count/P*100).toFixed(1):"0.0",Q=i>0?Math.max(x.count/i*100,2):2;return e.jsxs("div",{children:[C>0&&e.jsxs("div",{className:"flex items-center gap-2 pl-4 py-0.5",children:[e.jsx(Ct,{className:"w-3 h-3 text-white/20"}),e.jsxs("span",{className:`text-[10px] font-medium ${parseFloat(H)>=10?"text-emerald-400":parseFloat(H)>=3?"text-amber-400":"text-red-400"}`,children:[H,"% conversão"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[10px] text-white/50 w-28 shrink-0 text-right",children:x.name}),e.jsxs("div",{className:"flex-1 relative h-7 bg-white/5 rounded-lg overflow-hidden",children:[e.jsx("div",{className:`h-full ${x.color}/30 rounded-lg transition-all`,style:{width:`${Q}%`}}),e.jsx("span",{className:"absolute inset-0 flex items-center px-3 text-xs font-semibold text-white",children:x.count.toLocaleString("pt-BR")})]})]})]},x.name)})}),s[0].count>0&&s[6].count>0&&e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-3 text-center",children:[e.jsx("p",{className:"text-[10px] text-white/40",children:"Taxa total: Impressão → Purchase"}),e.jsxs("p",{className:"text-lg font-bold text-teal-400",children:[(s[6].count/s[0].count*100).toFixed(3),"%"]})]})]})})(),Ii==="attribution"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Atribuição por Campanha UTM"}),um.length>0?e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-6 gap-2 p-3 border-b border-white/10 text-[10px] uppercase tracking-wider text-white/40",children:[e.jsx("span",{children:"Campanha"}),e.jsx("span",{children:"Fonte"}),e.jsx("span",{children:"Meio"}),e.jsx("span",{className:"text-right",children:"Conversões"}),e.jsx("span",{className:"text-right",children:"Receita"}),e.jsx("span",{className:"text-right",children:"Usuários"})]}),[...um].sort((t,s)=>(s.revenue||0)-(t.revenue||0)).map((t,s)=>e.jsxs("div",{className:"grid grid-cols-6 gap-2 p-3 border-b border-white/5 last:border-0 text-xs hover:bg-white/5",children:[e.jsx("span",{className:"text-white font-medium truncate",title:t.utm_campaign||"Direto",children:t.utm_campaign||"Direto"}),e.jsx("span",{className:"text-white/60 truncate",children:t.utm_source||"-"}),e.jsx("span",{className:"text-white/60 truncate",children:t.utm_medium||"-"}),e.jsx("span",{className:"text-right text-teal-400 font-medium",children:t.conversions||0}),e.jsxs("span",{className:"text-right text-emerald-400 font-medium",children:["R$ ",((t.revenue||0)/100).toFixed(2)]}),e.jsx("span",{className:"text-right text-white/60",children:t.unique_users||0})]},s))]}):e.jsxs("div",{className:"border border-dashed border-white/10 rounded-xl p-8 text-center",children:[e.jsx(lt,{className:"w-8 h-8 text-white/10 mx-auto mb-2"}),e.jsx("p",{className:"text-white/40 text-xs",children:"Sem dados de atribuição UTM ainda"}),e.jsx("p",{className:"text-white/25 text-[10px] mt-1",children:"Os dados aparecem quando visitantes chegam com parâmetros UTM"})]})]}),Ii==="ltv"&&(()=>{const t=Hr?.summary||{},s=Dr==="campaign"?Hr?.byCampaign||[]:Dr==="audience"?Hr?.byAudience||[]:Hr?.byAd||[],i=Hr?.topUsers||[],x=Dr==="campaign"?"Campanha":Dr==="audience"?"Público (Ad Set)":"Anúncio",C=s.length>0?Math.max(...s.map(P=>Number(P.avg_ltv||0))):0;return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Lifetime Value (LTV) por Público"})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-3",children:[e.jsx("p",{className:"text-[10px] text-white/40 uppercase tracking-wider",children:"LTV Total"}),e.jsxs("p",{className:"text-lg font-bold text-emerald-400","data-testid":"ltv-total",children:["R$ ",Number(t.totalRevenue||0).toFixed(2)]})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-3",children:[e.jsx("p",{className:"text-[10px] text-white/40 uppercase tracking-wider",children:"LTV Médio/Usuário"}),e.jsxs("p",{className:"text-lg font-bold text-teal-400","data-testid":"ltv-avg",children:["R$ ",Number(t.avgLtv||0).toFixed(2)]})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-3",children:[e.jsx("p",{className:"text-[10px] text-white/40 uppercase tracking-wider",children:"Melhor Campanha"}),e.jsx("p",{className:"text-sm font-bold text-white truncate",title:t.bestCampaign?.name,"data-testid":"ltv-best-campaign",children:t.bestCampaign?.name||"-"}),e.jsx("p",{className:"text-[10px] text-emerald-400",children:t.bestCampaign?`R$ ${Number(t.bestCampaign.avgLtv).toFixed(2)}/user`:""})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-3",children:[e.jsx("p",{className:"text-[10px] text-white/40 uppercase tracking-wider",children:"Melhor Público"}),e.jsx("p",{className:"text-sm font-bold text-white truncate",title:t.bestAudience?.name,"data-testid":"ltv-best-audience",children:t.bestAudience?.name||"-"}),e.jsx("p",{className:"text-[10px] text-emerald-400",children:t.bestAudience?`R$ ${Number(t.bestAudience.avgLtv).toFixed(2)}/user`:""})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-[10px] text-white/40 uppercase tracking-wider",children:"Agrupar por:"}),e.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5",children:[{val:"campaign",label:"Campanha"},{val:"audience",label:"Público"},{val:"ad",label:"Anúncio"}].map(P=>e.jsx("button",{onClick:()=>Rp(P.val),className:`px-2.5 py-1 rounded-md text-[10px] font-medium transition-colors ${Dr===P.val?"bg-teal-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":`ltv-group-${P.val}`,children:P.label},P.val))})]}),s.length>0?e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-6 gap-2 p-3 border-b border-white/10 text-[10px] uppercase tracking-wider text-white/40",children:[e.jsx("span",{className:"col-span-2",children:x}),e.jsx("span",{className:"text-right",children:"Usuários"}),e.jsx("span",{className:"text-right",children:"Receita Total"}),e.jsx("span",{className:"text-right",children:"LTV Médio"}),e.jsx("span",{className:"text-right",children:"Pedidos/User"})]}),s.map((P,H)=>{const Q=Number(P.avg_ltv||0),G=H===0&&Q>0,ue=C>0?Q/C*100:0;return e.jsxs("div",{className:`grid grid-cols-6 gap-2 p-3 border-b border-white/5 last:border-0 text-xs hover:bg-white/5 relative ${G?"bg-emerald-500/5":""}`,"data-testid":`ltv-row-${H}`,children:[e.jsxs("div",{className:"col-span-2 flex items-center gap-2 min-w-0",children:[G&&e.jsx("span",{className:"text-amber-400 text-[10px]",children:"★"}),e.jsx("span",{className:"text-white font-medium truncate",title:P.group_key,children:P.group_key})]}),e.jsx("span",{className:"text-right text-white/60",children:P.users||0}),e.jsxs("span",{className:"text-right text-emerald-400 font-medium",children:["R$ ",Number(P.total_revenue||0).toFixed(2)]}),e.jsxs("div",{className:"text-right relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-teal-500/10 rounded-sm",style:{width:`${ue}%`}}),e.jsxs("span",{className:"relative text-teal-400 font-bold",children:["R$ ",Q.toFixed(2)]})]}),e.jsx("span",{className:"text-right text-white/60",children:P.avg_orders||0})]},H)})]}):e.jsxs("div",{className:"border border-dashed border-white/10 rounded-xl p-8 text-center",children:[e.jsx(lt,{className:"w-8 h-8 text-white/10 mx-auto mb-2"}),e.jsx("p",{className:"text-white/40 text-xs",children:"Sem dados de LTV ainda"}),e.jsx("p",{className:"text-white/25 text-[10px] mt-1",children:"Os dados aparecem quando clientes fazem compras atribuídas a campanhas"})]}),i.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold text-white/80",children:"Top 20 Clientes por LTV"}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-7 gap-2 p-3 border-b border-white/10 text-[10px] uppercase tracking-wider text-white/40",children:[e.jsx("span",{className:"col-span-2",children:"Cliente"}),e.jsx("span",{className:"text-right",children:"Pedidos"}),e.jsx("span",{className:"text-right",children:"Receita"}),e.jsx("span",{children:"Campanha"}),e.jsx("span",{children:"Público"}),e.jsx("span",{children:"Fonte"})]}),i.map((P,H)=>e.jsxs("div",{className:"grid grid-cols-7 gap-2 p-3 border-b border-white/5 last:border-0 text-xs hover:bg-white/5","data-testid":`ltv-user-${H}`,children:[e.jsxs("div",{className:"col-span-2 min-w-0",children:[e.jsx("p",{className:"text-white font-medium truncate",children:P.display_name||P.email||"Anônimo"}),e.jsx("p",{className:"text-[10px] text-white/30 truncate",children:P.email})]}),e.jsx("span",{className:"text-right text-white/60",children:P.total_orders||0}),e.jsxs("span",{className:"text-right text-emerald-400 font-bold",children:["R$ ",Number(P.total_revenue||0).toFixed(2)]}),e.jsx("span",{className:"text-white/50 truncate text-[10px]",title:P.first_utm_campaign,children:P.first_utm_campaign||"-"}),e.jsx("span",{className:"text-white/50 truncate text-[10px]",title:P.first_utm_term,children:P.first_utm_term||"-"}),e.jsx("span",{className:"text-white/50 truncate text-[10px]",title:P.first_utm_source,children:P.first_utm_source||"-"})]},H))]})]})]})})(),Ii==="ab"&&(()=>{const t=(Array.isArray(om)?om:[]).flatMap(i=>i.adSets?.flatMap(x=>x.ads||[])||[]),s=t.filter(i=>_x.includes(i.id));return e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Comparativo A/B de Criativos"}),e.jsx("p",{className:"text-[10px] text-white/40",children:"Selecione 2 criativos para comparar lado a lado"}),t.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:t.map(i=>e.jsxs("button",{onClick:()=>Fp(x=>x.includes(i.id)?x.filter(C=>C!==i.id):x.length>=2?[x[1],i.id]:[...x,i.id]),className:`border rounded-lg p-2 text-left text-xs transition-colors ${_x.includes(i.id)?"border-teal-500 bg-teal-500/10":"border-white/10 bg-white/[0.02] hover:border-white/20"}`,"data-testid":`ab-select-${i.id}`,children:[e.jsx("p",{className:"text-white font-medium truncate",children:i.name||i.id}),e.jsxs("p",{className:"text-white/40 text-[10px]",children:["ROAS: ",i.insights?.roas||"N/A"]})]},i.id))}),s.length===2&&e.jsx("div",{className:"grid grid-cols-2 gap-4",children:s.map((i,x)=>{const C=i.insights||{};return e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 space-y-2",children:[e.jsx("p",{className:"text-sm font-bold text-white truncate",children:i.name||i.id}),[{label:"ROAS",val:C.roas||"0",other:(s[1-x].insights||{}).roas||"0"},{label:"CPA",val:C.cpa||"0",other:(s[1-x].insights||{}).cpa||"0",lowerBetter:!0},{label:"CTR",val:C.ctr||"0",other:(s[1-x].insights||{}).ctr||"0"},{label:"Conversões",val:C.conversions||"0",other:(s[1-x].insights||{}).conversions||"0"},{label:"Impressões",val:C.impressions||"0",other:(s[1-x].insights||{}).impressions||"0"}].map(P=>{const H=parseFloat(String(P.val)),Q=parseFloat(String(P.other)),G=P.lowerBetter?H<Q&&H>0:H>Q;return e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-[10px] text-white/40",children:P.label}),e.jsxs("span",{className:`text-xs font-semibold ${G?"text-emerald-400":"text-white/60"}`,children:[P.val," ",G&&e.jsx(be,{className:"w-3 h-3 inline ml-1"})]})]},P.label)})]},i.id)})})]}):e.jsxs("div",{className:"border border-dashed border-white/10 rounded-xl p-8 text-center",children:[e.jsx(jt,{className:"w-8 h-8 text-white/10 mx-auto mb-2"}),e.jsx("p",{className:"text-white/40 text-xs",children:"Publique anúncios para usar o comparativo A/B"})]})]})})()]})]}),Qe==="audiences"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white",children:"Audiências Personalizadas"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custom Audiences e Lookalikes para campanhas Meta"})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(b,{size:"sm",className:"text-xs gap-1 bg-teal-600 hover:bg-teal-700",onClick:()=>eo.mutate({name:`Compradores SÁBHIA ${new Date().toLocaleDateString("pt-BR")}`,type:"buyers"}),disabled:eo.isPending,"data-testid":"btn-create-buyers-audience",children:[eo.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(_t,{className:"w-3 h-3"}),"Compradores"]})})]}),e.jsxs("div",{className:"border border-amber-500/20 rounded-xl bg-amber-500/5 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-amber-400"}),e.jsx("h3",{className:"text-sm font-bold text-white",children:"Audiências Inteligentes por Estágio do Funil"})]}),e.jsx("p",{className:"text-xs text-white/40 mt-1",children:"Segmentação automática baseada no comportamento real dos usuários no pipeline"})]}),e.jsxs(b,{size:"sm",className:"text-xs gap-1.5 bg-amber-600 hover:bg-amber-700 text-white",onClick:()=>
16{if(Xr.length===0){r({title:"Selecione segmentos",description:"Marque ao menos um segmento antes de criar",variant:"destructive"});return}ao.mutate(Xr)},disabled:ao.isPending||Xr.length===0,"data-testid":"btn-create-smart-audiences",children:[ao.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(He,{className:"w-3.5 h-3.5"}),"Criar Audiências Inteligentes (",Xr.length,")"]})]}),Zp?e.jsx("div",{className:"flex justify-center p-8",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-amber-400"})}):to?.segments?e.jsxs("div",{className:"space-y-2",children:[to.segments.map(t=>{const s=Xr.includes(t.key),i=t0?.find(C=>C.key===t.key),x={registered_no_plan:"📋",planned_not_bought:"💰",book_no_cover:"🎨",cover_no_illustration:"🖼️",illustration_no_publication:"📤",publication_no_marketing:"📣",marketing_no_translation:"🌍",all_buyers_lookalike:"👥"};return e.jsx("div",{className:`border rounded-xl p-4 cursor-pointer transition-all ${s?"border-amber-500/40 bg-amber-500/10":"border-white/10 bg-white/[0.02] hover:border-white/20"}`,onClick:()=>so(C=>C.includes(t.key)?C.filter(P=>P!==t.key):[...C,t.key]),"data-testid":`smart-segment-${t.key}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 shrink-0 mt-0.5",children:[e.jsx("input",{type:"checkbox",checked:s,readOnly:!0,className:"w-4 h-4 rounded border-white/20 bg-white/5 text-amber-500 focus:ring-amber-500 cursor-pointer","data-testid":`checkbox-segment-${t.key}`}),e.jsx("span",{className:"text-lg",children:x[t.key]||"📊"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-white",children:t.name}),e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-bold ${t.userCount>0?"bg-emerald-500/20 text-emerald-400":"bg-white/10 text-white/40"}`,children:[t.userCount.toLocaleString("pt-BR")," usuários"]}),t.key==="planned_not_bought"&&t.userCount>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-bold bg-red-500/20 text-red-400 animate-pulse",children:"OURO"})]}),e.jsx("p",{className:"text-[11px] text-white/40 mt-0.5",children:t.description}),e.jsx("div",{className:"mt-2 bg-white/5 rounded-lg p-2.5 border border-white/5",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(qe,{className:"w-3 h-3 text-amber-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-amber-300/70 font-medium uppercase tracking-wider mb-0.5",children:"Sugestão de criativo"}),e.jsxs("p",{className:"text-xs text-white/70 italic","data-testid":`creative-suggestion-${t.key}`,children:['"',t.creativeSuggestion,'"']})]})]})}),i&&e.jsxs("div",{className:`mt-2 flex items-center gap-1.5 text-[10px] ${i.error?"text-red-400":"text-emerald-400"}`,children:[i.error?e.jsx(dt,{className:"w-3 h-3"}):e.jsx(be,{className:"w-3 h-3"}),i.error?i.error:`Audiência criada • ${i.uploadedEmails} emails enviados${i.lookalikeId?" • Lookalike 1% criado":""}`]})]})]})},t.key)}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(b,{size:"sm",variant:"outline",className:"text-[10px] border-white/10",onClick:()=>so(to.segments.filter(t=>t.userCount>0).map(t=>t.key)),"data-testid":"btn-select-all-segments",children:"Selecionar Todos com Usuários"}),e.jsx(b,{size:"sm",variant:"outline",className:"text-[10px] border-white/10",onClick:()=>so([]),"data-testid":"btn-deselect-all-segments",children:"Limpar Seleção"}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-[10px] border-white/10 gap-1",onClick:()=>{e0(),jm(null)},"data-testid":"btn-refresh-segments",children:[e.jsx(xe,{className:"w-3 h-3"})," Atualizar"]})]})]}):e.jsx("div",{className:"text-center py-4",children:e.jsx("p",{className:"text-white/30 text-xs",children:"Não foi possível carregar os segmentos"})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-white mb-3",children:"Audiências no Meta"}),Jp?e.jsx("div",{className:"flex justify-center p-8",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-teal-400"})}):gm.length>0?e.jsx("div",{className:"space-y-2",children:gm.map(t=>e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 flex items-center justify-between","data-testid":`audience-${t.id}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-white truncate",children:t.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-medium ${t.subtype==="LOOKALIKE"?"bg-purple-500/20 text-purple-400":"bg-teal-500/20 text-teal-400"}`,children:t.subtype==="LOOKALIKE"?"Lookalike":"Custom"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-white/40",children:[e.jsxs("span",{children:[e.jsx(Re,{className:"w-3 h-3 inline mr-1"}
16),(t.approximate_count||0).toLocaleString("pt-BR")," usuários"]}),t.time_created&&e.jsx("span",{children:new Date(t.time_created).toLocaleDateString("pt-BR")})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-3",children:[t.subtype!=="LOOKALIKE"&&e.jsx(e.Fragment,{children:[1,3,5].map(s=>e.jsxs(b,{size:"sm",variant:"outline",className:"text-[10px] h-7 px-2 border-white/10",onClick:()=>bm.mutate({id:t.id,ratio:s/100}),disabled:bm.isPending,"data-testid":`lookalike-${s}-${t.id}`,children:["LAL ",s,"%"]},s))}),e.jsx(b,{size:"sm",variant:"ghost",className:"text-red-400 hover:text-red-300 h-7 w-7 p-0",onClick:()=>Yp.mutate(t.id),"data-testid":`delete-audience-${t.id}`,children:e.jsx(As,{className:"w-3.5 h-3.5"})})]})]},t.id))}):e.jsxs("div",{className:"border border-dashed border-white/10 rounded-xl p-8 text-center",children:[e.jsx(Re,{className:"w-10 h-10 text-white/10 mx-auto mb-3"}),e.jsx("p",{className:"text-white/40 text-sm",children:"Nenhuma audiência no Meta ainda"}),e.jsx("p",{className:"text-white/25 text-xs mt-1",children:"Use as Audiências Inteligentes acima ou crie manualmente"})]})]})]}),Qe==="optimizer"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white",children:"Auto-Optimizer"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Otimização automática de budget e performance"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{checked:!!cl?.simulation,onCheckedChange:t=>Pm.mutate({simulation:t}),"data-testid":"toggle-simulation",className:"data-[state=checked]:bg-amber-500"}),e.jsx("span",{className:"text-xs text-white/60 font-medium",children:"Simulação"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{checked:!!cl?.enabled,onCheckedChange:t=>Pm.mutate({enabled:t}),"data-testid":"toggle-optimizer"}),e.jsx("span",{className:"text-xs text-white/60 font-medium",children:cl?.enabled?"Ativo":"Inativo"})]}),e.jsxs(b,{size:"sm",className:"text-xs gap-1 bg-teal-600 hover:bg-teal-700",onClick:()=>wo.mutate(),disabled:wo.isPending,children:[wo.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(Us,{className:"w-3 h-3"})," Executar Agora"]})]})]}),cl?.simulation&&e.jsxs("div",{className:"bg-amber-500/10 border border-amber-500/20 rounded-lg p-3 flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-amber-400 shrink-0"}),e.jsx("p",{className:"text-xs text-amber-300",children:"Modo simulação ativo — as regras são avaliadas mas nenhuma ação é executada na Meta"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Regras de Otimização"}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-white/10",onClick:()=>{Di({name:"",condition:"roas_above",action:"increase_budget",threshold:"2",windowDays:"3",maxAdjustmentPct:"30"}),Yn(!0)},children:[e.jsx(_t,{className:"w-3 h-3"})," Nova Regra"]})]}),!io||io.length===0?e.jsxs("div",{className:"border border-dashed border-white/10 rounded-xl p-8 text-center",children:[e.jsx(Ht,{className:"w-10 h-10 text-white/10 mx-auto mb-3"}),e.jsx("p",{className:"text-white/40 text-sm",children:"Nenhuma regra configurada"}),e.jsx("p",{className:"text-white/25 text-xs mt-1",children:"Crie regras para otimizar automaticamente suas campanhas"})]}):e.jsx("div",{className:"space-y-2",children:io.map(t=>{const s={roas_above:"ROAS acima de",cpa_above:"CPA acima de R$",ctr_below:"CTR abaixo de",frequency_above:"Frequência acima de",spend_over_budget:"Gasto acima de %"},i={increase_budget:"Aumentar budget",pause:"Pausar ad set"};return e.jsxs("div",{className:"flex items-center gap-3 border border-white/10 rounded-lg bg-white/[0.02] p-3","data-testid":`rule-${t.id}`,children:[e.jsx(rt,{checked:!!t.isActive,onCheckedChange:x=>h0.mutate({id:t.id,isActive:x}),className:"shrink-0 scale-75"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-white truncate",children:t.name}),e.jsxs("p",{className:"text-[10px] text-white/40 mt-0.5",children:["Se ",s[t.condition]||t.condition," ",t.threshold," por ",t.windowDays,"d → ",i[t.action]||t.action," (max ",t.maxAdjustmentPct,"%)"]})]}),e.jsx(b,{size:"sm",variant:"ghost",className:"text-red-400 hover:text-red-300 h-7 w-7 p-0",onClick:()=>{confirm("Excluir esta regra?")&&p0.mutate(t.id)},children:e.jsx(As,{className:"w-3 h-3"})})]},t.id)})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-white mb-3",children:"Histórico de Ações"}),!ro||ro.length===0?e.jsx("p",{className:"text-xs text-white/30 text-center py-4",children:"Nenhuma ação registrada ainda"}):e.jsx("div",{className:"space-y-1.5 max-h-[300px] overflow-y-auto",children:ro.map(t=>e.jsxs("div",{className:"flex items-start gap-2 p-2 rounded-lg bg-white/[0.02] border border-white/5",children:[e.jsx("div",{className:`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${t.isSimulation?"bg-amber-400":"bg-emerald-400"}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[11px] text-white/80 truncate",children:t.actionTaken}),e.jsxs("p",{className:"text-[10px] text-white/30 mt-0.5",children:[t.ruleName," | ",t.createdAt?new Date(t.createdAt).toLocaleStr
16ing("pt-BR"):""]})]})]},t.id))})]})]}),Qe==="ia-gestor"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-bold text-white flex items-center gap-2",children:[e.jsx(Qi,{className:"w-5 h-5 text-teal-400"})," IA Gestor Autônomo"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Gerenciamento autônomo de tráfego com IA"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rt,{checked:Ue?.isEnabled||!1,onCheckedChange:()=>fm.mutate(!Ue?.isEnabled),disabled:fm.isPending,"data-testid":"switch-ia-gestor-toggle",className:"scale-125"}),e.jsx(E,{className:Ue?.isEnabled?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-red-500/20 text-red-400 border-red-500/30",children:Ue?.isEnabled?"Ativo":"Desativado"})]})]}),e.jsxs(b,{size:"sm",className:"bg-teal-600 hover:bg-teal-700 gap-1.5 text-xs",onClick:()=>oo.mutate(),disabled:oo.isPending,"data-testid":"btn-ia-gestor-run-now",children:[oo.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Us,{className:"w-3.5 h-3.5"}),"Rodar Agora"]})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] overflow-hidden",children:[e.jsxs("button",{onClick:()=>$p(!Dd),className:"w-full flex items-center justify-between p-4 hover:bg-white/[0.03] transition-colors","data-testid":"btn-ia-gestor-config-toggle",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"w-4 h-4 text-teal-400"}),e.jsx("span",{className:"text-sm font-semibold text-white",children:"Configuração"})]}),e.jsx(Ct,{className:`w-4 h-4 text-white/50 transition-transform ${Dd?"rotate-180":""}`})]}),Dd&&Le&&e.jsxs("div",{className:"p-4 pt-0 space-y-4 border-t border-white/10",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Budget de Teste R$/dia"}),e.jsx(J,{type:"number",step:"0.01",value:((Le.defaultTestBudget||0)/100).toFixed(2),onChange:t=>bt(s=>({...s,defaultTestBudget:Math.round(parseFloat(t.target.value||"0")*100)})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-budget"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Duração do teste (dias)"}),e.jsx(J,{type:"number",value:Le.testDurationDays||3,onChange:t=>bt(s=>({...s,testDurationDays:parseInt(t.target.value||"3")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-duration"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Multiplicador de escala"}),e.jsx(J,{type:"number",step:"0.1",value:Le.scaleMultiplier||1.5,onChange:t=>bt(s=>({...s,scaleMultiplier:parseFloat(t.target.value||"1.5")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-scale"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Max budget por campanha (R$)"}),e.jsx(J,{type:"number",step:"0.01",value:((Le.maxDailyBudgetPerCampaign||0)/100).toFixed(2),onChange:t=>bt(s=>({...s,maxDailyBudgetPerCampaign:Math.round(parseFloat(t.target.value||"0")*100)})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-max-budget"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Max gasto diário em testes (R$)"}),e.jsx(J,{type:"number",step:"0.01",value:((Le.maxDailyTestSpend||0)/100).toFixed(2),onChange:t=>bt(s=>({...s,maxDailyTestSpend:Math.round(parseFloat(t.target.value||"0")*100)})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-max-test-spend"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"ROAS alvo"}),e.jsx(J,{type:"number",step:"0.1",value:Le.targetRoas||2,onChange:t=>bt(s=>({...s,targetRoas:parseFloat(t.target.value||"2")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-roas"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Criativos por dia"}
16),e.jsx(J,{type:"number",value:Le.creativesPerDay||2,onChange:t=>bt(s=>({...s,creativesPerDay:parseInt(t.target.value||"2")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-creatives"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"URL destino"}),e.jsx(J,{value:Le.targetUrl||"",onChange:t=>bt(s=>({...s,targetUrl:t.target.value})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-url"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Países"}),e.jsx(J,{value:Le.targetCountries||"BR",onChange:t=>bt(s=>({...s,targetCountries:t.target.value})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-countries"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Idade min"}),e.jsx(J,{type:"number",value:Le.targetAgeMin||25,onChange:t=>bt(s=>({...s,targetAgeMin:parseInt(t.target.value||"25")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-age-min"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Idade max"}),e.jsx(J,{type:"number",value:Le.targetAgeMax||65,onChange:t=>bt(s=>({...s,targetAgeMax:parseInt(t.target.value||"65")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-age-max"})]})]}),e.jsxs("div",{className:"border-t border-white/10 pt-4 mt-2",children:[e.jsx("h4",{className:"text-xs font-semibold text-teal-400 mb-3 uppercase tracking-wider",children:"Realocação Dinâmica de Budget"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rt,{checked:Le.enableBudgetReallocation??!0,onCheckedChange:t=>bt(s=>({...s,enableBudgetReallocation:t})),"data-testid":"switch-ia-gestor-budget-reallocation"}),e.jsx(O,{className:"text-xs",children:"Realocação automática"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Budget mínimo por ad set (R$)"}),e.jsx(J,{type:"number",step:"0.01",value:((Le.minDailyBudget||1e3)/100).toFixed(2),onChange:t=>bt(s=>({...s,minDailyBudget:Math.round(parseFloat(t.target.value||"10")*100)})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-min-budget"})]})]})]}),e.jsxs("div",{className:"border-t border-white/10 pt-4 mt-2",children:[e.jsx("h4",{className:"text-xs font-semibold text-amber-400 mb-3 uppercase tracking-wider",children:"Sentinela de Performance (CPA)"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"CPA Ótimo (R$)"}),e.jsx(J,{type:"number",step:"0.01",value:((Le.optimalCpa||6300)/100).toFixed(2),onChange:t=>bt(s=>({...s,optimalCpa:Math.round(parseFloat(t.target.value||"63")*100)})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-sentinela-optimal-cpa"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Tolerância CPA (%)"}),e.jsx(J,{type:"number",step:"1",value:Le.cpaTolerance||30,onChange:t=>bt(s=>({...s,cpaTolerance:parseInt(t.target.value||"30")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-sentinela-cpa-tolerance"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Dias para pausar"}),e.jsx(J,{type:"number",value:Le.pauseWindowDays||5,onChange:t=>bt(s=>({...s,pauseWindowDays:parseInt(t.target.value||"5")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-sentinela-pause-days"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Dias para escalar"}),e.jsx(J,{type:"number",value:Le.scaleWindowDays||7,onChange:t=>bt(s=>({...s,scaleWindowDays:parseInt(t.target.value||"7")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-sentinela-scale-days"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Escala diária (%)"}),e.jsx(J,{type:"number",step:"1",value:Le.dailyScalePct||12,onChange:t=>bt(s=>({...s,dailyScalePct:parseInt(t.target.value||"12")})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-sentinela-daily-scale"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-5",children:[e.jsx(rt,{checked:Le.requireBudgetSpent??!0,onCheckedChange:t=>bt(s=>({...s,requireBudgetSpent:t})),"data-testid":"switch-sentinela-require-budget-spent"}),e.jsx(O,{className:"text-xs",children:"Exigir budget gasto"})]})]})]}),e.jsxs("div",{className:"border-t border-white/10 pt-4 mt-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-teal-400 mb-3 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(pt,{className:"w-3.5 h-3.5"})," Multi-Idioma Global"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Idiomas alvo (separados por vírgula)"}),e.jsx(J,{value:Le.targetLanguages||"pt-BR",onChange:t=>bt(s=>({...s,targetLanguages:t.target.value})),placeholder:"pt-BR,en-US,es-ES",className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-languages"}),e.jsx("p",{className:"text-[10px] text-white/40 mt-1",children:"Opções: pt-BR, en-US, es-ES, fr-FR, de-DE, it-IT. Cada idioma gera anúncios direcionados ao país correspondente."})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 items-start pt-5",children:(Le.targetLanguages||"pt-BR").split(",").map(t=>{const s=t.trim(),i={"pt-BR":"🇧🇷 PT-BR","en-US":"🇺🇸 EN-US","es-ES":"
16🇪🇸 ES-ES","fr-FR":"🇫🇷 FR-FR","de-DE":"🇩🇪 DE-DE","it-IT":"🇮🇹 IT-IT"},x={"pt-BR":"BR","en-US":"US,GB,AU,CA","es-ES":"ES,MX,AR,CO,CL","fr-FR":"FR,BE,CA","de-DE":"DE,AT,CH","it-IT":"IT"};return s?e.jsxs(E,{className:"bg-teal-600/20 text-teal-400 border-teal-500/30 text-[10px]",children:[i[s]||s," → ",x[s]||"?"]},s):null})})]})]}),e.jsxs("div",{className:"border-t border-white/10 pt-4 mt-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-teal-400 mb-3 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(nt,{className:"w-3.5 h-3.5"})," Estratégia de Lance (Bid Strategy)"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Bid Strategy padrão"}),e.jsxs(Se,{value:Le.bidStrategy||"LOWEST_COST_WITHOUT_CAP",onValueChange:t=>bt(s=>({...s,bidStrategy:t})),children:[e.jsx($e,{className:"border-white/10 bg-white/5 text-xs","data-testid":"select-ia-gestor-bid-strategy",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"LOWEST_COST_WITHOUT_CAP",children:"Menor Custo (sem cap)"}),e.jsx(U,{value:"COST_CAP",children:"Cost Cap (CPA máximo)"}),e.jsx(U,{value:"LOWEST_COST_WITH_BID_CAP",children:"Menor Custo (com cap)"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Cost Cap manual (R$)"}),e.jsx(J,{type:"number",step:"0.01",placeholder:"Automático",value:Le.costCapAmount?((Le.costCapAmount||0)/100).toFixed(2):"",onChange:t=>{const s=t.target.value;bt(i=>({...i,costCapAmount:s?Math.round(parseFloat(s)*100):null}))},className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-cost-cap"}),e.jsx("p",{className:"text-[10px] text-white/40 mt-1",children:"Deixe vazio para cálculo automático (CPA médio × 1.2)"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-4",children:[e.jsx(rt,{checked:Le.autoBidOptimization??!1,onCheckedChange:t=>bt(s=>({...s,autoBidOptimization:t})),"data-testid":"switch-ia-gestor-auto-bid"}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Auto-otimização de lance"}),e.jsx("p",{className:"text-[10px] text-white/40",children:"Campeões com CPA estável mudam para COST_CAP automaticamente"})]})]})]})]}),e.jsxs("div",{className:"border-t border-white/10 pt-4 mt-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-teal-400 mb-3 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Ot,{className:"w-3.5 h-3.5"})," Testes A/B Estruturados"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Proporção de testes estruturados (%)"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(J,{type:"range",min:"0",max:"100",value:Math.round((Le.structuredTestRatio??.7)*100),onChange:t=>bt(s=>({...s,structuredTestRatio:parseInt(t.target.value)/100})),className:"flex-1 h-2 accent-teal-500","data-testid":"input-ia-gestor-structured-ratio"}),e.jsxs("span",{className:"text-sm font-bold text-teal-400 min-w-[3rem] text-right",children:[Math.round((Le.structuredTestRatio??.7)*100),"%"]})]}),e.jsxs("p",{className:"text-[10px] text-white/40 mt-1",children:[Math.round((Le.structuredTestRatio??.7)*100),"% testes estruturados (isolam 1 variável) + ",100-Math.round((Le.structuredTestRatio??.7)*100),"% exploração aleatória"]})]})})]}),e.jsxs("div",{className:"border-t border-white/10 pt-4 mt-2",children:[e.jsxs("h4",{className:"text-xs font-semibold text-teal-400 mb-3 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(lt,{className:"w-3.5 h-3.5"})," Retargeting Automático"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rt,{checked:Le.enableRetargeting??!1,onCheckedChange:t=>bt(s=>({...s,enableRetargeting:t})),"data-testid":"switch-ia-gestor-retargeting"}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Retargeting por funil"}),e.jsx("p",{className:"text-[10px] text-white/40",children:"Cria audiências e campanhas por estágio automaticamente"})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Budget por estágio (R$/dia)"}),e.jsx(J,{type:"number",step:"0.01",value:((Le.retargetingBudgetPerStage||1500)/100).toFixed(2),onChange:t=>bt(s=>({...s,retargetingBudgetPerStage:Math.round(parseFloat(t.target.value||"15")*100)})),className:"border-white/10 bg-white/5 text-xs","data-testid":"input-ia-gestor-retargeting-budget"}),e.jsx("p",{className:"text-[10px] text-white/40 mt-1",children:"Budget diário para cada estágio do funil de retargeting"})]})]}),Le.enableRetargeting&&e.jsxs("div",{className:"mt-3 p-3 bg-white/[0.02] rounded-lg border border-white/5",children:[e.jsx("p",{className:"text-[10px] text-white/50 mb-2",children:"Estágios do funil de retargeting:"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"text-center p-2 bg-blue-500/5 rounded border border-blue-500/10",children:[e.jsx("p",{className:"text-[10px] font-medium text-blue-400",children:"Visitantes"}),e.jsx("p",{className:"text-[9px] text-white/40 mt-0.5",children:"Pixel (30 dias)"})]}),e.jsxs("div",{className:"text-center p-2 bg-amber-500/5 rounded border border-amber-500/10",children:[e.jsx("p",{className:"text-[10px] font-medium text-amber-400",children:"Cadastrados"}),e.jsx("p",{className:"text-[9px] text-white/40 mt-0.5",children:"Sem pedidos"})]}),e.jsxs("div",{className:"text-center p-2 bg-orange-500/5 rounded border border-orange-500/10",children:[e.jsx("p",{className:"text-[10px] font-medium text-orange-400",children:"Carrinho"}),e.jsx("p",{className:"text-[9px] text-white/40 mt-0.5",children:"Pedidos pendentes"})]}),e.jsxs("div",{className:"text-center p-2 bg-emerald-500/5 rounded border border-emerald-500/10",children:[e.jsx("p",{className:"text-[10px] font-medium text-emerald-400",children:"Cross-sell"}),e.jsx("p",{className:"text-[9px] text-white/40 mt-0.5",children:"Já compraram"})]})]})]})]}),e.jsxs(b,{size:"sm",className:"bg-teal-600 hover:bg-teal-700 gap-1 text-xs",onClick:()=>co.mutate(Le),disabled:co.isPending,"data-testid":"btn-ia-gestor-save-config",children:[co.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(is,{className:"w-3 h-3"}),"Salvar Configuração"]})]})]}),Ue?.anomalyCount>0&&Ue?.anomalies?.length>0&&e.jsxs("div",{className:"border border-red-500/30 rounded-xl bg-red-500/5 p-3 space-y-2","data-testid":"anomaly-alerts-banner",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-red-400"}),e.jsxs("span",{className:"text-xs font-semibold text-red-400",children:[Ue.anomalyCount," Anomalia(s) Detectada(s) nas últimas 24h"]})]}),Ue.anomalies.map((t,s)=>e.jsxs("div",{className:"text-[11px] text-red-300/70 pl-6 border-l-2 border-red-500/20 ml-1",children:[e.jsx("span",{className:"font-medium text-red-300",children:t.action})," — ",t.justification?.substring(0,120)]},s))]}
16),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:`border rounded-xl p-4 space-y-1 ${(Ue?.healthScore||0)>70?"bg-emerald-500/5 border-emerald-500/20":(Ue?.healthScore||0)>40?"bg-amber-500/5 border-amber-500/20":"bg-red-500/5 border-red-500/20"}`,"data-testid":"stat-health-score",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(as,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium",children:"Health Score"})]}),e.jsx("p",{className:`text-3xl font-black ${(Ue?.healthScore||0)>70?"text-emerald-400":(Ue?.healthScore||0)>40?"text-amber-400":"text-red-400"}`,children:Ue?.healthScore??0}),e.jsx("p",{className:"text-[10px] text-white/30",children:"de 100"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4 space-y-1","data-testid":"stat-testes-ativos",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(jt,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium",children:"Testes Ativos"})]}),e.jsx("p",{className:"text-2xl font-bold text-white",children:Ue?.activeTests??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4 space-y-1","data-testid":"stat-campeoes",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(wn,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium",children:"Campeões"})]}),e.jsx("p",{className:"text-2xl font-bold text-emerald-400",children:Ue?.winners??0})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4 space-y-1","data-testid":"stat-investido-hoje",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(nt,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium",children:"Investido Hoje"})]}),e.jsxs("p",{className:"text-2xl font-bold text-white",children:["R$ ",((Ue?.spentToday||0)/100).toFixed(2).replace(".",",")]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4 space-y-1","data-testid":"stat-roas-geral",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(Ie,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium",children:"ROAS Geral"})]}),e.jsxs("p",{className:`text-2xl font-bold ${parseFloat(Ue?.overallRoas||"0")>=2?"text-emerald-400":parseFloat(Ue?.overallRoas||"0")>=1?"text-amber-400":"text-red-400"}`,children:[Ue?.overallRoas||"0.0","x"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 space-y-2","data-testid":"budget-flow-card",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ka,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Fluxo de Budget (24h)"})]}),Ue?.budgetFlow?.losersReduced>0||Ue?.budgetFlow?.winnersBoosted>0?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("p",{className:"text-xs text-white/60",children:["R$",((Ue?.budgetFlow?.freed||0)/100).toFixed(2)," liberado de ",Ue?.budgetFlow?.losersReduced||0," perdedore(s) "," -> "," ",Ue?.budgetFlow?.winnersBoosted||0," vencedore(s)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(E,{className:"bg-red-500/10 text-red-400 border-red-500/20 text-[10px]",children:["-",Ue?.budgetFlow?.losersReduced||0," reduzidos"]}),e.jsxs(E,{className:"bg-emerald-500/10 text-emerald-400 border-emerald-500/20 text-[10px]",children:["+",Ue?.budgetFlow?.winnersBoosted||0," escalados"]})]})]}):e.jsx("p",{className:"text-xs text-white/40",children:"Nenhuma realocação nas últimas 24h"})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 space-y-2","data-testid":"global-reach-card",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pt,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Alcance Global"})]}),Ue?.languageCounts&&Object.keys(Ue.languageCounts).length>0?e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(Ue.languageCounts).map(([t,s])=>{const i={"pt-BR":"BR","en-US":"US","es-ES":"ES","fr-FR":"FR","de-DE":"DE","it-IT":"IT"};return e.jsxs(E,{className:"bg-teal-600/15 text-teal-300 border-teal-500/20 text-[10px] gap-1",children:[i[t]||t," ",e.jsx("span",{className:"text-white/40",children:"|"})," ",s," ads"]},t)})}):e.jsx("p",{className:"text-xs text-white/40",children:"Configurar idiomas nas configurações"}),e.jsxs("p",{className:"text-[10px] text-white/30",children:["Idiomas ativos: ",Ue?.targetLanguages||"pt-BR"]}
16)]})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 space-y-3","data-testid":"retargeting-funnel-card",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Funil de Retargeting"}),e.jsx(E,{className:`text-[10px] ${Le?.enableRetargeting?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-white/10 text-white/40 border-white/10"}`,children:Le?.enableRetargeting?"Ativo":"Desativado"})]}),We?e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/5 border border-blue-500/15 text-center space-y-1","data-testid":"funnel-visitantes",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 mb-1",children:[e.jsx(ht,{className:"w-3 h-3 text-blue-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium text-blue-400",children:"Visitantes"})]}),e.jsx("p",{className:"text-xl font-bold text-blue-300",children:We.visitantes||0}),e.jsx("p",{className:"text-[9px] text-white/30",children:"Pixel (30 dias)"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-amber-500/5 border border-amber-500/15 text-center space-y-1","data-testid":"funnel-cadastrados",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 mb-1",children:[e.jsx(Re,{className:"w-3 h-3 text-amber-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium text-amber-400",children:"Cadastrados"})]}),e.jsx("p",{className:"text-xl font-bold text-amber-300",children:We.cadastrados||0}),e.jsx("p",{className:"text-[9px] text-white/30",children:"Sem pedidos"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-orange-500/5 border border-orange-500/15 text-center space-y-1","data-testid":"funnel-carrinho",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 mb-1",children:[e.jsx(Jt,{className:"w-3 h-3 text-orange-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium text-orange-400",children:"Carrinho"})]}),e.jsx("p",{className:"text-xl font-bold text-orange-300",children:We.carrinho||0}),e.jsx("p",{className:"text-[9px] text-white/30",children:"Pedidos pendentes"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-emerald-500/5 border border-emerald-500/15 text-center space-y-1","data-testid":"funnel-crosssell",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 mb-1",children:[e.jsx(Nu,{className:"w-3 h-3 text-emerald-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-medium text-emerald-400",children:"Cross-sell"})]}),e.jsx("p",{className:"text-xl font-bold text-emerald-300",children:We.cross_sell||0}),e.jsx("p",{className:"text-[9px] text-white/30",children:"Compradores"})]})]}):e.jsx("p",{className:"text-xs text-white/40",children:"Carregando dados do funil..."}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs("div",{className:"flex-1 h-1.5 bg-white/5 rounded-full overflow-hidden flex",children:[e.jsx("div",{className:"bg-blue-500/60 h-full",style:{width:We?`${Math.max(5,(We.visitantes||0)/Math.max(1,(We.visitantes||0)+(We.cadastrados||0)+(We.carrinho||0)+(We.cross_sell||0))*100)}%`:"25%"}}),e.jsx("div",{className:"bg-amber-500/60 h-full",style:{width:We?`${Math.max(5,(We.cadastrados||0)/Math.max(1,(We.visitantes||0)+(We.cadastrados||0)+(We.carrinho||0)+(We.cross_sell||0))*100)}%`:"25%"}}),e.jsx("div",{className:"bg-orange-500/60 h-full",style:{width:We?`${Math.max(5,(We.carrinho||0)/Math.max(1,(We.visitantes||0)+(We.cadastrados||0)+(We.carrinho||0)+(We.cross_sell||0))*100)}%`:"25%"}}),e.jsx("div",{className:"bg-emerald-500/60 h-full",style:{width:We?`${Math.max(5,(We.cross_sell||0)/Math.max(1,(We.visitantes||0)+(We.cadastrados||0)+(We.carrinho||0)+(We.cross_sell||0))*100)}%`:"25%"}})]}),e.jsxs("span",{className:"text-[9px] text-white/30 whitespace-nowrap",children:["Total: ",We?(We.visitantes||0)+(We.cadastrados||0)+(We.carrinho||0)+(We.cross_sell||0):0]})]})]}),Ue?.saturationData?.length>0&&e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 space-y-3","data-testid":"saturation-card",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Saturação de Audiência"}),e.jsxs(E,{className:"bg-white/10 text-white/60 border-white/10 text-[10px]",children:[Ue.saturationData.length," ad sets"]})]}),e.jsx("div",{className:"space-y-2.5",children:Ue.saturationData.map(t=>{const s=t.saturationPct||0,i=t.level==="saturated"?"bg-red-500":t.level==="warning"?"bg-amber-500":"bg-emerald-500",x=t.level==="saturated"?"text-red-400":t.level==="warning"?"text-amber-400":"text-emerald-400",C={saturated:"Saturada",
16warning:"Atenção",healthy:"Saudável"};return e.jsxs("div",{className:"p-2.5 rounded-lg bg-white/[0.03] border border-white/5","data-testid":`saturation-item-${t.adSetId}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-white truncate max-w-[60%]",children:t.headline||t.adSetName}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{className:`text-[10px] ${t.level==="saturated"?"bg-red-500/20 text-red-400 border-red-500/30":t.level==="warning"?"bg-amber-500/20 text-amber-400 border-amber-500/30":"bg-emerald-500/20 text-emerald-400 border-emerald-500/30"}`,children:C[t.level]||t.level}),e.jsxs("span",{className:`text-xs font-bold ${x}`,children:[s.toFixed(1),"%"]})]})]}),e.jsx("div",{className:"w-full bg-white/10 rounded-full h-2 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${i}`,style:{width:`${Math.min(s,100)}%`}})}),e.jsxs("div",{className:"flex justify-between mt-1",children:[e.jsxs("span",{className:"text-[10px] text-white/30",children:["Reach: ",(t.totalReach||0).toLocaleString("pt-BR")]}),e.jsxs("span",{className:"text-[10px] text-white/30",children:["Audiência: ",(t.estimatedAudienceSize||0).toLocaleString("pt-BR")]})]})]},t.adSetId)})})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-amber-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"DNA Vencedor"}),e.jsxs(E,{className:"bg-white/10 text-white/60 border-white/10 text-[10px]",children:[Jr?.length||0," winners"]})]}),Jr&&Jr.length>0?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("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium mb-2",children:"Top Ângulos"}),e.jsx("div",{className:"space-y-1.5",children:(()=>{const t={};return Jr.forEach(s=>{s.angle&&(t[s.angle]||(t[s.angle]={count:0,totalRoas:0}),t[s.angle].count++,t[s.angle].totalRoas+=parseFloat(s.roas||"0"))}),Object.entries(t).sort((s,i)=>i[1].totalRoas/i[1].count-s[1].totalRoas/s[1].count).slice(0,5).map(([s,i])=>e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-white/80 truncate",children:s}),e.jsxs("span",{className:"text-emerald-400 font-medium",children:[(i.totalRoas/i.count).toFixed(1),"x ROAS"]})]},s))})()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium mb-2",children:"Top Audiências"}),e.jsx("div",{className:"space-y-1.5",children:(()=>{const t={};return Jr.forEach(s=>{s.targetAudience&&(t[s.targetAudience]||(t[s.targetAudience]={count:0,totalRoas:0}),t[s.targetAudience].count++,t[s.targetAudience].totalRoas+=parseFloat(s.roas||"0"))}),Object.entries(t).sort((s,i)=>i[1].totalRoas/i[1].count-s[1].totalRoas/s[1].count).slice(0,5).map(([s,i])=>e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-white/80 truncate",children:s}),e.jsxs("span",{className:"text-emerald-400 font-medium",children:[(i.totalRoas/i.count).toFixed(1),"x ROAS"]})]},s))})()})]})]}),Ue?.topCreatives?.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium mb-2",children:"Top 3 Criativos Campeões"}),e.jsx("div",{className:"space-y-2",children:Ue.topCreatives.map((t,s)=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg bg-white/[0.03] border border-white/5","data-testid":`top-creative-${s}`,children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-amber-500/20 flex items-center justify-center shrink-0",children:e.jsxs("span",{className:"text-[10px] font-bold text-amber-400",children:["#",s+1]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-white truncate",children:t.headline}),e.jsxs("p",{className:"text-[10px] text-white/40",children:[t.angle," | ",t.audience]})]}),e.jsxs("div",{className:"flex gap-3 shrink-0 text-[10px]",children:[e.jsxs("span",{className:"text-emerald-400 font-medium",children:[t.roas,"x"]}),e.jsxs("span",{className:"text-white/50",children:["CTR ",t.ctr,"%"]}),e.jsxs("span",{className:"text-white/50",children:[t.conversions||0," conv"]})]})]},s))})]})]}):e.jsx("p",{className:"text-xs text-white/40 text-center py-4",children:"Nenhum criativo campeão ainda. A IA precisa de dados para aprender."})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 space-y-3","data-testid":"ab-test-results-card",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Testes A/B Estruturados"}),e.jsxs(E,{className:"bg-white/10 text-white/60 border-white/10 text-[10px]",children:[xl?.length||0," grupos"]})]}),xl&&xl.length>0?e.jsx("div",{className:"space-y-3",children:xl.slice(0,5).map(t=>{const s={headline:"Headline",image:"Imagem",audience:"Audiência",cta:"CTA/Ângulo"},i=t.variants.sort((x,C)=>parseFloat(C.roas||"0")-parseFloat(x.roas||"0"))[0];return e.jsxs("div",{className:"border border-white/5 rounded-lg p-3 bg-white/[0.01] space-y-2","data-testid":`ab-group-${t.testGroup}`,children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{className:"bg-teal-600/20 text-teal-400 border-teal-500/30 text-[10px]",children:s[t.testVariable]||t.testVariable}),e.jsx("span",{className:"text-[10px] text-white/40 font-mono",children:t.testGroup})]}),e.jsxs("span",{className:"text-[10px] text-white/30",children:[t.variants.length," variante(s)"]})]}),t.control&&e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded bg-amber-500/5 border border-amber-500/10",children:[e.jsx(wn,{className:"w-3 h-3 text-amber-400 shrink-0"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("p",{className:"text-[11px] text-amber-300 font-medium truncate",children:["Controle: ",t.control.headline]})}),e.jsxs("div",{className:"flex gap-2 shrink-0 text-[10px]",children:[e.jsxs("span",{className:"text-emerald-400",children:[t.control.roas,"x"]}),e.jsxs("span",{className:"text-white/40",children:["CTR ",t.control.ctr,"%"]}),e.jsxs("span",{className:"text-white/40",children:[t.control.conversions," conv"]})]})]}),e.jsx("div",{className:"space-y-1",children:t.variants.map((x,C)=>e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded ${x.id===i?.id&&parseFloat(x.roas||"0")>0?"bg-emerald-500/5 border border-emerald-500/10":"bg-white/[0.02]"}`,"data-testid":`ab-variant-${x.id}`,children:[e.jsx("div",{className:"w-5 h-5 rounded-full bg-white/10 flex items-center justify-center shrink-0",children:e.jsxs("span",{className:"text-[9px] font-bold text-white/60",children:["V",C+1]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[11px] text-white/80 truncate",children:x.headline}),e.jsxs("p",{className:"text-[9px] text-white/30",children:[x.angle," | ",x.targetAudience," | ",x.style]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 text-[10px]",children:[e.jsxs("span",{className:parseFloat(x.roas||"0")>=parseFloat(t.control?.roas||"0")?"text-emerald-400 font-medium":"text-white/50",children:[x.roas,"x"]}),e.jsxs("span",{className:"text-white/40",children:["CTR ",x.ctr,"%"]}),e.jsxs("span",{className:"text-white/40",children:[x.conversions," conv"]}),e.jsx(E,{className:`text-[9px] ${x.insightStatus==="winner"?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":x.insightStatus==="loser"?"bg-red-500/20 text-red-400 border-red-500/30":x.insightStatus==="testing"?"bg-blue-500/20 text-blue-400 border-blue-500/30":"bg-white/10 text-white/40 border-white/10"}`,children:x.insightStatus==="winner"?"Vencedor":x.insightStatus==="loser"?"Perdedor":x.insightStatus==="testing"?"Testando":x.insightStatus})]})]},x.id))})]},t.testGroup)})}):e.jsx("p",{className:"text-xs text-white/40 text-center py-4",children:"Nenhum teste A/B estruturado ainda. A IA criará testes automaticamente quando houver criativos campeões."})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Log de Atividades"})]}),e.jsx("div",{className:"flex gap-1",children:[{val:"all",label:"Todas"},{val:"green",label:"Verdes"},{val:"blue",label:"Azuis"},{val:"red",label:"Vermelhas"}].map(t=>e.jsx("button",{onClick:()=>Ap(t.val),className:`px-2 py-1 rounded text-[10px] font-medium transition-colors ${Md===t.val?"bg-teal-600/20 text-teal-400 border border-teal-500/30":"text-white/40 hover:text-white/60 border border-transparent"}`,"data-testid":`btn-log-filter-${t.val}`,children:t.label},t.val))})]}),e.jsx("div",{className:"max-h-[600px] overflow-y-auto space-y-2 pr-1",children:lo&&lo.length>0?lo.filter(t=>
16Md==="all"||t.severity===Md).map(t=>e.jsx("div",{className:"group",children:e.jsxs("div",{className:"flex items-start gap-2.5 py-2 px-2 rounded-lg hover:bg-white/[0.03] transition-colors cursor-pointer",onClick:()=>Pp(Lx===t.id?null:t.id),"data-testid":`log-entry-${t.id}`,children:[e.jsx("div",{className:`w-2.5 h-2.5 rounded-full mt-1 shrink-0 ${t.severity==="green"?"bg-emerald-500":t.severity==="blue"?"bg-blue-500":"bg-red-500"}`}),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-[10px] text-white/30 font-mono",children:t.createdAt?new Date(t.createdAt).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):""}),e.jsx("span",{className:"text-xs font-semibold text-white",children:t.action}),t.metadata?.learningPhase&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-bold bg-blue-500/20 text-blue-400 border border-blue-500/30","data-testid":`badge-learning-${t.id}`,children:"Aprendizado"}),t.metadata?.safetyValveTriggered&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30","data-testid":`badge-safety-valve-${t.id}`,children:"Segurança"}),t.metadata?.learningLimited&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-bold bg-orange-500/20 text-orange-400 border border-orange-500/30","data-testid":`badge-learning-limited-${t.id}`,children:"Limitado"})]}),e.jsx("p",{className:"text-[11px] text-white/50 mt-0.5 line-clamp-2",children:t.justification}),Lx===t.id&&t.metadata&&e.jsx("div",{className:"mt-2 p-2 rounded bg-white/[0.03] border border-white/5",children:e.jsx("pre",{className:"text-[10px] text-white/40 font-mono whitespace-pre-wrap break-all",children:JSON.stringify(t.metadata,null,2)})})]})]})},t.id)):e.jsx("p",{className:"text-xs text-white/40 text-center py-8",children:"Nenhuma atividade registrada ainda."})})]})]}),Qe==="intelligence"&&e.jsx(Ju,{}),Qe==="multiplicador"&&e.jsx(Zu,{}),Qe==="instagram"&&e.jsx(Qb,{}),Qe==="config"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vb,{}),e.jsxs("div",{className:"border border-amber-500/20 rounded-xl bg-amber-500/[0.03] p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4 text-amber-400"}),e.jsx("h3",{className:"text-sm font-bold text-white",children:"Google Analytics 4"}),Qd.gaTrackingId?e.jsx(E,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-[10px]",children:"Ativo"}):e.jsx(E,{className:"bg-white/10 text-white/40 border-white/10 text-[10px]",children:"Não configurado"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Measurement ID (ID de medição)"}),e.jsx(J,{value:Qd.gaTrackingId,onChange:t=>sm(s=>({...s,gaTrackingId:t.target.value})),placeholder:"G-XXXXXXXXXX",className:"border-white/10 bg-white/5 text-xs font-mono","data-testid":"input-ga-tracking-id"}),e.jsx("p",{className:"text-[10px] text-white/25 mt-1",children:"Cole o ID de medição do Google Analytics 4 (começa com G-). Tracking automático de pageviews, eventos, conversões e e-commerce."})]}),e.jsxs("div",{className:"text-[10px] text-white/30 space-y-1",children:[e.jsx("p",{className:"font-medium text-white/50",children:"Eventos rastreados automaticamente:"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:["page_view","sign_up","login","view_item","begin_checkout","purchase","generate_lead","file_download","scroll","form_interaction","support_chat","book_created","plan_generated","cover_generated","cta_click"].map(t=>e.jsx("span",{className:"px-1.5 py-0.5 bg-white/5 rounded text-white/40 font-mono",children:t},t))})]}),e.jsx("div",{className:"flex gap-2 pt-2",children:e.jsxs(b,{size:"sm",className:"bg-amber-600 hover:bg-amber-700 gap-1 text-xs",onClick:()=>go.mutate({gaTrackingId:Qd.gaTrackingId}),disabled:go.isPending,children:[go.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(is,{className:"w-3 h-3"})," Salvar GA4"]})})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-4 space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Pré-requisitos"}),e.jsx("div",{className:"space-y-2",children:["Conta no Meta Business Manager com Business Verification","App registrado em developers.facebook.com com Marketing API ativada","Permissões ads_management e ads_read aprovadas (App Review)","Método de pagamento configurado na conta de anúncios","System User criado com token sem expiração"].map((t,s)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(is,{className:"w-3.5 h-3.5 text-white/20 shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-white/50",children:t})]},s))})]})]})]}),e.jsxs(Be,{value:"support",className:"mt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[[["chat","Chat IA"],["email","Email IA"],["kb","Base de Conhecimento"]].map(([t,s])=>e.jsxs("button",{onClick:()=>{w0(t),yo(null),Eo(null)},className:`px-4 py-1.5 rounded-lg text-xs font-medium transition-colors border ${di===t?"bg-teal-600/20 text-teal-400 border-teal-500/30":"bg-white/5 text-white/60 border-white/10 hover:bg-white/10"}`,"data-testid":`btn-support-view-${t}`,children:[t==="chat"?e.jsx(Ut,{className:"w-3.5 h-3.5 inline mr-1.5"}):t==="email"?e.jsx(Ge,{className:"w-3.5 h-3.5 inline mr-1.5"}):e.jsx(ot,{className:"w-3.5 h-3.5 inline mr-1.5"}),s]},t)),di==="email"&&e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-white/50",children:"IA Email Global:"}),e.jsx(rt,{checked:zo?.value!=="false",onCheckedChange:t=>$0.mutate(t),"data-testid":"switch-ai-email-global"}),e.jsx("span",{className:`text-xs font-medium ${zo?.value!=="false"?"text-emerald-400":"text-red-400"}`,children:zo?.value!=="false"?"Ativa":"Desativada"})]})]}),di==="email"?e.jsxs("div",{className:"flex gap-0 border border-white/10 rounded-xl overflow-hidden",style:{height:"calc(100vh - 330px)",minHeight:"400px"},children:[e.jsxs("div",{className:`w-full md:w-[350px] md:min-w-[350px] border-r border-white/10 flex flex-col bg-white/[0.02] ${Os?"hidden md:flex":"flex"}`,children:[e.jsx("div",{className:"p-4 border-b border-white/10 space-y-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Conversas por Email"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(Oo??[]).length," total"]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:(Oo??[]).length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm p-4 text-center",children:e.jsxs("div",{children:[e.jsx(Ge,{className:"w-10 h-10 mx-auto opacity-20 mb-2"}),e.jsx("p",{children:"Nenhuma conversa por email"}),e.jsx("p",{className:"text-[10px] mt-1 text-white/30",children:"Quando clientes responderem emails, as conversas aparecem aqui"})]})}):(Oo??[]).map(t=>{const s=Os===t.id,i={active:"bg-emerald-400",waiting_human:"bg-amber-400",closed:"bg-white/20"},x=t.lastMessageAt?new Date(t.lastMessageAt):null;let C="";if(x){const P=Date.now()-x.getTime(),H=Math.floor(P/6e4),Q=Math.floor(P/36e5),G=Math.floor(P/864e5);H<1?C="agora":H<60?C=`${H}min`:Q<24?C=`${Q}h`:C=`${G}d`}return e.jsx("button",{onClick:()=>Eo(t.id),className:`w-full text-left p-3 border-b border-white/5 transition-colors ${s?"bg-white/10":"hover:bg-white/[0.04]"}`,"data-testid":`btn-email-conv-${t.id}`,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:"flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${i[t.status]||"bg-white/20"}`}),e.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.contactName||t.contactEmail})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:t.subject||"Sem assunto"}),e.jsx("p",{className:"text-[10px] text-white/30 mt-0.5 truncate",children:t.contactEmail})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:C}),e.jsx(E,{variant:"outline",className:`text-[9px] ${t.status==="active"?"text-emerald-400 border-emerald-500/30":t.status==="waiting_human"?"text-amber-400 border-amber-500/30":"text-white/40 border-white/10"}`,children:t.status==="active"?"IA Ativa":t.status==="waiting_human"?"Aguardando":"Fechada"})]})]})},t.id)})})]}),e.jsx("div",{className:`flex-1 flex flex-col bg-white/[0.01] ${Os?"flex":"hidden md:flex"}`,children:Os?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-4 border-b border-white/10 bg-white/[0.03]",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>Eo(null),className:"md:hidden p-1.5 rounded-lg hover:bg-white/10 transition-colors text-white/60","data-testid":"btn-email-back-mobile",children:e.jsx(Jm,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-white","data-testid":"text-email-conv-name",children:oi?.conversation?.contactName||oi?.conversation?.contactEmail||"..."}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:oi?.conversation?.contactEmail}),oi?.user&&e.jsx("span",{className:"text-[10px] text-teal-400 bg-teal-500/10 px-1.5 py-0.5 rounded",children:"Cliente cadastrado"})]}),e.jsxs("p",{className:"text-xs text-white/40 mt-1",children:["Assunto: ",oi?.conversation?.subject||"—"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[oi?.conversation?.status==="active"?e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-amber-500/30 text-amber-400 hover:bg-amber-500/10",onClick:()=>Uo.mutate({id:Os,status:"waiting_human"}),"data-testid":"btn-pause-email-ai",children:[e.jsx(Ce,{className:"w-3 h-3"})," Pausar IA"]}):oi?.conversation?.status==="waiting_human"?e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/10",onClick:()=>Uo.mutate({id:Os,status:"active"}),"data-testid":"btn-resume-email-ai",children:[e.jsx(He,{className:"w-3 h-3"})," Reativar IA"]}):null,e.jsx(b,{size:"sm",variant:"outline",className:"text-xs gap-1 border-white/10 text-white/50",onClick:()=>Uo.mutate({id:Os,status:"closed"}),"data-testid":"btn-close-email-conv",children:"Fechar"})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-3","data-testid":"email-messages-area",ref:t=>{t&&(t.scrollTop=t.scrollHeight)},children:(oi?.messages??[]).map((t,s)=>{const i=t.direction==="inbound",x=t.createdAt?new Date(t.createdAt).toLocaleStr
16ing("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";return e.jsx("div",{className:`flex ${i?"justify-start":"justify-end"}`,children:e.jsxs("div",{className:`max-w-[85%] md:max-w-[75%] rounded-xl px-4 py-3 ${i?"bg-white/5 text-white/90 border border-white/10":"bg-teal-600/20 text-white border border-teal-500/20"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium text-white/50",children:i?t.fromEmail:"SÁBHIA"}),!i&&t.aiGenerated&&e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/20",children:"IA"}),!i&&!t.aiGenerated&&e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-blue-500/20 text-blue-300 border border-blue-500/20",children:"Manual"})]}),t.subject&&e.jsxs("p",{className:"text-[10px] text-white/30 mb-1",children:["Assunto: ",t.subject]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t.textContent||"(sem conteúdo de texto)"}),e.jsxs("p",{className:`text-[10px] mt-2 ${i?"text-white/30":"text-teal-300/50"}`,children:[x,t.status==="failed"&&e.jsx("span",{className:"text-red-400 ml-2",children:"Falhou"})]})]})},t.id||s)})}),e.jsx("div",{className:"p-3 border-t border-white/10 bg-white/[0.03]",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{value:Io,onChange:t=>Em(t.target.value),placeholder:"Escrever resposta manual...",className:"flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white resize-none focus:outline-none focus:ring-1 focus:ring-teal-500/50 placeholder:text-white/20",rows:2,"data-testid":"input-email-reply"}),e.jsxs(b,{className:"bg-teal-600 hover:bg-teal-700 self-end gap-1",size:"sm",disabled:!Io.trim()||Bo.isPending,onClick:()=>Bo.mutate({id:Os,body:Io}),"data-testid":"btn-send-email-reply",children:[Bo.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(ct,{className:"w-3 h-3"}),"Enviar"]})]})})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Ge,{className:"w-10 h-10 mx-auto opacity-30"}),e.jsx("p",{className:"text-sm",children:"Selecione uma conversa por email"})]})})})]}):di==="kb"?e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4 text-teal-400"}),"Base de Conhecimento do Suporte"]}),e.jsx("p",{className:"text-[11px] text-white/40 mt-1",children:"Converse com a IA para ensinar regras e informações. Ela organiza tudo automaticamente na base de conhecimento."})]}),e.jsxs(E,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-400 border-teal-500/30",children:[(Al||[]).filter(t=>t.isActive).length," ativa(s)"]})]}),e.jsxs("div",{className:"border border-white/10 rounded-lg bg-gradient-to-b from-white/[0.03] to-white/[0.01] overflow-hidden mb-4","data-testid":"kb-chat-container",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 border-b border-white/10 bg-white/[0.02]",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-gradient-to-br from-teal-500 to-teal-700 flex items-center justify-center",children:e.jsx(Ut,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:"text-xs font-medium text-white/70",children:"Chat com a IA"}),e.jsx("span",{className:"text-[10px] text-white/30 ml-auto",children:"Ensine regras, políticas e informações"})]}),e.jsxs("div",{className:"h-[240px] overflow-y-auto p-4 space-y-3","data-testid":"kb-chat-messages",children:[Ro.length===0&&e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-gradient-to-br from-teal-500 to-teal-700 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(qe,{className:"w-3.5 h-3.5 text-white"})}),e.jsx("div",{className:"bg-white/[0.05] rounded-xl rounded-tl-sm px-3.5 py-2.5 max-w-[85%]",children:e.jsx("p",{className:"text-[12px] text-white/70 leading-relaxed",children:"Olá! Sou sua assistente de gestão da base de conhecimento. Me diga o que a IA de suporte deve saber — regras, informações, como lidar com situações específicas — e eu organizo tudo automaticamente!"})})]}),Ro.map((t,s)=>e.jsxs("div",{className:`flex ${t.role==="user"?"justify-end":"items-start gap-2.5"}`,children:[t.role!=="user"&&e.jsx("div",{className:"w-7 h-7 rounded-full bg-gradient-to-br from-teal-500 to-teal-700 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(qe,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:`rounded-xl px-3.5 py-2.5 max-w-[85%] ${t.role==="user"?"bg-gradient-to-r from-violet-600/80 to-violet-700/80 rounded-tr-sm":"bg-white/[0.05] rounded-tl-sm"}`,children:[t.role==="user"&&e.jsx("p",{className:"text-[10px] font-semibold text-violet-300 mb-0.5",children:"Admin"}),e.jsx("p",{className:"text-[12px] text-white/80 leading-relaxed whitespace-pre-wrap",children:t.content}),t.action&&t.action.type!=="none"&&e.jsx("div",{className:`mt-2 pt-2 border-t ${t.role==="user"?"border-white/10":"border-white/5"}`,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[t.action.type==="created"?e.jsx(_t,{className:"w-3 h-3 text-emerald-400"}):e.jsx(Ga,{className:"w-3 h-3 text-amber-400"}),e.jsxs("span",{className:`text-[10px] font-medium ${t.action.type==="created"?"text-emerald-400":"text-amber-400"}`,children:[t.action.type==="created"?"Nova entrada criada":"Entrada atualizada",": ",t.action.title]})]})})]})]},s)),nn&&e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-gradient-to-br from-teal-500 to-teal-700 flex items-center justify-center flex-shrink-0",children:e.jsx(qe,{className:"w-3.5 h-3.5 text-white"})}),e.jsx("div",{className:"bg-white/[0.05] rounded-xl rounded-tl-sm px-4 py-3",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-teal-400/60 animate-bounce",style:{animationDelay:"0ms"}}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-teal-400/60 animate-bounce",style:{animationDelay:"150ms"}}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-teal-400/60 animate-bounce",style:{animationDelay:"300ms"}})]})})]}),e.jsx("div",{ref:Lo})]}),e.jsxs("form",{className:"flex items-center gap-2 px-3 py-2.5 border-t border-white/10 bg-white/[0.02]",onSubmit:async t=>{t.preventDefault();const s=Do.trim();if(!(!s||nn)){Im(""),Fo(i=>[...i,{role:"user",content:s}]),Rm(!0),setTimeout(()=>Lo.current?.scrollIntoView({behavior:"smooth"}),50);try{const i=Ro.map(P=>({role:P.role==="user"?"user":"model",content:P.content})),C=await(await N("POST","/api/admin/support/knowledge-base/chat",{message:s,history:i})).json();Fo(P=>[...P,{role:"assistant",content:C.reply,action:C.action}]),(C.action?.type==="created"||C.action?.type==="updated")&&K.invalidateQueries({queryKey:["/api/admin/support/knowledge-base"]})}catch{Fo(x=>[...x,{role:"assistant",content:"Desculpe, houve um erro. Tente novamente."}])}finally{Rm(!1),setTimeout(()=>Lo.current?.scrollIntoView({behavior:"smooth"}),50)}}},"data-testid":"kb-chat-form",children:[e.jsx("input",{type:"text",value:Do,onChange:t=>Im(t.target.value),placeholder:"Ensine algo para a IA de suporte...",className:"flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder:text-white/25 focus:outline-none focus:ring-1 focus:ring-teal-500/50",disabled:nn,"data-testid":"input-kb-chat"}),e.jsx(b,{type:"submit",size:"sm",className:"bg-teal-600 hover:bg-teal-700 h-9 w-9 p-0",disabled:!Do.trim()||nn,"data-testid":"btn-kb-chat-send",children:nn?e.jsx(T,{className:"w-4 h-4 animate-spin"}):e.jsx(ct,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("button",{onClick:()=>
16y0(!Mo),className:"flex items-center gap-2 text-xs text-white/40 hover:text-white/60 transition-colors","data-testid":"btn-kb-toggle-manual",children:[Mo?e.jsx(ta,{className:"w-3.5 h-3.5"}):e.jsx(Ct,{className:"w-3.5 h-3.5"}),"Adicionar entrada manualmente"]}),Mo&&e.jsxs("div",{className:"border border-white/10 rounded-lg bg-white/[0.03] p-4 space-y-3 mt-2",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block text-white/60",children:"Título / Assunto"}),e.jsx(J,{value:ma.title,onChange:t=>qi(s=>({...s,title:t.target.value})),placeholder:"Ex: Política de reembolso, Como funciona a escrita...",className:"border-white/10 bg-white/5 text-sm","data-testid":"input-kb-title"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block text-white/60",children:"Categoria"}),e.jsxs(Se,{value:ma.category,onValueChange:t=>qi(s=>({...s,category:t})),children:[e.jsx($e,{className:"border-white/10 bg-white/5","data-testid":"select-kb-category",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"geral",children:"Geral"}),e.jsx(U,{value:"servicos",children:"Serviços"}),e.jsx(U,{value:"precos",children:"Preços"}),e.jsx(U,{value:"politicas",children:"Políticas"}),e.jsx(U,{value:"faq",children:"FAQ"}),e.jsx(U,{value:"tecnico",children:"Técnico"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block text-white/60",children:"Conteúdo"}),e.jsx("textarea",{value:ma.content,onChange:t=>qi(s=>({...s,content:t.target.value})),placeholder:"Escreva aqui as informações que a IA deve saber. Pode incluir regras, explicações, respostas padrão, etc.",className:"w-full min-h-[100px] rounded-md border border-white/10 bg-white/5 text-sm text-white p-3 placeholder:text-white/20 focus:outline-none focus:ring-1 focus:ring-teal-500/50 resize-y","data-testid":"textarea-kb-content"})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[$l&&e.jsx(b,{variant:"outline",size:"sm",className:"border-white/10 text-white/60",onClick:()=>{To(null),qi({title:"",content:"",category:"geral"})},"data-testid":"btn-kb-cancel-edit",children:"Cancelar"}),e.jsxs(b,{size:"sm",className:"bg-teal-600 hover:bg-teal-700 gap-1.5",disabled:!ma.title.trim()||!ma.content.trim()||qo.isPending||_o.isPending,onClick:()=>{$l?_o.mutate({id:$l,title:ma.title,content:ma.content,category:ma.category}):qo.mutate({title:ma.title,content:ma.content,category:ma.category})},"data-testid":"btn-kb-save",children:[qo.isPending||_o.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(_t,{className:"w-3.5 h-3.5"}),$l?"Salvar Alterações":"Adicionar"]})]})]})]}),k0?e.jsx("div",{className:"flex justify-center p-8",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-teal-400"})}):!Al||Al.length===0?e.jsxs("div",{className:"text-center py-8 border border-dashed border-white/10 rounded-lg",children:[e.jsx(ot,{className:"w-10 h-10 text-white/10 mx-auto mb-2"}),e.jsx("p",{className:"text-white/40 text-sm",children:"Nenhuma entrada na base de conhecimento"}),e.jsx("p",{className:"text-white/25 text-xs mt-1",children:"Adicione informações acima para melhorar as respostas da IA"})]}):e.jsx("div",{className:"space-y-2",children:Al.map(t=>e.jsx("div",{className:`border rounded-lg p-3 transition-colors ${t.isActive?"border-white/10 bg-white/[0.02]":"border-white/5 bg-white/[0.01] opacity-50"}`,"data-testid":`kb-entry-${t.id}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:"text-sm font-medium text-white truncate",children:t.title}),e.jsx(E,{variant:"outline",className:"text-[9px] bg-white/5 text-white/40 border-white/10 shrink-0",children:t.category||"geral"})]}),e.jsx("p",{className:"text-xs text-white/50 line-clamp-2 whitespace-pre-wrap",children:t.content}),e.jsx("p",{className:"text-[9px] text-white/20 mt-1.5",children:t.updatedAt?`Atualizado: ${new Date(t.updatedAt).toLocaleDateString("pt-BR")}`:""})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(rt,{checked:t.isActive,onCheckedChange:s=>S0.mutate({id:t.id,isActive:s}),"data-testid":`switch-kb-active-${t.id}`,className:"scale-75"}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-white/40 hover:text-white",onClick:()=>
16{To(t.id),qi({title:t.title,content:t.content,category:t.category||"geral"})},"data-testid":`btn-kb-edit-${t.id}`,children:e.jsx(Ga,{className:"w-3.5 h-3.5"})}),e.jsxs(pi,{children:[e.jsx(ui,{asChild:!0,children:e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-red-400/50 hover:text-red-400","data-testid":`btn-kb-delete-${t.id}`,children:e.jsx(As,{className:"w-3.5 h-3.5"})})}),e.jsxs(gi,{className:"bg-[#1a1a2e] border-white/10",children:[e.jsxs(bi,{children:[e.jsx(ji,{className:"text-white",children:"Remover entrada?"}),e.jsxs(vi,{className:"text-white/60",children:['A entrada "',t.title,'" será removida permanentemente da base de conhecimento da IA de suporte.']})]}),e.jsxs(Ni,{children:[e.jsx(fi,{className:"bg-white/5 border-white/10 text-white hover:bg-white/10",children:"Cancelar"}),e.jsx(wi,{className:"bg-red-600 hover:bg-red-700",onClick:()=>C0.mutate(t.id),children:"Remover"})]})]})]})]})]})},t.id))})]})}):e.jsxs("div",{className:"flex gap-0 border border-white/10 rounded-xl overflow-hidden",style:{height:"calc(100vh - 330px)",minHeight:"400px"},children:[e.jsxs("div",{className:`w-full md:w-[350px] md:min-w-[350px] border-r border-white/10 flex flex-col bg-white/[0.02] ${us?"hidden md:flex":"flex"}`,children:[e.jsxs("div",{className:"p-4 border-b border-white/10 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Conversas"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{"data-testid":"text-support-total",children:[Sl?.totalAll??0," total"]}),e.jsxs("span",{className:"text-emerald-400","data-testid":"text-support-active",children:[Sl?.totalActive??0," ativas"]}),e.jsxs("div",{className:"relative",ref:ko,children:[e.jsx("button",{onClick:()=>en(!yl),className:"p-1 rounded hover:bg-white/10 transition-colors text-white/50 hover:text-white/80",title:"Exportar conversas (CSV)","data-testid":"button-export-all-conversations",children:e.jsx(Rt,{className:"w-3.5 h-3.5"})}),yl&&e.jsxs("div",{className:"absolute right-0 top-8 z-50 w-64 rounded-xl border border-white/10 bg-[#1a1a2e] shadow-2xl overflow-hidden",style:{backdropFilter:"blur(12px)"},children:[e.jsx("div",{className:"px-3 py-2 border-b border-white/10",children:e.jsx("span",{className:"text-[11px] font-semibold text-white/60 uppercase tracking-wider",children:"Exportar CSV por período"})}),e.jsx("div",{className:"py-1",children:[["Hoje",0,0],["Ontem",1,1],["Últimos 2 dias",1,0],["Últimos 3 dias",2,0],["Últimos 7 dias",6,0],["Últimos 15 dias",14,0],["Últimos 30 dias",29,0]].map(([t,s,i])=>{const x=new Date;x.setDate(x.getDate()-s);const C=new Date;C.setDate(C.getDate()-i);const P=x.toISOString().slice(0,10),H=C.toISOString().slice(0,10);return e.jsxs("button",{onClick:()=>{window.open(`/api/admin/support/conversations-export-all?from=${P}&to=${H}`,"_blank"),r({title:"Preparando export…",description:`Período: ${t}. O download começa em alguns segundos.`}),en(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-white/80 hover:bg-white/10 hover:text-white transition-colors flex items-center gap-2","data-testid":`btn-export-period-${t}`,children:[e.jsx(Ec,{className:"w-3 h-3 text-white/40"}),t]},t)})}),e.jsxs("div",{className:"border-t border-white/10 px-3 py-2.5 space-y-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-white/60 uppercase tracking-wider",children:"Período personalizado"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"date",value:tn,onChange:t=>g0(t.target.value),className:"flex-1 bg-white/5 border border-white/10 rounded-lg px-2 py-1.5 text-[11px] text-white outline-none focus:border-emerald-500/50","data-testid":"input-export-from"}),e.jsx("input",{type:"date",value:sn,onChange:t=>b0(t.target.value),className:"flex-1 bg-white/5 border border-white/10 rounded-lg px-2 py-1.5 text-[11px] text-white outline-none focus:border-emerald-500/50","data-testid":"input-export-to"})]}),e.jsxs("button",{onClick:()=>{if(tn){const t=new URLSearchParams;t.set("from",tn),sn&&t.set("to",sn),window.open(`/api/admin/support/conversations-export-all?${t.toString()}`,"_blank"),r({title:"Preparando export…",description:`Período: ${tn}${sn?` → ${sn}`:""}.`}),en(!1)}},disabled:!tn,className:"w-full py-1.5 rounded-lg text-[11px] font-semibold transition-colors flex items-center justify-center gap-1.5 disabled:opacity-30 disabled:cursor-not-allowed bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 hover:bg-emerald-500/30","data-testid":"btn-export-custom",children:[e.jsx(Rt,{className:"w-3 h-3"}),"Exportar período"]})]}),e.jsx("div",{className:"border-t border-white/10",children:e.jsxs("button",{onClick:()=>{window.confirm(`Exportar TODAS as conversas (todo o histórico)?
17
18Esse export pode ser grande e demorar até 1 minuto. Para janelas curtas use os atalhos acima.`)&&(window.open("/api/admin/support/conversations-export-all?all=1","_blank"),r({title:"Preparando export completo…",description:"Pode levar até 1 minuto. O download começa automaticamente."}),en(!1))},className:"w-full text-left px-3 py-2 text-[12px] text-white/50 hover:bg-white/10 hover:text-white transition-colors flex items-center gap-2","data-testid":"btn-export-all",children:[e.jsx(Rt,{className:"w-3 h-3"}),"Exportar tudo (todo histórico)"]})})]})]})]})]}),e.jsx("div",{className:"flex gap-1",children:[["all","Todas"],["active","Ativas"],["closed","Encerradas"]].map(([t,s])=>e.jsx("button",{onClick:()=>u0(t),className:`px-3 py-1 rounded-full text-xs font-medium transition-colors ${wl===t?"bg-emerald-500/20 text-emerald-400 border border-emerald-500/30":"bg-white/5 text-white/60 border border-white/10 hover:bg-white/10"}`,"data-testid":`button-support-filter-${t}`,children:s},t))})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:(Sl?.conversations??[]).length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Nenhuma conversa encontrada"}):(Sl?.conversations??[]).map(t=>{const s=us===t.id,i=t.lastMessageAt?new Date(t.lastMessageAt):t.createdAt?new Date(t.createdAt):null,x=new Date;let C="";if(i){const P=x.getTime()-i.getTime(),H=Math.floor(P/6e4),Q=Math.floor(P/36e5),G=Math.floor(P/864e5);H<1?C="agora":H<60?C=`${H} min`:Q<24?C=`${Q}h`:G===1?C="ontem":C=`${G}d`}return e.jsx("button",{onClick:()=>yo(t.id),className:`w-full text-left p-3 border-b border-white/5 transition-colors ${s?"bg-white/10":"hover:bg-white/[0.04]"}`,"data-testid":`button-conversation-${t.id}`,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:"flex items-center gap-2",children:[t.status==="active"&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 flex-shrink-0"}),e.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.user?.name||t.user?.email||"Usuário"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:t.summary||t.lastMessage||"Sem mensagens"}),t.messageCount>0&&e.jsxs("span",{className:"text-[10px] text-white/25 mt-0.5",children:[t.messageCount," msg",t.messageCount>1?"s":""]})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground whitespace-nowrap flex-shrink-0 mt-0.5",children:C})]})},t.id)})})]}),e.jsx("div",{className:`flex-1 flex flex-col bg-white/[0.01] ${us?"flex":"hidden md:flex"}`,children:us?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-4 border-b border-white/10 bg-white/[0.03]",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>yo(null),className:"md:hidden p-1.5 rounded-lg hover:bg-white/10 transition-colors text-white/60","data-testid":"btn-chat-back-mobile",children:e.jsx(Jm,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-white","data-testid":"text-support-user-name",children:Hs?.user?.name||Hs?.user?.email||"Carregando..."}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground","data-testid":"text-support-user-email",children:Hs?.user?.email}),Hs?.booksCount!==void 0&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ot,{className:"w-3 h-3"})," ",Hs.booksCount," livros"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:()=>window.open(`/api/admin/support/conversations/${us}/export`,"_blank"),className:"p-1.5 rounded hover:bg-white/10 transition-colors text-white/50 hover:text-white/80",title:"Exportar conversa (.txt)","data-testid":"button-export-conversation",children:e.jsx(Rt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:async()=>{const t=!Hs?.conversation?.aiPaused;try{await N("PATCH",`/api/admin/support/conversations/${us}/ai-status`,{aiPaused:t}),K.invalidateQueries({queryKey:["/api/admin/support/conversations",us]}),r({description:t?"IA pausada — você está no controle":"IA reativada"})}catch{}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${Hs?.conversation?.aiPaused?"bg-amber-500/20 text-amber-400 border border-amber-500/30 hover:bg-amber-500/30":"bg-teal-500/20 text-teal-400 border border-teal-500/30 hover:bg-teal-500/30"}`,"data-testid":"button-toggle-ai",children:Hs?.conversation?.aiPaused?e.
18jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"w-3 h-3"})," IA Pausada"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"w-3 h-3"})," IA Ativa"]})}),e.jsx(E,{variant:"outline",className:Hs?.conversation?.status==="active"?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-white/10 text-white/60 border-white/10",children:Hs?.conversation?.status==="active"?"Ativa":"Encerrada"})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-3","data-testid":"support-messages-area",ref:t=>{t&&(t.scrollTop=t.scrollHeight)},children:(Hs?.messages??[]).map((t,s)=>{const i=t.role==="user",x=t.actionType==="admin_message",C=t.createdAt?new Date(t.createdAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";return e.jsx("div",{className:`flex ${i?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[85%] md:max-w-[70%] rounded-xl px-3 py-2 ${i?"bg-emerald-600/30 text-white":x?"bg-violet-600/25 text-white border border-violet-500/20":"bg-white/5 text-white/90"}`,children:[x&&e.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium bg-violet-500/20 text-violet-400 border border-violet-500/30 mb-1",children:"Admin"}),t.actionType&&!x&&e.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium bg-blue-500/20 text-blue-400 border border-blue-500/30 mb-1",children:t.actionType}),e.jsx("div",{className:"text-sm whitespace-pre-wrap",children:t.content.split(/(\[IMG:[^\]]+\])/g).map((P,H)=>{const Q=P.match(/^\[IMG:([^\]]+)\]$/);return Q?e.jsx("img",{src:Q[1],alt:"",className:"max-w-full rounded-lg mt-1 mb-1 cursor-pointer hover:opacity-90 transition-opacity",style:{maxHeight:"300px"},onClick:()=>window.open(Q[1],"_blank")},H):P?e.jsx("span",{children:P},H):null})}),e.jsx("p",{className:`text-[10px] mt-1 ${i?"text-emerald-300/60":x?"text-violet-300/60":"text-white/30"}`,children:C})]})},t.id||s)})}),e.jsxs("div",{className:"p-3 border-t border-white/10 bg-white/[0.03]",children:[Co.length>0&&e.jsx("div",{className:"flex gap-2 mb-2 flex-wrap",children:Co.map((t,s)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:t,alt:"",className:"w-16 h-16 object-cover rounded-lg border border-violet-500/30"}),e.jsx("button",{type:"button",onClick:()=>kl(i=>i.filter((x,C)=>C!==s)),className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-red-500 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(ea,{className:"w-2.5 h-2.5 text-white"})})]},s))}),j0&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-xs text-violet-400",children:[e.jsx(T,{className:"w-3 h-3 animate-spin"})," Enviando imagem..."]}),e.jsxs("form",{onSubmit:async t=>{t.preventDefault();const i=t.target.querySelector("textarea"),x=i?.value?.trim()||"",C=Co.map(H=>`[IMG:${H}]`).join(`
19`),P=[x,C].filter(Boolean).join(`
20`);if(!(!P||!us))try{await N("POST",`/api/admin/support/conversations/${us}/reply`,{content:P}),i.value="",kl([]),K.invalidateQueries({queryKey:["/api/admin/support/conversations",us]}),K.invalidateQueries({queryKey:["/api/admin/support/conversations"]}),r({description:"Mensagem enviada — IA pausada automaticamente"})}catch{r({description:"Erro ao enviar mensagem",variant:"destructive"})}},className:"flex gap-2","data-testid":"form-admin-reply",children:[e.jsx($s,{placeholder:"Digite sua mensagem para o cliente...",className:"min-h-[40px] max-h-[100px] resize-none bg-white/5 border-white/10 text-white text-sm",onKeyDown:t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),t.target.form?.requestSubmit())},onPaste:async t=>{const s=t.clipboardData?.items;if(s){for(const i of Array.from(s))if(i.type.startsWith("image/")){t.preventDefault();const x=i.getAsFile();if(!x)return;Cl(!0);try{const C=await fetch("/api/uploads/request-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:`chat-image-${Date.now()}.png`,size:x.size,contentType:x.type})});if(!C.ok)throw new Error("Upload URL failed");const{uploadURL:P,objectPath:H}=await C.json();if(!(await fetch(P,{method:"PUT",body:x,headers:{"Content-Type":x.type}})).ok)throw new Error("Upload failed");if(!(await fetch("/api/uploads/confirm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectPath:H})})).ok)throw new Error("Failed to register upload ownership");kl(ue=>[...ue,H]),r({description:"Imagem adicionada"})}catch{r({description:"Erro ao enviar imagem",variant:"destructive"})}finally{Cl(!1)}return}}},"data-testid":"input-admin-reply"}),e.jsxs("div",{className:"flex flex-col gap-1 self-end",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:async t=>{const s=t.target.files?.[0];if(s){Cl(!0);try{const i=await fetch("/api/uploads/request-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:`chat-image-${Date.now()}.${s.name.split(".").pop()}`,size:s.size,contentType:s.type})});if(!i.ok)throw new Error("Upload URL failed");const{uploadURL:x,objectPath:C}=await i.json();if(!(await fetch(x,{method:"PUT",body:s,headers:{"Content-Type":s.type}})).ok)throw new Error("Upload failed");if(!(await fetch("/api/uploads/confirm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectPath:C})})).ok)throw new Error("Failed to register upload ownership");kl(Q=>[...Q,C]),r({description:"Imagem adicionada"})}catch{r({description:"Erro ao enviar imagem",variant:"destructive"})}finally{Cl(!1),t.target.value=""}}},"data-testid":"input-admin-image-upload"}),e.jsx("div",{className:"p-2 rounded-md bg-white/5 hover:bg-white/10 border border-white/10 transition-colors",children:e.jsx(yr,{className:"w-4 h-4 text-white/60"})})]}),e.jsx("button",{type:"button",title:"Enviar resumo das mensagens por email ao cliente",className:"p-2 rounded-md bg-white/5 hover:bg-amber-500/20 border border-white/10 hover:border-amber-500/30 transition-colors",onClick:async()=>
20{if(us)try{const s=await(await N("POST",`/api/admin/support/conversations/${us}/email-summary`)).json();s.success?r({description:`Email enviado com ${s.messageCount} mensagem(ns) do admin`}):r({description:s.message||"Erro ao enviar email",variant:"destructive"})}catch(t){const s=t?.message||"Erro ao enviar email";r({description:s,variant:"destructive"})}},"data-testid":"button-admin-email-summary",children:e.jsx(Ge,{className:"w-4 h-4 text-amber-400/70"})}),e.jsx(b,{type:"submit",size:"sm",className:"bg-violet-600 hover:bg-violet-700","data-testid":"button-admin-reply-send",children:e.jsx(ct,{className:"w-4 h-4"})})]})]}),Hs?.conversation?.aiPaused&&e.jsxs("p",{className:"text-[10px] text-amber-400/70 mt-1.5 flex items-center gap-1",children:[e.jsx(Ca,{className:"w-3 h-3"})," IA pausada — a IA volta automaticamente depois de 30 min sem atividade do admin"]})]})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Ut,{className:"w-10 h-10 mx-auto opacity-30"}),e.jsx("p",{className:"text-sm","data-testid":"text-support-empty",children:"Selecione uma conversa"})]})})})]})]}),e.jsx(Be,{value:"blog",className:"mt-6 space-y-4",children:e.jsx(Yb,{activeAdminTab:le})}),e.jsx(Be,{value:"origins",className:"mt-6 space-y-4",children:e.jsx(Dg,{activeAdminTab:le})}),e.jsx(Be,{value:"sales-attribution",className:"mt-6 space-y-4",children:e.jsx(zg,{activeAdminTab:le})}),e.jsxs(Be,{value:"orchestration",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx(Ot,{className:"w-6 h-6 text-teal-400"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-white",children:"Orquestração IA"}),e.jsx("p",{className:"text-xs text-white/50",children:"Gerencie os agentes de IA autônomos da plataforma"})]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-5",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Configuração da Orquestração"})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/10",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-white",children:"Ativar Orquestração"}),e.jsx("p",{className:"text-xs text-white/40",children:"Liga/desliga todo o sistema de orquestração"})]}),e.jsx(rt,{"data-testid":"orchestration-toggle-master",checked:ii?.enableOrchestration??!1,onCheckedChange:t=>rr(s=>({...s,enableOrchestration:t}))})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:[{key:"enableMarketingManager",label:"Marketing Manager"},{key:"enableEditorialManager",label:"Editorial Manager"},{key:"enableCrmManager",label:"CRM Manager"},{key:"enableSupportManager",label:"Suporte Manager"},{key:"enableOperationsManager",label:"Operações Manager"}].map(t=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/10",children:[e.jsx("span",{className:"text-xs font-medium text-white/80",children:t.label}),e.jsx(rt,{"data-testid":`orchestration-toggle-${t.key}`,checked:ii?.[t.key]??!1,onCheckedChange:s=>rr(i=>({...i,[t.key]:s}))})]},t.key))}),e.jsxs("div",{className:"flex items-center justify-between p-3 bg-white/5 rounded-lg border border-teal-500/20",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-teal-400",children:"CEO Agent"}),e.jsx("p",{className:"text-xs text-white/40",children:"Agente CEO que consolida relatórios"})]}),e.jsx(rt,{"data-testid":"orchestration-toggle-ceo",checked:ii?.enableCeoAgent??!1,onCheckedChange:t=>rr(s=>({...s,enableCeoAgent:t}))})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(O,{className:"text-xs text-white/60",children:"Horário do relatório CEO"}),e.jsx(J,{"data-testid":"orchestration-input-ceoReportTime",type:"time",value:ii?.ceoReportTime??"20:00",onChange:t=>rr(s=>({...s,ceoReportTime:t.target.value})),className:"bg-white/5 border-white/10 text-white text-sm"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(O,{className:"text-xs text-white/60",children:"Email do relatório CEO"}),e.jsx(J,{"data-testid":"orchestration-input-ceoReportEmail",type:"email",placeholder:"[email protected]",value:ii?.ceoReportEmail??"",onChange:t=>rr(s=>({...s,ceoReportEmail:t.target.value})),className:"bg-white/5 border-white/10 text-white text-sm"})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(b,{"data-testid":"orchestration-button-saveConfig",onClick:()=>ii&&uo.mutate(ii),disabled:uo.isPending,className:"bg-teal-600 hover:bg-teal-700 text-white text-xs",children:[uo.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin mr-1.5"}):e.jsx(Ua,{className:"w-3.5 h-3.5 mr-1.5"}),"Salvar Configuração"]})})]})]}),e.jsx(tg,{orchStatus:a0}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4 text-amber-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Relatórios Recentes"}),e.jsxs(E,{className:"bg-white/10 text-white/60 border-white/10 text-[10px] ml-auto",children:[ml?.length??0," relatórios"]})]}),ml&&ml.length>0?e.jsx("div",{className:"space-y-2",children:ml.map(t=>{const s={pending_review:"bg-amber-500/20 text-amber-400 border-amber-500/30",approved:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",rejected:"bg-red-500/20 text-red-400 border-red-500/30",escalated:"bg-orange-500/20 text-orange-400 border-orange-500/30"},i={pending_review:"Pendente",approved:"Aprovado",rejected:"Rejeitado",escalated:"Escalado"},x=Tp===t.id;return e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-lg overflow-hidden",children:[e.jsxs("button",{"data-testid":`orchestration-report-toggle-${t.id}`,onClick:()=>Ep(x?null:t.id),className:"w-full flex items-center justify-between p-3 text-left hover:bg-white/5 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx(E,{className:"text-[10px] bg-teal-500/20 text-teal-400 border-teal-500/30 flex-shrink-0",children:t.agentRole||"agent"}),e.jsx("span",{className:"text-xs text-white truncate",children:t.subject||"Sem assunto"}),t.type&&e.jsx("span",{className:"text-[10px] text-white/30 flex-shrink-0",children:t.type})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[e.jsx(E,{className:`text-[10px] ${s[t.status]||"bg-white/10 text-white/40 border-white/10"}`,children:i[t.status]||t.status}),t.createdAt&&e.jsx("span",{className:"text-[10px] text-white/30",children:new Date(t.createdAt).toLocaleStr
20ing("pt-BR")}),x?e.jsx(ta,{className:"w-3.5 h-3.5 text-white/40"}):e.jsx(Ct,{className:"w-3.5 h-3.5 text-white/40"})]})]}),x&&e.jsx("div",{className:"px-3 pb-3 border-t border-white/5",children:e.jsx("pre",{className:"text-xs text-white/60 whitespace-pre-wrap mt-2 max-h-60 overflow-y-auto bg-black/20 rounded p-3",children:t.content||"Sem conteúdo"})})]},t.id)})}):e.jsxs("div",{className:"text-center py-8",children:[e.jsx(tt,{className:"w-8 h-8 text-white/20 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-white/40",children:"Nenhum relatório recente"})]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"ceo-chat-container",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"w-4 h-4 text-teal-400"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Chat com CEO IA"}),e.jsx(E,{className:"bg-teal-500/20 text-teal-400 border-teal-500/30 text-[10px]",children:"Direto"})]}),e.jsxs(b,{"data-testid":"ceo-chat-clear",variant:"ghost",size:"sm",onClick:()=>Am.mutate(),disabled:Am.isPending||!Yr?.length,className:"text-xs text-white/40 hover:text-white/70",children:[e.jsx(xe,{className:"w-3 h-3 mr-1"}),"Nova Conversa"]})]}),e.jsxs("div",{className:"bg-black/20 rounded-lg border border-white/5 h-[400px] flex flex-col",children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-3","data-testid":"ceo-chat-messages",children:!Yr||Yr.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx(jn,{className:"w-10 h-10 text-teal-400/30 mb-3"}),e.jsx("p",{className:"text-sm text-white/40",children:"Converse com o CEO IA"}),e.jsx("p",{className:"text-xs text-white/25 mt-1 max-w-xs",children:"Pergunte sobre métricas, performance, suporte, receita ou dê direções estratégicas."})]}):e.jsxs(e.Fragment,{children:[Yr.map(t=>e.jsx("div",{className:`flex ${t.role==="user"?"justify-end":"justify-start"}`,"data-testid":`ceo-chat-message-${t.id}`,children:e.jsxs("div",{className:`max-w-[80%] ${t.role==="user"?"bg-teal-600/20 border-teal-500/30":"bg-white/5 border-white/10"} border rounded-xl px-4 py-3`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[t.role==="assistant"?e.jsxs(e.Fragment,{children:[e.jsx(jn,{className:"w-3 h-3 text-teal-400"}),e.jsx("span",{className:"text-[10px] font-medium text-teal-400",children:"CEO IA"})]}):e.jsxs(e.Fragment,{children:[e.jsx(as,{className:"w-3 h-3 text-emerald-400"}),e.jsx("span",{className:"text-[10px] font-medium text-emerald-400",children:"Gabriel"})]}),t.createdAt&&e.jsx("span",{className:"text-[9px] text-white/20 ml-auto",children:new Date(t.createdAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})]}),e.jsx("div",{className:"text-xs text-white/80 whitespace-pre-wrap leading-relaxed",children:t.content})]})},t.id)),e.jsx("div",{ref:qx})]})}),e.jsxs("div",{className:"border-t border-white/5 p-3 flex gap-2","data-testid":"ceo-chat-input-area",children:[e.jsx("textarea",{"data-testid":"ceo-chat-input",value:nr,onChange:t=>zx(t.target.value),onKeyDown:t=>{t.key==="Enter"&&!t.shiftKey&&nr.trim()&&!Li.isPending&&(t.preventDefault(),Li.mutate(nr.trim()))},placeholder:"Pergunte ao CEO IA... (ex: Qual o faturamento hoje?)",className:"flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-xs text-white placeholder-white/30 resize-none focus:outline-none focus:border-teal-500/50",rows:2,disabled:Li.isPending}),e.jsx(b,{"data-testid":"ceo-chat-send",onClick:()=>nr.trim()&&Li.mutate(nr.trim()),disabled:Li.isPending||!nr.trim(),className:"bg-teal-600 hover:bg-teal-700 text-white self-end px-3",size:"sm",children:Li.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin"}):e.jsx(ct,{className:"w-4 h-4"})})]})]}),Li.isPending&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-teal-400/60",children:[e.jsx(T,{className:"w-3 h-3 animate-spin"}),"CEO IA analisando dados e preparando resposta..."]})]})]}),e.jsx(Be,{value:"growth",className:"mt-6 space-y-6",children:e.jsx(eg,{})}),e.jsxs(Be,{value:"chat-ab",className:"mt-6 space-y-6",children:[i0?e.
20jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):(()=>{const t=li?.variants||[],s=Math.max(...t.map(Y=>Y.conversionRate),0),i=t.filter(Y=>Y.isActive).reduce((Y,Oe)=>Y+Oe.weight,0),x=new Set;t.forEach(Y=>Object.keys(Y.steps).forEach(Oe=>x.add(Oe)));const C=Array.from(x),P=Math.max(...t.flatMap(Y=>Object.values(Y.steps)),1),H=["text-blue-400","text-purple-400","text-orange-400","text-pink-400","text-cyan-400","text-yellow-400","text-lime-400","text-rose-400"],Q=["bg-blue-500/60","bg-purple-500/60","bg-orange-500/60","bg-pink-500/60","bg-cyan-500/60","bg-yellow-500/60","bg-lime-500/60","bg-rose-500/60"],G={};li?.daily?.forEach(Y=>{const Oe=typeof Y.date=="string"?Y.date.split("T")[0]:String(Y.date);G[Oe]||(G[Oe]={}),G[Oe][Y.variant]={sessions:Y.sessions,conversions:Y.conversions}});const ue=Object.keys(G).sort().reverse(),Te=t.map(Y=>Y.name);return e.jsxs("div",{className:"space-y-6","data-testid":"chat-ab-panel",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Il,{className:"w-6 h-6 text-purple-400"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-white","data-testid":"text-chat-ab-title",children:"Chat A/B Testing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gerencie variantes do chat e acompanhe qual converte mais"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.map(Y=>e.jsxs(b,{size:"sm",variant:"outline",className:"gap-1.5 border-white/20 text-white/70 hover:bg-white/10",onClick:()=>window.open(`/chat?variant=${Y.name}`,"_blank"),"data-testid":`btn-test-chat-variant-${Y.name}`,children:[e.jsx(vs,{className:"w-3.5 h-3.5"})," Testar ",Y.name]},Y.id)),e.jsxs(b,{size:"sm",className:"gap-1.5 bg-purple-500/20 text-purple-400 border border-purple-500/30 hover:bg-purple-500/30",onClick:()=>{pl(null),Ma({name:"",description:"",weight:50,isActive:!0,config:'{"chatPage": "chat"}'}),pr(!0)},"data-testid":"btn-create-chat-variant",children:[e.jsx(_t,{className:"w-3.5 h-3.5"})," Nova Variante"]})]})]}),i>0&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-2 flex items-center gap-1.5",children:[e.jsx(Ot,{className:"w-3.5 h-3.5"})," Distribuição de Tráfego"]}),e.jsx("div",{className:"flex h-6 rounded-full overflow-hidden bg-white/5",children:t.filter(Y=>Y.isActive).map((Y,Oe)=>{const ze=Y.weight/i*100;return e.jsx("div",{className:`${Q[Oe%Q.length]} flex items-center justify-center transition-all`,style:{width:`${ze}%`},title:`${Y.name}: ${ze.toFixed(0)}%`,children:e.jsxs("span",{className:"text-[10px] text-white font-bold truncate px-1",children:[Y.name," (",ze.toFixed(0),"%)"]})},Y.id)})})]}),li?.significance&&e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 rounded-xl border ${li.significance.significant?"bg-emerald-500/10 border-emerald-500/30":"bg-white/5 border-white/10"}`,"data-testid":"chat-ab-significance",children:[li.significance.significant?e.jsx(be,{className:"w-5 h-5 text-emerald-400 shrink-0"}):e.jsx(js,{className:"w-5 h-5 text-muted-foreground shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:`text-sm font-medium ${li.significance.significant?"text-emerald-400":"text-white"}`,children:li.significance.significant?"Resultado Significativo":"Análise Estatística"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:li.significance.message})]})]}),t.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:t.map((Y,Oe)=>{const ze=Y.conversionRate===s&&Y.totalSessions>0&&s>0;return e.jsxs("div",{className:`relative bg-white/5 border rounded-xl p-5 space-y-4 ${ze?"border-emerald-500/50 ring-1 ring-emerald-500/20":"border-white/10"}`,"data-testid":`card-chat-variant-${Y.id}`,children:[ze&&e.jsx("div",{className:"absolute -top-3 right-4",children:e.jsxs(E,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 gap-1",children:[e.jsx(_i,{className:"w-3 h-3"})," Vencedor"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-lg font-bold ${H[Oe%H.length]}`,children:Y.name}),e.jsx(E,{variant:"outline",className:`text-[10px] ${Y.isActive?"border-emerald-500/30 text-emerald-400":"border-red-500/30 text-red-400"}`,children:Y.isActive?"Ativo":"Inativo"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",title:"Editar",onClick:()=>{pl(Y),Ma({name:Y.name,description:Y.description||"",weight:Y.weight,isActive:Y.isActive,config:JSON.stringify(Y.config||{},null,2)}),pr(!0)},"data-testid":`btn-edit-chat-variant-${Y.id}`,children:e.jsx(Ga,{className:"w-3.5 h-3.5"})}),e.jsx(b,{size:"sm",variant:"ghost",className:`h-7 w-7 p-0 ${Y.isActive?"text-red-400 hover:text-red-300":"text-emerald-400 hover:text-emerald-300"}`,onClick:()=>ul.mutate({id:Y.id,data:{isActive:!Y.isActive}}),"data-testid":`btn-toggle-chat-variant-${Y.id}`,children:Y.isActive?e.jsx(Ca,{className:"w-3.5 h-3.5"}):e.jsx(Us,{className:"w-3.5 h-3.5"})}),e.jsxs(pi,{children:[e.jsx(ui,{asChild:!0,children:e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-red-400 hover:text-red-300",title:"Excluir","data-testid":`btn-delete-chat-variant-${Y.id}`,children:e.jsx(As,{className:"w-3.5 h-3.5"})})}),e.jsxs(gi,{children:[e.jsxs(bi,{children:[e.jsxs(ji,{children:['Excluir variante "',Y.name,'"?']}),e.jsx(vi,{children:"Esta ação não pode ser desfeita. A variante será removida permanentemente."})]}),e.jsxs(Ni,{children:[e.jsx(fi,{"data-testid":`btn-cancel-delete-chat-variant-${Y.id}`,children:"Cancelar"}),e.jsx(wi,{className:"bg-red-600 hover:bg-red-700",onClick:()=>n0.mutate(Y.id),"data-testid":`btn-confirm-delete-chat-variant-${Y.id}`,children:"Excluir"})]})]})]})]})]}),Y.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Y.description}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ot,{className:"w-3 h-3"})," Peso: ",Y.weight]}),i>0&&Y.isActive&&e.jsxs("span",{className:"text-[10px]",children:["(",(Y.weight/i*100).toFixed(0),"% do tráfego)"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"})," Sessões"]}),e.jsx("p",{className:"text-xl font-bold text-white","data-testid":`text-chat-sessions-${Y.id}
20`,children:Y.totalSessions.toLocaleString("pt-BR")})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(be,{className:"w-3 h-3"})," Conversões"]}),e.jsx("p",{className:"text-xl font-bold text-emerald-400","data-testid":`text-chat-conversions-${Y.id}`,children:Y.conversions.toLocaleString("pt-BR")})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ie,{className:"w-3 h-3"})," Taxa"]}),e.jsxs("p",{className:"text-xl font-bold text-white","data-testid":`text-chat-rate-${Y.id}`,children:[Y.conversionRate,"%"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(nt,{className:"w-3 h-3"})," Receita"]}),e.jsxs("p",{className:"text-xl font-bold text-emerald-400","data-testid":`text-chat-revenue-${Y.id}`,children:["R$ ",(Y.revenue/100).toLocaleString("pt-BR",{minimumFractionDigits:2})]})]})]})]},Y.id)})}),t.filter(Y=>Y.totalSessions>0).length>=2&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"chat-ab-comparison",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4"})," Comparação de Conversão"]}),e.jsx("div",{className:"space-y-3",children:t.filter(Y=>Y.totalSessions>0).map((Y,Oe)=>{const ze=Math.max(...t.map(Xs=>Xs.conversionRate),1),Wt=Y.conversionRate/ze*100;return e.jsxs("div",{className:"space-y-1","data-testid":`chat-comparison-bar-${Y.id}`,children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-xs text-white font-medium",children:Y.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Y.conversionRate,"% (",Y.conversions,"/",Y.totalSessions,")"]})]}),e.jsx("div",{className:"bg-white/5 rounded-full h-5 overflow-hidden",children:e.jsx("div",{className:`${Q[Oe%Q.length]} h-full rounded-full transition-all duration-500 flex items-center justify-end pr-2`,style:{width:`${Math.max(Wt,5)}%`},children:e.jsxs("span",{className:"text-[10px] text-white font-medium",children:[Y.conversionRate,"%"]})})})]},Y.id)})})]}),C.length>0&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"chat-ab-funnel",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4"})," Funil por Etapa"]}),e.jsx("div",{className:"space-y-3",children:C.map(Y=>e.jsxs("div",{className:"space-y-1","data-testid":`funnel-step-${Y}`,children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:Y}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Te.map(Oe=>`${Oe}: ${t.find(ze=>ze.name===Oe)?.steps[Y]||0}`).join(" | ")})]}),e.jsx("div",{className:"flex gap-1",children:t.map((Oe,ze)=>{const Xs=(Oe.steps[Y]||0)/P*100;return e.jsx("div",{className:"flex-1 bg-white/5 rounded-full h-4 overflow-hidden",children:e.jsx("div",{className:`${Q[ze%Q.length]} h-full rounded-full transition-all duration-500`,style:{width:`${Xs}%`}})},Oe.id)})})]},Y))}),e.jsx("div",{className:"flex flex-wrap gap-4 text-[10px] text-muted-foreground pt-1",children:t.map((Y,Oe)=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:`w-3 h-2 ${Q[Oe%Q.length]} rounded-sm inline-block`})," ",Y.name]},Y.id))})]}),ue.length>0&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"chat-ab-daily",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4"})," Últimos 7 Dias"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-white/10 text-muted-foreground",children:[e.jsx("th",{className:"text-left py-2 pr-4",children:"Data"}),Te.map(Y=>e.jsx("th",{className:"text-center py-2 px-2",colSpan:2,children:Y},Y))]}),e.jsxs("tr",{className:"border-b border-white/5 text-muted-foreground text-[10px]",children:[e.jsx("th",{}),Te.map(Y=>e.jsxs(Kl.Fragment,{children:[e.jsx("th",{className:"py-1 px-2",children:"Sess."}),e.jsx("th",{className:"py-1 px-2",children:"Conv."})]},Y))]})]}),e.jsx("tbody",{children:ue.map(Y=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5","data-testid":`row-chat-daily-${Y}`,children:[e.jsx("td",{className:"py-2 pr-4 text-white font-medium",children:new Date(Y+"T12:00:00").toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}),Te.map((Oe,ze)=>{const Wt=G[Y]?.[Oe];return e.jsxs(Kl.Fragment,{children:[e.jsx("td",{className:`py-2 px-2 text-center ${H[ze%H.length].replace("text-","text-")}`,children:Wt?.sessions??0}),e.jsx("td",{className:"py-2 px-2 text-center text-emerald-400",children:Wt?.conversions??0})]},Oe)})]},Y))})]})})]})]}):e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-10 text-center space-y-2","data-testid":"chat-ab-empty",children:[e.jsx(Il,{className:"w-10 h-10 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Nenhuma variante do chat criada ainda."}),e.jsx("p",{className:"text-muted-foreground text-xs",children:"Crie variantes para começar a testar diferentes fluxos de chat."})]})]})})(),e.jsx(Je,{open:r0,onOpenChange:pr,children:e.jsxs(Ye,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:hl?"Editar Variante do Chat":"Nova Variante do Chat"}),e.jsx(mt,{children:"Configure a variante para testes A/B do chat de vendas."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(O,{children:"Nome da variante"}),e.jsx(J,{value:Ss.name,onChange:t=>Ma(s=>({...s,name:t.target.value})),placeholder:"Ex: A, B, C, Urgency, Direct","data-testid":"input-chat-variant-name"})]}),e.jsxs("div",{children:[e.jsx(O,{children:"Descrição (opcional)"}),e.jsx(J,{value:Ss.description,onChange:t=>Ma(s=>({...s,description:t.target.value})),placeholder:"Ex: Chat Original baseado no Typebot campeão","data-testid":"input-chat-variant-description"})]}),e.jsxs("div",{children:[e.jsx(O,{children:"Peso (distribuição de tráfego: 0-100)"}),e.jsx(J,{type:"number",min:0,max:100,value:Ss.weight,onChange:t=>Ma(s=>({...s,weight:parseInt(t.target.value)||0})),"data-testid":"input-chat-variant-weight"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"O tráfego é distribuído proporcionalmente entre as variantes ativas. Ex: Peso 70 + Peso 30 = 70% e 30%."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{checked:Ss.isActive,onCheckedChange:t=>Ma(s=>({...s,isActive:t})),"data-testid":"switch-chat-variant-active"}),e.jsx(O,{children:"Ativo"})]}),e.jsxs("div",{children:[e.jsx(O,{children:"Config (JSON)"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mb-1",children:'chatPage: "chat" (original) ou "chat-v2" (otimizado)'}),e.jsx($s,{rows:6,className:"font-mono text-xs",value:Ss.config,onChange:t=>Ma(s=>({...s,config:t.target.value})),placeholder:'{"chatPage": "chat"}',"data-testid":"textarea-chat-variant-config"})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>pr(!1),"data-testid":"btn-cancel-chat-variant",children:"Cancelar"}),e.jsxs(b,{className:"bg-purple-500 hover:bg-purple-600",disabled:!Ss.name||ho.isPending||ul.isPending,onClick:()=>{let t={};try{t=JSON.parse(Ss.config)}catch{t={}}hl?ul.mutate({id:hl.id,data:{name:Ss.name,description:Ss.description||void 0,weight:Ss.weight,isActive:Ss.isActive,config:t}}):ho.mutate({name:Ss.name,description:Ss.description||void 0,weight:Ss.weight,isActive:Ss.isActive,config:t})},"data-testid":"btn-save-chat-variant",children:[(ho.isPending||ul.isPending)&&e.jsx(T,{className:"w-4 h-4 animate-spin mr-1.5"}),hl?"Salvar":"Criar"]})]})]})})]}),e.jsx(Be,{value:"checkouts",className:"mt-6 space-y-6",children:Cm&&!ps?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6","data-testid":"checkouts-panel",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bt,{className:"w-6 h-6 text-emerald-400"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-white","data-testid":"text-checkouts-title",children:"Checkout Sessions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gerencie sessões de checkout, métricas de conversão e funil"})]})]}),e.jsxs(b,{size:"sm",className:"gap-1.5 bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 hover:bg-emerald-500/30","data-testid":"btn-preview-checkout",onClick:async()=>{try{const s=await(await N("POST","/api/admin/checkout-preview")).json();s.checkoutUrl&&window.open(s.checkoutUrl,"_blank")}catch(t){r({title:"Erro",description:t.message,variant:"destructive"})}},children:[e.jsx(ht,{className:"w-3.5 h-3.5"})," Visualizar Checkout"]})]}),ps&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 ga
20p-3",children:[e.jsx(kt,{icon:Jt,label:"Total Sessões",value:ps.total,"data-testid":"metric-checkout-total"}),e.jsx(kt,{icon:be,label:"Pagos",value:`${ps.paidPercent}%`,sub:`${ps.paid} sessões`,color:"text-emerald-400","data-testid":"metric-checkout-paid"}),e.jsx(kt,{icon:dt,label:"Abandonados",value:`${ps.abandonedPercent}%`,sub:`${ps.abandoned} sessões`,color:"text-red-400","data-testid":"metric-checkout-abandoned"}),e.jsx(kt,{icon:ns,label:"Tempo Médio",value:`${ps.avgTimeToPurchaseMin}min`,sub:"até pagamento","data-testid":"metric-checkout-time"}),e.jsx(kt,{icon:nt,label:"Receita Total",value:`R$ ${(ps.totalRevenue/100).toLocaleString("pt-BR",{minimumFractionDigits:2})}`,color:"text-emerald-400","data-testid":"metric-checkout-revenue"})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"checkout-funnel",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4"})," Funil de Conversão"]}),e.jsx("div",{className:"space-y-3",children:[{label:"Sessões Criadas",value:ps.funnel.created,color:"bg-blue-500/60"},{label:"Checkout Visualizado",value:ps.funnel.viewed,color:"bg-sky-500/60"},{label:"Pagamento Iniciado",value:ps.funnel.paymentStarted,color:"bg-amber-500/60"},{label:"Pago",value:ps.funnel.paid,color:"bg-emerald-500/60"}].map((t,s,i)=>{const x=i[0].value||1,C=t.value/x*100,P=s>0&&i[s-1].value>0?((1-t.value/i[s-1].value)*100).toFixed(1):null;return e.jsxs("div",{className:"space-y-1","data-testid":`funnel-step-checkout-${s}`,children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:t.label}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-white font-bold",children:t.value}),P&&e.jsxs("span",{className:"text-[10px] text-red-400 flex items-center gap-0.5",children:[e.jsx(Tc,{className:"w-3 h-3"})," -",P,"%"]})]})]}),e.jsx("div",{className:"bg-white/5 rounded-full h-5 overflow-hidden",children:e.jsx("div",{className:`${t.color} h-full rounded-full transition-all duration-500`,style:{width:`${C}%`}})})]},t.label)})})]}),ps.variantStats&&ps.variantStats.length>0&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"checkout-variant-stats",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Il,{className:"w-4 h-4"})," Por Variante"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:ps.variantStats.map(t=>e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-lg p-4 space-y-2","data-testid":`checkout-variant-${t.variant}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-bold text-white",children:["Variante ",t.variant]}),e.jsxs(E,{variant:"outline",className:"text-[10px]",children:[t.total," sessões"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Conversão"}),e.jsxs("p",{className:"text-sm font-bold text-emerald-400",children:[t.conversionRate,"%"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Pagos"}),e.jsx("p",{className:"text-sm font-bold text-white",children:t.paid})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Receita"}),e.jsxs("p",{className:"text-sm font-bold text-emerald-400",children:["R$ ",(t.revenue/100).toLocaleString("pt-BR",{minimumFractionDigits:2})]})]})]})]},t.variant))})]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"checkout-sessions-list",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(Jt,{className:"w-4 h-4"})," Sessões de Checkout"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Se,{value:gl,onValueChange:l0,children:[e.jsx($e,{className:"w-[140px] h-8 text-xs","data-testid":"select-checkout-status-filter",children:e.jsx(Ae,{placeholder:"Status"})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"all",children:"Todos"}),e.jsx(U,{value:"pending",children:"Pendente"}),e.jsx(U,{value:"paid",children:"Pago"}),e.jsx(U,{value:"delivered",children:"Entregue"}),e.jsx(U,{value:"abandoned",children:"Abandonado"})]})]}),e.jsxs(Se,{value:bl,onValueChange:d0,children:[e.jsx($e,{className:"w-[120px] h-8 text-xs","data-testid":"select-checkout-variant-filter",children:e.jsx(Ae,{placeholder:"Variante"})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"all",children:"Todas"}),e.jsx(U,{value:"A",children:"Variante A"}),e.jsx(U,{value:"B",children:"Variante B"}),e.jsx(U,{value:"chat",children:"Chat"})]})]})]})]}),Cm?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(T,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):km.length===0?e.jsxs("div",{className:"text-center py-10 space-y-2",children:[e.jsx(Bt,{className:"w-10 h-10 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Nenhuma sessão de checkout encontrada."})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs","data-testid":"table-checkout-sessions",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-muted-foreground",children:[e.jsx("th",{className:"text-left py-2 pr-2",children:"ID"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Usuário"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Livro"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Status"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Variante"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Valor"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Pagamento"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Criado"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Pago em"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Drip"}),e.jsx("th",{className:"text-center py-2 px-2",children:"Ações"})]})}),e.jsx("tbody",{children:km.map(t=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/5","data-testid":`row-checkout-${t.id}`,children:[e.jsx("td",{className:"py-2 pr-2 text-white/60 font-mono",children:t.id.substring(0,8)}),e.jsx("td",{className:"py-2 px-2",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-white text-xs",children:t.userName||t.email}),t.userName&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:t.email})]})}),e.jsx("td",{className:"py-2 px-2 text-white max-w-[150px] truncate",children:t.bookTitle}),e.jsx("td",{className:"py-2 px-2 text-center",children:e.jsx("span",{className:`px-2 py-0.5 rounded-full text-[11px] font-medium border ${t.status==="paid"?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":t.status==="delivered"?"bg-blue-500/20 text-blue-400 border-blue-500/30":t.status==="pending"?"bg-amber-500/20 text-amber-400 border-amber-500/30":"bg-red-500/20 text-red-400 border-red-500/30"}`,children:t.status==="paid"?"Pago":t.status==="delivered"?"Entregue":t.status==="pending"?"Pendente":t.status})}),e.jsx("td",{className:"py-2 px-2 text-center",children:e.jsx(E,{variant:"outline",className:"text-[10px]",children:t.variant||"A"})}),e.jsx("td",{className:"py-2 px-2 text-right text-white font-medium",children:t.totalAmount?`R$ ${(t.totalAmount/100).toLocaleStr
20ing("pt-BR",{minimumFractionDigits:2})}`:"-"}),e.jsx("td",{className:"py-2 px-2 text-center text-muted-foreground",children:t.paymentMethod==="card"?e.jsx(Bt,{className:"w-3.5 h-3.5 mx-auto"}):t.paymentMethod==="pix"?e.jsx(Oa,{className:"w-3.5 h-3.5 mx-auto"}):"-"}),e.jsx("td",{className:"py-2 px-2 text-center text-muted-foreground",children:t.createdAt?new Date(t.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"-"}),e.jsx("td",{className:"py-2 px-2 text-center text-muted-foreground",children:t.paidAt?new Date(t.paidAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"-"}),e.jsx("td",{className:"py-2 px-2 text-center",children:t.abandonedEmailStep>0?e.jsxs(E,{variant:"outline",className:"text-[10px]",children:[t.abandonedEmailStep,"/15"]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx("td",{className:"py-2 px-2 text-center",children:e.jsx(b,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:()=>c0(t.id),"data-testid":`btn-checkout-detail-${t.id}`,children:e.jsx(ht,{className:"w-3.5 h-3.5"})})})]},t.id))})]})})]})]})}),e.jsx(Be,{value:"recovery",className:"mt-6 space-y-6",children:e.jsx(Og,{})}),e.jsx(Be,{value:"checkout-ab",className:"mt-6 space-y-6",children:e.jsxs("div",{className:"space-y-6","data-testid":"checkout-ab-panel",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ka,{className:"w-6 h-6 text-orange-400"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-white","data-testid":"text-checkout-ab-title",children:"A/B Checkout Testing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gerencie variantes do checkout e compare conversões"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(b,{size:"sm",className:"gap-1.5 bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 hover:bg-emerald-500/30","data-testid":"btn-preview-checkout-ab",onClick:async()=>{try{const s=await(await N("POST","/api/admin/checkout-preview")).json();s.checkoutUrl&&window.open(s.checkoutUrl,"_blank")}catch(t){r({title:"Erro",description:t.message,variant:"destructive"})}},children:[e.jsx(ht,{className:"w-3.5 h-3.5"})," Visualizar Checkout"]}),e.jsxs(b,{size:"sm",className:"gap-1.5 bg-orange-500/20 text-orange-400 border border-orange-500/30 hover:bg-orange-500/30",onClick:()=>{vl(null),Na({name:"",weight:50,isActive:!0,config:"{}"}),gr(!0)},"data-testid":"btn-create-checkout-variant",children:[e.jsx(_t,{className:"w-3.5 h-3.5"})," Nova Variante"]})]})]}),ur&&e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 rounded-xl border ${ur.significant?"bg-emerald-500/10 border-emerald-500/30":"bg-white/5 border-white/10"}`,"data-testid":"checkout-ab-significance",children:[ur.significant?e.jsx(be,{className:"w-5 h-5 text-emerald-400 shrink-0"}):e.jsx(js,{className:"w-5 h-5 text-muted-foreground shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:`text-sm font-medium ${ur.significant?"text-emerald-400":"text-white"}`,children:ur.significant?"Resultado Significativo":"Análise Estatística"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ur.message})]})]}),Mi&&Mi.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Mi.map(t=>{const s=Math.max(...Mi.map(x=>x.conversionRate)),i=t.conversionRate===s&&t.sessions>0&&s>0;return e.jsxs("div",{className:`relative bg-white/5 border rounded-xl p-5 space-y-4 ${i?"border-emerald-500/50 ring-1 ring-emerald-500/20":"border-white/10"}`,"data-testid":`card-checkout-variant-${t.id}`,children:[i&&e.jsx("div",{className:"absolute -top-3 right-4",children:e.jsxs(E,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 gap-1",children:[e.jsx(_i,{className:"w-3 h-3"})," Líder"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg font-bold text-white",children:t.name}),e.jsx(E,{variant:"outline",className:`text-[10px] ${t.isActive?"border-emerald-500/30 text-emerald-400":"border-red-500/30 text-red-400"}`,children:t.isActive?"Ativo":"Inativo"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-sky-400 hover:text-sky-300",title:`Visualizar variante ${t.name}`,onClick:async()=>{try{const C=await(await N("POST","/api/admin/checkout-preview")).json();if(C.checkoutUrl){const P=C.checkoutUrl.includes("?")?"&":"?";window.open(`${C.checkoutUrl}${P}variant=${encodeURIComponent(t.name)}`,"_blank")}}catch(x){r({title:"Erro",description:x.message,variant:"destructive"})}},"data-testid":`btn-preview-variant-${t.id}`,children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{vl(t),Na({name:t.name,weight:t.weight,isActive:t.isActive,config:JSON.stringify(t.config||{},null,2)}),gr(!0)},"data-testid":`btn-edit-variant-${t.id}`,children:e.jsx(Ga,{className:"w-3.5 h-3.5"})}),e.jsx(b,{size:"sm",variant:"ghost",className:`h-7 w-7 p-0 ${t.isActive?"text-red-400 hover:text-red-300":"text-emerald-400 hover:text-emerald-300"}`,onClick:()=>Nl.mutate({id:t.id,data:{isActive:!t.isActive}}),"data-testid":`btn-toggle-variant-${t.id}`,children:t.isActive?e.jsx(Ca,{className:"w-3.5 h-3.5"}):e.jsx(Us,{className:"w-3.5 h-3.5"})})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ot,{className:"w-3 h-3"})," Peso: ",t.weight]}),t.config?.layout&&e.jsx(E,{variant:"outline",className:`text-[10px] ${t.config.layout==="bumps"?"border-orange-500/30 text-orange-400":t.config.layout==="minimal"?"border-sky-500/30 text-sky-400":t.config.layout==="urgency"?"border-red-500/30 text-red-400":"border-emerald-500/30 text-emerald-400"}`,children:t.config.layout==="bumps"?"Bumps Clássico":t.config.layout==="minimal"?"Minimalista":t.config.layout==="urgency"?"Urgência":"Pacotes (Tiers)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"})," Sessões"]}),e.jsx("p",{className:"text-xl font-bold text-white","data-testid":`text-checkout-sessions-${t.id}
20`,children:t.sessions.toLocaleString("pt-BR")})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(be,{className:"w-3 h-3"})," Pagos"]}),e.jsx("p",{className:"text-xl font-bold text-emerald-400","data-testid":`text-checkout-paid-${t.id}`,children:t.paid.toLocaleString("pt-BR")})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ie,{className:"w-3 h-3"})," Conversão"]}),e.jsxs("p",{className:"text-xl font-bold text-white","data-testid":`text-checkout-rate-${t.id}`,children:[t.conversionRate,"%"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(nt,{className:"w-3 h-3"})," Receita"]}),e.jsxs("p",{className:"text-xl font-bold text-emerald-400","data-testid":`text-checkout-revenue-${t.id}`,children:["R$ ",t.revenue.toLocaleString("pt-BR",{minimumFractionDigits:2})]})]})]})]},t.id)})}),Mi.length>=2&&e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-5 space-y-4","data-testid":"checkout-ab-comparison",children:[e.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4"})," Comparação de Conversão"]}),e.jsx("div",{className:"space-y-3",children:Mi.filter(t=>t.sessions>0).map(t=>{const s=Math.max(...Mi.map(x=>x.conversionRate),1),i=t.conversionRate/s*100;return e.jsxs("div",{className:"space-y-1","data-testid":`comparison-bar-${t.id}`,children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-xs text-white font-medium",children:t.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.conversionRate,"% (",t.paid,"/",t.sessions,")"]})]}),e.jsx("div",{className:"bg-white/5 rounded-full h-5 overflow-hidden",children:e.jsx("div",{className:"bg-orange-500/60 h-full rounded-full transition-all duration-500 flex items-center justify-end pr-2",style:{width:`${Math.max(i,5)}%`},children:e.jsxs("span",{className:"text-[10px] text-white font-medium",children:[t.conversionRate,"%"]})})})]},t.id)})})]})]}):e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-10 text-center space-y-2","data-testid":"checkout-ab-empty",children:[e.jsx(ka,{className:"w-10 h-10 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Nenhuma variante de checkout criada ainda."}),e.jsx("p",{className:"text-muted-foreground text-xs",children:"Crie variantes para começar a testar diferentes layouts de checkout."})]})]})}),e.jsx(Be,{value:"plan-landing-ab",className:"mt-6 space-y-6",children:e.jsxs("div",{className:"space-y-6","data-testid":"plan-landing-ab-panel",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Oi,{className:"w-6 h-6 text-orange-400"}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-white","data-testid":"text-plan-landing-ab-title",children:"Hub vs Editor (plano pronto)"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Teste A/B temporário (Task #374) — compara conversão plano-pronto→pago entre o HUB verde (CTA forte) e o Editor (CTA leve no rodapé)."})]})]}),e.jsxs(E,{variant:"outline",className:`text-[10px] ${ss?.testEnabled?"border-emerald-500/30 text-emerald-400":"border-red-500/30 text-red-400"}`,"data-testid":"badge-plan-landing-ab-status",children:["Teste ",ss?.testEnabled?"ATIVO":"DESLIGADO"]})]}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4 text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:["Flag final atual (usada fora da janela do teste): ",e.jsx("span",{className:"text-white font-medium",children:ss?.winningFlagIsHub?"HUB":"EDITOR"})," (ENABLE_PLAN_READY_TO_HUB)"]}),ss?.testStartedAt&&e.jsxs("p",{children:["Teste coletando dados desde: ",e.jsx("span",{className:"text-white font-medium",children:new Date(ss.testStartedAt).toLocaleStr
20ing("pt-BR")})]})]}),ss?.significance&&e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 rounded-xl border ${ss.significance.significant?"bg-emerald-500/10 border-emerald-500/30":"bg-white/5 border-white/10"}`,"data-testid":"plan-landing-ab-significance",children:[ss.significance.significant?e.jsx(be,{className:"w-5 h-5 text-emerald-400 shrink-0"}):e.jsx(js,{className:"w-5 h-5 text-muted-foreground shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:`text-sm font-medium ${ss.significance.significant?"text-emerald-400":"text-white"}`,children:ss.significance.significant?`Vencedor estatisticamente significativo: ${ss.significance.leaderKey==="hub"?"HUB":"EDITOR"}`:"Análise Estatística"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ss.significance.message})]})]}),ss?.variants&&ss.variants.some(t=>t.attempts>0)?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:ss.variants.map(t=>{const s=ss.variants.find(x=>x.key!==t.key),i=!!s&&t.attempts>0&&t.conversionRate>s.conversionRate;return e.jsxs("div",{className:`relative bg-white/5 border rounded-xl p-5 space-y-4 ${i?"border-emerald-500/50 ring-1 ring-emerald-500/20":"border-white/10"}`,"data-testid":`card-plan-landing-variant-${t.key}`,children:[i&&e.jsx("div",{className:"absolute -top-3 right-4",children:e.jsxs(E,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 gap-1",children:[e.jsx(_i,{className:"w-3 h-3"})," Líder"]})}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-lg font-bold text-white",children:t.key==="hub"?"HUB (CTA forte)":"Editor (CTA leve)"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"})," Planos prontos"]}),e.jsx("p",{className:"text-xl font-bold text-white","data-testid":`text-plan-landing-attempts-${t.key}`,children:t.attempts.toLocaleString("pt-BR")})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(be,{className:"w-3 h-3"})," Pagos"]}),e.jsx("p",{className:"text-xl font-bold text-emerald-400","data-testid":`text-plan-landing-conversions-${t.key}`,children:t.conversions.toLocaleString("pt-BR")})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 col-span-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ie,{className:"w-3 h-3"})," Conversão plano→pago"]}),e.jsxs("p",{className:"text-xl font-bold text-white","data-testid":`text-plan-landing-rate-${t.key}`,children:[t.conversionRate,"%"]})]})]})]},t.key)})}):e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-10 text-center space-y-2","data-testid":"plan-landing-ab-empty",children:[e.jsx(Oi,{className:"w-10 h-10 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Ainda sem dados — nenhum livro foi atribuído a uma variante ainda."}),!ss?.testEnabled&&e.jsx("p",{className:"text-muted-foreground text-xs",children:"O teste está desligado (ENABLE_PLAN_LANDING_AB_TEST≠true)."})]})]})}),e.jsx(Be,{value:"margin",className:"mt-6 space-y-6",children:e.jsx(Hb,{})}),e.jsx(Be,{value:"social-media",className:"mt-6 space-y-6",children:e.jsx(hb,{})}),e.jsx(Be,{value:"author-health",className:"mt-6 space-y-6",children:sp?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-orange-400"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Frustrados",value:Ea?.summary?.frustrated_count||0,color:"text-red-400",bg:"bg-red-500/10"},{label:"Voz Negativa",value:Ea?.summary?.negative_voice_count||0,color:"text-orange-400",bg:"bg-orange-500/10"},{label:"Voz Parcial",value:Ea?.summary?.partial_voice_count||0,color:"text-amber-400",bg:"bg-amber-500/10"},{label:"Voz Positiva",value:Ea?.summary?.positive_voice_count||0,color:"text-emerald-400",bg:"bg-emerald-500/10"},{label:"Travados +30min",value:Ea?.summary?.stuck_count||0,color:"text-purple-400",bg:"bg-purple-500/10"}].map((t,s)=>e.jsxs("div",{className:`${t.bg} border border-white/5 rounded-xl p-4`,"data-testid":`health-stat-${s}`,children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:t.label}),e.jsx("p",{className:`text-2xl font-bold ${t.color}`,children:String(t.value)})]},s))}),e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 flex items-center gap-2",children:[e.jsx(Xm,{className:"w-4 h-4 text-red-400"}),e.jsx("h3",{className:"text-sm font-bold text-white",children:"Autores em Risco"}),e.jsxs(E,{variant:"outline",className:"ml-auto text-xs",children:[Ea?.atRiskAuthors?.length||0," autores"]})]}),!Ea?.atRiskAuthors||Ea.atRiskAuthors.length===0?e.jsx("div",{className:"p-8 text-center text-muted-foreground text-sm",children:"Nenhum autor em risco no momento"}):e.jsx("div",{className:"divide-y divide-white/5",children:Ea.atRiskAuthors.map(t=>e.jsxs("div",{className:"px-4 py-3 flex items-center gap-3 hover:bg-white/5 transition-colors","data-testid":`at-risk-author-${t.book_id}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-white truncate",children:t.user_name||t.email}),t.frustration_flag&&e.jsx(E,{variant:"destructive",className:"text-[10px] py-0",children:"Frustrado"}),t.voice_feedback==="negative"&&e.jsx(E,{className:"bg-orange-500/20 text-orange-300 text-[10px] py-0 border-orange-500/30",children:"Voz negativa"}),t.voice_feedback==="partial"&&e.jsx(E,{className:"bg-amber-500/20 text-amber-300 text-[10px] py-0 border-amber-500/30",children:"Voz parcial"}),t.status==="generating"&&e.jsx(E,{className:"bg-purple-500/20 text-purple-300 text-[10px] py-0 border-purple-500/30",children:"Travado"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:["Livro: ",t.title," — Modo: ",t.kb_mode||"inspired"," — Progresso: ",t.progress||0,"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground shrink-0",children:t.updated_at?new Date(t.updated_at).toLocaleDateString("pt-BR"):""})]},t.book_id))})]})]})}),e.jsx(Be,{value:"disputes",className:"mt-6",children:e.jsx(Yg,{})}),e.jsx(Be,{value:"influencers",className:"mt-6",children:e.jsx(eb,{})}),e.jsx(Be,{value:"author-prospector",className:"mt-6",children:e.jsx(db,{})}),e.jsx(Be,{value:"ebook-funnel",className:"mt-6",children:e.jsx(Ib,{})}),e.jsx(Be,{value:"ops",className:"mt-6",children:e.jsx(pu,{onUserClick:(t,s)=>{s&&F(s),v(t),aa("users")}})}
20),e.jsx(Be,{value:"quality",className:"mt-6",children:e.jsx(Mb,{onUserClick:(t,s)=>{s&&F(s),v(t),aa("users")}})})]}),e.jsx(Je,{open:x0,onOpenChange:gr,children:e.jsxs(Ye,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:jl?"Editar Variante":"Nova Variante de Checkout"}),e.jsx(mt,{children:"Configure a variante para testes A/B do checkout."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(O,{children:"Nome da variante"}),e.jsx(J,{value:Ds.name,onChange:t=>Na(s=>({...s,name:t.target.value})),placeholder:"Ex: Control, Urgency Timer, Social Proof","data-testid":"input-checkout-variant-name"})]}),e.jsxs("div",{children:[e.jsx(O,{children:"Peso (distribuição de tráfego: 0-100)"}),e.jsx(J,{type:"number",min:0,max:100,value:Ds.weight,onChange:t=>Na(s=>({...s,weight:parseInt(t.target.value)||0})),"data-testid":"input-checkout-variant-weight"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{checked:Ds.isActive,onCheckedChange:t=>Na(s=>({...s,isActive:t})),"data-testid":"switch-checkout-variant-active"}),e.jsx(O,{children:"Ativo"})]}),e.jsxs("div",{children:[e.jsx(O,{children:"Layout do Checkout"}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mb-3",children:[{key:"standard",label:"Pacotes (Tiers)",desc:"Essencial · Profissional · Premium",color:"emerald"},{key:"bumps",label:"Bumps Clássico",desc:"Produtos individuais",color:"orange"},{key:"minimal",label:"Minimalista",desc:"Limpo e focado em conversão",color:"sky"}].map(t=>{const s=(()=>{try{return JSON.parse(Ds.config)?.layout===t.key}catch{return t.key==="standard"}})(),i={emerald:{active:"border-emerald-500/50 bg-emerald-500/10 ring-1 ring-emerald-500/20",dot:"bg-emerald-500"},orange:{active:"border-orange-500/50 bg-orange-500/10 ring-1 ring-orange-500/20",dot:"bg-orange-500"},sky:{active:"border-sky-500/50 bg-sky-500/10 ring-1 ring-sky-500/20",dot:"bg-sky-500"}}[t.color];return e.jsxs("button",{type:"button","data-testid":`btn-layout-${t.key}`,className:`p-3 rounded-lg border text-left transition-all ${s?i.active:"border-white/10 bg-white/5 hover:bg-white/10"}`,onClick:()=>{try{const x=JSON.parse(Ds.config);x.layout=t.key,t.key==="minimal"&&(x.showTimer=!1,x.showSocialProof=!1),Na(C=>({...C,config:JSON.stringify(x,null,2)}))}catch{const x={layout:t.key};t.key==="minimal"&&(x.showTimer=!1,x.showSocialProof=!1),Na(C=>({...C,config:JSON.stringify(x,null,2)}))}},children:[e.jsx("span",{className:"text-sm font-bold text-white",children:t.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:t.desc})]},t.key)})})]}),e.jsxs("div",{children:[e.jsx(O,{children:"Config (JSON)"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mb-1",children:"layout (standard|bumps|minimal|urgency), showTimer, timerMinutes, showSocialProof, customHeadline, ctaText, ctaColor"}),e.jsx($s,{rows:8,className:"font-mono text-xs",value:Ds.config,onChange:t=>Na(s=>({...s,config:t.target.value})),placeholder:'{"layout":"standard","showTimer":true}',"data-testid":"textarea-checkout-variant-config"})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>gr(!1),"data-testid":"btn-cancel-checkout-variant",children:"Cancelar"}),e.jsxs(b,{className:"bg-orange-500 hover:bg-orange-600",disabled:!Ds.name||po.isPending||Nl.isPending,onClick:()=>{let t={};try{t=JSON.parse(Ds.config)}catch{t={}}jl?Nl.mutate({id:jl.id,data:{name:Ds.name,weight:Ds.weight,isActive:Ds.isActive,config:t}}):po.mutate({name:Ds.name,weight:Ds.weight,isActive:Ds.isActive,config:t})},"data-testid":"btn-save-checkout-variant",children:[(po.isPending||Nl.isPending)&&e.jsx(T,{className:"w-4 h-4 animate-spin mr-1.5"}),jl?"Salvar":"Criar"]})]})]})}),e.jsx(Je,{open:!!Ke,onOpenChange:t=>!t&&wm(null),children:e.jsxs(Ye,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:"Detalhes do Checkout"}),e.jsx(mt,{children:"Informações completas da sessão de checkout"})]}),o0?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):Ke&&e.jsxs("div",{className:"space-y-4","data-testid":"checkout-detail-modal",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs",children:[e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"ID"}),e.jsx("p",{className:"text-white font-mono",children:Ke.session?.id})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Status"}),e.jsx("p",{className:"text-white font-bold capitalize",children:Ke.session?.status})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Usuário"}),e.jsx("p",{className:"text-white",children:Ke.session?.userName||Ke.session?.email})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Livro"}),e.jsx("p",{className:"text-white",children:Ke.session?.bookTitle})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Variante"}),e.jsx("p",{className:"text-white",children:Ke.session?.variant||"A"})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Valor"}),e.jsx("p",{className:"text-emerald-400 font-bold",children:Ke.session?.totalAmount?`R$ ${(Ke.session.totalAmount/100).toLocaleStr
20ing("pt-BR",{minimumFractionDigits:2})}`:"-"})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Método de Pagamento"}),e.jsx("p",{className:"text-white capitalize",children:Ke.session?.paymentMethod||"-"})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Parcelas"}),e.jsx("p",{className:"text-white",children:Ke.session?.installments||"-"})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Criado em"}),e.jsx("p",{className:"text-white",children:Ke.session?.createdAt?new Date(Ke.session.createdAt).toLocaleString("pt-BR"):"-"})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Pago em"}),e.jsx("p",{className:"text-white",children:Ke.session?.paidAt?new Date(Ke.session.paidAt).toLocaleString("pt-BR"):"-"})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Checkout Visualizado"}),e.jsx("p",{className:"text-white",children:Ke.session?.checkoutViewedAt?new Date(Ke.session.checkoutViewedAt).toLocaleString("pt-BR"):"Não"})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Drip Email Step"}),e.jsxs("p",{className:"text-white",children:[Ke.session?.abandonedEmailStep||0,"/15"]})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Último Drip"}),e.jsx("p",{className:"text-white",children:Ke.session?.lastDripSentAt?new Date(Ke.session.lastDripSentAt).toLocaleString("pt-BR"):"-"})]}),e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Recovery Email"}),e.jsx("p",{className:"text-white",children:Ke.session?.recoverySentAt?new Date(Ke.session.recoverySentAt).toLocaleString("pt-BR"):"-"})]})]}),Ke.session?.selectedBumps&&e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground font-medium",children:"Bumps Selecionados"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:(Array.isArray(Ke.session.selectedBumps)?Ke.session.selectedBumps:[]).map((t,s)=>e.jsx(E,{variant:"outline",className:"text-[10px]",children:t.name||t.title||t},s))})]}),Ke.session?.pipelineStatus&&e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground font-medium",children:"Pipeline Status"}),e.jsx("div",{className:"space-y-1.5",children:["book","cover","publication","marketing"].map(t=>{const s=Ke.session.pipelineStatus?.[t];if(!s)return null;const i=s==="failed"||s==="generating";return e.jsxs("div",{className:"flex items-center justify-between text-xs bg-white/5 rounded p-2",children:[e.jsx("span",{className:"text-white capitalize font-medium",children:t}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono ${s==="done"?"bg-emerald-500/20 text-emerald-400":s==="failed"?"bg-red-500/20 text-red-400":s==="generating"?"bg-amber-500/20 text-amber-400":"bg-white/10 text-white/50"}`,children:s}),i&&Ke.session?.bookId&&e.jsx("button",{className:"px-2 py-0.5 rounded text-[10px] font-medium bg-violet-500/20 text-violet-400 hover:bg-violet-500/30 transition-colors","data-testid":`button-retry-pipeline-${t}`,onClick:async()=>{try{const x=await fetch(`/api/admin/books/${Ke.session.bookId}/retry-pipeline/${t}`,{method:"POST",credentials:"include"}),C=await x.json();x.ok?r({title:"Retry iniciado",description:C.message}):r({title:"Erro",description:C.message,variant:"destructive"})}catch(x){r({title:"Erro",description:x.message,variant:"destructive"})}},children:"Retry"})]})]},t)})}),e.jsx("pre",{className:"text-[10px] text-white/40 overflow-auto max-h-20 mt-1",children:JSON.stringify(Ke.session.pipelineStatus,null,2)})]}),Ke.orders&&Ke.orders.length>0&&e.jsxs("div",{className:"bg-white/5 rounded-lg p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground font-medium",children:["Pedidos Relacionados (",Ke.orders.length,")"]}),e.jsx("div",{className:"space-y-1",children:Ke.orders.map(t=>e.jsxs("div",{className:"flex items-center justify-between text-xs bg-white/5 rounded p-2",children:[e.jsx("span",{className:"text-white font-mono",children:t.id.substring(0,8)}),e.jsx("span",{className:"text-white",children:t.type}),e.jsxs("span",{className:"text-emerald-400",children:["R$ ",(t.amount/100).toLocaleStr
20ing("pt-BR",{minimumFractionDigits:2})]}),e.jsx(Gi,{status:t.status})]},t.id))})]})]})]})}),e.jsx(Je,{open:vd,onOpenChange:Nd,children:e.jsxs(Ye,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:fd?"Editar Template":"Novo Template"}),e.jsx(mt,{children:"Configure o template de notificação para marketing e vendas."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(O,{children:"Nome"}),e.jsx(J,{value:Et.name,onChange:t=>la(s=>({...s,name:t.target.value})),placeholder:"Ex: Boas-vindas","data-testid":"input-template-name"})]}),e.jsxs("div",{children:[e.jsx(O,{children:"Canal"}),e.jsxs(Se,{value:Et.channel,onValueChange:t=>la(s=>({...s,channel:t})),children:[e.jsx($e,{"data-testid":"select-template-channel",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"email",children:"Email"}),e.jsx(U,{value:"whatsapp",children:"WhatsApp"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(O,{children:"Categoria"}),e.jsxs(Se,{value:Et.category,onValueChange:t=>la(s=>({...s,category:t})),children:[e.jsx($e,{children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"marketing",children:"Marketing"}),e.jsx(U,{value:"transactional",children:"Transacional"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(rt,{checked:Et.active,onCheckedChange:t=>la(s=>({...s,active:t}))}),e.jsx(O,{children:"Ativo"})]})]}),Et.channel==="email"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(O,{children:"Assunto do Email"}),e.jsx(J,{value:Et.subject,onChange:t=>la(s=>({...s,subject:t.target.value})),placeholder:"Ex: {{user_name}}, seu livro está quase pronto!","data-testid":"input-template-subject"})]}),e.jsxs("div",{children:[e.jsx(O,{children:"Conteúdo HTML"}),e.jsx($s,{rows:10,className:"font-mono text-xs",value:Et.htmlContent,onChange:t=>la(s=>({...s,htmlContent:t.target.value})),placeholder:"HTML do email...","data-testid":"textarea-template-html"})]})]}),Et.channel==="whatsapp"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-green-500/5 border border-green-500/20 rounded-xl p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Ul,{className:"w-4 h-4 text-green-400"}),"Template Meta (API Oficial)"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"border-green-500/30 text-green-400 hover:bg-green-500/10",onClick:Fm,disabled:$x,"data-testid":"button-fetch-meta-templates",children:[$x?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin mr-1.5"}):e.jsx(xe,{className:"w-3.5 h-3.5 mr-1.5"}),Rr.length>0?"Atualizar":"Buscar Templates"]})]}),Rr.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{className:"text-xs",children:"Selecionar Template"}),e.jsxs(Se,{value:Et.whatsappTemplateName||"",onValueChange:t=>{const s=Rr.find(i=>i.name===t);s&&E0(s)},children:[e.jsx($e,{"data-testid":"select-meta-template",children:e.jsx(Ae,{placeholder:"Escolha um template aprovado..."})}),e.jsx(Pe,{children:Rr.map(t=>e.jsxs(U,{value:t.name,children:[t.name," (",t.language,") — ",t.category?.toLowerCase()]},`${t.name}-${t.language}`))})]})]}),er&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-black/20 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Prévia do Template"}),er.components?.map((t,s)=>e.jsxs("div",{className:"text-xs",children:[e.jsxs("span",{className:"text-[10px] text-green-400 uppercase font-mono mr-2",children:[t.type,":"]}),e.jsx("span",{className:"text-white/80",children:t.text||(t.format?`[${t.format}]`:"[sem texto]")})]},s))]}),Object.keys(Mn).length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Mapeamento de Variáveis"}),e.jsx("p",{className:"text-[10px] text-white/40",children:"Para cada variável do template Meta, escolha qual dado da plataforma será enviado."}),Object.entries(Mn).map(([t,s])=>{const[i,x]=t.split("_");return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-xs font-mono text-green-400 w-28 shrink-0",children:[i.toUpperCase()," ",`{{${x}}}`]}),e.jsxs(Se,{value:s,onValueChange:C=>Px(P=>({...P,[t]:C})),children:[e.jsx($e,{className:"flex-1 h-8 text-xs","data-testid":`select-var-${t}`,children:e.jsx(Ae,{placeholder:"Selecione a variável..."})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"{{user_name}}",children:"Nome do usuário"}),e.jsx(U,{value:"{{user_email}}",children:"Email do usuário"}),e.jsx(U,{value:"{{user_phone}}",children:"Telefone do usuário"}),e.jsx(U,{value:"{{book_title}}",children:"Título do livro"}),e.jsx(U,{value:"{{book_genre}}",children:"Gênero do livro"}),e.jsx(U,{value:"{{book_author}}",children:"Autor do livro"}),e.jsx(U,{value:"{{book_status}}",children:"Status do livro"}),e.jsx(U,{value:"{{total_chapters}}",children:"Total de capítulos"}),e.jsx(U,{value:"{{completed_chapters}}",children:"Capítulos concluídos"}),e.jsx(U,{value:"{{service_name}}",children:"Nome do serviço"}),e.jsx(U,{value:"{{service_price}}
20",children:"Preço do serviço"}),e.jsx(U,{value:"{{order_id}}",children:"ID do pedido"}),e.jsx(U,{value:"{{order_amount}}",children:"Valor do pedido"}),e.jsx(U,{value:"{{order_status}}",children:"Status do pedido"}),e.jsx(U,{value:"{{app_name}}",children:"Nome da plataforma"}),e.jsx(U,{value:"{{logo_url}}",children:"URL da logo"})]})]})]},t)})]})]}),!er&&Et.whatsappTemplateName&&e.jsxs("div",{className:"text-xs text-white/50 flex items-center gap-2",children:[e.jsx("span",{children:"Template configurado manualmente:"}),e.jsx("span",{className:"font-mono text-green-400",children:Et.whatsappTemplateName})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("button",{type:"button",className:"text-[10px] text-white/40 hover:text-white/60 transition-colors uppercase tracking-wider",onClick:()=>{const t=document.getElementById("whatsapp-advanced-config");t&&t.classList.toggle("hidden")},"data-testid":"button-toggle-advanced",children:"▸ Configuração Avançada (JSON)"}),e.jsxs("div",{id:"whatsapp-advanced-config",className:"hidden space-y-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Nome do Template"}),e.jsx(J,{value:Et.whatsappTemplateName,onChange:t=>la(s=>({...s,whatsappTemplateName:t.target.value})),placeholder:"Ex: book_ready_notification","data-testid":"input-whatsapp-template-name"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Idioma"}),e.jsx(J,{value:Et.whatsappTemplateLanguage,onChange:t=>la(s=>({...s,whatsappTemplateLanguage:t.target.value})),placeholder:"pt_BR"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Componentes (JSON)"}),e.jsx($s,{rows:6,className:"font-mono text-xs",value:Et.whatsappComponents,onChange:t=>la(s=>({...s,whatsappComponents:t.target.value})),placeholder:'[{"type":"body","parameters":[{"type":"text","text":"{{user_name}}"}]}]',"data-testid":"textarea-whatsapp-components"})]})]})]})]}),Et.channel!=="whatsapp"&&e.jsxs("div",{children:[e.jsx(O,{children:"Conteúdo Texto (fallback)"}),e.jsx($s,{rows:5,value:Et.textContent,onChange:t=>la(s=>({...s,textContent:t.target.value})),placeholder:"Texto simples com {{variáveis}}...","data-testid":"textarea-template-text"})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"ghost",onClick:()=>Nd(!1),children:"Cancelar"}),e.jsxs(b,{onClick:()=>{let t=[];if(er&&Object.values(Mn).some(s=>s))t=I0();else try{t=JSON.parse(Et.whatsappComponents)}catch{}Wo.mutate({...Et,whatsappComponents:Et.channel==="whatsapp"?t:null})},disabled:Wo.isPending,"data-testid":"button-save-template",children:[Wo.isPending&&e.jsx(T,{className:"w-4 h-4 mr-1 animate-spin"}),"Salvar"]})]})]})}),K0(),e.jsx(Je,{open:v0,onOpenChange:So,children:e.jsxs(Ye,{children:[e.jsxs(Ze,{children:[e.jsxs(et,{children:["Credenciais — ",oa?.name]}),e.jsx(mt,{children:"Gerencie as chaves de API e credenciais para integração."})]}),Ko&&Ko.length>0&&e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Credenciais Ativas"}),Ko.map(t=>e.jsxs("div",{className:"flex items-center justify-between bg-white/5 border border-white/10 rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-white",children:t.credentialKey}),e.jsx("p",{className:"text-[10px] text-muted-foreground font-mono",children:t.maskedValue}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx(E,{variant:"outline",className:"text-[9px]",children:t.environment}),e.jsx(E,{variant:"outline",className:"text-[9px]",children:t.credentialType})]})]}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7 text-red-400 hover:bg-red-500/10",onClick:()=>{confirm("Remover esta credencial?")&&T0.mutate(t.id)},children:e.jsx(As,{className:"w-3.5 h-3.5"})})]},t.id))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(O,{className:"text-xs text-muted-foreground",children:"Adicionar Nova Credencial"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Tipo"}),e.jsxs(Se,{value:ca.credentialType,onValueChange:t=>an({...ca,credentialType:t}),children:[e.jsx($e,{className:"bg-white/5 border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"api_key",children:"API Key"}),e.jsx(U,{value:"api_secret",children:"API Secret"}),e.jsx(U,{value:"oauth_token",children:"OAuth Token"}),e.jsx(U,{value:"webhook_secret",children:"Webhook Secret"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Ambiente"}),e.jsxs(Se,{value:ca.environment,onValueChange:t=>an({...ca,environment:t}),children:[e.jsx($e,{className:"bg-white/5 border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"sandbox",children:"Sandbox"}),e.jsx(U,{value:"production",children:"Produção"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Nome da Chave"}),e.jsx(J,{value:ca.credentialKey,onChange:t=>an({...ca,credentialKey:t.target.value}),placeholder:"x-api-key",className:"bg-white/5 border-white/10","data-testid":"input-credential-key"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Valor"}),e.jsx(J,{type:"password",value:ca.credentialValue,onChange:t=>an({...ca,credentialValue:t.target.value}),placeholder:"sk_live_...",className:"bg-white/5 border-white/10","data-testid":"input-credential-value"})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>So(!1),children:"Fechar"}),e.jsxs(b,{onClick:()=>Go.mutate(ca),disabled:!ca.credentialKey||!ca.credentialValue||Go.isPending,"data-testid":"btn-save-credential",children:[Go.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin mr-1"}):e.jsx(_t,{className:"w-4 h-4 mr-1"}),"Adicionar"]})]})]})}),e.jsx(Je,{open:N0,onOpenChange:$o,children:e.jsxs(Ye,{children:[e.jsxs(Ze,{children:[e.jsxs(et,{children:["Configuração — ",oa?.name]}),e.jsx(mt,{children:"Configure taxas, formatos e detalhes da integração."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Taxa de Royalty (0-1)"}),e.jsx(J,{type:"number",step:"0.01",min:"0",max:"1",value:xa.royaltyRate,onChange:t=>rn({...xa,royaltyRate:parseFloat(t.target.value)||0}),className:"bg-white/5 border-white/10","data-testid":"input-royalty-rate"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Ex: 0.70 = autor recebe 70%"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Comissão SÁBHIA (0-1)"}),e.jsx(J,{type:"number",step:"0.01",min:"0",max:"1",value:xa.sabhiaCommission,onChange:t=>rn({...xa,sabhiaCommission:parseFloat(t.target.value)||0}),className:"bg-white/5 border-white/10","data-testid":"input-sabhia-commission"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Ex: 0.05 = SÁBHIA fica com 5%"})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Método de Autenticação"}),e.jsxs(Se,{value:xa.authMethod,onValueChange:t=>rn({...xa,authMethod:t}),children:[e.jsx($e,{className:"bg-white/5 border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"api_key",children:"API Key"}),e.jsx(U,{value:"oauth2",children:"OAuth 2.0"}),e.jsx(U,{value:"manual",children:"Manual (sem API)"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"URL da Documentação da API"}),e.jsx(J,{value:xa.apiDocUrl,onChange:t=>rn({...xa,apiDocUrl:t.target.value}),placeholder:"https://developers.example.com/docs",className:"bg-white/5 border-white/10","data-testid":"input-api-doc-url"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Formatos Suportados"}),e.jsx(J,{value:(xa.supportedFormats||[]).join(", "),onChange:t=>rn({...xa,supportedFormats:t.target.value.split(",").map(s=>
20s.trim()).filter(Boolean)}),placeholder:"epub, pdf, docx",className:"bg-white/5 border-white/10","data-testid":"input-supported-formats"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Separe por vírgulas"})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>$o(!1),children:"Cancelar"}),e.jsxs(b,{onClick:()=>Vo.mutate(xa),disabled:Vo.isPending,"data-testid":"btn-save-config",children:[Vo.isPending&&e.jsx(T,{className:"w-4 h-4 animate-spin mr-1"}),"Salvar Configuração"]})]})]})}),e.jsx(Je,{open:f0,onOpenChange:Ao,children:e.jsxs(Ye,{className:"max-w-2xl",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:"Importar Vendas"}),e.jsx(mt,{children:"Cole os dados de vendas no formato JSON para importar registros de vendas das plataformas."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-black/20 border border-white/10 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Formato esperado (JSON array):"}),e.jsx("pre",{className:"text-[10px] text-emerald-400 font-mono overflow-x-auto",children:`[{
21  "bookId": "uuid-do-livro",
22  "userId": "uuid-do-autor",
23  "platform": "amazon_kdp",
24  "units": 5,
25  "grossRevenue": 49.95,
26  "netRevenue": 34.97,
27  "royaltyAmount": 33.22,
28  "platformFee": 14.98,
29  "sabhiaFee": 1.75,
30  "period": "2025-01",
31  "currency": "BRL"
32}]`})]}),e.jsx($s,{value:Po,onChange:t=>Tm(t.target.value),placeholder:'[{"bookId": "...", "userId": "...", ...}]',className:"bg-white/5 border-white/10 font-mono text-xs min-h-[200px]","data-testid":"textarea-sales-import"})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>Ao(!1),children:"Cancelar"}),e.jsxs(b,{onClick:()=>{try{const t=JSON.parse(Po);if(!Array.isArray(t))throw new Error("Dados devem ser um array JSON");Qo.mutate({records:t})}catch(t){r({title:"Formato inválido",description:t.message,variant:"destructive"})}},disabled:!Po||Qo.isPending,"data-testid":"btn-confirm-import",children:[Qo.isPending&&e.jsx(T,{className:"w-4 h-4 animate-spin mr-1"}),"Importar"]})]})]})}),e.jsx(Je,{open:np,onOpenChange:Fn,children:e.jsxs(Ye,{children:[e.jsxs(Ze,{children:[e.jsx(et,{children:Ir?"Editar Plataforma":"Nova Plataforma"}),e.jsx(mt,{children:Ir?"Atualize os dados da plataforma.":"Adicione uma nova plataforma de publicação."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Nome"}),e.jsx(J,{value:Ft.name,onChange:t=>ti({...Ft,name:t.target.value}),placeholder:"Amazon KDP","data-testid":"input-platform-name"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Slug (identificador)"}),e.jsx(J,{value:Ft.slug,onChange:t=>ti({...Ft,slug:t.target.value}),placeholder:"amazon_kdp","data-testid":"input-platform-slug"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Emoji"}),e.jsx(J,{value:Ft.emoji,onChange:t=>ti({...Ft,emoji:t.target.value}),placeholder:"📚","data-testid":"input-platform-emoji"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Tipo"}),e.jsxs(Se,{value:Ft.type,onValueChange:t=>ti({...Ft,type:t}),children:[e.jsx($e,{"data-testid":"select-platform-type",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"manual",children:"Manual"}),e.jsx(U,{value:"api",children:"API Automática"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Descrição"}),e.jsx(J,{value:Ft.description,onChange:t=>ti({...Ft,description:t.target.value}),placeholder:"Maior loja do mundo","data-testid":"input-platform-desc"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Nº de Lojas"}),e.jsx(J,{type:"number",value:Ft.storeCount,onChange:t=>ti({...Ft,storeCount:parseInt(t.target.value)||1}),"data-testid":"input-platform-stores"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Ordem de Exibição"}),e.jsx(J,{type:"number",value:Ft.displayOrder,onChange:t=>ti({...Ft,displayOrder:parseInt(t.target.value)||0}),"data-testid":"input-platform-order"})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"URL da Logo (opcional)"}),e.jsx(J,{value:Ft.logoUrl,onChange:t=>ti({...Ft,logoUrl:t.target.value}),placeholder:"https://...","data-testid":"input-platform-logo"})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>Fn(!1),children:"Cancelar"}),e.jsx(b,{onClick:()=>{Ir?P0.mutate({id:Ir.id,data:Ft}):A0.mutate(Ft)},disabled:!Ft.name||!Ft.slug,"data-testid":"btn-save-platform",children:Ir?"Salvar":"Criar"})]})]})})]}),e.jsx(Je,{open:!!q,onOpenChange:t=>{t||(V(null),Ta(""),Zi(""))},children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-md",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(jc,{className:"w-5 h-5 text-amber-400"}),"Adicionar Créditos"]}),e.jsxs(mt,{className:"text-muted-foreground",children:["Adicionando créditos para: ",e.jsx("span",{className:"text-white font-medium",children:q?.userName})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-sm",children:"Quantidade de créditos"}),e.jsx(J,{type:"number",min:"1",max:"1000000",placeholder:"Ex: 10000",value:os,onChange:t=>Ta(t.target.value),className:"mt-1","data-testid":"input-admin-credits-amount"}),os&&parseInt(os)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Equivalente a R$ ",(parseInt(os)/100).toFixed(2).replace(".",",")]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-sm",children:"Motivo"}),e.jsx($s,{placeholder:"Ex: Compensação por problema técnico",value:Ps,onChange:t=>Zi(t.target.value),className:"mt-1",rows:3,"data-testid":"input-admin-credits-reason"})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>{V(null),Ta(""),Zi("")},children:"Cancelar"}),e.jsxs(b,{onClick:()=>{const t=parseInt(os);t>0&&Ps.trim()&&q&&dd.mutate({userId:q.userId,amount:t,reason:Ps.trim()})},disabled:!os||parseInt(os)<=0||!Ps.trim()||dd.isPending,className:"bg-amber-500 hover:bg-amber-600 text-black","data-testid":"button-confirm-ad
32d-credits",children:[dd.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin mr-1"}):e.jsx(_t,{className:"w-4 h-4 mr-1"}),"Adicionar"]})]})]})}),e.jsx(Je,{open:!!ia,onOpenChange:t=>{t||(En(null),Ja(null),Tr(""))},children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-lg",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Oi,{className:"w-5 h-5 text-orange-400"}),"Mesclar Contas Duplicadas"]}),e.jsx(mt,{className:"text-muted-foreground",children:"Transferir todos os dados da conta temporária para uma conta com email real."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-white/5 border border-white/10 space-y-1",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Conta Origem (será removida)"}),e.jsx("p",{className:"text-sm font-medium text-white",children:ia?.sourceUser?.name||"Sem nome"}),e.jsx("p",{className:"text-xs text-orange-400 font-mono",children:ia?.sourceUser?.email}),ia?.sourceUser?.phone&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Tel: ",ia.sourceUser.phone]}),e.jsxs("div",{className:"flex gap-3 mt-2",children:[e.jsxs("span",{className:"text-xs text-white",children:[ia?.sourceUser?.booksCount||0," livros"]}),e.jsxs("span",{className:"text-xs text-emerald-400",children:["R$ ",ia?.sourceUser?.totalSpent?.toFixed(2)||"0.00"]})]})]}),e.jsx("div",{className:"flex justify-center",children:e.jsx(ka,{className:"w-5 h-5 text-orange-400 rotate-90"})}),e.jsxs("div",{children:[e.jsx(O,{className:"text-sm",children:"Email da conta destino"}),e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(J,{type:"email",placeholder:"[email protected]",value:id,onChange:t=>{Tr(t.target.value),Ja(null)},className:"flex-1","data-testid":"input-merge-target-email"}),e.jsx(b,{size:"sm",variant:"outline",className:"border-orange-500/20 text-orange-400 hover:bg-orange-500/10",onClick:()=>ia&&qh(ia.sourceUser,id),disabled:!id.trim()||Bc,"data-testid":"button-merge-search",children:Bc?e.jsx(T,{className:"w-4 h-4 animate-spin"}):e.jsx(St,{className:"w-4 h-4"})})]})]}),Ts&&e.jsxs("div",{className:"p-3 rounded-lg bg-emerald-500/5 border border-emerald-500/10 space-y-1",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Conta Destino (será mantida)"}),e.jsx("p",{className:"text-sm font-medium text-white",children:Ts.targetUser.name||"Sem nome"}),e.jsx("p",{className:"text-xs text-emerald-400 font-mono",children:Ts.targetUser.email}),Ts.targetUser.phone&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Tel: ",Ts.targetUser.phone]}),e.jsxs("div",{className:"flex gap-3 mt-2",children:[e.jsxs("span",{className:"text-xs text-white",children:[Ts.targetUser.booksCount||0," livros"]}),e.jsxs("span",{className:"text-xs text-emerald-400",children:["R$ ",Ts.targetUser.totalSpent?.toFixed(2)||"0.00"]})]})]}),Ts&&e.jsxs("div",{className:"p-3 rounded-lg bg-amber-500/5 border border-amber-500/20 flex items-start gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-amber-400 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-amber-200/80",children:[e.jsx("p",{className:"font-medium",children:"Esta ação é irreversível!"}),e.jsxs("p",{className:"mt-1",children:["Todos os livros, créditos, pedidos e dados da conta ",e.jsx("span",{className:"text-orange-400",children:ia?.sourceUser?.email})," serão transferidos para ",e.jsx("span",{className:"text-emerald-400",children:Ts.targetUser.email}),". A conta de origem será removida."]})]})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>{En(null),Ja(null),Tr("")},children:"Cancelar"}),e.jsxs(b,{onClick:_h,disabled:!Ts||_c,className:"bg-orange-500 hover:bg-orange-600 text-black","data-testid":"button-confirm-merge",children:[_c?e.jsx(T,{className:"w-4 h-4 animate-spin mr-1"}):e.jsx(Oi,{className:"w-4 h-4 mr-1"}),"Confirmar Mesclagem"]})]})]})}),e.jsx(Je,{open:!!ce,onOpenChange:t=>{t||(he(null),xt(""),Zt(""))},children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-lg",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Fu,{className:"w-5 h-5 text-primary"}),"Alterar Papel do Usuário"]}),e.jsxs(mt,{className:"text-muted-foreground",children:["Usuário: ",e.jsx("span",{className:"text-white font-medium",children:ce?.userName})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[ce?.userId===a?.id&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border border-amber-500/20 bg-amber-500/5",children:[e.jsx(Ce,{className:"w-5 h-5 text-amber-400 shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-sm text-amber-200",children:["Você está alterando o ",e.jsx("span",{className:"font-semibold",children:"seu próprio"})," papel. Por segurança, a plataforma nunca pode ficar sem nenhum administrador — se você for o único admin, promova outro usuário a administrador antes de remover seu acesso."]})]}),e.jsx("div",{className:"space-y-2",children:[{role:"user",label:"Usuário",description:"Acesso padrão à plataforma. Pode criar livros e usar os serviços.",icon:Re,color:"border-white/10 hover:border-white/30",selectedColor:"border-white/40 bg-white/5",textColor:"text-white"},{role:"openclaw",label:"Publicador",description:"Acesso ao painel de publicação OpenClaw. Pode processar publicações de livros.",icon:ot,color:"border-blue-500/20 hover:border-blue-500/40",selectedColor:"border-blue-500/50 bg-blue-500/10",textColor:"text-blue-400"},{role:"support",label:"Suporte",description:"Acesso ao painel de atendimento. Pode responder chats, adicionar créditos (máx 500) e gerar magic links.",icon:Um,color:"border-orange-500/20 hover:border-orange-500/40",selectedColor:"border-orange-500/50 bg-orange-500/10",textColor:"text-orange-400"},{role:"admin",label:"Administrador",description:"Acesso TOTAL à plataforma. Gerencia usuários, pedidos, configurações e tudo mais.",icon:Ks,color:"border-red-500/20 hover:border-red-500/40",selectedColor:"border-red-500/50 bg-red-500/10",textColor:"text-red-400"}].map(t=>{const s=ce?.currentRole===t.role,i=ke===t.role;return e.jsxs("button",{onClick:()=>{xt(t.role),Zt("")},disabled:s,className:`w-full flex items-start gap-3 p-3 rounded-lg border transition-all text-left ${s?"border-primary/30 bg-primary/5 opacity-60 cursor-not-allowed":i?t.selectedColor:`${t.color} cursor-pointer`}`,"data-testid":`button-role-option-${t.role}`,children:[e.jsx(t.icon,{className:`w-5 h-5 mt-0.5 shrink-0 ${s?"text-primary":i?t.textColor:"text-muted-foreground"}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-sm font-medium ${s?"text-primary":i?t.textColor:"text-white"}`,children:t.label}),s&&e.jsx(E,{variant:"outline",className:"text-[9px] border-primary/30 text-primary",children:"Atual"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t.description})]})]},t.role)})}),ke==="admin"&&e.jsxs("div",{className:"space-y-2 p-3 rounded-lg border border-red-500/20 bg-red-500/5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-red-400"}),e.jsx("p",{className:"text-xs font-medium text-red-300",children:"Esta ação dará acesso TOTAL à plataforma"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Digite ",e.jsx("span",{className:"font-mono text-red-400 font-bold",children:"CONFIRMAR"})," abaixo para habilitar a mudança:"]}),e.jsx(J,{value:At,onChange:t=>Zt(t.target.value.toUpperCase()),placeholder:"Digite CONFIRMAR",className:"mt-1 border-red-500/20 bg-black/30 text-center font-mono tracking-widest uppercase","data-testid":"input-role-admin-confirm"})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>{he(null),xt(""),Zt("")},"data-testid":"button-role-cancel",children:"Cancelar"}),e.jsxs(b,{onClick:()=>{ce&&ke&&ke!==ce.currentRole&&(Yo.mutate({id:ce.userId,role:ke}),he(null),xt(""),Zt(""))},disabled:!ke||ke===ce?.currentRole||ke==="admin"&&At!=="CONFIRMAR"||Yo.isPending,className:`${ke==="admin"?"bg-red-600 hover:bg-red-700":ke==="openclaw"?"bg-blue-600 hover:bg-blue-700":"bg-primary hover:bg-primary/90"} text-white`,"data-testid":"button-role-confirm",children:[Yo.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin mr-1"}):e.jsx(is,{className:"w-4 h-4 mr-1"}),"Confirmar Alteração"]})]})]})}),e.jsx(Je,{open:Np,onOpenChange:tr,children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-lg",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Xt,{className:"w-5 h-5 text-teal-400"}),"Gerar Novo Criativo"]}),e.jsx(mt,{className:"text-muted-foreground",children:"Configure o ângulo de persuasão, público e formato do anúncio."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"flex rounded-lg border border-white/10 overflow-hidden",children:[e.jsx("button",{onClick:()=>Ws(t=>({...t,mode:"standard"})),className:`flex-1 py-2.5 text-xs font-medium transition-colors ${Ve.mode==="standard"?"bg-teal-600/20 text-teal-400":"bg-white/5 text-white/60 hover:bg-white/10"}`,"data-testid":"btn-mode-standard",children:"Modo Padrão"}),e.jsx("button",{onClick:()=>Ws(t=>({...t,mode:"concept"})),className:`flex-1 py-2.5 text-xs font-medium transition-colors ${Ve.mode==="concept"?"bg-teal-600/20 text-teal-400":"bg-white/5 text-white/60 hover:bg-white/10"}`,"data-testid":"btn-mode-concept",children:"Conceito Livre"})]}),Ve.mode==="concept"?e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-2 block",children:"Descreva sua ideia / conceito criativo"}),e.jsx("textarea",{value:Ve.conceptIdea,onChange:t=>Ws(s=>({...s,conceptIdea:t.target.value})),placeholder:"Ex: Dia da Mulher — mulheres que realizaram o sonho de publicar seu livro, empoderamento feminino, histórias reais de autoras na plataforma...",className:"w-full bg-black/20 border border-white/10 rounded-lg px-3 py-2.5 text-sm text-white placeholder:text-white/30 resize-none focus:outline-none focus:ring-1 focus:ring-teal-500/50",rows:4,maxLength:2e3,"data-testid":"textarea-concept-idea"}),e.jsxs("p",{className:"text-[10px] text-white/30 mt-1",children:[Ve.conceptIdea.length,"/2000 — Descreva o tema, tom, público, datas comemorativas, referências..."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-2 block",children:"Ângulo de Persuasão"}),e.jsxs(Se,{value:Ve.angle,onValueChange:t=>Ws(s=>({...s,angle:t})),children:[e.jsx($e,{"data-testid":"select-ad-angle",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"transformacao",children:"🎯 Transformação Pessoal"}
32),e.jsx(U,{value:"preco",children:"💰 Facilidade / Preço Acessível"}),e.jsx(U,{value:"tecnologia",children:"⚡ Tecnologia / IA"}),e.jsx(U,{value:"prova_social",children:"📊 Prova Social"}),e.jsx(U,{value:"urgencia",children:"🔥 Urgência"}),e.jsx(U,{value:"autoridade",children:"🌟 Autoridade"}),e.jsx(U,{value:"curiosidade",children:"❓ Curiosidade"}),e.jsx(U,{value:"antes_depois",children:"🔄 Antes / Depois"}),e.jsx(U,{value:"contrario",children:"🔀 Contrário"}),e.jsx(U,{value:"paradoxo",children:"🧩 Paradoxo"}),e.jsx(U,{value:"pop_quiz",children:"🎲 Pop Quiz"}),e.jsx(U,{value:"curiosidade_especifica",children:"🔍 Curiosidade Específica"}),e.jsx(U,{value:"conspiracao",children:"🕵️ Conspiração"}),e.jsx(U,{value:"teaser_mecanismo",children:"⚙️ Teaser do Mecanismo"}),e.jsx(U,{value:"truque",children:"🎩 Truque"}),e.jsx(U,{value:"receita_estranha",children:"🧪 Receita Estranha"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-2 block",children:"Público-Alvo"}),e.jsxs(Se,{value:Ve.targetAudience,onValueChange:t=>Ws(s=>({...s,targetAudience:t})),children:[e.jsx($e,{"data-testid":"select-ad-audience",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"autores_iniciantes",children:"✍️ Autores Iniciantes"}),e.jsx(U,{value:"empreendedores",children:"💼 Empreendedores"}),e.jsx(U,{value:"coaches",children:"🎓 Coaches / Mentores"}),e.jsx(U,{value:"religiosos",children:"⛪ Pastores / Líderes Religiosos"}),e.jsx(U,{value:"professores",children:"📚 Professores / Educadores"}),e.jsx(U,{value:"saude",children:"🏥 Profissionais de Saúde"}),e.jsx(U,{value:"geral",children:"🌐 Público Geral"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-2 block",children:"Formato"}),e.jsxs(Se,{value:Ve.format,onValueChange:t=>Ws(s=>({...s,format:t})),children:[e.jsx($e,{"data-testid":"select-ad-format",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"feed_square",children:"⬜ Feed 1:1"}),e.jsx(U,{value:"feed_vertical",children:"📱 Feed 4:5"}),e.jsx(U,{value:"story",children:"📲 Story 9:16"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-2 block",children:"Estilo Visual"}),e.jsxs(Se,{value:Ve.style,onValueChange:t=>Ws(s=>({...s,style:t})),children:[e.jsx($e,{"data-testid":"select-ad-style",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"moderno",children:"🎨 Moderno / Clean"}),e.jsx(U,{value:"luxuoso",children:"✨ Luxuoso / Premium"}),e.jsx(U,{value:"inspiracional",children:"🌅 Inspiracional"}),e.jsx(U,{value:"tech",children:"🔮 Tech / Futurista"}),e.jsx(U,{value:"editorial",children:"📰 Editorial / Clássico"})]})]})]})]}),e.jsxs("div",{className:"border-t border-white/10 pt-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(O,{className:"text-xs",children:"Incluir texto na imagem?"}),e.jsx(rt,{checked:Ve.includeOverlay,onCheckedChange:t=>Ws(s=>({...s,includeOverlay:t,overlayText:t?s.overlayText:""})),"data-testid":"toggle-overlay-text"})]}),Ve.includeOverlay&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>Ws(t=>({...t,overlayMode:"auto",overlayText:""})),className:`flex-1 py-2 rounded-lg text-xs font-medium transition-colors border ${Ve.overlayMode==="auto"?"bg-teal-600/20 text-teal-400 border-teal-500/30":"bg-white/5 text-white/60 border-white/10 hover:bg-white/10"}`,"data-testid":"btn-overlay-auto",children:"IA gera automaticamente"}),e.jsx("button",{onClick:()=>Ws(t=>({...t,overlayMode:"custom"})),className:`flex-1 py-2 rounded-lg text-xs font-medium transition-colors border ${Ve.overlayMode==="custom"?"bg-teal-600/20 text-teal-400 border-teal-500/30":"bg-white/5 text-white/60 border-white/10 hover:bg-white/10"}`,"data-testid":"btn-overlay-custom",children:"Texto personalizado"})]}),Ve.overlayMode==="auto"?e.jsx("p",{className:"text-[10px] text-teal-400/70",children:"A IA vai criar o melhor texto para a imagem baseado no ângulo e público selecionados"}):e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Texto para a imagem"}),e.jsx(J,{value:Ve.overlayText,onChange:t=>Ws(s=>({...s,overlayText:t.target.value})),placeholder:"Ex: Seu livro em dias, não meses",className:"border-white/10 bg-white/5","data-testid":"input-overlay-text"}),e.jsx("p",{className:"text-[10px] text-white/30 mt-1",children:"A IA vai integrar esse texto ao design da imagem"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-2 block",children:"Quantidade de variações"}),e.jsx("div",{className:"flex gap-2",children:[1,3,5].map(t=>e.jsxs("button",{onClick:()=>Ws(s=>
32({...s,count:t})),className:`flex-1 py-1.5 rounded-lg text-xs font-medium transition-colors border ${Ve.count===t?"bg-teal-600/20 text-teal-400 border-teal-500/30":"bg-white/5 text-white/60 border-white/10 hover:bg-white/10"}`,"data-testid":`btn-count-${t}`,children:[t," ",t===1?"criativo":"criativos"]},t))}),Ve.count>1&&e.jsxs("p",{className:"text-[10px] text-white/30 mt-1",children:["Gera ",Ve.count," copies diferentes com o mesmo ângulo/público"]})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>tr(!1),className:"border-white/10",children:"Cancelar"}),e.jsx(b,{onClick:()=>{const t={format:Ve.format,style:Ve.style};Ve.mode==="concept"?t.conceptIdea=Ve.conceptIdea.trim():(t.angle=Ve.angle,t.targetAudience=Ve.targetAudience),Ve.includeOverlay&&(Ve.overlayMode==="auto"?t.overlayText="auto":Ve.overlayText.trim()&&(t.overlayText=Ve.overlayText.trim())),Ve.count>1&&(t.count=Ve.count),Xd.mutate(t)},disabled:Xd.isPending||Ve.mode==="concept"&&!Ve.conceptIdea.trim(),className:"bg-teal-600 hover:bg-teal-700 gap-1.5","data-testid":"btn-confirm-generate-creative",children:Xd.isPending?e.jsx(e.Fragment,{children:Rx||e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Gerando..."]})}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"w-4 h-4"})," Gerar ",Ve.count>1?`${Ve.count} Criativos`:"Criativo"]})})]})]})}),e.jsx(Je,{open:fp,onOpenChange:Ln,children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(rc,{className:"w-5 h-5 text-violet-400"}),"Upload Manual de Criativo"]}),e.jsx(mt,{className:"text-muted-foreground",children:"Suba sua própria imagem e textos para criar um criativo personalizado."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:`relative border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-all ${kd?"border-violet-500/50 bg-violet-500/5":"border-white/20 hover:border-white/40 bg-white/5"}`,onClick:()=>document.getElementById("manual-image-input")?.click(),"data-testid":"dropzone-manual-image",children:[e.jsx("input",{id:"manual-image-input",type:"file",accept:"image/*",className:"hidden",onChange:t=>{const s=t.target.files?.[0];if(s){yd(s);const i=new FileReader;i.onload=x=>Cd(x.target?.result),i.readAsDataURL(s)}},"data-testid":"input-manual-image"}),kd?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:kd,alt:"Preview",className:"max-h-64 mx-auto rounded-lg object-contain"}),e.jsx("button",{onClick:t=>{t.stopPropagation(),yd(null),Cd(null)},className:"absolute top-2 right-2 bg-black/70 rounded-full p-1 hover:bg-red-500/50 transition-colors","data-testid":"btn-remove-manual-image",children:e.jsx(ea,{className:"w-4 h-4"})}),e.jsxs("p",{className:"text-xs text-violet-400 mt-2",children:[wd?.name," — Clique para trocar"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(yr,{className:"w-10 h-10 mx-auto text-white/30"}),e.jsx("p",{className:"text-sm text-white/60",children:"Clique para selecionar uma imagem"}),e.jsx("p",{className:"text-xs text-white/30",children:"PNG, JPG ou WebP — recomendado 1080x1080 ou 1080x1350"})]})]}),e.jsxs("div",{children:[e.jsxs(O,{className:"text-xs mb-1.5 block",children:["Headline ",e.jsxs("span",{className:"text-white/30",children:["(",Gt.headline.length,"/40)"]})]}),e.jsx(J,{value:Gt.headline,onChange:t=>Ti(s=>({...s,headline:t.target.value.substring(0,40)})),placeholder:"Ex: Mercado de ebooks vai movimentar bilhões",className:"border-white/10 bg-white/5",maxLength:40,"data-testid":"input-manual-headline"})]}),e.jsxs("div",{children:[e.jsxs(O,{className:"text-xs mb-1.5 block",children:["Texto Principal ",e.jsxs("span",{className:"text-white/30",children:["(",Gt.primaryText.length,"/500)"]})]}),e.jsx("textarea",{value:Gt.primaryText,onChange:t=>Ti(s=>({...s,primaryText:t.target.value.substring(0,500)})),placeholder:"O texto completo do anúncio. Escreva com informações reais, dados de mercado, e o diferencial da Sábhia...",className:"w-full bg-black/20 border border-white/10 rounded-lg px-3 py-2.5 text-sm text-white placeholder:text-white/30 resize-none focus:outline-none focus:ring-1 focus:ring-violet-500/50",rows:6,maxLength:500,"data-testid":"textarea-manual-primary-text"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsxs(O,{className:"text-xs mb-1.5 block",children:["Descrição ",e.jsxs("span",{className:"text-white/30",children:["(",Gt.description.length,"/30)"]})]}),e.jsx(J,{value:Gt.description,onChange:t=>Ti(s=>({...s,description:t.target.value.substring(0,30)})),placeholder:"Ex: Seu livro vendendo 24h",className:"border-white/10 bg-white/5",maxLength:30,"data-testid":"input-manual-description"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"CTA"}),e.jsxs(Se,{value:Gt.callToAction,onValueChange:t=>Ti(s=>({...s,callToAction:t})),children:[e.jsx($e,{"data-testid":"select-manual-cta",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"LEARN_MORE",children:"Saiba Mais"}),e.jsx(U,{value:"SIGN_UP",children:"Cadastre-se"}),e.jsx(U,{value:"SHOP_NOW",children:"Comprar Agora"}),e.jsx(U,{value:"GET_OFFER",children:"Obter Oferta"}),e.jsx(U,{value:"BOOK_TRAVEL",children:"Reservar"}),e.jsx(U,{value:"CONTACT_US",children:"Fale Conosco"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Formato"}),e.jsxs(Se,{value:Gt.format,onValueChange:t=>Ti(s=>({...s,format:t})),children:[e.jsx($e,{"data-testid":"select-manual-format",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"feed_square",children:"⬜ Feed 1:1"}),e.jsx(U,{value:"feed_vertical",children:"📱 Feed 4:5"}),e.jsx(U,{value:"story",children:"📲 Story 9:16"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Público-Alvo"}),e.jsxs(Se,{value:Gt.targetAudience,onValueChange:t=>Ti(s=>({...s,targetAudience:t})),children:[e.jsx($e,{"data-testid":"select-manual-audience",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"geral",children:"🌐 Público Geral"}),e.jsx(U,{value:"autores_iniciantes",children:"✍️ Autores Iniciantes"}),e.jsx(U,{value:"empreendedores",children:"💼 Empreendedores"}),e.jsx(U,{value:"coaches",children:"🎓 Coaches / Mentores"}),e.jsx(U,{value:"religiosos",children:"⛪ Pastores / Líderes Religiosos"}),e.jsx(U,{value:"professores",children:"📚 Professores / Educadores"}),e.jsx(U,{value:"saude",children:"🏥 Profissionais de Saúde"})]})]})]})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>Ln(!1),className:"border-white/10","data-testid":"btn-cancel-manual",children:"Cancelar"}),e.jsx(b,{onClick:()=>{const t=new FormData;wd&&t.append("image",wd),t.append("headline",Gt.headline.trim()),t.append("primaryText",Gt.primaryText.trim()),t.append("description",Gt.description.trim()),t.append("callToAction",Gt.callToAction),t.append("format",Gt.format),t.append("targetAudience",Gt.targetAudience),t.append("angle",Gt.angle),Jd.mutate(t)},disabled:Jd.isPending||!Gt.headline.trim()||!Gt.primaryText.trim(),className:"bg-violet-600 hover:bg-violet-700 gap-1.5","data-testid":"btn-confirm-manual-upload",children:Jd.isPending?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 animate-spin"}
32)," Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(rc,{className:"w-4 h-4"})," Criar Criativo"]})})]})]})}),e.jsx(Je,{open:wp,onOpenChange:t=>{Vr.isPending||zn(t)},children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-4xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"w-5 h-5 text-violet-400"}),"Matriz de Testes — Upload em Massa"]}),e.jsx(mt,{className:"text-muted-foreground",children:"Suba várias imagens e textos — o sistema cria automaticamente todas as combinações para teste."})]}),e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsxs("div",{className:"bg-violet-500/5 border border-violet-500/20 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h4",{className:"text-sm font-semibold text-violet-300 flex items-center gap-2",children:[e.jsx(yr,{className:"w-4 h-4"})," Imagens (",It.length,")"]}),e.jsxs("button",{onClick:()=>document.getElementById("bulk-images-input")?.click(),className:"text-xs bg-violet-500/20 hover:bg-violet-500/30 text-violet-300 px-3 py-1.5 rounded-lg transition-colors flex items-center gap-1.5","data-testid":"btn-add-bulk-images",children:[e.jsx(_t,{className:"w-3.5 h-3.5"})," Adicionar Imagens"]})]}),e.jsx("input",{id:"bulk-images-input",type:"file",accept:"image/jpeg,image/png,image/webp",multiple:!0,className:"hidden",onChange:t=>{const s=Array.from(t.target.files||[]),i=s.filter(x=>["image/jpeg","image/png","image/webp"].includes(x.type));i.length<s.length&&r({title:"Alguns arquivos ignorados",description:"Apenas JPG, PNG e WebP são aceitos."}),i.forEach(x=>{const C=new FileReader;C.onload=P=>Sd(H=>[...H,{file:x,preview:P.target?.result}]),C.readAsDataURL(x)}),t.target.value=""},"data-testid":"input-bulk-images"}),It.length===0?e.jsxs("div",{className:"border-2 border-dashed border-white/15 rounded-xl p-8 text-center cursor-pointer hover:border-violet-500/30 transition-colors",onClick:()=>document.getElementById("bulk-images-input")?.click(),"data-testid":"dropzone-bulk-images",children:[e.jsx(yr,{className:"w-10 h-10 mx-auto text-white/20 mb-2"}),e.jsx("p",{className:"text-sm text-white/50",children:"Clique para selecionar imagens"}),e.jsx("p",{className:"text-xs text-white/30 mt-1",children:"JPG, PNG ou WebP — selecione várias de uma vez"})]}):e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[It.map((t,s)=>e.jsxs("div",{className:"relative group aspect-square rounded-lg overflow-hidden border border-white/10","data-testid":`bulk-image-${s}`,children:[e.jsx("img",{src:t.preview,alt:`Imagem ${s+1}`,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:e.jsx("button",{onClick:()=>Sd(i=>i.filter((x,C)=>C!==s)),className:"bg-red-500/80 rounded-full p-1 hover:bg-red-500","data-testid":`btn-remove-bulk-image-${s}`,children:e.jsx(ea,{className:"w-3.5 h-3.5"})})}),e.jsx("span",{className:"absolute bottom-1 left-1 text-[10px] bg-black/60 px-1.5 py-0.5 rounded text-white/70",children:s+1})]},s)),e.jsx("div",{className:"aspect-square rounded-lg border-2 border-dashed border-white/10 flex items-center justify-center cursor-pointer hover:border-violet-500/30 transition-colors",onClick:()=>document.getElementById("bulk-images-input")?.click(),"data-testid":"btn-add-more-images",children:e.jsx(_t,{className:"w-5 h-5 text-white/30"})})]})]}),e.jsxs("div",{className:"bg-blue-500/5 border border-blue-500/20 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h4",{className:"text-sm font-semibold text-blue-300 flex items-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"})," Textos (",Ia.length,")"]}),e.jsxs("button",{onClick:()=>sr(t=>[...t,{headline:"",primaryText:"",description:""}]),className:"text-xs bg-blue-500/20 hover:bg-blue-500/30 text-blue-300 px-3 py-1.5 rounded-lg transition-colors flex items-center gap-1.5","data-testid":"btn-add-bul
32k-text",children:[e.jsx(_t,{className:"w-3.5 h-3.5"})," Adicionar Texto"]})]}),e.jsx("div",{className:"space-y-3",children:Ia.map((t,s)=>e.jsxs("div",{className:"bg-black/20 border border-white/10 rounded-lg p-3 relative","data-testid":`bulk-text-${s}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{className:"text-xs text-white/40 font-medium",children:["Texto ",s+1]}),Ia.length>1&&e.jsx("button",{onClick:()=>sr(i=>i.filter((x,C)=>C!==s)),className:"text-white/30 hover:text-red-400 transition-colors","data-testid":`btn-remove-bulk-text-${s}`,children:e.jsx(As,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{value:t.headline,onChange:i=>sr(x=>x.map((C,P)=>P===s?{...C,headline:i.target.value.substring(0,40)}:C)),placeholder:"Headline (máx 40 caracteres)",className:"border-white/10 bg-white/5 text-sm h-8",maxLength:40,"data-testid":`input-bulk-headline-${s}`}),e.jsx("textarea",{value:t.primaryText,onChange:i=>sr(x=>x.map((C,P)=>P===s?{...C,primaryText:i.target.value.substring(0,500)}:C)),placeholder:"Texto principal do anúncio (máx 500 caracteres)",className:"w-full bg-white/5 border border-white/10 rounded-md px-3 py-2 text-sm text-white placeholder:text-white/30 resize-none focus:outline-none focus:ring-1 focus:ring-blue-500/50",rows:3,maxLength:500,"data-testid":`textarea-bulk-primary-${s}`}),e.jsx(J,{value:t.description,onChange:i=>sr(x=>x.map((C,P)=>P===s?{...C,description:i.target.value.substring(0,30)}:C)),placeholder:"Descrição curta (máx 30 caracteres)",className:"border-white/10 bg-white/5 text-sm h-8",maxLength:30,"data-testid":`input-bulk-description-${s}`})]})]},s))})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"CTA"}),e.jsxs(Se,{value:ar.callToAction,onValueChange:t=>$d(s=>({...s,callToAction:t})),children:[e.jsx($e,{"data-testid":"select-bulk-cta",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"LEARN_MORE",children:"Saiba Mais"}),e.jsx(U,{value:"SIGN_UP",children:"Cadastre-se"}),e.jsx(U,{value:"SHOP_NOW",children:"Comprar Agora"}),e.jsx(U,{value:"GET_OFFER",children:"Obter Oferta"}),e.jsx(U,{value:"CONTACT_US",children:"Fale Conosco"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Formato"}),e.jsxs(Se,{value:ar.format,onValueChange:t=>$d(s=>({...s,format:t})),children:[e.jsx($e,{"data-testid":"select-bulk-format",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"feed_square",children:"⬜ Feed 1:1"}),e.jsx(U,{value:"feed_vertical",children:"📱 Feed 4:5"}),e.jsx(U,{value:"story",children:"📲 Story 9:16"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Público-Alvo"}),e.jsxs(Se,{value:ar.targetAudience,onValueChange:t=>$d(s=>({...s,targetAudience:t})),children:[e.jsx($e,{"data-testid":"select-bulk-audience",className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"geral",children:"🌐 Público Geral"}),e.jsx(U,{value:"autores_iniciantes",children:"✍️ Autores Iniciantes"}),e.jsx(U,{value:"empreendedores",children:"💼 Empreendedores"}),e.jsx(U,{value:"coaches",children:"🎓 Coaches / Mentores"}),e.jsx(U,{value:"religiosos",children:"⛪ Pastores / Líderes Religiosos"}),e.jsx(U,{value:"professores",children:"📚 Professores / Educadores"}),e.jsx(U,{value:"saude",children:"🏥 Profissionais de Saúde"})]})]})]})]}),It.length>0&&Ia.some(t=>t.headline.trim()&&t.primaryText.trim())&&e.jsxs("div",{className:"bg-gradient-to-r from-violet-500/10 via-blue-500/10 to-teal-500/10 border border-violet-500/20 rounded-xl p-4",children:[e.jsxs("h4",{className:"text-sm font-semibold text-white mb-3 flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 text-yellow-400"})," Plano de Teste"]}),(()=>{const t=Ia.filter(P=>P.headline.trim()&&P.primaryText.trim()).length,s=It.length*t,i=It.length>1&&t>1?"both":It.length>1?"image":"text",x=i==="image"?t:It.length,C=i==="image"?It.length:t;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{className:"bg-black/30 rounded-lg p-3",children:[e.jsx("div",{className:"text-2xl font-bold text-violet-400","data-testid":"text-total-combos",children:s}),e.jsx("div",{className:"text-[10px] text-white/50 mt-1",children:"Criativos Totais"})]}),e.jsxs("div",{className:"bg-black/30 rounded-lg p-3",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-400","data-testid":"text-ad-sets-count",children:x}),e.jsx("div",{className:"text-[10px] text-white/50 mt-1",children:"Conjuntos de Anúncios"})]}),e.jsxs("div",{className:"bg-black/30 rounded-lg p-3",children:[e.jsx("div",{className:"text-2xl font-bold text-teal-400","data-testid":"text-ads-per-set",children:C}),e.jsx("div",{className:"text-[10px] text-white/50 mt-1",children:"Anúncios por Conjunto"})]})]}),e.jsxs("div",{className:"text-xs text-white/60 mt-2 bg-black/20 rounded-lg p-3",children:[i==="image"&&e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-3.5 h-3.5 inline mr-1.5 text-violet-400"}),e.jsx("strong",{className:"text-violet-300",children:"Teste de Imagens:"})," ",t," conjunto",t>1?"s":""," de anúncio (1 por texto), cada um com ",It.length," imagens diferentes. A Meta otimiza qual imagem performa melhor para cada copy."]}),i==="text"&&e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-3.5 h-3.5 inline mr-1.5 text-blue-400"}),e.jsx("strong",{className:"text-blue-300",children:"Teste de Textos:"})," ",It.length," conjunto",It.length>
321?"s":""," de anúncio (1 por imagem), cada um com ",t," textos diferentes. A Meta otimiza qual copy performa melhor para cada visual."]}),i==="both"&&e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-3.5 h-3.5 inline mr-1.5 text-teal-400"}),e.jsx("strong",{className:"text-teal-300",children:"Teste Completo:"})," ",It.length," conjunto",It.length>1?"s":""," de anúncio (1 por imagem), cada um com ",t," variações de texto. Total de ",s," combinações para teste massivo."]})]})]})})()]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>zn(!1),className:"border-white/10",disabled:Vr.isPending,"data-testid":"btn-cancel-bulk",children:"Cancelar"}),e.jsx(b,{onClick:()=>{const t=Ia.filter(i=>i.headline.trim()&&i.primaryText.trim());if(It.length===0||t.length===0)return;const s=new FormData;It.forEach(i=>s.append("images",i.file)),s.append("texts",JSON.stringify(t)),s.append("callToAction",ar.callToAction),s.append("format",ar.format),s.append("targetAudience",ar.targetAudience),Ad(`Criando ${It.length*t.length} combinações...`),Vr.mutate(s)},disabled:Vr.isPending||It.length===0||!Ia.some(t=>t.headline.trim()&&t.primaryText.trim()),className:"bg-violet-600 hover:bg-violet-700 gap-1.5","data-testid":"btn-confirm-bulk-matrix",children:Vr.isPending?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," ",yp||"Criando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"w-4 h-4"})," Criar ",It.length>0&&Ia.some(t=>t.headline.trim()&&t.primaryText.trim())?`${It.length*Ia.filter(t=>t.headline.trim()&&t.primaryText.trim()).length} Criativos`:"Matriz"]})})]})]})}),e.jsx(Je,{open:!!Gr,onOpenChange:t=>{t||am(null)},children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-4xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"w-5 h-5 text-teal-400"}),"Dashboard de Performance da Matriz"]}),e.jsx(mt,{className:"text-white/40",children:wt?`Grupo ${Gr?.substring(0,8)} • Matriz ${wt.matrix} • ${wt.totalCreatives} criativos`:"Carregando..."})]}),Bp?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-teal-400"})}):wt?e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[{label:"Total Gasto",value:`R$${(wt.performanceData.reduce((t,s)=>t+s.spend,0)/100).toFixed(2)}`,color:"text-white"},{label:"Impressões",value:wt.performanceData.reduce((t,s)=>t+s.impressions,0).toLocaleString("pt-BR"),color:"text-blue-400"},{label:"Conversões",value:wt.performanceData.reduce((t,s)=>t+s.conversions,0).toLocaleString("pt-BR"),color:"text-emerald-400"},{label:"Receita Reconciliada",value:`R$${(wt.performanceData.reduce((t,s)=>t+s.reconciledRevenue,0)/100).toFixed(2)}`,color:"text-violet-400"}].map((t,s)=>e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-3",children:[e.jsx("p",{className:"text-[10px] text-white/40 uppercase tracking-wider mb-1",children:t.label}),e.jsx("p",{className:`text-lg font-bold ${t.color}`,children:t.value})]},s))}),wt.winners.bestByRoas&&e.jsxs("div",{className:"bg-gradient-to-r from-amber-500/5 to-amber-500/[0.02] border border-amber-500/20 rounded-xl p-4",children:[e.jsxs("h4",{className:"text-sm font-semibold text-amber-400 flex items-center gap-2 mb-3",children:[e.jsx(_i,{className:"w-4 h-4"})," Vencedores"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[wt.winners.bestByRoas&&e.jsxs("div",{className:"bg-black/20 rounded-lg p-3 border border-white/5",children:[e.jsx("p",{className:"text-[10px] text-white/40 mb-1",children:"Melhor ROAS"}),e.jsx("p",{className:"text-xs font-medium text-white truncate",children:wt.winners.bestByRoas.headline}),e.jsxs("p",{className:"text-sm font-bold text-emerald-400 mt-1",children:[wt.winners.bestByRoas.roas.toFixed(2),"x"]})]}),wt.winners.bestByCpa&&e.jsxs("div",{className:"bg-black/20 rounded-lg p-3 border border-white/5",children:[e.jsx("p",{className:"text-[10px] text-white/40 mb-1",children:"Melhor CPA"}),e.jsx("p",{className:"text-xs font-medium text-white truncate",children:wt.winners.bestByCpa.headline}),e.jsxs("p",{className:"text-sm font-bold text-teal-400 mt-1",children:["R$",(wt.winners.bestByCpa.cpa/100).toFixed(2)]})]}),wt.winners.bestByCtr&&e.jsxs("div",{className:"bg-black/20 rounded-lg p-3 border border-white/5",children:[e.jsx("p",{className:"text-[10px] text-white/40 mb-1",children:"Melhor CTR"}),e.jsx("p",{className:"text-xs font-medium text-white truncate",children:wt.winners.bestByCtr.headline}),e.jsxs("p",{className:"text-sm font-bold text-blue-400 mt-1",children:[wt.winners.bestByCtr.ctr.toFixed(2),"%"]})]})]})]}),e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl overflow-hidden",children:[e.jsxs("h4",{className:"text-sm font-semibold text-white px-4 py-3 border-b border-white/5 flex items-center gap-2",children:[e.jsx(Ot,{className:"w-4 h-4 text-violet-400"}),"Heatmap Imagem × Título"]}),e.jsx("div",{className:"overflow-x-auto p-3",children:(()=>{const t=[...new Set(wt.performanceData.map(P=>
32P.imageUrl).filter(Boolean))],s=[...new Set(wt.performanceData.map(P=>P.headline))],i=Math.max(...wt.performanceData.map(P=>P.roas),.01),x=wt.winners.bestByRoas?.creativeId,C=(P,H)=>wt.performanceData.find(Q=>Q.imageUrl===P&&Q.headline===H);return e.jsxs("table",{className:"w-full text-xs border-collapse","data-testid":"matrix-heatmap-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-2 px-2 text-left text-white/40 font-medium w-16"}),s.map((P,H)=>e.jsx("th",{className:"py-2 px-2 text-center text-white/60 font-medium max-w-[120px]",children:e.jsx("p",{className:"truncate text-[10px]",title:P,children:P.length>20?P.substring(0,20)+"…":P})},H))]})}),e.jsx("tbody",{children:t.map((P,H)=>e.jsxs("tr",{children:[e.jsx("td",{className:"py-1 px-2",children:e.jsx("img",{src:P,alt:"",className:"w-12 h-12 rounded object-cover"})}),s.map((Q,G)=>{const ue=C(P,Q);if(!ue)return e.jsx("td",{className:"py-1 px-2",children:e.jsx("div",{className:"w-full h-14 rounded bg-white/[0.02] flex items-center justify-center text-white/20 text-[10px]",children:"—"})},G);const Te=i>0?ue.roas/i:0,Y=ue.creativeId===x;return e.jsx("td",{className:"py-1 px-2","data-testid":`heatmap-cell-${ue.creativeId}`,children:e.jsxs("div",{className:`rounded-lg p-2 h-14 flex flex-col items-center justify-center transition-all ${Y?"ring-2 ring-amber-400/60":""}`,style:{background:`rgba(16, 185, 129, ${.05+Te*.35})`},title:`${ue.headline}
33ROAS: ${ue.roas.toFixed(2)}x | CTR: ${ue.ctr.toFixed(2)}% | CPA: R$${(ue.cpa/100).toFixed(2)}`,children:[e.jsxs("span",{className:"text-xs font-bold",style:{color:`rgba(110, 231, 183, ${.5+Te*.5})`},children:[ue.roas.toFixed(2),"x"]}),e.jsxs("span",{className:"text-[9px] text-white/50 mt-0.5",children:["CTR ",ue.ctr.toFixed(1),"%"]}),Y&&e.jsx(_i,{className:"w-3 h-3 text-amber-400 mt-0.5"})]})},G)})]},H))})]})})()})]})]}):e.jsx("div",{className:"py-8 text-center text-white/40 text-sm",children:"Nenhum dado disponível"})]})}),e.jsx(Je,{open:lr,onOpenChange:t=>{Kn(t),t||(cr(""),Or(!1),Br(""),Ur(""),_r(!1))},children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-lg",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"w-5 h-5 text-blue-400"}),"Publicar na Meta Ads",rl&&e.jsxs(E,{variant:"outline",className:"text-[10px] border-teal-500/30 text-teal-400 bg-teal-500/10 ml-2","data-testid":"badge-ai-configured",children:[e.jsx(Qi,{className:"w-3 h-3 mr-1"})," Configurado pela IA"]})]}),e.jsx(mt,{className:"text-muted-foreground",children:"Configure campanha, targeting e budget para publicar este criativo."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[Nt&&!Nt.valid&&e.jsxs("div",{className:"bg-red-500/10 border border-red-500/30 rounded-lg p-3 space-y-1",children:[e.jsxs("p",{className:"text-xs font-medium text-red-400 flex items-center gap-1.5",children:[e.jsx(Xe,{className:"w-3.5 h-3.5"})," Configuração incompleta"]}),Nt.errors.map((t,s)=>e.jsxs("p",{className:"text-[11px] text-red-300/80 pl-5",children:["• ",t]},s)),e.jsx(b,{size:"sm",variant:"outline",className:"mt-2 text-[10px] border-orange-500/30 text-orange-400 hover:bg-orange-500/10 h-7",onClick:async()=>{try{const s=await(await fetch("/api/admin/meta-config/detect-page",{method:"POST",headers:{"Content-Type":"application/json"}})).json();s.success?(r({title:`Página detectada: ${s.pageName}`,description:`Page ID: ${s.pageId}`}),dl()):r({title:"Erro",description:s.message,variant:"destructive"})}catch(t){r({title:"Erro",description:t.message,variant:"destructive"})}},children:"Detectar Page ID"})]}),Nt?.valid&&Nt.warnings?.length>0&&e.jsxs("div",{className:"bg-amber-500/10 border border-amber-500/30 rounded-lg p-3 space-y-1",children:[Nt.warnings.map((t,s)=>e.jsxs("p",{className:"text-[11px] text-amber-300/80 flex items-center gap-1.5",children:[e.jsx(Xe,{className:"w-3 h-3 flex-shrink-0"})," ",t]},s)),Nt.warnings.some(t=>t.toLowerCase().includes("instagram"))&&e.jsx(b,{size:"sm",variant:"outline",className:"mt-2 text-[10px] border-orange-500/30 text-orange-400 hover:bg-orange-500/10 h-7",onClick:async()=>{try{const s=await(await fetch("/api/admin/meta-config/fix-instagram",{method:"POST",headers:{"Content-Type":"application/json"}})).json();s.currentIsValid?r({title:"Instagram OK",description:`Conta ${s.currentIg} já está válida`}):s.fixedTo?r({title:"Instagram corrigido",description:`Conta atualizada para ${s.fixedTo}`}):r({title:"Sem contas IG",description:"Nenhuma conta Instagram autorizada na Ad Account.",variant:"destructive"}),dl()}catch(t){r({title:"Erro",description:t.message,variant:"destructive"})}},children:"Corrigir Instagram Automaticamente"})]}),(Xn||Jn?.needsTokenRefresh)&&e.jsxs("div",{className:"bg-orange-500/10 border border-orange-500/30 rounded-lg p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-orange-400 flex items-center gap-1.5",children:[e.jsx(Xe,{className:"w-3.5 h-3.5"})," Token Meta precisa ser atualizado"]}),e.jsx("p",{className:"text-[11px] text-orange-300/80 pl-5",children:"Se você já aceitou a certificação de não discriminação, atualize o Access Token em Admin → Meta Ads → Configuração com um novo token gerado após a certificação."})]}),Nt?.valid&&(!Nt.warnings||Nt.warnings.length===0)&&!Xn&&!Jn?.needsTokenRefresh&&e.jsxs("div",{className:"bg-emerald-500/10 border border-emerald-500/30 rounded-lg p-2.5 flex items-center gap-2",children:[e.jsx(be,{className:"w-3.5 h-3.5 text-emerald-400"}),e.jsx("p",{className:"text-[11px] text-emerald-300",children:"Configuração Meta Ads verificada — pronto para publicar"})]}),nl.length>1&&e.jsxs("div",{"data-testid":"publish-account-selector",children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Conta Meta Ads"}),e.jsxs("select",{"data-testid":"select-meta-account",className:"w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white",value:ba,onChange:t=>qr(t.target.value),children:[e.jsx("option",{value:"",children:"Conta padrão"}),nl.map(t=>e.jsxs("option",{value:String(t.id),children:[t.name||`Conta #${t.id}`,t.isDefault?" (padrão)":""]},t.id))]})]}),e.jsx(gh,{testIdPrefix:"publish",loading:cm,error:xm,data:ll,value:ri,onChange:cr,showDiagnostics:Ux,onToggleDiagnostics:()=>_r(t=>!t),manualMode:Vn,onToggleManual:()=>Or(t=>!t),manualPageId:Kx,onManualPageId:Br,manualIgId:Qn,onManualIgId:Ur,onRefetch:()=>mm(),applyAllText:!1}),e.jsxs("div",{className:"flex items-center justify-between bg-white/5 border border-white/10 rounded-lg p-3","data-testid":"autonomous-mode-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(He,{className:`w-4 h-4 ${Cs?"text-amber-400":"text-white/40"}`}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Modo Autônomo"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:Cs?"IA gerencia testes, pausa perdedores e escala vencedores":"Publicação manual com configuração pré-preenchida"})]})]}),e.jsx(rt,{checked:Cs,onCheckedChange:qd,"data-testid":"switch-autonomous-mode"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-2 block text-white/60",children:"Destino da publicação"}),e.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5","data-testid":"publish-mode-selector",children:[{val:"new",label:"Nova Campanha",icon:e.jsx(_t,{className:"w-3 h-3"})},{val:"existing_campaign",label:"Campanha Existente",icon:e.jsx(Xt,{className:"w-3 h-3"})},{val:"existing_adset",label:"Conjunto Existente",icon:e.jsx(lt,{className:"w-3 h-3"})}].map(t=>e.jsxs("button",{onClick:()=>{Ox(t.val),Ld(""),Gn("")},className:`flex-1 flex items-center justify-center gap-1 px-2 py-1.5 rounded-md text-[10px] font-medium transition-colors ${hs===t.val?"bg-teal-600 text-white":"text-white/50 hover:text-white/80"}`,"data-testid":`publish-mode-${t.val}`,children:[t.icon," ",t.label]},t.val))})]}),hs==="new"&&e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Nome da Campanha"}),e.jsx(J,{value:_e.campaignName,onChange:t=>zt(s=>({...s,campaignName:t.target.value})),placeholder:"[SABHIA] Campanha Automatica",className:"border-white/10 bg-white/5","data-testid":"input-campaign-name",readOnly:Cs}),Cs&&e.jsx("p",{className:"text-[10px] text-teal-400/70 mt-1",children:"Nome gerado automaticamente pela IA"})]}),hs!=="new"&&e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Campanha"}),e.jsxs(Se,{value:dr,onValueChange:t=>{Ld(t),Gn("")},children:[e.jsx($e,{className:"border-white/10 bg-white/5","data-testid":"select-existing-campaign",children:e.jsx(Ae,{placeholder:"Selecione uma campanha..."})}),e.jsx(Pe,{children:(pm?.campaigns||[]).map(t=>e.jsx(U,{value:String(t.id),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t.status==="ACTIVE"?"bg-emerald-400":"bg-amber-400"}`}),t.name," ",e.jsxs("span",{className:"text-white/30 ml-1",children:["(",t.adSets?.length||0," conj.)"]})]})},t.id))})]})]}),hs==="existing_adset"&&dr&&(()=>{const s=pm?.campaigns?.find(i=>String(i.id)===dr)?.adSets||[];return e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Conjunto de Anúncios"}),e.jsxs(Se,{value:or,onValueChange:Gn,children:[e.jsx($e,{className:"border-white/10 bg-white/5","data-testid":"select-existing-adset",children:e.jsx(Ae,{placeholder:"Selecione um conjunto..."})}),e.jsx(Pe,{children:s.map(i=>e.jsx(U,{value:String(i.id),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${i.status==="ACTIVE"?"bg-emerald-400":"bg-amber-400"}`}),i.name," ",e.jsxs("span",{className:"text-white/30 ml-1",children:["(",i.ads?.length||0," anúncio(s))"]})]})},i.id))})]}),or&&(()=>{const x=s.find(C=>String(C.id)===or)?.ads?.length||0;return e.jsxs("div",{className:`mt-2 p-2 rounded-lg text-[10px] flex items-center gap-1.5 ${x>=5?"bg-amber-500/10 border border-amber-500/20 text-amber-300":"bg-teal-500/10 border border-teal-500/20 text-teal-300"}`,children:[e.jsx(js,{className:"w-3 h-3 flex-shrink-0"}),"Este conjunto já tem ",x," anúncio(s). ",x>=5?"Meta recomenda no máximo 5 anúncios por conjunto.":"Recomendado: 3-5 anúncios por conjunto."]})})()]})})(),hs!=="existing_adset"&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Budget Diário (R$)"}),e.jsx(J,{type:"number",value:_e.dailyBudget,onChange:t=>zt(s=>({...s,dailyBudget:t.target.value})),className:"border-white/10 bg-white/5","data-testid":"input-daily-budget"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Status Inicial"}),e.jsxs(Se,{value:_e.status,onValueChange:t=>zt(s=>({...s,status:t})),children:[e.jsx($e,{className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"PAUSED",children:"Pausado"}),e.jsx(U,{value:"ACTIVE",children:"Ativo"})]})]})]})]}),hs==="existing_adset"&&e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Status do Anúncio"}),e.jsxs(Se,{value:_e.status,onValueChange:t=>zt(s=>({...s,status:t})),children:[e.jsx($e,{className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"PAUSED",children:"Pausado"}),e.jsx(U,{value:"ACTIVE",children:"Ativo"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"URL de Destino"}),e.jsx(J,{value:_e.destinationUrl,onChange:t=>zt(s=>({...s,destinationUrl:t.target.value})),className:"border-white/10 bg-white/5 font-mono text-xs","data-testid":"input-destination-url"})]}),hs!=="existing_adset"&&e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Países"}),e.jsx(J,{value:_e.countries,onChange:t=>zt(s=>({...s,countries:t.target.value})),className:"border-white/10 bg-white/5 text-xs"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Idade Min"}),e.jsx(J,{type:"number",value:_e.ageMin,onChange:t=>zt(s=>({...s,ageMin:t.target.value})),className:"border-white/10 bg-white/5"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Idade Max"}),e.jsx(J,{type:"number",value:_e.ageMax,onChange:t=>zt(s=>({...s,ageMax:t.target.value})),className:"border-white/10 bg-white/5"})]})]}),hs!=="existing_adset"&&parseInt(_e.ageMin)>25&&e.jsxs("p",{className:"text-[10px] text-amber-400/80 mt-1 px-1",children:["Advantage+ limita idade mínima a 25. O sistema ajustará automaticamente para 25 e usará ",_e.ageMin,"+ como sugestão de audiência."]}),hs!=="existing_adset"&&hr&&hr.length>0&&e.jsxs("div",{children:[e.jsxs(O,{className:"text-xs mb-1.5 block flex items-center gap-1.5",children:[e.jsx(Re,{className:"w-3 h-3"})," Audiências Personalizadas ",e.jsx("span",{className:"text-white/30 font-normal",children:"(opcional)"})]}),e.jsx("div",{className:"max-h-36 overflow-y-auto border border-white/10 rounded-lg bg-white/5 p-2 space-y-1","data-testid":"audience-selector",children:hr.map(t=>e.jsxs("button",{type:"button",onClick:()=>Ri(s=>s.includes(t.id)?s.filter(i=>i!==t.id):[...s,t.id]),className:`w-full text-left px-2.5 py-1.5 rounded-md text-xs flex items-center justify-between transition-colors ${ga.includes(t.id)?"bg-teal-600/20 border border-teal-500/30 text-teal-300":"hover:bg-white/5 text-white/70"}`,"data-testid":`audience-option-${t.id}`,children:[e.jsx("span",{className:"truncate",children:t.name}),e.jsx("span",{className:"text-[10px] text-white/30 ml-2 flex-shrink-0",children:t.approximate_count?`~${Number(t.approximate_count).toLocaleStr
33ing("pt-BR")}`:"—"})]},t.id))}),ga.length>0&&e.jsxs("p",{className:"text-[10px] text-teal-400/70 mt-1",children:[ga.length," audiência(s) selecionada(s) — anúncios serão exibidos para esses públicos"]})]}),Cs&&e.jsx("div",{className:"bg-amber-500/10 border border-amber-500/20 rounded-lg p-3","data-testid":"autonomous-info",children:e.jsxs("p",{className:"text-xs text-amber-300 flex items-center gap-1.5",children:[e.jsx(js,{className:"w-3.5 h-3.5 flex-shrink-0"}),"Este criativo entrará no pipeline autônomo: será monitorado, testado por ",rl?.testDurationDays||3," dias, e a IA decidirá se escala ou pausa."]})}),hs!=="new"&&e.jsx("div",{className:"bg-blue-500/10 border border-blue-500/20 rounded-lg p-3",children:e.jsxs("p",{className:"text-xs text-blue-300 flex items-center gap-1.5",children:[e.jsx(js,{className:"w-3.5 h-3.5 flex-shrink-0"}),hs==="existing_campaign"?"Um novo conjunto de anúncios será criado dentro da campanha selecionada.":"O anúncio será adicionado diretamente ao conjunto existente. Ideal para testar variações de criativo com o mesmo público."]})})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>Kn(!1),className:"border-white/10",children:"Cancelar"}),e.jsx(b,{className:"bg-blue-600 hover:bg-blue-700 gap-1.5",disabled:bo.isPending||!_e.destinationUrl||hs!=="new"&&!dr||hs==="existing_adset"&&!or||Nt&&!Nt.valid,onClick:()=>{oe&&bo.mutate({creativeId:oe.id,campaignName:hs==="new"&&_e.campaignName||void 0,campaignId:hs!=="new"&&dr?dr:void 0,adSetId:hs==="existing_adset"&&or?or:void 0,dailyBudget:parseFloat(_e.dailyBudget)||10,targeting:{countries:_e.countries,ageMin:parseInt(_e.ageMin)||25,ageMax:parseInt(_e.ageMax)||65},destinationUrl:_e.destinationUrl,status:_e.status,autonomousMode:Cs,customAudienceIds:ga.length>0?ga:void 0,metaAccountId:ba?parseInt(ba):void 0,...ri?{pageId:ri,instagramActorId:Vn?Qn.trim()||void 0:ll?.pages.find(t=>t.id===ri)?.instagram?.id||void 0}:{}})},"data-testid":"btn-confirm-publish",children:bo.isPending?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Publicando..."]}):Cs?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-4 h-4"})," Publicar Autônomo"]}):e.jsxs(e.Fragment,{children:[e.jsx(vs,{className:"w-4 h-4"})," Publicar"]})})]})]})}),e.jsx(Je,{open:qp,onOpenChange:Yn,children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-md",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-5 h-5 text-teal-400"})," Nova Regra de Otimização"]}),e.jsx(mt,{className:"text-muted-foreground",children:"Configure condição e ação automática."})]}),e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Nome da Regra"}),e.jsx(J,{value:_s.name,onChange:t=>Di(s=>({...s,name:t.target.value})),placeholder:"Ex: Escalar bom ROAS",className:"border-white/10 bg-white/5"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Condição"}),e.jsxs(Se,{value:_s.condition,onValueChange:t=>Di(s=>({...s,condition:t})),children:[e.jsx($e,{className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"roas_above",children:"ROAS acima de"}),e.jsx(U,{value:"cpa_above",children:"CPA acima de R$"}),e.jsx(U,{value:"ctr_below",children:"CTR abaixo de %"}),e.jsx(U,{value:"frequency_above",children:"Frequência acima de"}),e.jsx(U,{value:"spend_over_budget",children:"Gasto acima de %"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Ação"}),e.jsxs(Se,{value:_s.action,onValueChange:t=>Di(s=>({...s,action:t})),children:[e.jsx($e,{className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"increase_budget",children:"Aumentar budget"}),e.jsx(U,{value:"pause",children:"Pausar ad set"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Threshold"}),e.jsx(J,{type:"number",value:_s.threshold,onChange:t=>Di(s=>({...s,threshold:t.target.value})),className:"border-white/10 bg-white/5"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Janela (dias)"}),e.jsx(J,{type:"number",value:_s.windowDays,onChange:t=>Di(s=>({...s,windowDays:t.target.value})),className:"border-white/10 bg-white/5"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Max %"}),e.jsx(J,{type:"number",value:_s.maxAdjustmentPct,onChange:t=>Di(s=>({...s,maxAdjustmentPct:t.target.value})),className:"border-white/10 bg-white/5"})]})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>Yn(!1),className:"border-white/10",children:"Cancelar"}),e.jsxs(b,{className:"bg-teal-600 hover:bg-teal-700 gap-1.5",disabled:!_s.name||fo.isPending,onClick:()=>fo.mutate({name:_s.name,condition:_s.condition,action:_s.action,threshold:_s.threshold,windowDays:parseInt(_s.windowDays)||3,maxAdjustmentPct:parseInt(_s.maxAdjustmentPct)||30}),children:[fo.isPending?e.jsx(T,{className:"w-4 h-4 animate-spin"}):e.jsx(_t,{className:"w-4 h-4"})," Criar Regra"]})]})]})}),e.jsx(Je,{open:Fi,onOpenChange:t=>{Lr(t),t||(cr(""),Or(!1),Br(""),Ur(""),_r(!1))},children:e.jsxs(Ye,{className:"bg-[#101012] border-white/10 text-white sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"w-5 h-5 text-violet-400"}),"Publicação Inteligente — ",ks.size," Criativos"]}),e.jsx(mt,{className:"text-muted-foreground",children:"Configure e publique seus anúncios com IA para maximizar conversões."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[Wp&&e.jsxs("div",{className:"flex items-center gap-2 bg-white/5 border border-white/10 rounded-lg p-3 text-xs text-white/50",children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"})," Verificando configuração Meta Ads..."]}),Nt&&!Nt.valid&&e.jsxs("div",{className:"bg-red-500/10 border border-red-500/30 rounded-lg p-3 space-y-1","data-testid":"preflight-errors",children:[e.jsxs("p",{className:"text-xs font-medium text-red-400 flex items-center gap-1.5",children:[e.jsx(Xe,{className:"w-3.5 h-3.5"})," Configuração incompleta — publicação bloqueada"]}),Nt.errors.map((t,s)=>e.jsxs("p",{className:"text-[11px] text-red-300/80 pl-5",children:["• ",t]},s)),e.jsx(b,{size:"sm",variant:"outline",className:"mt-2 text-[10px] border-orange-500/30 text-orange-400 hover:bg-orange-500/10 h-7",onClick:async()=>{try{const s=await(await fetch("/api/admin/meta-config/detect-page",{method:"POST",headers:{"Content-Type":"application/json"}})).json();s.success?(r({title:`Página detectada: ${s.pageName}`,description:`Page ID: ${s.pageId} configurado automaticamente`}),dl()):r({title:"Erro",description:s.message,variant:"destructive"})}catch(t){r({title:"Erro",description:t.message,variant:"destructive"})}},"data-testid":"btn-preflight-autofix",children:"Detectar Page ID Automaticamente"})]}),Nt?.valid&&Nt.warnings?.length>0&&e.jsxs("div",{className:"bg-amber-500/10 border border-amber-500/30 rounded-lg p-3 space-y-1","data-testid":"preflight-warnings",children:[Nt.warnings.map((t,s)=>e.jsxs("p",{className:"text-[11px] text-amber-300/80 flex items-center gap-1.5",children:[e.jsx(Xe,{className:"w-3 h-3 flex-shrink-0"})," ",t]},s)),Nt.warnings.some(t=>t.toLowerCase().includes("instagram"))&&e.jsx(b,{size:"sm",variant:"outline",className:"mt-2 text-[10px] border-orange-500/30 text-orange-400 hover:bg-orange-500/10 h-7",onClick:async()=>{try{const s=await(await fetch("/api/admin/meta-config/fix-instagram",{method:"POST",headers:{"Content-Type":"application/json"}})).json();s.currentIsValid?r({title:"Instagram OK",description:`Conta ${s.currentIg} já está válida na Ad Account`}):s.fixedTo?r({title:"Instagram corrigido",description:`Conta atualizada para ${s.fixedTo}`}):r({title:"Sem contas IG",description:"Nenhuma conta Instagram autorizada na Ad Account. Anúncios rodarão apenas no Facebook.",variant:"destructive"}),dl()}catch(t){r({title:"Erro",description:t.message,variant:"destructive"})}},"data-testid":"btn-fix-instagram",children:"Corrigir Instagram Automaticamente"})]}),Nt?.valid&&(!Nt.warnings||Nt.warnings.length===0)&&!Xn&&!Jn?.needsTokenRefresh&&e.jsxs("div",{className:"bg-emerald-500/10 border border-emerald-500/30 rounded-lg p-2.5 flex items-center gap-2","data-testid":"preflight-ok",children:[e.jsx(be,{className:"w-3.5 h-3.5 text-emerald-400"}),e.jsx("p",{className:"text-[11px] text-emerald-300",children:"Configuração Meta Ads verificada — pronto para publicar"})]}),(Xn||Jn?.needsTokenRefresh)&&e.jsxs("div",{className:"bg-orange-500/10 border border-orange-500/30 rounded-lg p-3 space-y-2","data-testid":"cert-error-banner",children:[e.jsxs("p",{className:"text-xs font-medium text-orange-400 flex items-center gap-1.5",children:[e.jsx(Xe,{className:"w-3.5 h-3.5"})," Certificação Meta não reconhecida"]}),e.jsx("p",{className:"text-[11px] text-orange-300/80 pl-5",children:"Você já aceitou a certificação de não discriminação, mas o token de acesso atual foi gerado antes disso. Para resolver:"}),e.jsxs("ol",{className:"text-[11px] text-orange-300/70 pl-5 space-y-1 list-decimal list-inside",children:[e.jsxs("li",{children:["Acesse ",e.jsx("a",{href:"https://developers.facebook.com/tools/explorer/",target:"_blank",rel:"noopener noreferrer",className:"underline text-blue-400 hover:text-blue-300",children:"Meta Graph API Explorer"})]}),e.jsx("li",{children:"Gere um novo token com as mesmas permissões"}),e.jsxs("li",{children:["Cole o novo token em ",e.jsx("span",{className:"text-white/80 font-medium",children:"Admin → Meta Ads → Configuração"})]}),e.jsx("li",{children:"Tente publicar novamente"})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(b,{size:"sm",variant:"outline",className:"text-[10px] border-orange-500/30 text-orange-400 hover:bg-orange-500/10 h-7",disabled:em,onClick:async()=>{tm(!0);try{const s=await(await fetch("/api/admin/ads-config/check-certification",{headers:{"Content-Type":"application/json"}})).json();zp(s),s.status==="certified"?(Kr(!1),r({title:"Certificação OK!",description:"A certificação está válida. Tente publicar novamente."})):s.status==="not_certified"||s.needsTokenRefresh?r({title:"Token precisa ser atualizado",description:s.error||"Atualize o Access Token após aceitar a certificação.",variant:"destructive",duration:1e4}):(r({title:"Verificação inconclusiva",description:s.error||"Tente publicar — se falhar com erro de certificação, atualize o token.",duration:8e3}),Kr(!1))}catch(t){r({title:"Erro na verificação",description:t.message,variant:"destructive"})}finally{tm(!1)}},"data-testid":"btn-check-certification",children:em?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"})," Verificando..."]}):"Verificar Certificação Novamente"}),e.jsx(b,{size:"sm",variant:"outline",className:"text-[10px] border-blue-500/30 text-blue-400 hover:bg-blue-500/10 h-7",onClick:()=>window.open("https://facebook.com/certification/nondiscrimination","_blank"),"data-testid":"btn-open-certification",children:"Abrir Página de Certificação"})]})]}),e.jsx(b,{variant:"outline",size:"sm",className:"w-full gap-2 border-violet-500/30 text-violet-300 hover:bg-violet-500/10 h-9",disabled:Hn.loading,onClick:async()=>{Vd({loading:!0});try{const s=await(await fetch("/api/admin/ad-creatives/ai-recommend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({creativeIds:Array.from(ks)})})).json();if(s.recommendation){const i=s.recommendation;zt(x=>({...x,dailyBudget:String(i.budget||x.dailyBudget),ageMin:String(i.ageMin||x.ageMin),ageMax:String(i.ageMax||x.ageMax)}
33)),i.gender&&Wx(i.gender),i.placement&&Hx(i.placement),i.bidStrategy&&Xx(i.bidStrategy),i.costCap&&Jx(String(i.costCap)),i.promotedEvent&&Zx(i.promotedEvent),i.expandTargeting!==void 0&&Mp(i.expandTargeting),i.groupBy&&Wn(i.groupBy),Vd({loading:!1,result:i}),r({title:"IA configurou tudo!",description:i.reasoning})}}catch{Vd({loading:!1})}},"data-testid":"btn-ai-recommend",children:Hn.loading?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"})," Analisando criativos..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"w-3.5 h-3.5"})," IA Recomendar Configuração Ideal"]})}),Hn.result?.reasoning&&e.jsx("div",{className:"bg-violet-500/10 border border-violet-500/20 rounded-lg p-3","data-testid":"ai-recommendation-result",children:e.jsxs("p",{className:"text-[11px] text-violet-300 flex items-center gap-1.5",children:[e.jsx(qe,{className:"w-3 h-3 flex-shrink-0"})," ",Hn.result.reasoning]})}),nl.length>1&&e.jsxs("div",{"data-testid":"batch-publish-account-selector",children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Conta Meta Ads"}),e.jsxs("select",{"data-testid":"batch-select-meta-account",className:"w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white",value:ba,onChange:t=>qr(t.target.value),children:[e.jsx("option",{value:"",children:"Conta padrão"}),nl.map(t=>e.jsxs("option",{value:String(t.id),children:[t.name||`Conta #${t.id}`,t.isDefault?" (padrão)":""]},t.id))]})]}),e.jsx(gh,{testIdPrefix:"batch-publish",loading:cm,error:xm,data:ll,value:ri,onChange:cr,showDiagnostics:Ux,onToggleDiagnostics:()=>_r(t=>!t),manualMode:Vn,onToggleManual:()=>Or(t=>!t),manualPageId:Kx,onManualPageId:Br,manualIgId:Qn,onManualIgId:Ur,onRefetch:()=>mm(),applyAllText:!0}),e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-3 space-y-3",children:[e.jsxs("h4",{className:"text-xs font-semibold text-white/80 flex items-center gap-2",children:[e.jsx(lt,{className:"w-3.5 h-3.5 text-teal-400"})," Destino da Publicação"]}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"new",label:"Nova Campanha",desc:"Criar do zero"},{value:"existing_campaign",label:"Campanha Existente",desc:"Novo conjunto"},{value:"existing_adset",label:"Conjunto Existente",desc:"Só anúncios"}].map(t=>e.jsxs("button",{type:"button",onClick:()=>Gx(t.value),className:`px-2 py-1.5 rounded-lg text-center transition-all ${Qt===t.value?"bg-teal-600/20 border border-teal-500/40 ring-1 ring-teal-500/20":"bg-white/[0.03] border border-white/5 hover:border-white/10"}`,"data-testid":`batch-mode-${t.value}`,children:[e.jsx("p",{className:`text-[11px] font-medium ${Qt===t.value?"text-teal-300":"text-white/70"}`,children:t.label}),e.jsx("p",{className:"text-[9px] text-white/30",children:t.desc})]},t.value))}),Qt==="existing_campaign"&&ol&&e.jsxs("select",{className:"w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-xs text-white",value:ja,onChange:t=>Vx(t.target.value),"data-testid":"batch-select-existing-campaign",children:[e.jsx("option",{value:"",children:"Selecione uma campanha..."}),ol.filter(t=>t.metaCampaignId).map(t=>e.jsxs("option",{value:String(t.id),children:[t.name," (",t.status,")"]},t.id))]}),Qt==="existing_adset"&&e.jsxs(e.Fragment,{children:[e.jsxs("select",{className:"w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-xs text-white mb-2",value:ja,onChange:t=>{Vx(t.target.value),Qx("")},"data-testid":"batch-select-campaign-for-adset",children:[e.jsx("option",{value:"",children:"Selecione a campanha..."}),ol&&ol.filter(t=>t.metaCampaignId).map(t=>e.jsx("option",{value:String(t.id),children:t.name},t.id))]}),ja&&hm&&e.jsxs("select",{className:"w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-xs text-white",value:_d,onChange:t=>Qx(t.target.value),"data-testid":"batch-select-existing-adset",children:[e.jsx("option",{value:"",children:"Selecione o conjunto..."}),hm.filter(t=>String(t.campaignId)===ja&&t.metaAdSetId).map(t=>e.jsxs("option",{value:String(t.id),children:[t.name," (",t.status,")"]},t.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between bg-white/5 border border-white/10 rounded-lg p-3","data-testid":"batch-autonomous-mode-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(He,{className:`w-4 h-4 ${Cs?"text-amber-400":"text-white/40"}`}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Modo Autônomo"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:Cs?"IA gerencia testes, pausa perdedores e escala vencedores":"Publicação manual — você gerencia tudo"})]})]}),e.jsx(rt,{checked:Cs,onCheckedChange:qd,"data-testid":"batch-switch-autonomous-mode"})]}),(()=>{const t=Array.from(ks),s=t.map(G=>Ra?.find(ue=>
33ue.id===G)).filter(Boolean),i=[...new Set(s.map(G=>G.imageUrl))].filter(Boolean),x=[...new Set(s.map(G=>G.headline))],C=da==="single"?"single":da==="auto"?i.length>1?"image":"text":da;let P=[];if(Qt==="existing_adset")P=[{label:"Conjunto existente",creativeIds:t}];else if(C==="single")P=[{label:"Todos os criativos",creativeIds:t}];else if(C==="image")for(const G of i){const ue=s.filter(Te=>Te.imageUrl===G);P.push({label:`Imagem ${P.length+1}`,image:G,creativeIds:ue.map(Te=>Te.id)})}else for(const G of x){const ue=s.filter(Te=>Te.headline===G);P.push({label:`"${G.substring(0,25)}${G.length>25?"...":""}"`,headline:G,creativeIds:ue.map(Te=>Te.id)})}const H=parseFloat(_e.dailyBudget)||10,Q=H*P.length;return e.jsxs(e.Fragment,{children:[Qt==="new"&&e.jsxs("div",{className:"bg-gradient-to-r from-violet-500/10 to-violet-500/[0.02] border border-violet-500/20 rounded-xl p-4","data-testid":"smart-structure-section",children:[e.jsxs("h4",{className:"text-xs font-semibold text-violet-400 mb-3 flex items-center gap-2",children:[e.jsx(ft,{className:"w-3.5 h-3.5"})," Estratégia de Separação"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 mb-3",children:[{value:"auto",label:"Automático",desc:"IA decide",icon:"✦"},{value:"image",label:"Por Imagem",desc:`${i.length} conjuntos`,icon:"🖼"},{value:"text",label:"Por Texto",desc:`${x.length} conjuntos`,icon:"✏"},{value:"single",label:"Conjunto Único",desc:"1 conjunto",icon:"📦"}].map(G=>e.jsxs("button",{type:"button",onClick:()=>Wn(G.value),className:`px-3 py-2 rounded-lg text-left transition-all ${da===G.value?"bg-violet-600/20 border border-violet-500/40 ring-1 ring-violet-500/20":"bg-white/[0.03] border border-white/5 hover:border-white/10"}`,"data-testid":`groupby-option-${G.value}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm",children:G.icon}),e.jsx("span",{className:`text-xs font-medium ${da===G.value?"text-violet-300":"text-white/70"}`,children:G.label})]}),e.jsx("p",{className:"text-[10px] text-white/40 mt-0.5",children:G.desc})]},G.value))}),e.jsxs("div",{className:"bg-black/20 rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("div",{className:"w-5 h-5 rounded bg-violet-600/30 flex items-center justify-center text-[10px] text-violet-300 font-bold",children:"C"}),e.jsx("span",{className:"text-white font-medium",children:"1 Campanha"}),e.jsx("span",{className:"text-white/30",children:"→"}),e.jsx("div",{className:"w-5 h-5 rounded bg-teal-600/30 flex items-center justify-center text-[10px] text-teal-300 font-bold",children:P.length}),e.jsx("span",{className:"text-white font-medium",children:P.length===1?"Conjunto":"Conjuntos"}),e.jsx("span",{className:"text-white/30",children:"→"}),e.jsx("div",{className:"w-5 h-5 rounded bg-blue-600/30 flex items-center justify-center text-[10px] text-blue-300 font-bold",children:t.length}),e.jsx("span",{className:"text-white font-medium",children:"Anúncios"})]}),P.length>1&&e.jsx("div",{className:"space-y-1.5 mt-2 max-h-32 overflow-y-auto",children:P.map((G,ue)=>e.jsxs("div",{className:"flex items-center gap-2 bg-white/[0.03] rounded-md px-2.5 py-1.5","data-testid":`adset-preview-${ue}`,children:[G.image&&e.jsx("img",{src:G.image,alt:"",className:"w-7 h-7 rounded object-cover shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[11px] text-white/80 truncate",children:G.label}),e.jsxs("p",{className:"text-[10px] text-white/30",children:[G.creativeIds.length," anúncio(s) • R$",H.toFixed(0),"/dia"]})]}),e.jsxs("div",{className:"flex -space-x-1",children:[G.creativeIds.slice(0,4).map((Te,Y)=>{const Oe=s.find(ze=>ze.id===Te);return Oe?.imageUrl?e.jsx("img",{src:Oe.imageUrl,alt:"",className:"w-5 h-5 rounded-sm object-cover border border-[#101012]"},Y):null}),G.creativeIds.length>4&&e.jsxs("div",{className:"w-5 h-5 rounded-sm bg-white/10 flex items-center justify-center text-[8px] text-white/50 border border-[#101012]",children:["+",G.creativeIds.length-4]})]})]},ue))})]})]}),Qt!=="existing_adset"&&e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:Qt==="new"?"Nome da Campanha":"Nome da Campanha (existente)"}),e.jsx(J,{value:_e.campaignName,onChange:G=>zt(ue=>({...ue,campaignName:G.target.value})),placeholder:"[SABHIA] Matrix | Audience | Date",className:"border-white/10 bg-white/5","data-testid":"batch-input-campaign-name",readOnly:Cs||Qt==="existing_campaign"}),Cs&&Qt==="new"&&e.jsx("p",{className:"text-[10px] text-teal-400/70 mt-1",children:"Nome gerado automaticamente pela IA"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Budget por Conjunto (R$/dia)"}),e.jsx(J,{type:"number",value:_e.dailyBudget,onChange:G=>zt(ue=>({...ue,dailyBudget:G.target.value})),className:"border-white/10 bg-white/5","data-testid":"batch-input-daily-budget"}),e.jsxs("p",{className:"text-[10px] text-white/30 mt-1",children:["Total diário: R$",Q.toFixed(0)," (",P.length," × R$",H.toFixed(0),")"]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Status Inicial"}),e.jsxs(Se,{value:_e.status,onValueChange:G=>zt(ue=>({...ue,status:G})),children:[e.jsx($e,{className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"PAUSED",children:"Pausado"}),e.jsx(U,{value:"ACTIVE",children:"Ativo"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"URL de Destino"}),e.jsx(J,{value:_e.destinationUrl,onChange:G=>zt(ue=>({...ue,destinationUrl:G.target.value})),className:"border-white/10 bg-white/5 font-mono text-xs","data-testid":"batch-input-destination-url"})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Países"}),e.jsx(J,{value:_e.countries,onChange:G=>zt(ue=>({...ue,countries:G.target.value})),className:"border-white/10 bg-white/5 text-xs"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Idade Min"}),e.jsx(J,{type:"number",value:_e.ageMin,onChange:G=>zt(ue=>({...ue,ageMin:G.target.value})),className:"border-white/10 bg-white/5"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Idade Max"}),e.jsx(J,{type:"number",value:_e.ageMax,onChange:G=>zt(ue=>({...ue,ageMax:G.target.value})),className:"border-white/10 bg-white/5"})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block",children:"Gênero"}),e.jsxs(Se,{value:Od,onValueChange:G=>Wx(G),children:[e.jsx($e,{className:"border-white/10",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"all",children:"Todos"}),e.jsx(U,{value:"female",children:"Feminino"}),e.jsx(U,{value:"male",children:"Masculino"})]})]})]})]}),parseInt(_e.ageMin)>25&&e.jsxs("p",{className:"text-[10px] text-amber-400/80 mt-1 px-1",children:["Advantage+ limita idade mínima a 25. O sistema ajustará automaticamente para 25 e usará ",_e.ageMin,"+ como sugestão de audiência."]}),e.jsxs("div",{className:"bg-white/[0.02] border border-white/5 rounded-xl p-3 space-y-3",children:[e.jsxs("button",{type:"button",onClick:()=>Lp(!Gd),className:"flex items-center justify-between w-full","data-testid":"toggle-advanced-options",children:[e.jsxs("h4",{className:"text-xs font-semibold text-white/80 flex items-center gap-2",children:[e.jsx(qa,{className:"w-3.5 h-3.5 text-violet-400"})," Opções Avançadas de Conversão"]}),e.jsx(Ct,{className:`w-3.5 h-3.5 text-white/40 transition-transform ${Gd?"rotate-180":""}`})]}),Gd&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-2 block text-white/60",children:"Posicionamento"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[{value:"advantage_plus",label:"Advantage+",desc:"Meta otimiza"},{value:"manual_feed",label:"Feed",desc:"FB + IG feed"},{value:"manual_stories",label:"Stories",desc:"FB + IG stories"},{value:"manual_reels",label:"Reels",desc:"FB + IG reels"}].map(G=>e.jsxs("button",{type:"button",onClick:()=>Hx(G.value),className:`px-2 py-1.5 rounded-lg text-center transition-all ${Bd===G.value?"bg-teal-600/20 border border-teal-500/40":"bg-white/[0.03] border border-white/5 hover:border-white/10"}`,"data-testid":`placement-${G.value}`,children:[e.jsx("p",{className:`text-[11px] font-medium ${Bd===G.value?"text-teal-300":"text-white/60"}`,children:G.label}),e.jsx("p",{className:"text-[9px] text-white/30",children:G.desc})]},G.value))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block text-white/60",children:"Estratégia de Lance"}),e.jsxs(Se,{value:xr,onValueChange:G=>Xx(G),children:[e.jsx($e,{className:"border-white/10 text-xs",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"LOWEST_COST_WITHOUT_CAP",children:"Maior Volume"}),e.jsx(U,{value:"COST_CAP",children:"Custo por Resultado"}
33),e.jsx(U,{value:"MINIMUM_ROAS",children:"ROAS Mínimo"})]})]})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block text-white/60",children:"Evento de Conversão"}),e.jsxs(Se,{value:Yx,onValueChange:G=>Zx(G),children:[e.jsx($e,{className:"border-white/10 text-xs",children:e.jsx(Ae,{})}),e.jsxs(Pe,{children:[e.jsx(U,{value:"PURCHASE",children:"Compra"}),e.jsx(U,{value:"INITIATED_CHECKOUT",children:"Início de Checkout"}),e.jsx(U,{value:"ADD_TO_CART",children:"Add to Cart"}),e.jsx(U,{value:"LEAD",children:"Lead (Cadastro)"}),e.jsx(U,{value:"COMPLETE_REGISTRATION",children:"Registro Completo"})]})]})]})]}),xr==="COST_CAP"&&e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block text-white/60",children:"Custo Máximo por Resultado (R$)"}),e.jsx(J,{type:"number",value:Ud,onChange:G=>Jx(G.target.value),placeholder:"Ex: 50",className:"border-white/10 bg-white/5","data-testid":"batch-cost-cap"})]}),xr==="MINIMUM_ROAS"&&e.jsxs("div",{children:[e.jsx(O,{className:"text-xs mb-1.5 block text-white/60",children:"ROAS Mínimo Desejado"}),e.jsx(J,{type:"number",step:"0.1",value:Kd,onChange:G=>Dp(G.target.value),placeholder:"Ex: 2.0",className:"border-white/10 bg-white/5","data-testid":"batch-min-roas"})]}),e.jsxs("div",{className:"flex items-center justify-between bg-emerald-500/5 border border-emerald-500/10 rounded-lg p-2.5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-emerald-400/80 font-medium",children:"Advantage+ Targeting Ativo"}),e.jsx("p",{className:"text-[10px] text-white/30",children:"O Meta expande automaticamente o público para maximizar resultados"})]}),e.jsx("span",{className:"text-[10px] text-emerald-400/60 bg-emerald-500/10 px-2 py-0.5 rounded-full",children:"Automático"})]})]})]}),hr&&hr.length>0&&e.jsxs("div",{children:[e.jsxs(O,{className:"text-xs mb-1.5 block flex items-center gap-1.5",children:[e.jsx(Re,{className:"w-3 h-3"})," Audiências Personalizadas ",e.jsx("span",{className:"text-white/30 font-normal",children:"(opcional)"})]}),e.jsx("div",{className:"max-h-36 overflow-y-auto border border-white/10 rounded-lg bg-white/5 p-2 space-y-1","data-testid":"batch-audience-selector",children:hr.map(G=>e.jsxs("button",{type:"button",onClick:()=>Ri(ue=>ue.includes(G.id)?ue.filter(Te=>Te!==G.id):[...ue,G.id]),className:`w-full text-left px-2.5 py-1.5 rounded-md text-xs flex items-center justify-between transition-colors ${ga.includes(G.id)?"bg-teal-600/20 border border-teal-500/30 text-teal-300":"hover:bg-white/5 text-white/70"}`,"data-testid":`batch-audience-option-${G.id}`,children:[e.jsx("span",{className:"truncate",children:G.name}),e.jsx("span",{className:"text-[10px] text-white/30 ml-2 flex-shrink-0",children:G.approximate_count?`~${Number(G.approximate_count).toLocaleString("pt-BR")}`:"—"})]},G.id))}),ga.length>0&&e.jsxs("p",{className:"text-[10px] text-teal-400/70 mt-1",children:[ga.length," audiência(s) selecionada(s)"]})]}),Cs&&e.jsx("div",{className:"bg-amber-500/10 border border-amber-500/20 rounded-lg p-3","data-testid":"batch-autonomous-info",children:e.jsxs("p",{className:"text-xs text-amber-300 flex items-center gap-1.5",children:[e.jsx(js,{className:"w-3.5 h-3.5 flex-shrink-0"}),"Estes ",t.length," criativos em ",P.length," conjuntos entrarão no pipeline autônomo: testados por ",rl?.testDurationDays||3," dias, a IA decide escalar ou pausar."]})})]})})()]}),zr&&ts&&e.jsxs("div",{className:"bg-violet-500/10 border border-violet-500/20 rounded-lg p-4 space-y-3","data-testid":"publish-progress-bar",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"text-violet-300 font-medium flex items-center gap-2",children:[e.jsx(T,{className:"w-4 h-4 animate-spin"}),ts.phase]}),e.jsx("span",{className:"text-white/60 text-xs",children:ts.total>0?`${Math.round(ts.current/ts.total*100)}%`:"..."})]}),e.jsx("div",{className:"w-full bg-white/10 rounded-full h-2 overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-violet-500 to-teal-400 rounded-full transition-all duration-500",style:{width:ts.total>0?`${ts.current/ts.total*100}%`:"5%"}})}),e.jsxs("div",{className:"flex justify-between text-[10px] text-white/40",children:[e.jsxs("span",{children:[ts.current,"/",ts.total," anúncios"]}),ts.adSetsTotal>0&&e.jsxs("span",{children:[ts.adSetsCreated,"/",ts.adSetsTotal," conjuntos"]})]})]}),e.jsxs(Mt,{children:[e.jsx(b,{variant:"outline",onClick:()=>{zr||Lr(!1)},className:"border-white/10",disabled:!!zr,children:"Cancelar"}
33),e.jsx(b,{className:"gap-1.5 bg-violet-600 hover:bg-violet-700",disabled:vo.isPending||!!zr||!_e.destinationUrl||Nt&&!Nt.valid||Qt==="existing_campaign"&&!ja||Qt==="existing_adset"&&!_d,onClick:()=>{const t=Od==="male"?"1":Od==="female"?"2":void 0;vo.mutate({creativeIds:Array.from(ks),campaignName:_e.campaignName||void 0,dailyBudgetPerAdSet:parseFloat(_e.dailyBudget)||10,targeting:{countries:_e.countries,ageMin:parseInt(_e.ageMin)||25,ageMax:parseInt(_e.ageMax)||65,...t?{genders:t}:{}},destinationUrl:_e.destinationUrl,status:_e.status,autonomousMode:Cs,groupBy:da==="single"?"auto":da,...da==="single"?{adSetsOverride:[{name:"Conjunto Único",creativeIds:Array.from(ks)}]}:{},customAudienceIds:ga.length>0?ga:void 0,metaAccountId:ba?parseInt(ba):void 0,...ri?{pageId:ri,instagramActorId:Vn?Qn.trim()||void 0:ll?.pages.find(s=>s.id===ri)?.instagram?.id||void 0}:{},...Qt==="existing_campaign"?{existingCampaignId:ja}:{},...Qt==="existing_adset"?{existingCampaignId:ja,existingAdSetId:_d}:{},advancedOptions:{placementMode:Bd,bidStrategy:xr,...xr==="COST_CAP"&&Ud?{costCapAmount:parseFloat(Ud)}:{},...xr==="MINIMUM_ROAS"&&Kd?{minRoasTarget:parseFloat(Kd)}:{},promotedEvent:Yx}})},"data-testid":"btn-confirm-batch-publish",children:vo.isPending||zr?ts?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," ",ts.phase," (",ts.current,"/",ts.total,")"]}):e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-4 h-4 animate-spin"})," Iniciando publicação..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"w-4 h-4"})," Publicar ",ks.size," em ",(()=>{if(Qt==="existing_adset")return"1 Conjunto (existente)";const s=Array.from(ks).map(C=>Ra?.find(P=>P.id===C)).filter(Boolean),i=new Set(s.map(C=>C?.imageUrl)),x=new Set(s.map(C=>C?.headline));return da==="single"?"1 Conjunto":da==="image"||da==="auto"&&i.size>1?`${i.size} Conjuntos`:`${x.size} Conjuntos`})()]})})]})]})})]})}function Hb(){const{user:a}=Sa(),r=!!a&&a.role==="admin",{data:l,isLoading:n}=z({queryKey:["/api/admin/margin-dashboard"],enabled:r});if(n)return e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-primary"})});const u=l?.totals,f=l?.products||[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold","data-testid":"text-margin-title",children:"Margem por Produto"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Receita vs custo de IA por tipo de serviço",l?.usdBrlRate&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground/70","data-testid":"text-usd-brl-rate",children:["(USD/BRL: ",l.usdBrlRate.toFixed(2),")"]})]})]}),u&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"p-4 rounded-xl border border-white/10 bg-white/[0.02]",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Receita Total"}),e.jsxs("p",{className:"text-lg font-bold text-emerald-400","data-testid":"text-margin-revenue",children:["R$ ",u.totalRevenue.toFixed(2)]})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-white/10 bg-white/[0.02]",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Custo IA Total"}),e.jsxs("p",{className:"text-lg font-bold text-red-400","data-testid":"text-margin-cost",children:["R$ ",u.totalCost.toFixed(2)]})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-white/10 bg-white/[0.02]",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Margem Bruta"}),e.jsxs("p",{className:`text-lg font-bold ${u.totalMargin>=0?"text-emerald-400":"text-red-400"}`,"data-testid":"text-margin-total",children:["R$ ",u.totalMargin.toFixed(2)]})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-white/10 bg-white/[0.02]",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Margem 
33%"}),e.jsxs("p",{className:`text-lg font-bold ${u.overallMarginPercent>=50?"text-emerald-400":u.overallMarginPercent>=20?"text-amber-400":"text-red-400"}`,"data-testid":"text-margin-percent",children:[u.overallMarginPercent.toFixed(1),"%"]})]})]}),e.jsx("div",{className:"rounded-xl border border-white/10 overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 bg-white/[0.02]",children:[e.jsx("th",{className:"text-left p-3 text-xs font-semibold text-muted-foreground",children:"Produto"}),e.jsx("th",{className:"text-right p-3 text-xs font-semibold text-muted-foreground",children:"Vendas"}),e.jsx("th",{className:"text-right p-3 text-xs font-semibold text-muted-foreground",children:"Receita"}),e.jsx("th",{className:"text-right p-3 text-xs font-semibold text-muted-foreground",children:"Custo IA"}),e.jsx("th",{className:"text-right p-3 text-xs font-semibold text-muted-foreground",children:"Margem"}),e.jsx("th",{className:"text-right p-3 text-xs font-semibold text-muted-foreground",children:"%"})]})}),e.jsx("tbody",{children:f.map(j=>e.jsxs("tr",{className:"border-b border-white/5 hover:bg-white/[0.02]","data-testid":`row-margin-${j.type}`,children:[e.jsx("td",{className:"p-3 font-medium text-white",children:j.label}),e.jsx("td",{className:"p-3 text-right text-muted-foreground",children:j.orderCount}),e.jsxs("td",{className:"p-3 text-right text-emerald-400 font-medium",children:["R$ ",j.revenue.toFixed(2)]}),e.jsxs("td",{className:"p-3 text-right text-red-400",children:["R$ ",j.cost.toFixed(2)]}),e.jsxs("td",{className:`p-3 text-right font-bold ${j.margin>=0?"text-emerald-400":"text-red-400"}`,children:["R$ ",j.margin.toFixed(2)]}),e.jsxs("td",{className:`p-3 text-right font-bold ${j.marginPercent>=50?"text-emerald-400":j.marginPercent>=20?"text-amber-400":"text-red-400"}`,children:[j.marginPercent.toFixed(1),"%"]})]},j.type))})]})}),f.length===0&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:e.jsx("p",{children:"Nenhuma venda confirmada encontrada."})})]})}function Xb({treeData:a,optimizerActionsData:r,sentinelaSuppressionsData:l}){const{toast:n}=st(),[u,f]=d.useState(new Set),[j,p]=d.useState(new Set),[g,w]=d.useState(!1),y=d.useMemo(()=>{const o=new Map,L=new Set;if(l){const v=Date.now(),I=new Map;if(a?.campaigns)for(const de of a.campaigns)for(const me of de.adSets||[])I.set(me.id,de.id);for(const de of l){const me=parseInt(de.entityId);if(isNaN(me)||!de.createdAt)continue;const ne=new Date(de.createdAt).getTime();if(v-ne>=24*36e5)continue;let S;if(de.entityType==="campaign"?S=me:de.entityType==="adset"&&(S=I.get(me)),!S)continue;const re=(de.actionTaken||"").toLowerCase(),_=(de.ruleName||"").toLowerCase(),ee=re.includes("escal")||_.includes("escala"),h=re.includes("pausar")||re.includes("paused")||re.includes("pausada");if(ee){const te=o.get(S);(!te||ne>te.lastScaledAt.getTime())&&o.set(S,{lastScaledAt:new Date(ne),cooldownEndsAt:new Date(ne+24*36e5)})}h&&L.add(S)}}return{cooldowns:o,pauseSuppressed:L}},[l,a]),F=[];if(a?.campaigns)for(const o of a.campaigns){const L=o.metrics;if(!L||!L.spend||L.conversions<=0)continue;const v=L.spend/L.conversions,I=o.createdAt?Math.floor((Date.now()-new Date(o.createdAt).getTime())/864e5):0,de=o.status==="ACTIVE",me=o.adSets?.some(ne=>ne.status==="ACTIVE");if(v<=6300&&I>=7&&de&&me){const ne=y.cooldowns.get(o.id);if(ne){const Z=Math.ceil((ne.cooldownEndsAt.getTime()-Date.now())/36e5),S=ne.lastScaledAt.toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"});F.push({type:"scale_cooldown",msg:`${o.name}: CPA R$${(v/100).toFixed(2)} ≤ ótimo — já escalada em ${S}. Próxima escala em ~${Z}h`,id:`a-sc-${o.id}`,campaignId:o.id,action:"dismiss"})}else F.push({type:"scale",msg:`${o.name}: CPA R$${(v/100).toFixed(2)} ≤ ótimo — pronta para escalar (+12%/dia)`,id:`a-s-${o.id}`,campaignId:o.id,action:"scale"})}else if(v>8190&&I>=5&&de){const ne=[],Z=[];for(const ee of o.adSets||[])for(const h of ee.ads||[])Z.push(h),(h.effectiveStatus==="ACTIVE"||h.status==="ACTIVE")&&ne.push(h);const S=[],re=[];for(const ee of ne){const h=ee.metrics;if(!h||h.spend<=0)continue;const te=h.conversions>0?h.spend/h.conversions:1/0;te<=8190&&h.conversions>0?S.push(ee):(te>8190||h.conversions===0)&&re.push({...ee,adCpa:te})}const _=Z.filter(ee=>{if(ee.effectiveStatus==="ACTIVE"||ee.status==="ACTIVE")return!1;const h=ee.metrics;return!h||h.spend<=0?!1:(h.conversions>0?h.spend/h.conversions:1/0)>8190||h.conversions===0});if(S.length>0&&re.length>0)F.push({type:"pause_losers",msg:`${o.name}: ${re.length} ad(s) ruim(ns) — pausar losers, manter ${S.length} winner(s)`,id:`a-pl-${o.id}`,campaignId:o.id,action:"pause_losers",loserAdIds:re.map(ee=>ee.id||ee.metaAdId),winnerCount:S.length});else if(S.length>0&&re.length===0)if(_.length>0){const ee=ne.reduce((M,ae)=>M+(ae.metrics?.spend||0),0),h=ne.reduce((M,ae)=>M+(ae.metrics?.conversions||0),0),te=h>0?ee/h:0;F.push({type:"monitor",msg:`${o.name}: CPA campanha R$${(v/100).toFixed(2)} (histórico) — ${S.length} winner(s) ativo(s) com CPA R$${(te/100).toFixed(2)}, ${_.length} loser(s) já pausado(s)`,id:`a-m-${o.id}`,campaignId:o.id,action:"dismiss"})}else F.push({type:"monitor",msg:`${o.name}: CPA campanha R$${(v/100).toFixed(2)} — ${S.length} ad(s) ativo(s) performando bem, monitorar`,id:`a-m-${o.id}`,campaignId:o.id,action:"dismiss"});else S.length===0&&ne.length===0?F.push({type:"pause",msg:`${o.name}: CPA R$${(v/100).toFixed(2)} > limite R$81,90 — sem ads ativos, pausar campanha`,id:`a-p-${o.id}`,campaignId:o.id,action:"pause"}):F.push({type:"pause",msg:`${o.name}: CPA R$${(v/100).toFixed(2)} > limite R$81,90 — nenhum ad com bom CPA, pausar campanha`,id:`a-p-${o.id}`,campaignId:o.id,action:"pause"})}else v>6300&&v<=8190&&de&&F.push({type:"monitor",msg:`${o.name}: CPA R$${(v/100).toFixed(2)} entre ótimo e limite — monitorar`,id:`a-m-${o.id}`,campaignId:o.id,action:"dismiss"})}const c=F.filter(o=>!u.has(o.id)),m=c.filter(o=>o.type!=="monitor"&&o.type!=="scale_cooldown"),$=async o=>{p(L=>new Set(L).add(o.id));try{const L={campaignId:o.campaignId,action:o.action};o.action==="pause_losers"&&o.loserAdIds&&(L.adIds=o.loserAdIds);const I=await(await N("POST","/api/admin/ads/apply-optimization",L)).json();if(I.success){f(Z=>new Set(Z).add(o.id)),K.invalidateQueries({queryKey:["/api/admin/ads/tree"]}),K.invalidateQueries({queryKey:["/api/admin/optimizer/actions"]}),K.invalidateQueries({queryKey:["/api/admin/optimizer/sentinela-suppressions"]});const de=I.results?.filter(Z=>Z.success).map(Z=>
33Z.details).filter(Boolean).join("; ")||"",me=I.results?.filter(Z=>Z.metaError).map(Z=>Z.metaError).join("; ")||"",ne=I.partial?"Otimização parcial":o.type==="pause_losers"?`${I.summary?.paused||0} loser(s) pausado(s), ${I.summary?.preserved||0} winner(s) preservado(s)`:o.type==="pause"?"Campanha pausada":"Budget escalado +12%";n({title:ne,description:me?`${de}. Aviso Meta: ${me}`:de||"Otimização aplicada com sucesso",variant:I.partial?"destructive":void 0})}else n({title:"Erro",description:I.message||"Falha ao aplicar",variant:"destructive"})}catch(L){n({title:"Erro",description:L.message||"Falha ao aplicar otimização",variant:"destructive"})}finally{p(L=>{const v=new Set(L);return v.delete(o.id),v})}},D=async o=>{f(L=>new Set(L).add(o.id));try{await N("POST","/api/admin/ads/apply-optimization",{campaignId:o.campaignId,action:"dismiss"}),K.invalidateQueries({queryKey:["/api/admin/optimizer/actions"]}),K.invalidateQueries({queryKey:["/api/admin/optimizer/sentinela-suppressions"]})}catch{}},A=async()=>{w(!0);for(const o of m)await $(o);for(const o of c.filter(L=>L.type==="monitor"||L.type==="scale_cooldown"))await D(o);w(!1)};return c.length===0&&(!r||r.length===0)?null:e.jsxs("div",{className:"space-y-2","data-testid":"reconciliation-section",children:[c.length>0&&e.jsxs("div",{className:"rounded-xl border border-white/[0.06] bg-gradient-to-r from-amber-500/[0.03] to-red-500/[0.03] p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-white/60 uppercase tracking-wider",children:"Sentinela de Performance"}),m.length>1&&e.jsxs(b,{size:"sm",variant:"outline",className:"h-6 px-2.5 text-[10px] border-orange-500/30 bg-
33orange-500/10 hover:bg-orange-500/20 text-orange-400",onClick:A,disabled:g,"data-testid":"btn-apply-all-optimizations",children:[g?e.jsx(T,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(He,{className:"w-3 h-3 mr-1"}),"Aplicar Todas (",m.length,")"]})]}),c.map(o=>e.jsxs("div",{className:`flex items-center gap-2 text-xs px-2.5 py-1.5 rounded-lg ${o.type==="scale"?"bg-emerald-500/10 text-emerald-400":o.type==="scale_cooldown"?"bg-blue-500/10 text-blue-400":o.type==="pause"||o.type==="pause_losers"?"bg-red-500/10 text-red-400":"bg-amber-500/10 text-amber-400"}`,"data-testid":o.id,children:[o.type==="scale"?e.jsx(Ie,{className:"w-3.5 h-3.5 shrink-0"}):o.type==="scale_cooldown"?e.jsx(ns,{className:"w-3.5 h-3.5 shrink-0"}):o.type==="pause"||o.type==="pause_losers"?e.jsx(Ca,{className:"w-3.5 h-3.5 shrink-0"}):e.jsx(Ce,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"flex-1 min-w-0 truncate",children:o.msg}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[o.type!=="monitor"&&o.type!=="scale_cooldown"?e.jsx(b,{size:"sm",variant:"ghost",className:`h-5 px-2 text-[9px] font-medium ${o.type==="pause"||o.type==="pause_losers"?"hover:bg-red-500/20 text-red-300":"hover:bg-emerald-500/20 text-emerald-300"}`,onClick:()=>$(o),disabled:j.has(o.id),"data-testid":`btn-apply-${o.id}`,children:j.has(o.id)?e.jsx(T,{className:"w-3 h-3 animate-spin"}):o.type==="pause_losers"?e.jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"w-3 h-3 mr-0.5"})," Pausar Losers"]}):o.type==="pause"?e.jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"w-3 h-3 mr-0.5"})," Pausar"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-3 h-3 mr-0.5"})," Escalar"]})}):null,e.jsx(b,{size:"sm",variant:"ghost",className:"h-5 w-5 p-0 hover:bg-white/10 text-white/30 hover:text-white/60",onClick:()=>D(o),"data-testid":`btn-dismiss-${o.id}`,children:e.jsx(ea,{className:"w-3 h-3"})})]})]},o.id))]}),r&&r.length>0&&e.jsxs("details",{className:"rounded-xl border border-white/[0.06] bg-white/[0.02] overflow-hidden",children:[e.jsxs("summary",{className:"p-3 cursor-pointer hover:bg-white/[0.02] transition-colors text-xs font-medium text-white/60 flex items-center gap-2",children:[e.jsx(jt,{className:"w-3.5 h-3.5 text-teal-400"}),"Histórico do Otimizador (",r.length," ações recentes)"]}),e.jsx("div",{className:"border-t border-white/5 max-h-48 overflow-y-auto",children:r.map((o,L)=>e.jsxs("div",{className:"px-4 py-2 border-b border-white/[0.03] last:border-b-0 flex items-center justify-between gap-3","data-testid":`optimizer-action-${L}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[11px] text-white/70 truncate",children:o.actionTaken}),e.jsxs("p",{className:"text-[9px] text-white/30",children:[o.ruleName," · ",o.entityType," #",o.entityId]})]}),e.jsxs("div",{className:"text-right shrink-0",children:[o.valueBefore&&o.valueAfter&&e.jsxs("p",{className:"text-[10px] text-white/50",children:[o.valueBefore," → ",o.valueAfter]}),e.jsx("p",{className:"text-[9px] text-white/25",children:o.createdAt?new Date(o.createdAt).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):""})]}),o.isSimulation&&e.jsx(E,{variant:"outline",className:"text-[8px] bg-blue-500/20 text-blue-400 border-blue-500/30 shrink-0",children:"SIM"})]},o.id||L))})]})]})}function Jb({onCreateFromWinner:a}){const{user:r}=Sa(),l=!!r&&r.role==="admin",{toast:n}=st(),[u,f]=d.useState(null),[j,p]=d.useState(new Set),[g,w]=d.useState(new Set),[y,F]=d.useState(null),[c,m]=d.useState({open:!1,campaignName:"",loading:!1,data:null,totalRevenue:0}),[$,D]=d.useState(null),[A,o]=d.useState("all"),[L,v]=d.useState("active_first"),[I,de]=d.useState(new Set),[me,ne]=d.useState(""),[Z,S]=d.useState(()=>{if(typeof window>"u")return 3e4;const k=window.localStorage.getItem("ads_live_refresh_interval"),q=k?parseInt(k):3e4;return[0,15e3,3e4,6e4].includes(q)?q:3e4}),[re,_]=d.useState(0),ee=A==="today"||A==="yesterday",{data:h}=z({queryKey:["/api/admin/optimizer/actions"],queryFn:()=>N("GET","/api/admin/optimizer/actions?limit=20").then(k=>k.json()),enabled:l}),{data:te}=z({queryKey:["/api/admin/optimizer/sentinela-suppressions"],queryFn:()=>N("GET","/api/admin/optimizer/actions?sinceHours=24&limit=200").then(k=>k.json()),enabled:l}),{data:M=[]}=z({queryKey:["/api/admin/meta-configs"],queryFn:()=>N("GET","/api/admin/meta-configs").then(k=>k.json()),enabled:l,staleTime:12e4}),ae=d.useMemo(()=>{const k={};for(const q of M)k[q.id]=q.name||`Conta #${q.id}`;return k},[M]),ye=d.useMemo(()=>
33{if(A==="all")return{startDate:void 0,endDate:void 0};const k=new Date,q=new Date(k.toLocaleString("en-US",{timeZone:"America/Sao_Paulo"})),V=he=>`${he.getFullYear()}-${String(he.getMonth()+1).padStart(2,"0")}-${String(he.getDate()).padStart(2,"0")}`;if(A==="today"){const he=V(q);return{startDate:he,endDate:he}}if(A==="yesterday"){const he=new Date(q);he.setDate(he.getDate()-1);const ke=V(he);return{startDate:ke,endDate:ke}}if(A==="last_7d"){const he=new Date(q);return he.setDate(he.getDate()-6),{startDate:V(he),endDate:V(q)}}const ce=new Date(q);return ce.setDate(ce.getDate()-29),{startDate:V(ce),endDate:V(q)}},[A]),Me=async k=>{m({open:!0,campaignName:k,loading:!0,data:null,totalRevenue:0});try{const V=await(await N("GET",`/api/admin/conversions?campaignName=${encodeURIComponent(k)}`)).json();m(ce=>({...ce,loading:!1,data:V.conversions||[],totalRevenue:V.totalRevenue||0}))}catch{m(q=>({...q,loading:!1,data:[]}))}},se=d.useMemo(()=>{const k=new URLSearchParams;return ye.startDate&&k.set("startDate",ye.startDate),ye.endDate&&k.set("endDate",ye.endDate),me&&k.set("metaAccountId",me),k.toString()},[ye,me]),Ne=ee?"/api/admin/ads/live":"/api/admin/ads/tree",{data:ie,isLoading:X,isFetching:B,dataUpdatedAt:ge,refetch:ut}=z({queryKey:[Ne,ye.startDate,ye.endDate,me],queryFn:()=>N("GET",`${Ne}${se?`?${se}`:""}`).then(k=>k.json()),enabled:l,refetchInterval:ee&&Z>0?Z:!1,refetchIntervalInBackground:!1,staleTime:ee?5e3:6e4});d.useEffect(()=>{typeof window<"u"&&window.localStorage.setItem("ads_live_refresh_interval",String(Z))},[Z]),d.useEffect(()=>{if(!ee||Z===0||!ge){_(0);return}const k=()=>{const V=Date.now()-ge,ce=Math.max(0,Math.ceil((Z-V)/1e3));_(ce)};k();const q=window.setInterval(k,1e3);return()=>window.clearInterval(q)},[ee,Z,ge]);const{data:at}=z({queryKey:["/api/admin/ads/sales-by-destination",ye.startDate,ye.endDate],queryFn:()=>N("GET",`/api/admin/ads/sales-by-destination${se?`?${se}`:""}`).then(k=>k.json()),enabled:l}),{data:$t}=z({queryKey:["/api/admin/ads/sync-status"],queryFn:()=>N("GET","/api/admin/ads/sync-status").then(k=>k.json()),enabled:l,refetchInterval:3e4}),pa=W({mutationFn:()=>N("POST","/api/admin/ads/sync-all").then(k=>k.json()),onSuccess:k=>{f(new Date),K.invalidateQueries({queryKey:["/api/admin/ads/tree"]}),K.invalidateQueries({queryKey:["/api/admin/ads/sync-status"]});let q;k.synced>0?q=`${k.synced} métricas sincronizadas | ${k.statusesUpdated||0} status atualizados`:k.noDataReasons?.length>0?q=k.noDataReasons.join(". "):k.details?q=`Nenhuma métrica encontrada. ${k.details.substring(0,250)}`:q="Nenhuma métrica encontrada. Campanhas podem ser muito recentes — a Meta leva ~24h para disponibilizar dados.",n({title:k.synced>0?"Sincronizado!":"Sincronização concluída",description:q,duration:k.synced>0?4e3:1e4})},onError:k=>n({title:"Erro ao sincronizar",description:k.message,variant:"destructive"})}),Ms=W({mutationFn:()=>N("POST","/api/admin/ads/sync-today").then(k=>k.json()),onSuccess:k=>{f(new Date),K.invalidateQueries({queryKey:["/api/admin/ads/tree"]}),K.invalidateQueries({queryKey:["/api/admin/ads/sync-status"]}),n({title:k.synced>0?"Atualizado!":"Sem dados novos",description:k.synced>0?`${k.synced} métricas de hoje sincronizadas`:"Nenhuma métrica nova encontrada para hoje",duration:3e3})},onError:k=>n({title:"Erro ao atualizar hoje",description:k.message,variant:"destructive"})}),fe=k=>k==="campaign"?"Campanha":k==="adset"?"Conjunto":"Anúncio",sa=W({mutationFn:k=>N("POST",`/api/admin/ads/${k.metaId}/pause`,{entityType:k.entityType}).then(q=>q.json()),onSuccess:(k,q)=>{K.invalidateQueries({queryKey:["/api/admin/ads/tree"]});const V=fe(q.entityType);k.metaError?n({title:`${V} pausado(a) localmente`,description:`Status local atualizado. Aviso Meta: ${k.metaError.substring(0,120)}`,variant:"default"}):n({title:"Pausado",description:`${V} pausado(a) com sucesso na Meta e localmente.`})},onError:k=>n({title:"Erro ao pausar",description:k.message,variant:"destructive"})}),Ha=W({mutationFn:k=>N("POST",`/api/admin/ads/${k.metaId}/resume`,{entityType:k.entityType}).then(q=>q.json()),onSuccess:(k,q)=>{K.invalidateQueries({queryKey:["/api/admin/ads/tree"]});const V=fe(q.entityType);k.metaError?n({title:`${V} ativado(a) localmente`,description:`Status local atualizado. Aviso Meta: ${k.metaError.substring(0,120)}`,variant:"default"}):n({title:"Ativado",description:`${V} ativado(a) com sucesso na Meta e localmente.`})},onError:k=>n({title:"Erro ao ativar",description:k.message,variant:"destructive"})}),Aa=W({mutationFn:k=>N("DELETE",`/api/admin/ads/campaigns/${k}`).then(q=>q.json()),onSuccess:()=>{K.invalidateQueries({queryKey:["/api/admin/ads/tree"]}),n({title:"Campanha excluída",description:"A campanha e todos os seus conjuntos e anúncios foram remov
33idos do sistema."})},onError:k=>n({title:"Erro ao excluir",description:k.message,variant:"destructive"})}),Tn=k=>{p(q=>{const V=new Set(q);return V.has(k)?V.delete(k):V.add(k),V})},ki=k=>{w(q=>{const V=new Set(q);return V.has(k)?V.delete(k):V.add(k),V})},le=k=>`R$ ${(k/100).toFixed(2)}`,aa=k=>k.toLocaleString("pt-BR"),Pa=u?Math.floor((Date.now()-u.getTime())/6e4):null,Ji=d.useMemo(()=>{if(!ie?.campaigns)return[];const k=new Set;for(const V of ie.campaigns)for(const ce of V.adSets||[])for(const he of ce.ads||[])if(he.destinationUrl)try{const ke=new URL(he.destinationUrl);k.add(ke.pathname==="/"?"/":ke.pathname.replace(/\/$/,""))}catch{k.add(he.destinationUrl)}return Array.from(k).sort((V,ce)=>V==="/"?-1:ce==="/"?1:V.localeCompare(ce))},[ie]),Kt=k=>{if(k==="/")return"Landing Page";const q=k.replace(/^\//,"").replace(/-/g," ");return q.charAt(0).toUpperCase()+q.slice(1)},R=d.useCallback((k,q)=>{if(!k)return!1;try{const V=new URL(k);return(V.pathname==="/"?"/":V.pathname.replace(/\/$/,""))===q}catch{return k===q}},[]),Ee=d.useCallback(k=>{const q={spend:0,impressions:0,clicks:0,conversions:0,revenue:0,leads:0,ctr:"0",roas:"0",cpa:null,costPerLead:null,platformLeads:0,platformConversions:0,platformRevenue:0};for(const V of k)V.metrics&&(q.spend+=V.metrics.spend||0,q.impressions+=V.metrics.impressions||0,q.clicks+=V.metrics.clicks||0,q.conversions+=V.metrics.conversions||0,q.revenue+=V.metrics.revenue||0,q.leads+=V.metrics.leads||0),q.platformLeads+=V.platformLeads||0,q.platformConversions+=V.platformConversions||0,q.platformRevenue+=V.platformRevenue||0;return q.ctr=q.impressions>0?(q.clicks/q.impressions*100).toFixed(2):"0",q.roas=q.spend>0?(q.revenue/q.spend).toFixed(2):"0",q.cpa=q.conversions>0?Math.round(q.spend/q.conversions):null,q.costPerLead=q.leads>0?Math.round(q.spend/q.leads):null,q},[]),ds=d.useMemo(()=>ie?.campaigns?$?ie.campaigns.map(k=>{const q=(k.adSets||[]).map(he=>{const ke=(he.ads||[]).filter(At=>R(At.destinationUrl,$));if(ke.length===0)return null;const xt=Ee(ke);return{...he,ads:ke,metrics:xt,platformLeads:xt.platformLeads,platformConversions:xt.platformConversions,platformRevenue:xt.platformRevenue}}).filter(Boolean);if(q.length===0)return null;const V=q.flatMap(he=>he.ads),ce=Ee(V);return{...k,adSets:q,metrics:ce,platformLeads:ce.platformLeads,platformConversions:ce.platformConversions,platformRevenue:ce.platformRevenue}}).filter(Boolean):ie.campaigns:[],[ie,$,R,Ee]),Yi=d.useMemo(()=>{if(!ds||ds.length===0)return ds;const k=[...ds],q=(V,ce)=>{const he=V.metrics;return he?ce==="roas"?he.spend>0?(he.revenue||0)/he.spend:0:ce==="cpa"?he.conversions>0?he.spend/he.conversions:1/0:ce==="spend"?he.spend||0:ce==="conversions"&&he.conversions||0:0};switch(L){case"active_first":k.sort((V,ce)=>{const he=V.status==="ACTIVE"?1:0,ke=ce.status==="ACTIVE"?1:0;return ke!==he?ke-he:q(ce,"spend")-q(V,"spend")});break;case"roas_desc":k.sort((V,ce)=>q(ce,"roas")-q(V,"roas"));break;case"roas_asc":k.sort((V,ce)=>q(V,"roas")-q(ce,"roas"));break;case"cpa_asc":k.sort((V,ce)=>{const he=q(V,"cpa"),ke=q(ce,"cpa");return he===1/0&&ke===1/0?0:he===1/0?1:ke===1/0?-1:he-ke});break;case"cpa_desc":k.sort((V,ce)=>{const he=q(V,"cpa"),ke=q(ce,"cpa");return he===1/0&&ke===1/0?0:he===1/0?-1:ke===1/0?1:ke-he});break;case"spend_desc":k.sort((V,ce)=>q(ce,"spend")-q(V,"spend"));break;case"conversions_desc":k.sort((V,ce)=>q(ce,"conversions")-q(V,"conversions"));break}return k},[ds,L]),Yt=d.useMemo(()=>{if(!$||!ie?.summary)return ie?.summary||null;let k=0,q=0,V=0,ce=0,he=0,ke=0,xt=0,At=0,Zt=0;for(const Ps of ds)for(const Zi of Ps.adSets||[])for(const Ns of Zi.ads||[])Ns.metrics&&(k+=Ns.metrics.spend||0,q+=Ns.metrics.impressions||0,V+=Ns.metrics.clicks||0,ce+=Ns.metrics.conversions||0,he+=Ns.metrics.revenue||0,ke+=Ns.metrics.leads||0),xt+=Ns.platformLeads||0,At+=Ns.platformConversions||0,Zt+=Ns.platformRevenue||0;let os=0,Ta=0;if(at?.destinations){const Ps=at.destinations[$];Ps&&(os=Ps.orders,Ta=Math.round(Ps.revenue*100))}return{totalCampaigns:ds.length,activeCampaigns:ds.filter(Ps=>Ps.status==="ACTIVE").length,totalSpend:k,totalImpressions:q,totalClicks:V,totalConversions:ce,totalRevenue:he,totalLeads:ke,platformSales:os,platformRevenue:Ta,platformLeads:xt,platformConversions:At,platformRevenueByAd:Zt,roas:k>0?(he/k).toFixed(2):"0"}},[ds,$,ie,at]),Xa=({status:k,effectiveStatus:q})=>{const V=q||k,ce=V==="ACTIVE",he=V==="CAMPAIGN_PAUSED",ke=V==="ADSET_PAUSED",xt=he||ke;return e.jsxs(E,{variant:"outline",className:`text-[10px] ${ce?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":xt?"bg-zinc-500/20 text-zinc-400 border-zinc-500/30":"bg-amber-500/20 text-amber-400 border-amber-500/30"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full mr-1 inline-block ${ce?"bg-emerald-400 animate-pulse":xt?"bg-zinc-400":"bg-amber-400"}`}),ce?"Ativo":he?"Camp. Pausada":ke?"Conj. Pausado":"Pausado"]})},Ar=({m:k,compact:q,campaignName:V})=>{const ce=k||{spend:0,impressions:0,clicks:0,conversions:0,roas:"0"},he=ce.spend>0||ce.impressions>0,ke=ce.conversions||0,xt=ke>0&&ce.spend>0?Math.round(ce.spend/ke):null,At=Number(ce.roas),Zt=he?At>=2.5?"text-emerald-400":At>=1?"text-amber-400":At>0?"text-red-400":"text-white/30":"text-white/20",os=xt?xt/100:null,Ta=he?os===null?"text-white/30":os<=63?"text-emerald-400":os<=82?"text-amber-400":"text-red-400":"text-white/20";return e.jsxs("div",{className:"mt-2",children:[e.jsxs("div",{className:"grid grid-cols-6 gap-3","data-testid":"metrics-row",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Investido"}),e.jsx("p",{className:`text-xs font-semibold ${he?"text-white":"text-white/20"}`,children:le(ce.spend)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Impressões"}),e.jsx("p",{className:`text-xs font-semibold ${he?"text-white":"text-white/20"}`,children:aa(ce.impressions)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Cliques"}),e.jsx("p",{className:`text-xs font-semibold ${he?"text-white":"text-white/20"}`,children:aa(ce.clicks)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"Conversões"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("p",{className:`text-xs font-semibold ${he&&ke>0?"text-emerald-400":he?"text-white/30":"text-white/20"}`,children:ke>0?aa(ke):"—"}),V&&ke>0&&e.jsx("button",{onClick:Ps=>{Ps.stopPropagation(),Me(V)},className:"text-white/30 hover:text-emerald-400 transition-colors p-0.5 rounded hover:bg-white/5",title:"Ver detalhes das conversões","data-testid":`btn-view-conversions-${V.substring(0,20)}`,children:e.jsx(ht,{className:"w-3 h-3"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"ROAS"}),e.jsx("p",{className:`text-xs font-semibold ${Zt}`,children:he&&At>0?`${At.toFixed(2)}x`:"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40",children:"CPA"}),e.jsx("p",{className:`text-xs font-semibold ${Ta}`,children:xt?le(xt):"—"})]})]}),!he&&e.jsx("p",{className:"text-[9px] text-white/20 mt-1",children:'Clique em "Sincronizar Tudo" para buscar métricas da Meta'})]})},Ci=({metaId:k,entityType:q,status:V})=>{if(!k)return null;const ce=V==="ACTIVE",he=sa.isPending||Ha.isPending,ke=q==="campaign"?"campanha":q==="adset"?"conjunto de anúncios":"anúncio",xt=q==="campaign"?"A campanha inteira será pausada. Todos os conjuntos e anúncios dentro dela deixarão de ser exibidos na Meta.":q==="adset"?"O conjunto de anúncios será pausado. Todos os anúncios dentro dele deixarão de ser exibidos.":"O anúncio deixar
33á de ser exibido na Meta até ser reativado.",At=q==="campaign"?"A campanha será reativada. Os conjuntos e anúncios que estavam ativos antes voltarão a ser exibidos.":q==="adset"?"O conjunto será reativado. Os anúncios que estavam ativos antes voltarão a ser exibidos.":"O anúncio voltará a ser exibido na Meta.";return e.jsxs(pi,{children:[e.jsx(ui,{asChild:!0,children:e.jsx(b,{size:"sm",variant:"ghost",className:`h-7 w-7 p-0 ${ce?"text-amber-400 hover:text-amber-300 hover:bg-amber-500/10":"text-emerald-400 hover:text-emerald-300 hover:bg-emerald-500/10"}`,disabled:he,onClick:Zt=>Zt.stopPropagation(),"data-testid":`btn-${ce?"pause":"resume"}-${k}`,children:he?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):ce?e.jsx(Ca,{className:"w-3.5 h-3.5"}):e.jsx(Us,{className:"w-3.5 h-3.5"})})}),e.jsxs(gi,{className:"bg-[#1a1a2e] border-white/10",onClick:Zt=>Zt.stopPropagation(),children:[e.jsxs(bi,{children:[e.jsxs(ji,{className:"text-white",children:[ce?"Pausar":"Ativar"," ",ke,"?"]}),e.jsx(vi,{className:"text-white/60",children:ce?xt:At})]}),e.jsxs(Ni,{children:[e.jsx(fi,{className:"bg-white/5 border-white/10 text-white hover:bg-white/10",children:"Cancelar"}),e.jsx(wi,{className:ce?"bg-amber-600 hover:bg-amber-700":"bg-emerald-600 hover:bg-emerald-700",onClick:()=>ce?sa.mutate({metaId:k,entityType:q}):Ha.mutate({metaId:k,entityType:q}),children:ce?"Pausar":"Ativar"})]})]})]})};return ie?.summary,e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold text-white",children:"Gerenciador de Anúncios"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Campanhas, conjuntos e anúncios na Meta"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[Pa!==null&&e.jsxs("span",{className:"text-[10px] text-white/30",children:["Última sync: ",Pa===0?"agora":`${Pa} min atrás`]}),ie?.campaigns&&ie.campaigns.length>0&&(()=>{const k=ie.campaigns.filter(V=>V.status==="ACTIVE"&&V.metaCampaignId),q=k.length>0;return e.jsxs(pi,{children:[e.jsx(ui,{asChild:!0,children:e.jsx(b,{size:"sm",variant:"outline",className:`text-xs gap-1.5 ${q?"border-amber-500/30 text-amber-400 hover:bg-amber-500/10":"border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/10"}`,disabled:sa.isPending||Ha.isPending,"data-testid":"btn-pause-all-campaigns",children:q?e.jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"w-3 h-3"})," Pausar Todas"]}):e.jsxs(e.Fragment,{children:[e.jsx(Us,{className:"w-3 h-3"})," Ativar Todas"]})})}),e.jsxs(gi,{className:"bg-[#1a1a2e] border-white/10",children:[e.jsxs(bi,{children:[e.jsxs(ji,{className:"text-white",children:[q?"Pausar":"Ativar"," todas as campanhas?"]}),e.jsx(vi,{className:"text-white/60",children:q?`${k.length} campanha(s) ativa(s) serão pausadas. Todos os anúncios deixarão de ser exibidos na Meta.`:"Todas as campanhas pausadas serão reativadas na Meta."})]}),e.jsxs(Ni,{children:[e.jsx(fi,{className:"bg-white/5 border-white/10 text-white hover:bg-white/10",children:"Cancelar"}),e.jsx(wi,{className:q?"bg-amber-600 hover:bg-amber-700":"bg-emerald-600 hover:bg-emerald-700",onClick:()=>{q?k.forEach(V=>sa.mutate({metaId:V.metaCampaignId,entityType:"campaign"})):ie.campaigns.filter(V=>V.status==="PAUSED"&&V.metaCampaignId).forEach(V=>Ha.mutate({metaId:V.metaCampaignId,entityType:"campaign"}))},children:q?`Pausar ${k.length} Campanha(s)`:"Ativar Todas"})]})]})]})})(),e.jsxs("div",{className:"flex items-center gap-2",children:[($t?.lastSyncAt||u)&&e.jsx("span",{className:"text-[10px] text-white/30","data-testid":"last-sync-time",children:$t?.isSyncing?e.jsxs("span",{className:"flex items-center gap-1 text-blue-400/60",children:[e.jsx(T,{className:"w-2.5 h-2.5 animate-spin"})," Sincronizando..."]}):$t?.lastSyncAt?e.jsxs(e.Fragment,{children:["Última sync: ",new Date($t.lastSyncAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})," (",$t.lastSyncAgo!==null&&$t.lastSyncAgo<120?`${$t.lastSyncAgo}s atrás`:$t.lastSyncAgo!==null?`${Math.round($t.lastSyncAgo/60)}min atrás`:"",")"]}):u?e.jsxs(e.Fragment,{children:["Última sync: ",u.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})]}):null}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1.5 border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/10",onClick:()=>Ms.mutate(),disabled:Ms.isPending||pa.isPending,"data-testid":"btn-sync-today",children:[Ms.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),"Atualizar Hoje"]}),e.jsxs(b,{size:"sm",variant:"outline",className:"text-xs gap-1.5 border-white/10",onClick:()=>pa.mutate(),disabled:pa.isPending||Ms.isPending,"data-testid":"btn-sync-all",children:[pa.isPending?e.jsx(T,{className:"w-3 h-3 animate-spin"}):e.jsx(xe,{className:"w-3 h-3"}),"Sincronizar Tudo"]})]})]})]}),e.jsxs("div",{className:"text-[10px] text-white/25 flex items-center gap-1.5 -mt-2 mb-2","data-testid":"sync-auto-info",children:[e.jsx(xe,{className:"w-3 h-3"}),e.jsx("span",{children:'Sincronização automática a cada 1h · Modo AO VIVO ativo nos filtros "Hoje" e "Ontem" — dados direto da Meta'})]}),ee&&e.jsxs("div",{className:"mb-3 rounded-xl border border-emerald-400/20 bg-gradient-to-r from-emerald-500/[0.07] via-teal-500/[0.05] to-violet-500/[0.05] backdrop-blur-sm px-3 py-2 flex items-center gap-3 flex-wrap","data-testid":"live-mode-bar",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:`absolute inline-flex h-full w-full rounded-full ${ie?.freshness?.source==="cache_fallback"?"bg-amber-400":"bg-emerald-400"} ${B?"":"animate-ping opacity-75"}`}),e.jsx("span",{className:`relative inline-flex rounded-full h-2 w-2 ${ie?.freshness?.source==="cache_fallback"?"bg-amber-500":"bg-emerald-500"}`})]}),e.jsx("span",{className:`text-[11px] font-bold tracking-wider ${ie?.freshness?.source==="cache_fallback"?"text-amber-300":"text-emerald-300"}`,"data-testid":"text-live-status",children:ie?.freshness?.source==="cache_fallback"?"CACHE":"AO VIVO"})]}),e.jsx("div",{className:"text-[10px] text-white/50 flex items-center gap-1.5","data-testid":"text-live-freshness",children:B?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-3 h-3 animate-spin"}),e.jsx("span",{children:"Atualizando..."})]}):ie?.freshness?e.jsxs(e.Fragment,{children:[e.jsx(jt,{className:"w-3 h-3"}),e.jsx("span",{children:ie.freshness.source==="cache_fallback"?`Cache · sincronizado há ${ie.freshness.cacheLastSyncAt?Math.max(0,Math.floor((Date.now()-ie.freshness.cacheLastSyncAt)/1e3/60))+"min":"—"}`:ie.freshness.source==="live_partial"?`Meta (parcial) · há ${Math.max(0,Math.floor((Date.now()-(ie.freshness.fetchedAt||ge))/1e3))}s`:`Direto da Meta · há ${Math.max(0,Math.floor((Date.now()-(ie.freshness.fetchedAt||ge))/1e3))}s`})]}):e.jsxs(e.Fragment,{children:[e.jsx(jt,{className:"w-3 h-3"}),e.jsx("span",{children:"Aguardando dados..."})]})}),Z>0&&re>0&&!B&&e.jsxs("div",{className:"text-[10px] text-white/40 flex items-center gap-1","data-testid":"text-live-countdown",children:[e.jsx(xe,{className:"w-2.5 h-2.5"}),e.jsxs("span",{children:["próx. em ",re,"s"]})]}),ie?.freshness?.warning&&e.jsxs("div",{className:"text-[10px] text-amber-300/90 flex items-center gap-1.5 max-w-md truncate","data-testid":"text-live-warning",children:[e.jsx(Xe,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"truncate",title:ie.freshness.warning,children:ie.freshness.warning})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>ut(),disabled:B,className:"text-[10px] px-2 py-1 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 text-white/60 hover:text-white/90 transition-all disabled:opacity-50 flex items-center gap-1","data-testid":"button-live-refresh-now",children:[e.jsx(xe,{className:`w-3 h-3 ${B?"animate-spin":""}`}),e.jsx("span",{children:"Atualizar agora"})]}),e.jsxs("div",{className:"flex items-center gap-1 bg-white/[0.04] border border-white/10 rounded-lg px-1.5 py-0.5","data-testid":"live-interval-control",children:[e.jsx(qa,{className:"w-3 h-3 text-white/40"}),e.jsx("span",{className:"text-[10px] text-white/40 mr-1",children:"auto:"}),[{v:0,l:"off"},{v:15e3,l:"15s"},{v:3e4,l:"30s"},{v:6e4,l:"60s"}].map(k=>e.jsx("button",{onClick:()=>S(k.v),className:`text-[10px] px-1.5 py-0.5 rounded font-medium transition-all ${Z===k.v?"bg-gradient-to-r from-emerald-500/40 to-teal-500/40 text-white":"text-white/40 hover:text-white/70 hover:bg-white/5"}`,"data-testid":`button-live-interval-${k.l}`,children:k.l},k.v))]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap","data-testid":"date-filter-bar",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-white/40 shrink-0",children:[e.jsx(Ec,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wider",children:"Período"})]}),[{key:"today",label:"Hoje"},{key:"yesterday",label:"Ontem"},{key:"last_7d",label:"7 dias"},{key:"last_30d",label:"30 dias"},{key:"all",label:"Todo período"}].map(k=>e.jsx("button",{onClick:()=>o(k.key),className:`px-2.5 py-1 rounded-full text-[11px] font-medium transition-all ${A===k.key?"bg-gradient-to-r from-teal-500/30 to-violet-500/30 text-white border border-teal-500/40 shadow-[0_0_8px_rgba(20,184,166,0.15)]":"bg-white/[0.04] text-white/50 border border-white/[0.06] hover:bg-white/[0.08] hover:text-white/70"}`,"data-testid":`filter-date-${k.key}`,children:k.label},k.key)),ye.startDate&&e.jsx("span",{className:"text-[10px] text-white/30 ml-1",children:ye.startDate===ye.endDate?ye.startDate.split("-").reverse().join("/"):`${ye.startDate.split("-").reverse().join("/")} — ${ye.endDate.split("-").reverse().join("/")}`}),M.length>1&&e.jsxs("select",{"data-testid":"filter-meta-account",className:"ml-3 bg-white/5 border border-white/10 rounded-lg px-2 py-1 text-[11px] text-white/70",value:me,onChange:k=>ne(k.target.value),children:[e.jsx("option",{value:"",children:"Todas as contas"}),M.map(k=>e.jsx("option",{value:String(k.id),children:k.name||`Conta #${k.id}`},k.id))]})]}),Ji.length>1&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap","data-testid":"destination-filter-bar",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-white/40 shrink-0",children:[e.jsx(Xl,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wider",children:"Destino"})]}),e.jsx("button",{onClick:()=>D(null),className:`px-2.5 py-1 rounded-full text-[11px] font-medium transition-all ${$?"bg-white/[0.04] text-white/50 border border-white/[0.06] hover:bg-white/[0.08] hover:text-white/70":"bg-gradient-to-r from-teal-500/30 to-violet-500/30 text-white border border-teal-500/40 shadow-[0_0_8px_rgba(20,184,166,0.15)]"}`,"data-testid":"filter-destination-all",children:"Todas"}),Ji.map(k=>{const q=$===k,V=ie?.campaigns?.reduce((ce,he)=>ce+(he.adSets||[]).reduce((ke,xt)=>ke+(xt.ads||[]).filter(At=>R(At.destinationUrl,k)).length,0),0)||0;return e.jsxs("button",{onClick:()=>D(q?null:k),className:`px-2.5 py-1 rounded-full text-[11px] font-medium transition-all flex items-center gap-1.5 ${q?"bg-gradient-to-r from-teal-500/30 to-violet-500/30 text-white border border-teal-500/40 shadow-[0_0_8px_rgba(20,184,166,0.15)]":"bg-white/[0.04] text-white/50 border border-white/[0.06] hover:bg-white/[0.08] hover:text-white/70"}`,"data-testid":`filter-destination-${k.replace(/\//g,"-")}`,children:[e.jsx(pt,{className:"w-3 h-3"}),e.jsx("span",{children:Kt(k)}),e.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full ${q?"bg-white/20 text-white":"bg-white/[0.06] text-white/30"}`,children:V})]},k)})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap","data-testid":"sort-filter-bar",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-white/40 shrink-0",children:[e.jsx($r,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wider",children:"Ordenar"})]}),[{key:"active_first",label:"Ativos primeiro"},{key:"roas_desc",label:"ROAS ↓"},{key:"roas_asc",label:"ROAS ↑"},{key:"cpa_asc",label:"CPA ↓ (melhor)"},{key:"cpa_desc",label:"CPA ↑ (pior)"},{key:"spend_desc",label:"Investimento ↓"},{key:"conversions_desc",label:"Conversões ↓"}].map(k=>e.jsx("button",{onClick:()=>v(k.key),className:`px-2.5 py-1 rounded-full text-[11px] font-medium transition-all ${L===k.key?"bg-gradient-to-r from-teal-500/30 to-violet-500/30 text-white border border-teal-500/40 shadow-[0_0_8px_rgba(20,184,166,0.15)]":"bg-white/[0.04] text-white/50 border border-white/[0.06] hover:bg-white/[0.08] hover:text-white/70"}`,"data-testid":`sort-${k.key}`,children:k.label},k.key))]}),Yt&&(Yt.totalSpend>0||Yt.totalCampaigns>0)&&(()=>{const k=Yt.totalSpend>0?Yt.totalRevenue/Yt.totalSpend:0,q=k>=2.5?"text-emerald-400":k>=1?"text-amber-400":k>0?"text-red-400":"text-white/30",V=Yt.totalConversions>0?Yt.totalSpend/Yt.totalConversions:null,ce=V?V/100:null,he=ce===null?"text-white/30":ce<=63?"text-emerald-400":ce<=82?"text-amber-400":"text-red-400";return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 ga
33p-3","data-testid":"ad-manager-summary",children:[e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.03] p-4 text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Campanhas Ativas"}),e.jsxs("p",{className:"text-2xl font-bold text-teal-400 mt-1",children:[Yt.activeCampaigns,e.jsxs("span",{className:"text-sm text-white/30",children:["/",Yt.totalCampaigns]})]})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.03] p-4 text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Investido"}),e.jsx("p",{className:"text-xl font-bold text-white mt-1",children:le(Yt.totalSpend)})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.03] p-4 text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"Conversões"}),e.jsx("p",{className:"text-2xl font-bold text-emerald-400 mt-1","data-testid":"text-platform-sales",children:aa(Yt.totalConversions)}),Yt.totalRevenue>0&&e.jsxs("p",{className:"text-[10px] text-emerald-400/60 mt-0.5",children:["Receita ",le(Yt.totalRevenue)]})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.03] p-4 text-center",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"ROAS"}),e.jsx("p",{className:`text-2xl font-bold mt-1 ${q}`,children:k>0?`${k.toFixed(2)}x`:"—"})]}),e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.03] p-4 text-center","data-testid":"card-cpa-medio",children:[e.jsx("p",{className:"text-[9px] text-white/40 uppercase tracking-wider",children:"CPA"}),e.jsx("p",{className:`text-2xl font-bold mt-1 ${he}`,children:V?le(Math.round(V)):"—"}),ce!==null&&e.jsx("p",{className:"text-[10px] text-white/25 mt-0.5",children:"Meta: R$63"})]})]})}
33)(),e.jsx(Xb,{treeData:ie,optimizerActionsData:h,sentinelaSuppressionsData:te}),X?e.jsx("div",{className:"flex justify-center p-12",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-teal-400"})}):!ie?.campaigns||ie.campaigns.length===0?e.jsxs("div",{className:"border border-dashed border-white/10 rounded-xl p-12 text-center",children:[e.jsx(lt,{className:"w-12 h-12 text-white/10 mx-auto mb-3"}),e.jsx("p",{className:"text-white/40 text-sm",children:"Nenhuma campanha ainda"}),e.jsx("p",{className:"text-white/25 text-xs mt-1",children:"Publique criativos para criar campanhas automaticamente"})]}):Yi.length===0&&$?e.jsxs("div",{className:"border border-dashed border-white/10 rounded-xl p-8 text-center",children:[e.jsx(Xl,{className:"w-10 h-10 text-white/10 mx-auto mb-3"}),e.jsxs("p",{className:"text-white/40 text-sm",children:["Nenhuma campanha direciona para ",e.jsx("span",{className:"text-teal-400 font-medium",children:Kt($)})]}),e.jsx("button",{onClick:()=>D(null),className:"text-xs text-teal-400 hover:text-teal-300 mt-2 underline underline-offset-2","data-testid":"btn-clear-filter",children:"Limpar filtro"})]}):e.jsx("div",{className:"space-y-2",children:Yi.map(k=>e.jsxs("div",{className:"border border-white/10 rounded-xl bg-white/[0.02] overflow-hidden","data-testid":`campaign-${k.id}`,children:[e.jsxs("div",{className:"p-3 cursor-pointer hover:bg-white/[0.02] transition-colors",onClick:()=>Tn(k.id),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[j.has(k.id)?e.jsx(Ct,{className:"w-4 h-4 text-white/40 shrink-0"}):e.jsx(ya,{className:"w-4 h-4 text-white/40 shrink-0"}),e.jsx(Xt,{className:"w-4 h-4 text-teal-400 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-white truncate",children:k.name}),k.metaAccountId&&M.length>1&&ae[k.metaAccountId]&&e.jsx(E,{variant:"outline",className:"text-[9px] border-violet-500/30 text-violet-400 bg-violet-500/10 shrink-0","data-testid":`badge-account-${k.id}`,children:ae[k.metaAccountId]})]}),e.jsxs("p",{className:"text-[10px] text-white/30 truncate",children:[k.objective," · ",le(k.dailyBudget||0),"/dia · ",k.adSets?.length||0," conjunto(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 ml-3",children:[(()=>{const q=k.createdAt?Math.round((Date.now()-new Date(k.createdAt).getTime())/36e5):null,V=!k.metrics?.spend&&!k.metrics?.impressions;return q!==null&&q<48&&V?e.jsxs(E,{variant:"outline",className:"text-[10px] bg-blue-500/20 text-blue-400 border-blue-500/30","data-testid":`badge-new-campaign-${k.id}`,children:[e.jsx(ns,{className:"w-3 h-3 mr-1"}),"Nova — métricas em breve"]}):null})(),(!k.adSets||k.adSets.length===0)&&e.jsxs(E,{variant:"outline",className:"text-[10px] bg-orange-500/20 text-orange-400 border-orange-500/30","data-testid":`warning-no-adsets-${k.id}`,children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"Sem conjuntos"]}),k.adSets?.length>0&&k.adSets.every(q=>!q.ads||q.ads.length===0)&&e.jsxs(E,{variant:"outline",className:"text-[10px] bg-orange-500/20 text-orange-400 border-orange-500/30","data-testid":`warning-no-ads-${k.id}`,children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"Sem anúncios"]}),(()=>{const q=k.metrics;if(!q||!q.spend)return null;const V=q.conversions>0?q.spend/q.conversions:0,ce=k.createdAt?Math.floor((Date.now()-new Date(k.createdAt).getTime())/864e5):0,he=6300,ke=Math.round(he*1.3);return q.conversions>0&&V<=he&&ce>=7?e.jsx(E,{variant:"outline",className:"text-[10px] bg-emerald-500/20 text-emerald-400 border-emerald-500/30","data-testid":`sentinela-scale-${k.id}`,title:`CPA R$${(V/100).toFixed(2)} ≤ ótimo R$${(he/100).toFixed(2)} | ${ce} dias → Escalar +12%/dia`,children:"Escalar"}):q.conversions>0&&V>ke&&ce>=5?e.jsx(E,{variant:"outline",className:"text-[10px] bg-red-500/20 text-red-400 border-red-500/30","data-testid":`sentinela-pause-${k.id}`,title:`CPA R$${(V/100).toFixed(2)} > limite R$${(ke/100).toFixed(2)} | ${ce} dias → Pausar`,children:"Pausar"}):q.conversions>0&&V>he&&V<=ke?e.jsx(E,{variant:"outline",className:"text-[10px] bg-amber-500/20 text-amber-400 border-amber-500/30","data-testid":`sentinela-monitor-${k.id}`,title:`CPA R$${(V/100).toFixed(2)} entre ótimo e limite | Monitorar`,children:"Monitorar"}):ce<5?e.jsx(E,{variant:"outline",className:"text-[10px] bg-white/10 text-white/50 border-white/20","data-testid":`sentinela-data-${k.id}`,title:`${ce} dias — coletando dados (mín. 5 dias)`,children:"Coletando"}):null})(),e.jsx(Xa,{status:k.status,effectiveStatus:k.status}),e.jsx(Ci,{metaId:k.metaCampaignId,entityType:"campaign",status:k.status}),e.jsxs(pi,{children:[e.jsx(ui,{asChild:!0,children:e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-red-400/60 hover:text-red-400 hover:bg-red-500/10",disabled:Aa.isPending,onClick:q=>q.stopPropagation(),"data-testid":`btn-delete-campaign-${k.id}`,children:Aa.isPending?e.jsx(T,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(As,{className:"w-3.5 h-3.5"})})}),e.jsxs(gi,{className:"bg-[#1a1a2e] border-white/10",onClick:q=>q.stopPropagation(),children:[e.jsxs(bi,{children:[e.jsx(ji,{className:"text-white",children:"Excluir campanha?"}),e.jsxs(vi,{className:"text-white/60",children:["A campanha ",e.jsxs("strong",{className:"text-white/80",children:['"',k.name,'"']})," será removida do sistema junto com todos os seus conjuntos de anúncios (",k.adSets?.length||0,") e anúncios vinculados. Esta ação não pode ser desfeita. A campanha na Meta Ads não será afetada."]})]}),e.jsxs(Ni,{children:[e.jsx(fi,{className:"bg-white/5 border-white/10 text-white hover:bg-white/10",children:"Cancelar"}),e.jsx(wi,{className:"bg-red-600 hover:bg-red-700",onClick:()=>Aa.mutate(k.id),children:"Excluir Campanha"})]})]})]})]})]}),e.jsx(Ar,{m:k.metrics,campaignName:k.name,platformData:{platformLeads:k.platformLeads,platformConversions:k.platformConversions,platformRevenue:k.platformRevenue}})]}),j.has(k.id)&&e.jsx(qu,{campaignId:k.id,range:15}),j.has(k.id)&&k.adSets&&k.adSets.length>0&&e.jsx("div",{className:"border-t border-white/5",children:k.adSets.map(q=>e.jsxs("div",{className:"border-b border-white/5 last:border-b-0","data-testid":`adset-${q.id}`,children:[e.jsxs("div",{className:"pl-8 pr-3 py-2.5 cursor-pointer hover:bg-white/[0.02] transition-colors",onClick:V=>{V.stopPropagation(),ki(q.id)},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[g.has(q.id)?e.jsx(Ct,{className:"w-3.5 h-3.5 text-white/30 shrink-0"}):e.jsx(ya,{className:"w-3.5 h-3.5 text-white/30 shrink-0"}),e.jsx(lt,{className:"w-3.5 h-3.5 text-indigo-400 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"text-xs font-medium text-white/90 truncate",children:q.name}),e.jsxs("p",{className:"text-[10px] text-white/30",children:[le(q.dailyBudget||0),"/dia · ",q.targetingAgeMin,"-",q.targetingAgeMax," anos · ",q.targetingCountries||"BR"," · ",q.ads?.length||0," anúncio(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 ml-3",children:[(!q.ads||q.ads.length===0)&&e.jsxs(E,{variant:"outline",className:"text-[10px] bg-
33orange-500/20 text-orange-400 border-orange-500/30",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"Vazio"]}),e.jsx(Xa,{status:q.status,effectiveStatus:q.effectiveStatus}),e.jsx(Ci,{metaId:q.metaAdSetId,entityType:"adset",status:q.status})]})]}),e.jsx("div",{className:"pl-7",children:e.jsx(Ar,{m:q.metrics,compact:!0,campaignName:q.name,platformData:{platformLeads:q.platformLeads,platformConversions:q.platformConversions,platformRevenue:q.platformRevenue}})})]}),g.has(q.id)&&q.ads&&q.ads.length>0&&e.jsx("div",{className:"bg-white/[0.01]",children:q.ads.map(V=>{const ce=Number(V.metrics?.roas||0),he=Number(V.platformConversions||V.metrics?.conversions||0),ke=V.creative&&(ce>=1.5||he>=2),xt=V.creative&&I.has(V.creative.id);return e.jsxs("div",{className:"pl-16 pr-3 py-2 border-t border-white/[0.03]","data-testid":`ad-${V.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[V.creative?.imageUrl&&e.jsx("img",{src:V.creative.imageUrl,alt:"",className:"w-8 h-8 rounded object-cover shrink-0 border border-white/10"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs text-white/80 truncate",children:V.creative?.headline||V.name}),e.jsx("p",{className:"text-[10px] text-white/30 truncate",children:V.creative?.primaryText?.substring(0,60)||V.destinationUrl||"—"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 ml-3",children:[ke&&a&&e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 gap-1 px-2 text-[10px] font-bold bg-gradient-to-r from-amber-500/20 to-orange-500/20 text-amber-400 border border-amber-500/30 hover:from-amber-500/30 hover:to-orange-500/30 hover:text-amber-300 rounded-lg whitespace-nowrap",disabled:xt,onClick:At=>{if(At.stopPropagation(),!V.creative?.id)return;const Zt={countries:q.targetingCountries||"BR",ageMin:q.targetingAgeMin||25,ageMax:q.targetingAgeMax||65,genders:q.targetingGenders||"",interests:q.targetingInterests||"",adSetName:q.name||"",campaignName:k.name||"",sourceHeadline:V.creative?.headline||"",sourceAngle:V.creative?.angle||"",sourceAudience:V.creative?.targetAudience||"",roas:ce.toFixed(2),cpa:V.metrics?.cpa?(V.metrics.cpa/100).toFixed(2):"—",conversions:he};de(os=>new Set(os).add(V.creative.id)),a(V.creative.id,Zt),n({title:"🔥 Criando 5 variações do campeão!",description:`Baseado em "${V.creative.headline}" (ROAS ${ce.toFixed(1)}x). Redirecionando para Criativos...`})},"data-testid":`btn-create-from-winner-${V.id}`,children:xt?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"w-3 h-3 animate-spin"})," Gerando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"w-3 h-3"})," CRIAR CRIATIVOS"]})}),V.creative&&e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-white/40 hover:text-white hover:bg-white/10",onClick:At=>{At.stopPropagation(),F(V)},"data-testid":`btn-preview-${V.id}`,children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),e.jsx(Xa,{status:V.status,effectiveStatus:V.effectiveStatus}),e.jsx(Ci,{metaId:V.metaAdId,entityType:"ad",status:V.status})]})]}),V.metrics&&e.jsx("div",{className:"pl-10 mt-1",children:e.jsx(Ar,{m:V.metrics,compact:!0,campaignName:V.name||V.creative?.headline,platformData:{platformLeads:V.platformLeads,platformConversions:V.platformConversions,platformRevenue:V.platformRevenue}})})]},V.id)})})]},q.id))})]},k.id))}),e.jsx(Je,{open:!!y,onOpenChange:k=>!k&&F(null),children:e.jsxs(Ye,{className:"bg-[#0f0f1a] border-white/10 max-w-5xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"text-white flex items-center gap-2",children:[e.jsx(ht,{className:"w-4 h-4 text-teal-400"}),"Pré-visualização do Anúncio"]}),e.jsx(mt,{className:"text-white/40",children:"Simulação de como o anúncio aparece nos diferentes formatos da Meta"})]}),y?.creative&&(()=>{const k=y.creative,q=k.format==="story"?"Stories / Reels (9:16)":k.format==="feed_vertical"?"Feed Vertical (4:5)":"Feed Quadrado (1:1)",V=k.format==="story";return e.jsxs("div",{className:"space-y-6 mt-2",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(E,{variant:"outline",className:"bg-teal-500/10 text-teal-400 border-teal-500/30 text-xs",children:q}),e.jsx(E,{variant:"outline",className:"bg-indigo-500/10 text-indigo-400 border-indigo-500/30 text-xs",children:k.style}),e.jsx(E,{variant:"outline",className:"bg-white/5 text-white/50 border-white/10 text-xs",children:k.angle}),e.jsx(E,{variant:"outline",className:"bg-white/5 text-white/50 border-white/10 text-xs",children:k.targetAudience}),e.jsx(Xa,{status:y.status})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] text-white/40 uppercase tracking-wider font-semibold",children:"Feed do Facebook / Instagram"}),e.jsxs("div",{className:"bg-white rounded-lg overflow-hidden max-w-[320px] mx-auto 
33shadow-lg","data-testid":"preview-feed",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-gradient-to-br from-teal-500 to-emerald-600 flex items-center justify-center",children:e.jsx("span",{className:"text-white text-[10px] font-bold",children:"S"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold text-gray-900",children:"Sabhia.ia"}),e.jsxs("p",{className:"text-[9px] text-gray-500",children:["Patrocinado · ",e.jsx(pt,{className:"w-2.5 h-2.5 inline"})]})]})]}),e.jsx("p",{className:"px-3 pb-2 text-[11px] text-gray-800 leading-snug",children:k.primaryText}),k.imageUrl&&e.jsx("div",{className:`w-full bg-gray-100 relative ${V||k.format==="feed_vertical"?"aspect-[4/5]":"aspect-square"}`,children:e.jsx("img",{src:k.imageUrl,alt:"",className:"w-full h-full object-cover"})}),e.jsx("div",{className:"px-3 py-2 border-t border-gray-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[9px] text-gray-500 uppercase truncate",children:y.destinationUrl?.replace(/https?:\/\//,"").split("/")[0]||"sabhia.ai"}),e.jsx("p",{className:"text-[12px] font-semibold text-gray-900 truncate",children:k.headline}),e.jsx("p",{className:"text-[10px] text-gray-600 truncate",children:k.description})]}),e.jsx("div",{className:"ml-2 shrink-0",children:e.jsx("div",{className:"bg-gray-200 text-gray-800 text-[10px] font-semibold px-3 py-1.5 rounded",children:k.callToAction?.replace(/_/g," ")||"Saiba mais"})})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] text-white/40 uppercase tracking-wider font-semibold",children:"Stories / Reels"}),e.jsxs("div",{className:"bg-black rounded-2xl overflow-hidden max-w-[200px] mx-auto shadow-lg relative",style:{aspectRatio:"9/16"},"data-testid":"preview-story",children:[k.imageUrl&&e.jsx("img",{src:k.imageUrl,alt:"",className:`w-full h-full ${V?"object-cover":"object-contain"}`,style:{backgroundColor:"#111"}}),e.jsx("div",{className:"absolute top-0 left-0 right-0 p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-gradient-to-br from-teal-500 to-emerald-600 flex items-center justify-center border border-white/30",children:e.jsx("span",{className:"text-white text-[8px] font-bold",children:"S"})}),e.jsx("p",{className:"text-[9px] text-white font-semibold drop-shadow",children:"Sabhia.ia"}),e.jsx("p",{className:"text-[8px] text-white/70",children:"Patrocinado"})]})}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-3 pt-8",children:[e.jsx("p",{className:"text-[9px] text-white/90 leading-snug mb-1 line-clamp-2",children:k.primaryText?.substring(0,80)}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsx("p",{className:"text-[8px] text-white/60 truncate flex-1",children:k.headline}),e.jsx("div",{className:"bg-white text-black text-[8px] font-semibold px-2 py-1 rounded-full ml-2 shrink-0",children:k.callToAction?.replace(/_/g," ")||"Saiba mais"})]})]})]})]})]}),e.jsxs("div",{className:"border-t border-white/5 pt-4 space-y-3",children:[e.jsx("p",{className:"text-[10px] text-white/40 uppercase tracking-wider font-semibold",children:"Detalhes do Criativo"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-white/[0.03] border border-white/5 rounded-lg p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 mb-1",children:"Texto Principal"}),e.jsx("p",{className:"text-xs text-white/80 leading-relaxed",children:k.primaryText})]}),e.jsxs("div",{className:"bg-white/[0.03] border border-white/5 rounded-lg p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40 mb-0.5",children:"Headline"}),e.jsx("p",{className:"text-xs text-white font-semibold",children:k.headline})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40 mb-0.5",children:"Descrição"}),e.jsx("p",{className:"text-xs text-white/70",children:k.description})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40 mb-0.5",children:"CTA"}),e.jsx("p",{className:"text-xs text-white/70",children:k.callToAction?.replace(/_/g," ")})]}),k.overlayText&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[9px] text-white/40 mb-0.5",children:"Texto na Imagem"}),e.jsx("p",{className:"text-xs text-white/70",children:k.overlayText})]})]})]}),y.destinationUrl&&e.jsxs("div",{className:"bg-white/[0.03] border border-white/5 rounded-lg p-3",children:[e.jsx("p",{className:"text-[9px] text-white/40 mb-1",children:"URL de Destino"}),e.jsx("p",{className:"text-xs text-teal-400 break-all",children:y.destinationUrl})]})]}),k.imageUrl&&e.jsxs("div",{className:"border-t border-white/5 pt-4",children:[e.jsxs("p",{className:"text-[10px] text-white/40 uppercase tracking-wider font-semibold mb-2",children:["Imagem Original (",q,")"]}),e.jsx("div",{className:`rounded-lg overflow-hidden border border-white/10 mx-auto ${V?"max-w-[250px]":k.format==="feed_vertical"?"max-w-[300px]":"max-w-[350px]"}`,children:e.jsx("img",{src:k.imageUrl,alt:"",className:"w-full"})})]})]})})(),!y?.creative&&y&&e.jsxs("div",{className:"text-center py-8",children:[e.jsx(ht,{className:"w-10 h-10 text-white/10 mx-auto mb-3"}),e.jsx("p",{className:"text-white/40 text-sm",children:"Criativo não disponível para este anúncio"})]})]})}),e.jsx(Je,{open:c.open,onOpenChange:k=>!k&&m(q=>({...q,open:!1})),children:e.jsxs(Ye,{className:"bg-[#0f0f1a] border-white/10 max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Ze,{children:[e.jsxs(et,{className:"text-white flex items-center gap-2",children:[e.jsx(ht,{className:"w-4 h-4 text-emerald-400"}),"Relatório de Conversões"]}),e.jsxs(mt,{className:"text-white/40",children:[c.campaignName&&e.jsx("span",{className:"text-white/60 font-medium",children:c.campaignName}),c.data&&c.data.length>0&&e.jsxs("span",{className:"ml-2",children:["— ",c.data.length," conversão(ões) · Total: R$ ",c.totalRevenue.toFixed(2)]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto -mx-6 px-6",children:c.loading?e.jsxs("div",{className:"flex items-center justify-center py-12",children:[e.jsx(T,{className:"w-6 h-6 text-emerald-400 animate-spin"}),e.jsx("span",{className:"ml-2 text-white/50 text-sm",children:"Carregando conversões..."})]}):c.data&&c.data.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ht,{className:"w-8 h-8 text-white/10 mx-auto mb-3"}),e.jsx("p",{className:"text-white/40 text-sm",children:"Nenhuma conversão encontrada para esta campanha"})]}):e.jsx("div",{className:"space-y-2 pb-4",children:c.data?.map(k=>e.jsx("div",{className:"rounded-xl border border-white/5 bg-white/[0.02] p-3 hover:bg-white/[0.04] transition-colors","data-testid":`conversion-${k.id}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("p",{className:"text-sm font-semibold text-white truncate",children:k.customerName}),e.jsx("span",{className:"text-[10px] text-white/30 shrink-0",children:k.customerEmail})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-xs text-white/60",children:k.product}),k.bookTitle!=="—"&&e.jsxs("span",{className:"text-xs text-primary/70 truncate max-w-[200px]",children:["📖 ",k.bookTitle]}),e.jsx("span",{className:"text-[10px] text-white/30",children:k.paymentMethod}),k.utmSource!=="—"&&e.jsx("span",{className:"text-[10px] bg-white/5 text-white/40 px-1.5 py-0.5 rounded",children:k.utmSource})]})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs("p",{className:"text-sm font-bold text-emerald-400",children:["R$ ",k.amount.toFixed(2)]}),e.jsx("p",{className:"text-[10px] text-white/30",children:k.date?new Date(k.date).toLocaleDateString("pt-BR"):""})]})]})},k.id))})})]})})]})}function Yb({activeAdminTab:a}){const{user:r}=Sa(),l=!!r&&r.role==="admin",{toast:n}=st(),[u,f]=d.useState(!1),{data:j=[],isLoading:p,refetch:g}=z({queryKey:["/api/admin/blog/posts"],enabled:l&&a==="blog"}),w={"como-escrever":"Como Escrever",autopublicacao:"Autopublicação","marketing-literario":"Marketing Literário","ia-para-autores":"IA para Autores","historias-de-sucesso":"Histórias de Sucesso","dicas-de-escrita":"Dicas de Escrita"},y=async()=>{f(!0);try{(await(await N("POST","/api/admin/blog/generate")).json()).success&&(n({title:"Artigo gerado!",description:"Novo artigo publicado no blog."}),g())}catch(D){n({title:"Erro ao gerar",description:D.message,variant:"destructive"})}finally{f(!1)}},F=async D=>{try{const A=D.status==="published"?"draft":"published";await N("PUT",`/api/admin/blog/posts/${D.id}`,{status:A,publishedAt:A==="published"?new Date().toISOString():null}),n({title:A==="published"?"Publicado!":"Despublicado"}),g()}catch(A){n({title:"Erro",description:A.message,variant:"destructive"})}},c=async D=>{try{await N("DELETE",`/api/admin/blog/posts/${D}`),n({title:"Artigo excluído"}),g()}catch(A){n({title:"Erro",description:A.message,variant:"destructive"})}},m=j.filter(D=>D.status==="published").length,$=j.filter(D=>D.status==="draft").length;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("h3",{className:"text-lg font-bold text-white",children:"Blog SEO Automatizado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Artigos gerados automaticamente por IA — 1 por dia, otimizados para Google e IAs."})]}),e.jsxs(b,{onClick:y,disabled:u,className:"bg-amber-600 hover:bg-amber-700 gap-1.5","data-testid":"button-generate-blog",children:[u?e.jsx(T,{className:"w-4 h-4 animate-spin"}):e.jsx(qe,{className:"w-4 h-4"}),"Gerar Artigo Agora"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(kt,{icon:tt,label:"Total Posts",value:j.length,"data-testid":"metric-blog-total"}),e.jsx(kt,{icon:is,label:"Publicados",value:m,color:"text-emerald-400","data-testid":"metric-blog-published"}),e.jsx(kt,{icon:Yl,label:"Rascunhos",value:$,color:"text-amber-400","data-testid":"metric-blog-drafts"})]}),p?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{className:"w-6 h-6 animate-spin text-white/40"})}):j.length===0?e.jsxs("div",{className:"text-center py-10",children:[e.jsx(tt,{className:"w-10 h-10 text-white/20 mx-auto mb-3"}),e.jsx("p",{className:"text-white/40",children:'Nenhum artigo ainda. Clique em "Gerar Artigo Agora" para criar o primeiro.'})]}):e.jsx("div",{className:"space-y-3",children:j.map(D=>e.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-xl p-4 flex items-start gap-4 hover:bg-white/[0.07] transition-colors","data-testid":`blog-admin-post-${D.id}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-medium border ${D.status==="published"?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-amber-500/20 text-amber-400 border-amber-500/30"}`,children:D.status==="published"?"Publicado":"Rascunho"}),D.category&&e.jsx("span",{className:"text-[10px] text-white/40",children:w[D.category]||D.category}),D.publishedAt&&e.jsx("span",{className:"text-[10px] text-white/30",children:new Date(D.publishedAt).toLocaleDateString("pt-BR")})]}),e.jsx("h4",{className:"text-sm font-medium text-white truncate",children:D.title}),D.excerpt&&e.jsx("p",{className:"text-xs text-white/40 mt-1 line-clamp-1",children:D.excerpt}),e.jsx("div",{className:"flex items-center gap-2 mt-2",children:e.jsxs("a",{href:`/blog/${D.slug}`,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-amber-400 hover:underline flex items-center gap-1","data-testid":`link-view-post-${D.id}`,children:[e.jsx(vs,{className:"w-3 h-3"})," Ver no blog"]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>F(D),className:"h-7 px-2 text-xs","data-testid":`button-toggle-status-${D.id}`,children:D.status==="published"?e.jsxs(e.Fragment,{children:[e.jsx(Hl,{className:"w-3 h-3 mr-1"})," Despublicar"]}):e.jsxs(e.Fragment,{children:[e.jsx(ht,{className:"w-3 h-3 mr-1"})," Publicar"]})}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>c(D.id),className:"h-7 px-2 text-xs text-red-400 hover:text-red-300 hover:bg-red-500/10","data-testid":`button-delete-post-${D.id}`,children:e.jsx(As,{className:"w-3 h-3"})})]})]},D.id))})]})}export{SN 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.