1import{j as e}from"./query-DYcR4fI_.js";import{r,a1 as ts,a5 as ge,aP as as,l as Ns,aQ as Xe,O as je,aR as rs,aS as vs,_ as Ke,T as ls,aT as ys,a8 as Be,ag as ws,aU as Ss,G as ks,ax as _s,ae as Cs,L as Q,p as Re,aV as Rs,aW as Ts,aK as Ls,n as Ds,I as ns,aN as Es,C as As,s as Fs,ao as Ps,aX as We,o as Os,aY as $s,af as ye,J as Ms,aZ as qs,Z as Is,a_ as Bs}from"./ui-B2iMbamQ.js";import{s as N,ab as J,ac as ee,ad as se,ae as te,af as w,B as F,I as ze,al as Se,ag as Ue,ai as He,aj as Ve,ak as Ge,c as me,L as Ye,am as Ws,an as is,ao as Ze,ap as zs,a as Us}from"./index-oO2A1mAZ.js";import{A as Me}from"./AdminLayout-NfAoc13o.js";import{T as cs,a as os,b as ie,c as ue}from"./tabs-DrSYhQpf.js";import{S as pe}from"./skeleton-C33Bf8cZ.js";import{u as Hs,D as Vs,A as qe}from"./DateRangePicker-BHQ4qrQS.js";import{K as U}from"./KpiCard-CCb-hQut.js";import{S as O,E as ae,C as ds}from"./EmptyState-DLPoSp07.js";import{C as M,a as z,b as ke,c as _e}from"./card-Bvvua0kj.js";import{R as xs,X as ms,Y as us,T as hs,L as Gs,B as Ie}from"./generateCategoricalChart-ux6gJKbo.js";import{A as Ks}from"./AreaChart-DriIaoKM.js";import{C as Ce}from"./checkbox--ziW8h-K.js";import{T as Te,a as Le,b as G,c as L,d as De,e as C}from"./table-DoJ_C1d0.js";import{S as ps}from"./StatusPill-DduSo4cf.js";import{T as Ys}from"./textarea-DTdfZSLV.js";import{B as ce}from"./badge-C3_pDSBl.js";import{B as Qs}from"./BarChart-zIg4KQAp.js";import{b as Xs}from"./vendor-Dd1NO3KL.js";import"./supabase-DzW4_pBN.js";async function Je(s,l){const{data:f,error:h}=await N.rpc("email_marketing_metrics",{p_from:s.toISOString(),p_to:l.toISOString()});if(h)throw h;return f}const Zs=()=>{const[s,l]=r.useState({signups:0,emailsSent:0,emailsOpened:0,emailsClicked:0,purchases:0,emailRevenue:0,totalRevenue:0}),[f,h]=r.useState(!0),[u,R]=r.useState("30days"),x=async()=>{h(!0);try{const i=new Date;let o=null;if(u!=="all"){const H=u==="7days"?7:u==="30days"?30:90,P=new Date(i);P.setDate(P.getDate()-H),o=P.toISOString()}let v=N.from("profiles").select("id",{count:"exact",head:!0});o&&(v=v.gte("created_at",o));const{count:d}=await v;let c=N.from("email_sends").select("id",{count:"exact",head:!0});o&&(c=c.gte("sent_at",o));const{count:S}=await c;let T=N.from("email_sends").select("id",{count:"exact",head:!0}).not("opened_at","is",null);o&&(T=T.gte("sent_at",o));const{count:b}=await T;let K=N.from("email_sends").select("id",{count:"exact",head:!0}).not("clicked_at","is",null);o&&(K=K.gte("sent_at",o));const{count:k}=await K;let p=N.from("purchases").select("id, final_price_usd").eq("payment_status","completed");o&&(p=p.gte("created_at",o));const{data:y}=await p;let A=N.from("email_sends").select("purchase_amount").not("converted_at","is",null);o&&(A=A.gte("sent_at",o));const{data:oe}=await A,de=(oe||[]).reduce((H,P)=>H+(Number(P.purchase_amount)||0),0),re=(y||[]).reduce((H,P)=>H+(Number(P.final_price_usd)||0),0);l({signups:d||0,emailsSent:S||0,emailsOpened:b||0,emailsClicked:k||0,purchases:y?.length||0,emailRevenue:de,totalRevenue:re})}catch(i){console.error("Error fetching funnel data:",i)}finally{h(!1)}};r.useEffect(()=>{x()},[u]);const n=r.useMemo(()=>(Math.max(s.signups,1),[{label:"Cadastros",value:s.signups,percentage:100,icon:ts,color:"from-blue-500 to-blue-600",bgColor:"bg-blue-500/10",borderColor:"border-blue-500/30",textColor:"text-blue-400"},{label:"Emails Enviados",value:s.emailsSent,percentage:s.signups>0?s.emailsSent/s.signups*100:0,icon:ge,color:"from-purple-500 to-purple-600",bgColor:"bg-purple-500/10",borderColor:"border-purple-500/30",textColor:"text-purple-400"},{label:"Emails Abertos",value:s.emailsOpened,percentage:s.emailsSent>0?s.emailsOpened/s.emailsSent*100:0,icon:ge,color:"from-amber-500 to-amber-600",bgColor:"bg-amber-500/10",borderColor:"border-amber-500/30",textColor:"text-amber-400",dropoff:s.emailsSent>0?(s.emailsSent-s.emailsOpened)/s.emailsSent*100:0},{label:"Cliques",value:s.emailsClicked,percentage:s.emailsOpened>0?s.emailsClicked/s.emailsOpened*100:0,icon:as,color:"from-orange-500 to-orange-600",bgColor:"bg-orange-500/10",borderColor:"border-orange-500/30",textColor:"text-orange-400",dropoff:s.emailsOpened>0?(s.emailsOpened-s.emailsClicked)/s.emailsOpened*100:0},{label:"Compras",value:s.purchases,percentage:s.emailsClicked>0?s.purchases/s.emailsClicked*100:0,icon:Ns,color:"from-emerald-500 to-emerald-600",bgColor:"bg-emerald-500/10",borderColor:"border-emerald-500/30",textColor:"text-emerald-400",dropoff:s.emailsClicked>0?(s.emailsClicked-s.purchases)/s.emailsClicked*100:0}]),[s]),m=r.useMemo(()=>s.signups===0?0:s.purchases/s.signups*100,[s]);return f?e.jsx(M,{className:"bg-slate-900/50 border-slate-800",children:e.jsx(z,{className:"p-6",children:e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-8 bg-slate-800 rounded w-1/3"}),e.jsx("div",{className:"space-y-3",children:[1,2,3,4,5].map(i=>e.jsx("div",{className:"h-16 bg-slate-800 rounded"},i))})]})})}):e.jsxs(M,{className:"bg-slate-900/50 border-slate-800",children:[e.jsx(ke,{className:"pb-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(_e,{className:"text-white flex items-center gap-2",children:[e.jsx(Xe,{className:"w-5 h-5 text-amber-400"}),"Funil de Conversão de Emails"]}
1),e.jsx("p",{className:"text-sm text-slate-400 mt-1",children:"Cadastro â Email Aberto â Clique â Compra"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(J,{value:u,onValueChange:i=>R(i),children:[e.jsx(ee,{className:"w-32 bg-slate-800 border-slate-700",children:e.jsx(se,{})}),e.jsxs(te,{children:[e.jsx(w,{value:"7days",children:"7 dias"}),e.jsx(w,{value:"30days",children:"30 dias"}),e.jsx(w,{value:"90days",children:"90 dias"}),e.jsx(w,{value:"all",children:"Tudo"})]})]}),e.jsx(F,{variant:"outline",size:"icon",onClick:x,className:"border-slate-700",children:e.jsx(je,{className:"w-4 h-4"})})]})]})}),e.jsxs(z,{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-r from-emerald-500/10 to-blue-500/10 rounded-xl p-4 border border-emerald-500/20",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-slate-300",children:"Taxa de Conversão Total"}),e.jsxs("span",{className:"text-2xl font-bold text-emerald-400",children:[m.toFixed(2),"%"]})]}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[s.purchases," compras de ",s.signups," cadastros"]})]}),e.jsx("div",{className:"space-y-3",children:n.map((i,o)=>{const v=i.icon,d=o===0?100:Math.max(20,i.value/Math.max(n[0].value,1)*100);return e.jsxs("div",{className:"relative",children:[i.dropoff!==void 0&&i.dropoff>0&&e.jsxs("div",{className:"absolute -top-2 right-0 flex items-center gap-1 text-xs text-red-400",children:[e.jsx(Xe,{className:"w-3 h-3"}),"-",i.dropoff.toFixed(1),"% perda"]}),e.jsxs("div",{className:`relative overflow-hidden rounded-xl ${i.bgColor} border ${i.borderColor} transition-all duration-500`,style:{width:`${d}%`,minWidth:"200px"},children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${i.color} opacity-20`,style:{width:`${i.percentage}%`}}),e.jsxs("div",{className:"relative p-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg bg-gradient-to-br ${i.color} flex items-center justify-center`,children:e.jsx(v,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-white",children:i.label}),e.jsxs("p",{className:`text-xs ${i.textColor}`,children:[i.percentage.toFixed(1),"% do anterior"]})]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:`text-2xl font-bold ${i.textColor}`,children:i.value.toLocaleString()})})]})]}),o<n.length-1&&e.jsx("div",{className:"flex justify-center my-1",children:e.jsx("div",{className:"w-0 h-0 border-l-8 border-r-8 border-t-8 border-l-transparent border-r-transparent border-t-slate-700"})})]},i.label)})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 pt-4 border-t border-slate-800",children:[e.jsxs("div",{className:"bg-slate-800/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Taxa Abertura"}),e.jsxs("p",{className:"text-lg font-bold text-amber-400",children:[s.emailsSent>0?(s.emailsOpened/s.emailsSent*100).toFixed(1):0,"%"]})]}),e.jsxs("div",{className:"bg-slate-800/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Taxa Clique"}),e.jsxs("p",{className:"text-lg font-bold text-orange-400",children:[s.emailsOpened>0?(s.emailsClicked/s.emailsOpened*100).toFixed(1):0,"%"]})]}),e.jsxs("div",{className:"bg-slate-800/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"CTR Geral"}),e.jsxs("p",{className:"text-lg font-bold text-purple-400",children:[s.emailsSent>0?(s.emailsClicked/s.emailsSent*100).toFixed(1):0,"%"]})]}),e.jsxs("div",{className:"bg-slate-800/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Conv. CliqueâCompra"}),e.jsxs("p",{className:"text-lg font-bold text-emerald-400",children:[s.emailsClicked>0?(s.purchases/s.emailsClicked*100).toFixed(1):0,"%"]})]}),e.jsxs("div",{className:"bg-gradient-to-br from-green-500/10 to-green-600/5 rounded-lg p-3 text-center border border-green-500/20",children:[e.jsx("p",{className:"text-xs text-green-400",children:"Receita via Email"}),e.jsxs("p",{className:"text-lg font-bold text-green-400",children:["$",s.emailRevenue.toLocaleStr
1ing()]}),e.jsxs("p",{className:"text-xs text-slate-500",children:[s.totalRevenue>0?(s.emailRevenue/s.totalRevenue*100).toFixed(1):0,"% do total"]})]}),e.jsxs("div",{className:"bg-gradient-to-br from-emerald-500/10 to-emerald-600/5 rounded-lg p-3 text-center border border-emerald-500/20",children:[e.jsx("p",{className:"text-xs text-emerald-400",children:"Receita Total"}),e.jsxs("p",{className:"text-lg font-bold text-emerald-400",children:["$",s.totalRevenue.toLocaleString()]})]})]})]})]})};function Js(){const s=Hs("30d"),[l,f]=r.useState(null),[h,u]=r.useState(null),[R,x]=r.useState(!0);r.useEffect(()=>{let i=!1;return x(!0),Promise.all([Je(s.from,s.to),Je(s.prevFrom,s.prevTo)]).then(([o,v])=>{i||(f(o),u(v))}).catch(o=>console.error("metrics",o)).finally(()=>!i&&x(!1)),()=>{i=!0}},[s.from,s.to,s.prevFrom,s.prevTo]);const n=i=>i.toLocaleString(),m=i=>`$${i.toFixed(2)}`;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground font-mono uppercase tracking-wider",children:"Window"}),e.jsx("p",{className:"text-sm font-medium",children:s.label})]}),e.jsx(Vs,{value:s})]}),R&&!l?e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:Array.from({length:8}).map((i,o)=>e.jsx(pe,{className:"h-24 rounded-lg"},o))}):l?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(U,{label:"Sent",value:n(l.sent),current:l.sent,previous:h?.sent,hint:e.jsxs(e.Fragment,{children:[e.jsx(ge,{className:"inline h-3 w-3 mr-1"}),"unique recipients"]})}),e.jsx(U,{label:"Open rate",value:`${l.open_rate}%`,current:l.open_rate,previous:h?.open_rate,hint:e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"inline h-3 w-3 mr-1"}),n(l.unique_opens)]})}),e.jsx(U,{label:"Click rate",value:`${l.click_rate}%`,current:l.click_rate,previous:h?.click_rate,hint:e.jsxs(e.Fragment,{children:[e.jsx(vs,{className:"inline h-3 w-3 mr-1"}),n(l.unique_clicks)]})}),e.jsx(U,{label:"CTOR",value:`${l.ctor}%`,current:l.ctor,previous:h?.ctor,hint:"click ÷ open"}),e.jsx(U,{label:"Revenue",value:m(l.revenue),current:l.revenue,previous:h?.revenue,hint:e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"inline h-3 w-3 mr-1"}),l.attributed_purchases," purchases"]})}),e.jsx(U,{label:"$ / email",value:`$${l.revenue_per_email.toFixed(3)}`,current:l.revenue_per_email,previous:h?.revenue_per_email,hint:"attributed (7d)"}),e.jsx(U,{label:"Bounced / DLQ",value:n(l.bounced),current:l.bounced,previous:h?.bounced,hint:e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"inline h-3 w-3 mr-1"}),"delivery issues"]})}),e.jsx(U,{label:"Unsubscribed",value:n(l.unsubscribed),current:l.unsubscribed,previous:h?.unsubscribed,hint:e.jsxs(e.Fragment,{children:[e.jsx(ys,{className:"inline h-3 w-3 mr-1"}),"opt-outs"]})})]}),e.jsx(O,{title:"Performance over time",description:"Sent, opened and clicked per day",children:l.daily.length===0?e.jsx(ae,{title:"No sends in this window"}):e.jsx("div",{className:"h-[260px]",children:e.jsx(xs,{width:"100%",height:"100%",children:e.jsxs(Ks,{data:l.daily,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"g-sent",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"g-open",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--success))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--success))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"g-click",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx(ds,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(ms,{dataKey:"day",stroke:"hsl(var(--muted-foreground))",fontSize:11}),e.jsx(us,{stroke:"hsl(var(--muted-foreground))",fontSize:11}),e.jsx(hs,{contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:6,fontSize:12}}),e.jsx(qe,{type:"monotone",dataKey:"sent",stroke:"hsl(var(--primary))",fill:"url(#g-sent)",strokeWidth:2,name:"Sent"}),e.jsx(qe,{type:"monotone",dataKey:"opened",stroke:"hsl(var(--success))",fill:"url(#g-open)",strokeWidth:2,name:"Opened"}),e.jsx(qe,{type:"monotone",dataKey:"clicked",stroke:"hsl(var(--accent))",fill:"url(#g-click)",strokeWidth:2,name:"Clicked"})]})})})}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-4",children:[e.jsx(O,{title:"Top subjects by open rate",description:"min 5 sends",children:l.top_subjects.length===0?e.jsx(ae,{title:"No data yet"}):e.jsx("ol",{className:"space-y-2",children:l.top_subjects.map((i,o)=>e.jsxs("li",{className:"flex items-start justify-between gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground font-mono",children:["#",o+1]}),e.jsx("p",{className:"truncate",children:i.subject_line})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs("p",{className:"font-mono text-success",children:[i.open_rate,"%"]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground font-mono",children:[i.sent," sent"]})]})]},o))})}),e.jsx(O,{title:"Conversion funnel",children:e.jsx(Zs,{})})]}),e.jsx(O,{title:"ROI per template",description:"Last-click attribution within 7 days",children:l.per_template.length===0?e.jsx(ae,{title:"No template data in this window"}):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] uppercase tracking-wider text-muted-foreground font-mono border-b border-border",children:[e.jsx("th",{className:"text-left py-2 pr-3",children:"#"}),e.jsx("th",{className:"text-left py-2 pr-3",children:"Subject"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Sent"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Open%"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Click%"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Conv."}),e.jsx("th",{className:"text-right py-2 px-2",children:"Revenue"}),e.jsx("th",{className:"text-right py-2 pl-2",children:"$/email"})]})}),e.jsx("tbody",{children:l.per_template.slice(0,15).map(i=>e.jsxs("tr",{className:"border-b border-border/40 hover:bg-muted/30",children:[e.jsxs("td",{className:"py-2 pr-3 font-mono text-muted-foreground",children:["T",i.template_index+1]}),e.jsx("td",{className:"py-2 pr-3 truncate max-w-[280px]",children:i.subject}),e.jsx("td",{className:"py-2 px-2 text-right font-mono tabular-nums",children:i.sent}),e.jsxs("td",{className:"py-2 px-2 text-right font-mono tabular-nums",children:[i.open_rate,"%"]}),e.jsxs("td",{className:"py-2 px-2 text-right font-mono tabular-nums",children:[i.click_rate,"%"]}),e.jsx("td",{className:"py-2 px-2 text-right font-mono tabular-nums",children:i.conversions}),e.jsxs("td",{className:"py-2 px-2 text-right font-mono tabular-nums text-success",children:["$",Number(i.revenue).toFixed(0)]}),e.jsxs("td",{className:"py-2 pl-2 text-right font-mono tabular-nums",children:["$",Number(i.revenue_per_email).toFixed(3)]})]},i.template_index))})]})})})]}):e.jsx(ae,{title:"Failed to load metrics"})]})}const et=[{index:0,day:1,phase:"Curiosity",subject:"Something is happening at the tables right now"},{index:1,day:2,phase:"Curiosity",subject:"The question nobody asks before sitting down"},{index:2,day:3,phase:"Curiosity",subject:"Why your reads are never quite right"},{index:3,day:4,phase:"Pain",subject:"That hand you lost yesterday - here is what really happened"},{index:4,day:5,phase:"Pain",subject:"The invisible leak draining your bankroll"},{index:5,day:6,phase:"Pain",subject:"Every session, opportunities slip away unseen"},{index:6,day:7,phase:"Pain",subject:"You are not running bad - you are playing blind"},{index:7,day:8,phase:"Social",subject:"While you grind, some players barely try and win more"},{index:8,day:9,phase:"Social",subject:"The player at your table knows something you do not"},{index:9,day:10,phase:"Social",subject:"4,000+ players already see what you cannot"},{index:10,day:11,phase:"Social",subject:"Your opponents talk about players like you"},{index:11,day:12,phase:"Social",subject:"The gap between winners and losers is not skill"},{index:12,day:13,phase:"Loss",subject:"Calculate how much you have lost to players who can see"}
1,{index:13,day:14,phase:"Loss",subject:"Last week alone, you probably lost more than you needed to"},{index:14,day:15,phase:"Loss",subject:"Every day you wait costs you more than you realize"},{index:15,day:16,phase:"Loss",subject:"Your bankroll could be twice what it is right now"},{index:16,day:17,phase:"Loss",subject:"The money you lost this month is gone forever"},{index:17,day:18,phase:"Urgency",subject:"Right now, tables are running and you are not there"},{index:18,day:19,phase:"Urgency",subject:"Peak hours are happening and opportunities are passing"},{index:19,day:20,phase:"Urgency",subject:"Weekend games start in hours - will you be ready?"},{index:20,day:21,phase:"Urgency",subject:"Time passes - your edge does not wait"},{index:21,day:22,phase:"Urgency",subject:"While you think, others do"},{index:22,day:23,phase:"Pressure",subject:"How many more losing sessions until you decide?"},{index:23,day:24,phase:"Pressure",subject:"You have been thinking about this for too long"},{index:24,day:25,phase:"Pressure",subject:"The delay is costing you more than you realize"},{index:25,day:26,phase:"Pressure",subject:"Last chances come quietly"},{index:26,day:27,phase:"Final",subject:"This is not about poker anymore"},{index:27,day:28,phase:"Final",subject:"Some players never find out - will you be one of them?"},{index:28,day:29,phase:"Final",subject:"Tomorrow you will wish you started today"},{index:29,day:30,phase:"Final",subject:"Final message - the choice is yours"}],st=et.map(s=>({...s,name:`Day ${s.day}: ${s.phase}`})),gs=[...st,{index:30,phase:"Platform",name:"Platform - PPPoker",subject:"PPPoker players are printing money right now"},{index:31,phase:"Platform",name:"Platform - ClubGG",subject:"ClubGG whales are waiting for you"},{index:32,phase:"Platform",name:"Platform - PokerBros",subject:"PokerBros players cannot stop losing to our users"},{index:33,phase:"Special",name:"Weekend Special",subject:"Weekend warriors are making $3,000+ tonight"},{index:34,phase:"Social",name:"Social Proof",subject:"How Mike made $12,847 last month playing poker"},{index:35,phase:"FOMO",name:"FOMO",subject:"Your poker opponents have an unfair advantage over you"},{index:36,phase:"Demo",name:"Demo",subject:"Watch me win $500 in 3 hands (video proof)"},{index:37,phase:"ROI",name:"ROI Focus",subject:"How to turn $9 into $2,000+ this week"},{index:38,phase:"Final",name:"Last Chance",subject:"This is my last email to you (read this)"},{index:39,phase:"Final",name:"Price Increase",subject:"FINAL WARNING: Prices increase in 48 hours"}];function Qe(s){return gs.find(l=>l.index===s)}const tt=[{id:"hot",label:"Hot leads",icon:ws,hint:"Score ⥠5"},{id:"cold",label:"Cold",icon:Ss,hint:"0 opens"},{id:"buyers",label:"Buyers",icon:Ke,hint:"Recent purchase"},{id:"br",label:"BR / PT speakers",icon:ks,hint:"lang=pt"}];function at(){const[s,l]=r.useState([]),[f,h]=r.useState(new Set),[u,R]=r.useState(!0),[x,n]=r.useState(!1),[m,i]=r.useState(""),[o,v]=r.useState("all"),[d,c]=r.useState("all"),[S,T]=r.useState("all"),[b,K]=r.useState(null),[k,p]=r.useState(new Set),[y,A]=r.useState("0"),[oe,de]=r.useState(!1),[re,H]=r.useState(!1),[P,Ee]=r.useState(!1),[le,Ae]=r.useState(()=>{const a=new Date(Date.now()+36e5);return a.setSeconds(0,0),a.toISOString().slice(0,16)});r.useEffect(()=>{(async()=>{R(!0);const[{data:a},{data:j},{data:D}]=await Promise.all([N.from("profiles").select("id,user_id,email,telegram_username,country_code,preferred_language,created_at,email_unsubscribed").or("email_unsubscribed.is.null,email_unsubscribed.eq.false").order("created_at",{ascending:!1}).limit(2e3),N.from("purchases").select("user_id"),N.from("email_sends").select("user_id,opened_at,clicked_at").gte("sent_at",new Date(Date.now()-90*24*3600*1e3).toISOString()).limit(5e3)]),V=new Set((j??[]).map(I=>I.user_id));h(V);const Y=new Map;(D??[]).forEach(I=>
1{const t=Y.get(I.user_id)??{opens:0,clicks:0};I.opened_at&&t.opens++,I.clicked_at&&t.clicks++,Y.set(I.user_id,t)});const Oe=(a??[]).filter(I=>!V.has(I.user_id)).map(I=>{const t=Y.get(I.user_id)??{opens:0,clicks:0};return{...I,opens:t.opens,clicks:t.clicks,score:t.opens+t.clicks*3}});l(Oe),R(!1)})()},[]);const fe=r.useMemo(()=>Array.from(new Set(s.map(a=>a.country_code).filter(Boolean))).sort(),[s]),Fe=r.useMemo(()=>Array.from(new Set(s.map(a=>a.preferred_language||"en"))).sort(),[s]),q=r.useMemo(()=>{let a=s;if(m){const j=m.toLowerCase();a=a.filter(D=>D.email?.toLowerCase().includes(j)||D.telegram_username?.toLowerCase().includes(j)||D.country_code?.toLowerCase().includes(j))}return o!=="all"&&(a=a.filter(j=>j.country_code===o)),d!=="all"&&(a=a.filter(j=>(j.preferred_language||"en")===d)),S==="high"?a=a.filter(j=>j.score>=5):S==="med"?a=a.filter(j=>j.score>=1&&j.score<5):S==="low"&&(a=a.filter(j=>j.score===0)),b==="hot"?a=a.filter(j=>j.score>=5):b==="cold"?a=a.filter(j=>j.opens===0):b==="br"?a=a.filter(j=>(j.preferred_language||"en")==="pt"):b==="buyers"&&(a=[]),a.sort((j,D)=>D.score-j.score)},[s,m,o,d,S,b]),X=Qe(parseInt(y)),ne=()=>{k.size===q.length?p(new Set):p(new Set(q.map(a=>a.user_id)))},be=a=>{p(j=>{const D=new Set(j);return D.has(a)?D.delete(a):D.add(a),D})},Pe=async()=>{if(k.size===0){me.error("Select at least one recipient");return}n(!0);try{const a=Array.from(k),j=parseInt(y);if(P){const D=new Date(le).toISOString(),{data:{user:V}}=await N.auth.getUser(),{error:Y}=await N.from("scheduled_email_jobs").insert({template_index:j,user_ids:a,scheduled_for:D,created_by:V?.id});if(Y)throw Y;me.success(`Scheduled for ${new Date(le).toLocaleString()}`)}else{const{data:D,error:V}=await N.functions.invoke("weekly-recovery-email",{body:{manual:!0,userIds:a,templateIndex:j}});if(V)throw V;me.success(`Sent ${D?.sent??k.size} emails`)}p(new Set)}catch(a){me.error(a.message??"Send failed")}finally{n(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(O,{title:"1 · Choose template",actions:e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>de(!0),children:[e.jsx(Be,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),children:[e.jsxs(J,{value:y,onValueChange:A,children:[e.jsx(ee,{children:e.jsx(se,{})}),e.jsx(te,{className:"max-h-[400px]",children:gs.map(a=>e.jsxs(w,{value:a.index.toString(),children:[e.jsxs("span",{className:"font-mono text-xs text-muted-foreground mr-2",children:["T",a.index+1]}),a.name," â ",e.jsx("span",{className:"text-muted-foreground",children:a.subject})]},a.index))})]}),X&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Subject preview: ",e.jsx("span",{className:"text-foreground",children:X.subject})]})]}),e.jsxs(O,{title:"2 · Pick audience",description:`${k.size} of ${q.length} selected · ${s.length} total leads (buyers excluded)`,children:[e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:tt.map(a=>e.jsxs(F,{variant:b===a.id?"default":"outline",size:"sm",onClick:()=>K(b===a.id?null:a.id),children:[e.jsx(a.icon,{className:"h-3.5 w-3.5 mr-1.5"}),a.label,e.jsxs("span",{className:"ml-1 text-[10px] text-muted-foreground",children:["· ",a.hint]})]},a.id))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2 mb-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_s,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ze,{className:"pl-8 h-9",placeholder:"Searchâ¦",value:m,onChange:a=>i(a.target.value)})]}),e.jsxs(J,{value:o,onValueChange:v,children:[e.jsx(ee,{className:"h-9",children:e.jsx(se,{placeholder:"Country"})}),e.jsxs(te,{children:[e.jsx(w,{value:"all",children:"All countries"}),fe.map(a=>e.jsx(w,{value:a,children:a},a))]})]}),e.jsxs(J,{value:d,onValueChange:c,children:[e.jsx(ee,{className:"h-9",children:e.jsx(se,{placeholder:"Language"})}),e.jsxs(te,{children:[e.jsx(w,{value:"all",children:"All languages"}),Fe.map(a=>e.jsx(w,{value:a,children:a.toUpperCase()},a))]})]}),e.jsxs(J,{value:S,onValueChange:T,children:[e.jsx(ee,{className:"h-9",children:e.jsx(se,{placeholder:"Engagement"})}),e.jsxs(te,{children:[e.jsx(w,{value:"all",children:"All engagement"}),e.jsx(w,{value:"high",children:"High (5+)"}),e.jsx(w,{value:"med",children:"Medium (1â4)"}),e.jsx(w,{value:"low",children:"No engagement"})]})]})]}),e.jsx("div",{className:"border border-border rounded-md max-h-[360px] overflow-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(G,{children:[e.jsx(L,{className:"w-10",children:e.jsx(Ce,{checked:k.size>0&&k.size===q.length,onCheckedChange:ne})}),e.jsx(L,{children:"Email"}),e.jsx(L,{className:"w-16",children:"Lang"}),e.jsx(L,{className:"w-16",children:"Country"}),e.jsx(L,{className:"w-16 text-right",children:"Score"})]})}),e.jsx(De,{children:u?e.jsx(G,{children:e.jsx(C,{colSpan:5,className:"text-center text-muted-foreground py-6",children:"Loadingâ¦"})}):q.length===0?e.jsx(G,{children:e.jsx(C,{colSpan:5,children:e.jsx(ae,{title:"No leads match filters"})})}):q.slice(0,500).map(a=>e.jsxs(G,{children:[e.jsx(C,{children:e.jsx(Ce,{checked:k.has(a.user_id
1),onCheckedChange:()=>be(a.user_id)})}),e.jsx(C,{className:"text-xs font-mono truncate max-w-[280px]",children:a.email}),e.jsx(C,{className:"text-xs",children:(a.preferred_language||"en").toUpperCase()}),e.jsx(C,{className:"text-xs",children:a.country_code||"â"}),e.jsx(C,{className:"text-right font-mono text-xs",children:e.jsx("span",{className:a.score>=5?"text-success":a.score>0?"text-warning":"text-muted-foreground",children:a.score})})]},a.id))})]})}),q.length>500&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2",children:["Showing first 500 of ",q.length,". Use filters to narrow down."]})]}),e.jsxs(O,{title:"3 · Send or schedule",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx(Ce,{id:"sched",checked:P,onCheckedChange:a=>Ee(!!a)}),e.jsxs(Se,{htmlFor:"sched",className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Cs,{className:"h-4 w-4"})," Schedule for later"]}),P&&e.jsx(ze,{type:"datetime-local",value:le,onChange:a=>Ae(a.target.value),className:"h-8 w-[220px]"})]}),e.jsxs(F,{onClick:Pe,disabled:x||k.size===0,children:[x?e.jsx(Q,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Re,{className:"h-4 w-4 mr-2"}),P?`Schedule for ${k.size} recipient${k.size===1?"":"s"}`:`Send now to ${k.size} recipient${k.size===1?"":"s"}`]})]}),e.jsx(Ue,{open:oe,onOpenChange:de,children:e.jsxs(He,{className:"max-w-2xl",children:[e.jsx(Ve,{children:e.jsxs(Ge,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Email preview"}),e.jsx(cs,{value:re?"mobile":"desktop",onValueChange:a=>H(a==="mobile"),children:e.jsxs(os,{children:[e.jsx(ie,{value:"desktop",children:"Desktop"}),e.jsx(ie,{value:"mobile",children:"Mobile"})]})})]})}),e.jsxs("div",{className:"border border-border rounded-md bg-muted/30 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"From: PokerHack <[email protected]>"}),e.jsx("p",{className:"text-sm font-semibold mb-3",children:X?.subject}),e.jsxs("div",{style:{width:re?360:"100%",margin:"0 auto"},className:"bg-background border border-border rounded p-4 text-sm space-y-2",children:[e.jsxs("p",{className:"text-muted-foreground italic",children:["The actual rendered template is generated server-side from the user's locale and personalization data. Subject and tone match: ",e.jsx("span",{className:"text-foreground",children:X?.phase}),"."]}),e.jsx("p",{children:X?.subject}),e.jsx("p",{className:"text-xs text-muted-foreground border-t border-border pt-3 mt-3",children:"Footer: unsubscribe link and contact information are appended automatically."})]})]})]})})]})}function rt(){const[s,l]=r.useState([]),[f,h]=r.useState({dlq:0,failed:0,bounced:0,suppressed:0}),[u,R]=r.useState(!0),x=async()=>{R(!0);try{const{data:n}=await N.from("email_send_log").select("id,template_name,recipient_email,status,error_message,created_at").in("status",["dlq","failed","bounced","complained","suppressed"]).order("created_at",{ascending:!1}).limit(100);l(n??[]);const m={dlq:0,failed:0,bounced:0,suppressed:0};(n??[]).forEach(i=>{i.status==="dlq"?m.dlq++:i.status==="failed"?m.failed++:i.status==="bounced"||i.status==="complained"?m.bounced++:i.status==="suppressed"&&m.suppressed++}),h(m)}catch(n){console.error(n)}finally{R(!1)}};return r.useEffect(()=>{x()},[]),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(U,{label:"Dead-letter",value:f.dlq,hint:e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"inline h-3 w-3 mr-1"}),"retry exhausted"]})}),e.jsx(U,{label:"Failed",value:f.failed,hint:e.jsxs(e.Fragment,{children:[e.jsx(Ts,{className:"inline h-3 w-3 mr-1"}),"transient errors"]})}),e.jsx(U,{label:"Bounced",value:f.bounced,hint:"rejected by server"}),e.jsx(U,{label:"Suppressed",value:f.suppressed,hint:e.jsxs(e.Fragment,{children:[e.jsx(Ls,{className:"inline h-3 w-3 mr-1"}),"opt-out list"]})})]}),e.jsx(O,{title:"Inbox of problems",description:"Latest 100 entries from the email queue log",actions:e.jsxs(F,{size:"sm",variant:"outline",onClick:x,disabled:u,children:[e.jsx(je,{className:`h-3.5 w-3.5 mr-1.5 ${u?"animate-spin":""}`}),"Refresh"]}),children:u?e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((n,m)=>e.jsx(pe,{className:"h-10 rounded"},m))}):s.length===0?e.jsx(ae,{title:"No delivery problems ð",description:"The queue is healthy."}):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] uppercase tracking-wider text-muted-foreground font-mono border-b border-border",children:[e.jsx("th",{className:"text-left py-2 pr-3",children:"When"}),e.jsx("th",{className:"text-left py-2 pr-3",children:"Template"}),e.jsx("th",{className:"text-left py-2 pr-3",children:"Recipient"}),e.jsx("th",{className:"text-left py-2 pr-3",children:"Status"}),e.jsx("th",{className:"text-left py-2",children:"Error"})]})}),e.jsx("tbody",{children:s.map(n=>e.jsxs("tr",{className:"border-b border-border/40 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2 pr-3 font-mono text-[11px] text-muted-foreground whitespace-nowrap",children:new Date(n.created_at).toLocaleStr
1ing()}),e.jsx("td",{className:"py-2 pr-3 truncate max-w-[160px]",children:n.template_name}),e.jsx("td",{className:"py-2 pr-3 font-mono text-[11px] truncate max-w-[200px]",children:n.recipient_email}),e.jsx("td",{className:"py-2 pr-3",children:e.jsx(ps,{tone:n.status==="dlq"||n.status==="failed"||n.status==="bounced"?"danger":n.status==="suppressed"||n.status==="complained"?"warn":"neutral",children:n.status})}),e.jsx("td",{className:"py-2 text-[11px] text-muted-foreground truncate max-w-[320px]",title:n.error_message??"",children:n.error_message??"â"})]},n.id))})]})})})]})}function lt(){const[s,l]=r.useState([]),[f,h]=r.useState(!0),[u,R]=r.useState("30d");r.useEffect(()=>{const n=new Date;u==="7d"?n.setDate(n.getDate()-7):u==="30d"?n.setDate(n.getDate()-30):u==="90d"?n.setDate(n.getDate()-90):n.setFullYear(n.getFullYear()-5),h(!0),N.from("email_campaigns").select("*").gte("sent_at",n.toISOString()).order("sent_at",{ascending:!1}).limit(200).then(({data:m})=>{l(m??[]),h(!1)})},[u]);const x=r.useMemo(()=>s.reduce((n,m)=>({sent:n.sent+m.total_sent,failed:n.failed+m.total_failed}),{sent:0,failed:0}),[s]);return e.jsx(O,{title:"Campaign history",description:`${s.length} campaigns · ${x.sent} sent · ${x.failed} failed`,actions:e.jsxs(J,{value:u,onValueChange:R,children:[e.jsx(ee,{className:"h-8 w-[140px] text-xs",children:e.jsx(se,{})}),e.jsxs(te,{children:[e.jsx(w,{value:"7d",children:"Last 7 days"}),e.jsx(w,{value:"30d",children:"Last 30 days"}),e.jsx(w,{value:"90d",children:"Last 90 days"}),e.jsx(w,{value:"all",children:"All time"})]})]}),children:f?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Loadingâ¦"}):s.length===0?e.jsx(ae,{title:"No campaigns in this window"}):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] uppercase tracking-wider text-muted-foreground font-mono border-b border-border",children:[e.jsx("th",{className:"text-left py-2 pr-3",children:"When"}),e.jsx("th",{className:"text-left py-2 pr-3",children:"Template"}),e.jsx("th",{className:"text-left py-2 pr-3",children:"Subject"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Sent"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Failed"}),e.jsx("th",{className:"text-right py-2 pl-2",children:"Mode"})]})}),e.jsx("tbody",{children:s.map(n=>{const m=Qe(n.template_index);return e.jsxs("tr",{className:"border-b border-border/40 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2 pr-3 font-mono text-[11px] text-muted-foreground whitespace-nowrap",children:new Date(n.sent_at).toLocaleString()}),e.jsxs("td",{className:"py-2 pr-3 font-mono text-[11px]",children:["T",n.template_index+1," ",m?`· ${m.phase}`:""]}),e.jsx("td",{className:"py-2 pr-3 truncate max-w-[360px]",children:n.template_subject}),e.jsx("td",{className:"py-2 px-2 text-right font-mono tabular-nums",children:n.total_sent}),e.jsx("td",{className:"py-2 px-2 text-right font-mono tabular-nums text-destructive",children:n.total_failed>0?n.total_failed:"â"}),e.jsx("td",{className:"py-2 pl-2 text-right text-[11px] text-muted-foreground",children:n.is_manual?"manual":"auto"})]},n.id)})})]})})})}function nt(){const[s,l]=r.useState([]),[f,h]=r.useState(!0),u=async()=>{h(!0);const{data:x}=await N.from("scheduled_email_jobs").select("*").order("scheduled_for",{ascending:!0}).limit(50);l(x??[]),h(!1)};r.useEffect(()=>{u()},[]);const R=async x=>{const{error:n}=await N.from("scheduled_email_jobs").update({status:"cancelled"}).eq("id",x);n?me.error(n.message):(me.success("Cancelled"),u())};return e.jsx(O,{title:"Scheduled jobs",description:"Upcoming and recent automated dispatches",actions:e.jsxs(F,{size:"sm",variant:"outline",onClick:u,disabled:f,children:[e.jsx(je,{className:`h-3.5 w-3.5 mr-1.5 ${f?"animate-spin":""}`}),"Refresh"]}),children:f?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Loadingâ¦"}):s.length===0?e.jsx(ae,{title:"No scheduled jobs",description:"Create one from the Composer tab."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-mono border-b border-border",children:[e.jsx("th",{className:"text-left py-2 pr-3",children:"When"}),e.jsx("th",{className:"text-left py-2 pr-3",children:"Template"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Recipients"}),e.jsx("th",{className:"text-left py-2 pr-3",children:"Status"}),e.jsx("th",{className:"text-right py-2"})]})}),e.jsx("tbody",{children:s.map(x=>{const n=Qe(x.template_index);return e.jsxs("tr",{className:"border-b border-border/40",children:[e.jsx("td",{className:"py-2 pr-3 font-mono text-[11px] whitespace-nowrap",children:new Date(x.scheduled_for).toLocaleStr
1ing()}),e.jsxs("td",{className:"py-2 pr-3 truncate max-w-[260px]",children:["T",x.template_index+1," · ",n?.name]}),e.jsx("td",{className:"py-2 px-2 text-right font-mono",children:x.user_ids?.length??0}),e.jsx("td",{className:"py-2 pr-3",children:e.jsx(ps,{tone:x.status==="done"?"success":x.status==="running"?"info":x.status==="failed"?"danger":x.status==="cancelled"?"neutral":"warn",children:x.status})}),e.jsx("td",{className:"py-2 text-right",children:x.status==="pending"&&e.jsx(F,{size:"sm",variant:"ghost",onClick:()=>R(x.id),children:e.jsx(Ds,{className:"h-3.5 w-3.5"})})})]},x.id)})})]})})}const it=Ws("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),js=r.forwardRef(({className:s,variant:l,...f},h)=>e.jsx("div",{ref:h,role:"alert",className:Ye(it({variant:l}),s),...f}));js.displayName="Alert";const fs=r.forwardRef(({className:s,...l},f)=>e.jsx("h5",{ref:f,className:Ye("mb-1 font-medium leading-none tracking-tight",s),...l}));fs.displayName="AlertTitle";const bs=r.forwardRef(({className:s,...l},f)=>e.jsx("div",{ref:f,className:Ye("text-sm [&_p]:leading-relaxed",s),...l}));bs.displayName="AlertDescription";const es=[{code:"en",label:"English"},{code:"pt",label:"Português"},{code:"es",label:"Español"},{code:"de",label:"Deutsch"},{code:"ru",label:"Ð ÑÑÑкий"},{code:"zh",label:"䏿"},{code:"vi",label:"Tiếng Viá»t"},{code:"ja",label:"æ¥æ¬èª"},{code:"fr",label:"Français"},{code:"it",label:"Italiano"},{code:"ar",label:"Ø§ÙØ¹Ø±Ø¨ÙØ©"},{code:"ms",label:"Bahasa Melayu"},{code:"tl",label:"Tagalog"},{code:"pl",label:"Polski"},{code:"ko",label:"íêµì´"}],we="https://www.pokerhack.org/images/email/ad-01.png",xe="https://www.pokerhack.org/images/blog/default.jpg",ct=[{id:"ad-01",url:"https://www.pokerhack.org/images/email/ad-01.png",label:"Total Exposure (Hole Card Reader)",copy:"Discover How Our Tool Is Changing The Poker World â Reveal Poker Total Exposure for complete table domination."},{id:"ad-02",url:"https://www.pokerhack.org/images/email/ad-02.png",label:"Revolutionizing Poker (Night Skyline)",copy:"Revolutionizing Online Poker â Our undetectable tool is changing the game forever. Learn how to master the tables."},{id:"ad-03",url:"https://www.pokerhack.org/images/email/ad-03.png",label:"Master The Game (Penthouse Suite)",copy:"Master The Game. See Their Cards. Discover how our tool changed the poker world."},{id:"ad-04",url:"https://www.pokerhack.org/images/email/ad-04.png",label:"Master The Board (Multi-Table Reader)",copy:"Reveal Poker: Master the Board. Master Your Game with real-time multi-table detection."},{id:"ad-05",url:"https://www.pokerhack.org/images/email/ad-05.png",label:"Flop, Turn & River (High-Roller Lifestyle)",copy:"The Poker Revolution Is Here â Board Reader: See the Flop, Turn & River Before They Hit."}];function ot(){const[s,l]=r.useState([]),[f,h]=r.useState(!0),[u,R]=r.useState(!1),[x,n]=r.useState(!1),[m,i]=r.useState(null),[o,v]=r.useState("en"),[d,c]=r.useState(!1),[S,T]=r.useState(!1),[b,K]=r.useState(["en","pt","es","de","ru","zh","vi","ja","fr","it","ar","ms","tl","pl","ko"]),[k,p]=r.useState(""),[y,A]=r.useState(""),[oe,de]=r.useState({}),[re,H]=r.useState(!0),[P,Ee]=r.useState(""),[le,Ae]=r.useState(""),[fe,Fe]=r.useState(""),[q,X]=r.useState(null),{toast:ne}=is(),be=async()=>{try{const{data:t,error:g}=await N.from("newsletter_digest_sends").select("*").order("send_date",{ascending:!1}).limit(10);if(g)throw g;l(t??[])}catch(t){ne({title:"Error fetching history",description:t.message,variant:"destructive"})}finally{h(!1)}},Pe=async()=>{H(!0);const t={en:0,pt:0,es:0,de:0,ru:0,zh:0,vi:0,ja:0,fr:0,it:0,ar:0,ms:0,tl:0,pl:0,ko:0},g=(B,W)=>{const _=(B??"").toLowerCase().trim();if(_.startsWith("pt"))return"pt";if(_.startsWith("es"))return"es";if(_.startsWith("de"))return"de";if(_.startsWith("ru"))return"ru";if(_.startsWith("zh"))return"zh";if(_.startsWith("vi"))return"vi";if(_.startsWith("ja"))return"ja";if(_.startsWith("fr"))return"fr";if(_.startsWith("it"))return"it";if(_.startsWith("ar"))return"ar";if(_.startsWith("ms"))return"ms";if(_.startsWith("tl")||_.startsWith("fil"))return"tl";if(_.startsWith("pl"))return"pl";if(_.startsWith("ko"))return"ko";if(_.startsWith("en"))return"en";const $=(W??"").toUpperCase().trim();return["BR","PT","AO","MZ"].includes($)?"pt":["ES","MX","AR","CO","CL","PE","VE","EC","GT","CU","BO","DO","HN","PY","SV","NI","CR","PR","UY"].includes($)?"es":["DE","AT","CH"].includes($)?"de":["RU","BY","KZ"].includes($)?"ru":["CN","TW","HK"].includes($)?"zh":["VN"].includes($)?"vi":["JP"].includes($)?"ja":["FR","BE"].includes($)?"fr":["IT"].includes($)?"it":["SA","AE","EG","QA","KW","OM","BH","JO","LB"].includes($)?"ar":["MY"].includes($)?"ms":["PH"].includes($)?"tl":["PL"].includes($)?"pl":["
1KR"].includes($)?"ko":"en"},E=new Set,{data:$e}=await N.from("profiles").select("email,preferred_language,country_code").or("email_unsubscribed.is.null,email_unsubscribed.eq.false");for(const B of $e??[]){const W=String(B.email??"").toLowerCase().trim();if(!W||E.has(W))continue;E.add(W);const _=g(B.preferred_language,B.country_code);t[_]=(t[_]??0)+1}const{data:Ne}=await N.from("newsletter_leads").select("email,preferred_language,country_code");for(const B of Ne??[]){const W=String(B.email??"").toLowerCase().trim();if(!W||E.has(W))continue;E.add(W);const _=g(B.preferred_language,B.country_code);t[_]=(t[_]??0)+1}const{data:ve}=await N.from("email_subscriptions").select("email,language,country_code");for(const B of ve??[]){const W=String(B.email??"").toLowerCase().trim();if(!W||E.has(W))continue;E.add(W);const _=g(B.language,B.country_code);t[_]=(t[_]??0)+1}de(t),H(!1)};r.useEffect(()=>{be(),Pe()},[]);const a=async()=>{try{const t=["profiles","newsletter_leads","email_subscriptions"];let g=0,E=0;for(const $e of t)for(const Ne of["daily","monthly"]){const{count:ve}=await N.from($e).select("id",{count:"exact",head:!0}).eq("newsletter_frequency",Ne);Ne==="daily"?g+=ve??0:E+=ve??0}X({daily:g,monthly:E})}catch{X(null)}};r.useEffect(()=>{a()},[]);const j=b.reduce((t,g)=>t+(oe[g]??0),0),D=t=>{K(g=>g.includes(t)?g.filter(E=>E!==t):[...g,t])},V=(t={})=>({languages:b,segment:"all",adOverride:{imageUrl:k.trim()||void 0,copy:y.trim()||void 0},...t}),Y=async t=>{R(!0),v(t);try{const{data:g,error:E}=await N.functions.invoke("send-newsletter-digest",{body:V({preview:!0,languages:[t]})});if(E)throw E;i(g.digest),Ee(g.html??""),Ae(g.source??""),Fe(g.subject??""),c(!0)}catch(g){ne({title:`Preview failed (${t.toUpperCase()})`,description:g.message,variant:"destructive"})}finally{R(!1)}},Oe=async()=>{if(b.length===0){ne({title:"Pick at least one language",variant:"destructive"});return}await Y(b[0])},I=async()=>{T(!1),n(!0);try{const{data:t,error:g}=await N.functions.invoke("send-newsletter-digest",{body:V({manual:!0,regenerate:!0})});if(g)throw g;ne({title:"Digest sent",description:`Delivered ${t.total_sent??t.sent??0} · Failed ${t.total_failed??t.failed??0} · Enqueued ${t.enqueued??0}`}),be()}catch(t){ne({title:"Send failed",description:t.message,variant:"destructive"})}finally{n(!1)}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:"Newsletter Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Curated value-first content. Delivered only to opted-in subscribers."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(F,{variant:"outline",onClick:Oe,disabled:u||x,children:[u?e.jsx(Q,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Be,{className:"mr-2 h-4 w-4"}),"Preview"]}),e.jsxs(F,{onClick:()=>T(!0),disabled:x||b.length===0,children:[x?e.jsx(Q,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Re,{className:"mr-2 h-4 w-4"}),"Send digest"]})]})]}),e.jsxs(js,{className:"border-success/40 bg-success/5",children:[e.jsx(ns,{className:"h-4 w-4 text-success"}),e.jsx(fs,{className:"text-success",children:"Value-first checklist"}),e.jsx(bs,{children:e.jsxs("ul",{className:"text-xs mt-1 space-y-0.5",children:[e.jsx("li",{children:"â Educational curated content only â no sales pressure"}),e.jsx("li",{children:"â Unsubscribe link appended automatically"}),e.jsx("li",{children:"â Sent exclusively to users who opted in"}),e.jsx("li",{children:"â Each recipient receives content in their own preferred language"})]})})]}),e.jsx(O,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"h-4 w-4"})," Audience & languages"]}),description:re?"Counting opted-in subscribersâ¦":`${j.toLocaleString()} opted-in subscribers across ${b.length} selected language${b.length===1?"":"s"}`,children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3",children:es.map(t=>e.jsxs("label",{className:"flex items-center gap-2 border border-border rounded-md p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Ce,{checked:b.includes(t.code),onCheckedChange:()=>D(t.code)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:t.label}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:re?"â¦":`${(oe[t.code]??0).toLocaleStr
1ing()} opted-in`})]})]},t.code))})}),e.jsxs(O,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"h-4 w-4"})," Sponsor banner (optional override)"]}),description:"Leave blank to auto-generate. Fields apply to preview and send.",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx(Se,{className:"text-xs text-muted-foreground mb-2 block",children:"Click an official creative below to set banner image and headline instantly:"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-2.5",children:ct.map(t=>{const g=k===t.url;return e.jsxs("button",{type:"button",onClick:()=>{p(t.url),A(t.copy)},className:`group text-left border rounded-lg p-1.5 transition-all overflow-hidden ${g?"border-primary bg-primary/10 ring-2 ring-primary/40":"border-border hover:border-foreground/30 bg-card hover:bg-accent/20"}`,children:[e.jsx("img",{src:t.url,alt:t.label,className:"w-full aspect-[4/3] object-cover rounded-md mb-1.5 group-hover:scale-105 transition-transform"}),e.jsx("p",{className:"text-[11px] font-semibold truncate leading-tight",children:t.label}),e.jsx("p",{className:"text-[9px] text-muted-foreground truncate",children:t.id.toUpperCase()})]},t.id)})})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(Se,{htmlFor:"ad-url",className:"text-xs",children:"Banner image URL"}),e.jsx(ze,{id:"ad-url",placeholder:"https://â¦/banner.png",value:k,onChange:t=>p(t.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(Se,{htmlFor:"ad-copy",className:"text-xs",children:"Banner copy"}),e.jsx(Ys,{id:"ad-copy",placeholder:"Short, curiosity-driven line (1-2 sentences)",value:y,onChange:t=>A(t.target.value),rows:2,className:"mt-1"})]})]}),(k||y)&&e.jsxs("div",{className:"mt-4 border border-border rounded-md p-3 flex gap-3 items-start bg-muted/30",children:[e.jsx("img",{src:k||we,alt:"banner",className:"w-24 h-24 object-cover rounded",onError:t=>{t.currentTarget.src=we}}),e.jsx("p",{className:"text-sm italic text-muted-foreground",children:y||"Auto-generated copy will render here."})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-accent/10 border border-accent/20 rounded-lg",children:[e.jsx(As,{className:"h-5 w-5 text-accent mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-sm text-accent",children:"Automated schedule"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"The digest runs automatically every 2 days. Manual sends are additive and never break the cadence."})]})]}),e.jsx(O,{title:"Recent send history",children:f?e.jsx("div",{className:"flex justify-center p-8",children:e.jsx(Q,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx("div",{className:"text-center p-8 text-muted-foreground text-sm",children:"No digests sent yet."}):e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(G,{children:[e.jsx(L,{children:"Date"}),e.jsx(L,{children:"Languages"}),e.jsx(L,{children:"Sent"}),e.jsx(L,{children:"Failed"}),e.jsx(L,{children:"Featured"})]})}),e.jsx(De,{children:s.map(t=>e.jsxs(G,{children:[e.jsx(C,{className:"whitespace-nowrap text-xs",children:new Date(t.send_date).toLocaleString()}),e.jsx(C,{children:e.jsx("div",{className:"flex gap-1 flex-wrap",children:(t.languages??[]).map(g=>e.jsx(ce,{variant:"outline",className:"text-[10px] uppercase",children:g},g))})}),e.jsxs(C,{className:"text-success font-medium text-xs",children:[e.jsx(Fs,{className:"inline h-3.5 w-3.5 mr-1 mb-0.5"}),t.total_sent]}),e.jsxs(C,{className:t.total_failed>0?"text-destructive font-medium text-xs":"text-muted-foreground text-xs",children:[t.total_failed>0&&e.jsx(Ps,{className:"inline h-3.5 w-3.5 mr-1 mb-0.5"}),t.total_failed]}),e.jsx(C,{className:"text-xs text-muted-foreground",children:e.jsx("div",{className:"max-w-[280px] truncate",children:(Array.isArray(t.results)?t.results?.[0]?.featured_article:t.results?.languages?.[0]?.featured_article)??"â"})})]},t.id))})]})}),e.jsxs(O,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(We,{className:"h-4 w-4"})," Per-language preview"]}),description:"Open the exact rendered edition for any of the 15 languages. Languages without local content fall back to the English edition, so nobody is skipped.",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:es.map(t=>e.jsxs(F,{size:"sm",variant:o===t.code?"default":"outline",disabled:u||x,onClick:()=>Y(t.code),className:"text-xs",children:[u&&o===t.code?e.jsx(Q,{className:"mr-1.5 h-3 w-3 animate-spin"}):e.jsx(Be,{className:"mr-1.5 h-3 w-3"}),t.code.toUpperCase()," · ",t.label]},t.code))}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:"Daily cohort"}),e.jsx("p",{className:"text-2xl font-mono font-semibold",children:q?q.daily:"â"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Receive the digest every day at 09:00 local time."})]}),e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:"Monthly cohort"}),e.jsx("p",{className:"text-2xl font-mono font-semibold",children:q?q.monthly:"â"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No opens during their 7-day window â now mailed once a month."})]})]})]}),e.jsx(Ue,{open:d,onOpenChange:c,children:e.jsxs(He,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Ve,{children:[e.jsxs(Ge,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"h-4 w-4"})," Newsletter preview · ",o.toUpperCase()]}),e.jsx(Ze,{children:"Curated content, AI copy and RSS feed â exactly what subscribers will receive."})]}),P&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[le&&e.jsxs(ce,{variant:le==="en_fallback"?"destructive":"secondary",className:"text-[10px]",children:["source: ",le]}),fe&&e.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["Subject: ",fe]})]}),e.jsx("iframe",{title:`Newsletter preview ${o}`,srcDoc:P,className:"w-full h-[520px] rounded-lg border bg-white"})]}),m&&e.jsxs("div",{className:"space-y-5 mt-2",children:[e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsxs("p",{className:"text-[11px] uppercase font-mono tracking-wider text-muted-foreground mb-1",children:[e.jsx(Os,{className:"inline h-3 w-3 mr-1"})," Mindset greeting"]}),e.jsx("p",{className:"font-bold uppercase text-sm",children:m.dynamic_greeting_title}),e.jsx("p",{className:"text-sm mt-1",children:m.dynamic_greeting_text}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Recipients see their first name auto-merged in place of"," ",e.jsx("code",{className:"font-mono",children:"{{first_name}}"}),"."]})]}),e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsx("p",{className:"text-[11px] uppercase font-mono tracking-wider text-muted-foreground mb-2",children:"Sponsor banner"}),e.jsxs("div",{className:"bg-background p-3 rounded border border-border flex flex-col md:flex-row gap-4 items-center",children:[e.jsx("img",{src:m.dynamic_ad_image||we,alt:"Ad",className:"w-32 h-32 object-cover rounded-md bg-black",onError:t=>{t.currentTarget.src=we}}),e.jsxs("p",{className:"text-sm italic",children:['"',m.dynamic_ad_copy,'"']})]})]}),e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsx("p",{className:"text-[11px] uppercase font-mono tracking-wider text-muted-foreground mb-2",children:"Featured article"}),e.jsxs("div",{className:"bg-background p-3 rounded border border-border flex gap-3",children:[e.jsx("img",{src:m.featured_article?.featured_image||xe,alt:"",className:"w-24 h-24 object-cover rounded",onError:t=>{t.currentTarget.src=xe}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-bold text-sm",children:m.featured_article?.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Source:"," ",m.featured_article?.is_external?m.featured_article?.source_name:"RevealPoker Blog"," ","· Category: ",m.featured_article?.category]})]})]})]}),e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsxs("p",{className:"text-[11px] uppercase font-mono tracking-wider text-muted-foreground mb-2",children:["Secondary articles (",m.secondary_articles?.length??0,")"]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:(m.secondary_articles??[]).map((t,g)=>e.jsxs("div",{className:"bg-background p-2 rounded border border-border flex gap-2",children:[e.jsx("img",{src:t.featured_image||xe,alt:"",className:"w-14 h-14 object-cover rounded shrink-0",onError:E=>{E.currentTarget.src=xe}}),e.jsx("p",{className:"text-xs font-medium leading-snug line-clamp-3",children:t.title})]},g))})]}),e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsxs("p",{className:"text-[11px] uppercase font-mono tracking-wider text-muted-foreground mb-2",children:["World news RSS (",m.rss_news?.length??0,")"]}),m.rss_news?.length?e.jsx("div",{className:"space-y-2",children:m.rss_news.map((t,g)=>e.jsxs("div",{className:"bg-background p-3 rounded border border-border flex gap-3",children:[e.jsx("img",{src:t.image||xe,alt:"",className:"w-16 h-16 object-cover rounded shrink-0",onError:E=>{E.currentTarget.src=xe}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t.title}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:t.source??"External"})]})]},g))}):e.jsxs("p",{className:"text-xs text-warning",children:[e.jsx(ls,{className:"inline h-3 w-3 mr-1"}),"No RSS items fetched. Feeds may be temporarily blocked."]})]})]})]})}),e.jsx(Ue,{open:S,onOpenChange:T,children:e.jsxs(He,{children:[e.jsxs(Ve,{children:[e.jsx(Ge,{children:"Confirm digest send"}),e.jsx(Ze,{children:"This dispatches the digest immediately to every opted-in subscriber matching the selected languages. Unsubscribed users are always excluded."})]}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between border-b border-border pb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Languages"}),e.jsx("span",{className:"font-mono uppercase",children:b.join(", ")})]}),e.jsxs("div",{className:"flex justify-between border-b border-border pb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Estimated recipients"}
1),e.jsx("span",{className:"font-mono",children:j.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between border-b border-border pb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sponsor override"}),e.jsx("span",{className:"text-xs",children:k||y?"custom banner applied":"auto-generated"})]})]}),e.jsxs(zs,{children:[e.jsx(F,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsxs(F,{onClick:I,disabled:x,children:[x?e.jsx(Q,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Re,{className:"h-4 w-4 mr-2"}),"Send to ",j.toLocaleString()]})]})]})})]})}const ss=["daily","weekly","monthly","paused"];function dt(){const{toast:s}=is(),[l,f]=r.useState(null),[h,u]=r.useState(null),[R,x]=r.useState(!0),[n,m]=r.useState(!1),i=r.useCallback(async()=>{x(!0);try{const{data:c,error:S}=await N.functions.invoke("send-newsletter-digest",{body:{action:"reach"}});if(S)throw S;f(c?.reach??null)}catch(c){s({title:"Could not load reach report",description:c?.message??"Unknown error",variant:"destructive"})}finally{x(!1)}},[s]),o=r.useCallback(async()=>{const c={};for(const S of["profiles","newsletter_leads"])for(const T of ss){const{count:b}=await N.from(S).select("id",{count:"exact",head:!0}).eq("newsletter_frequency",T);c[T]=(c[T]??0)+(b??0)}u(c)},[]);r.useEffect(()=>{i(),o().catch(()=>u(null))},[i,o]);const v=async()=>{m(!0);try{const{data:c,error:S}=await N.functions.invoke("send-newsletter-digest",{body:{action:"resend_missed"}});if(S)throw S;s({title:"Resend started",description:`${c?.requeued??0} recipients re-queued with the deliverability-safe edition.`}),i()}catch(c){s({title:"Resend failed",description:c?.message??"Unknown error",variant:"destructive"})}finally{m(!1)}},d=c=>l?.audience?Math.round(c.delivered/l.audience*100):0;return e.jsx(O,{title:"Reach & delivery recovery",description:"Per-edition coverage, provider rejection reasons and the recipients who received nothing.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(F,{variant:"outline",size:"sm",onClick:i,disabled:R,children:R?e.jsx(Q,{className:"h-4 w-4 animate-spin"}):e.jsx(je,{className:"h-4 w-4"})}),e.jsxs(F,{size:"sm",onClick:v,disabled:n||!l?.missed_count,children:[n?e.jsx(Q,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx($s,{className:"h-4 w-4 mr-1.5"}),"Resend to missed",l?.missed_count?` (${l.missed_count})`:""]})]}),children:R&&!l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-6",children:[e.jsx(Q,{className:"h-4 w-4 animate-spin"})," Loading reach dataâ¦"]}):l?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(he,{label:"Subscribable base",value:l.audience}),e.jsx(he,{label:"Last edition delivered",value:l.editions[0]?.delivered??0}),e.jsx(he,{label:"Last edition rejected",value:l.editions[0]?.rejected??0}),e.jsx(he,{label:"No delivery (3 editions)",value:l.missed_count})]}),h&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Engagement ladder cohorts"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:ss.map(c=>e.jsx(he,{label:c==="paused"?"paused (stopped)":c,value:h[c]??0},c))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Daily = every edition · weekly = Tuesdays · monthly = the 1st · paused = no sends. Max 5 digests per address in any 7-day window."})]}),l.error_kinds.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:l.error_kinds.map(c=>e.jsxs(ce,{variant:"outline",className:"font-mono text-xs",children:[c.kind,": ",c.n]},c.kind))}),e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(G,{children:[e.jsx(L,{children:"Edition"}),e.jsx(L,{className:"text-right",children:"Queued"}),e.jsx(L,{className:"text-right",children:"Delivered"}),e.jsx(L,{className:"text-right",children:"Rejected"}),e.jsx(L,{className:"text-right",children:"Waiting"}),e.jsx(L,{className:"text-right",children:"Coverage"})]})}),e.jsx(De,{children:l.editions.map(c=>e.jsxs(G,{children:[e.jsx(C,{className:"font-mono text-xs",children:c.edition_date}),e.jsx(C,{className:"text-right font-mono text-xs",children:c.queued}),e.jsx(C,{className:"text-right font-mono text-xs text-emerald-600",children:c.delivered}),e.jsx(C,{className:"text-right font-mono text-xs text-destructive",children:c.rejected}),e.jsx(C,{className:"text-right font-mono text-xs",children:c.waiting}),e.jsxs(C,{className:"text-right font-mono text-xs",children:[d(c),"%"]})]},c.edition_date))})]})}),l.missed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"No successful delivery in the last 3 editions"}),e.jsx("div",{className:"rounded-md border overflow-x-auto max-h-72 overflow-y-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(G,{children:[e.jsx(L,{children:"Recipient"}),e.jsx(L,{children:"Lang"}),e.jsx(L,{children:"Country"}),e.jsx(L,{className:"text-right",children:"Rejections"}),e.jsx(L,{children:"Reason"})]})}),e.jsx(De,{children:l.missed.map(c=>e.jsxs(G,{children:[e.jsx(C,{className:"font-mono text-xs",children:c.email}),e.jsx(C,{className:"text-xs uppercase",children:c.language??"â"}),e.jsx(C,{className:"text-xs uppercase",children:c.country_code??"â"}),e.jsx(C,{className:"text-right font-mono text-xs",children:c.fails}),e.jsx(C,{className:"text-xs",children:c.error_kind??"â"})]},c.email))})]})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-6",children:"No delivery data yet."})})}function he({label:s,value:l}){return e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:s}),e.jsx("p",{className:"text-xl font-mono font-semibold",children:l.toLocaleStr
1ing()})]})}const Z=["#22c55e","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#06b6d4"],xt=()=>{const[s,l]=r.useState([]),[f,h]=r.useState(!0),[u,R]=r.useState("30days"),[x,n]=r.useState("all"),m=async()=>{h(!0);try{const d=new Date;let c=null;if(u!=="all"){const p=u==="7days"?7:u==="30days"?30:90,y=new Date(d);y.setDate(y.getDate()-p),c=y.toISOString()}let S=N.from("email_sends").select("ab_variant, subject_line, email_type, opened_at, clicked_at, converted_at, purchase_amount").not("ab_variant","is",null);c&&(S=S.gte("sent_at",c)),x!=="all"&&(S=S.eq("email_type",x));const{data:T,error:b}=await S;if(b)throw b;const K=(T||[]).reduce((p,y)=>{const A=`${y.ab_variant||"unknown"}_${y.email_type||"marketing"}`;return p[A]||(p[A]={variant:y.ab_variant||"unknown",subjectLine:y.subject_line||"Unknown Subject",emailType:y.email_type||"marketing",totalSent:0,opened:0,clicked:0,converted:0,revenue:0}),p[A].totalSent++,y.opened_at&&p[A].opened++,y.clicked_at&&p[A].clicked++,y.converted_at&&p[A].converted++,p[A].revenue+=Number(y.purchase_amount)||0,p},{}),k=Object.values(K).map(p=>({...p,openRate:p.totalSent>0?p.opened/p.totalSent*100:0,clickRate:p.opened>0?p.clicked/p.opened*100:0,conversionRate:p.clicked>0?p.converted/p.clicked*100:0}));k.sort((p,y)=>y.openRate-p.openRate),l(k)}catch(d){console.error("Error fetching A/B test data:",d)}finally{h(!1)}};r.useEffect(()=>{m()},[u,x]);const i=r.useMemo(()=>s.map((d,c)=>({name:`${d.variant} (${d.emailType.replace("onboarding_","D").replace("day","")})`,"Taxa Abertura":Number(d.openRate.toFixed(1)),"Taxa Clique":Number(d.clickRate.toFixed(1)),"Taxa Conversão":Number(d.conversionRate.toFixed(1)),color:Z[c%Z.length]})),[s]),o=r.useMemo(()=>{if(s.length===0)return{openRate:null,clickRate:null,conversion:null};const d=[...s].sort((T,b)=>b.openRate-T.openRate)[0],c=[...s].sort((T,b)=>b.clickRate-T.clickRate)[0],S=[...s].sort((T,b)=>b.conversionRate-T.conversionRate)[0];return{openRate:d,clickRate:c,conversion:S}},[s]),v=r.useMemo(()=>s.reduce((d,c)=>({sent:d.sent+c.totalSent,opened:d.opened+c.opened,clicked:d.clicked+c.clicked,converted:d.converted+c.converted,revenue:d.revenue+c.revenue}),{sent:0,opened:0,clicked:0,converted:0,revenue:0}),[s]);return f?e.jsx(M,{className:"bg-slate-900/50 border-slate-800",children:e.jsx(z,{className:"p-6",children:e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-8 bg-slate-800 rounded w-1/3"}),e.jsx("div",{className:"h-64 bg-slate-800 rounded"})]})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(M,{className:"bg-slate-900/50 border-slate-800",children:e.jsx(ke,{className:"pb-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(_e,{className:"text-white flex items-center gap-2",children:[e.jsx(ye,{className:"w-5 h-5 text-amber-400"}),"Dashboard de Testes A/B"]}),e.jsx("p",{className:"text-sm text-slate-400 mt-1",children:"Compare performance das variantes de subject por tipo de email"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(J,{value:x,onValueChange:d=>n(d),children:[e.jsx(ee,{className:"w-40 bg-slate-800 border-slate-700",children:e.jsx(se,{})}),e.jsxs(te,{children:[e.jsx(w,{value:"all",children:"Todos os Tipos"}),e.jsx(w,{value:"onboarding_day1",children:"Onboarding D1"}),e.jsx(w,{value:"onboarding_day3",children:"Onboarding D3"}),e.jsx(w,{value:"onboarding_day7",children:"Onboarding D7"}),e.jsx(w,{value:"marketing",children:"Marketing"})]})]}),e.jsxs(J,{value:u,onValueChange:d=>R(d),children:[e.jsx(ee,{className:"w-28 bg-slate-800 border-slate-700",children:e.jsx(se,{})}),e.jsxs(te,{children:[e.jsx(w,{value:"7days",children:"7 dias"}),e.jsx(w,{value:"30days",children:"30 dias"}),e.jsx(w,{value:"90days",children:"90 dias"}),e.jsx(w,{value:"all",children:"Tudo"})]})]}),e.jsx(F,{variant:"outline",size:"icon",onClick:m,className:"border-slate-700",children:e.jsx(je,{className:"w-4 h-4"})})]})]})})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsx(M,{className:"bg-slate-900/50 border-slate-800",children:e.jsxs(z,{className:"p-4 text-center",children:[e.jsx(ge,{className:"w-6 h-6 text-blue-400 mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Total Enviados"}),e.jsx("p",{className:"text-2xl font-bold text-white",children:v.sent.toLocaleStr
1ing()})]})}),e.jsx(M,{className:"bg-slate-900/50 border-slate-800",children:e.jsxs(z,{className:"p-4 text-center",children:[e.jsx(rs,{className:"w-6 h-6 text-amber-400 mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Abertos"}),e.jsx("p",{className:"text-2xl font-bold text-amber-400",children:v.opened.toLocaleString()}),e.jsxs("p",{className:"text-xs text-slate-500",children:[v.sent>0?(v.opened/v.sent*100).toFixed(1):0,"%"]})]})}),e.jsx(M,{className:"bg-slate-900/50 border-slate-800",children:e.jsxs(z,{className:"p-4 text-center",children:[e.jsx(as,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Cliques"}),e.jsx("p",{className:"text-2xl font-bold text-orange-400",children:v.clicked.toLocaleString()}),e.jsxs("p",{className:"text-xs text-slate-500",children:[v.opened>0?(v.clicked/v.opened*100).toFixed(1):0,"%"]})]})}),e.jsx(M,{className:"bg-slate-900/50 border-slate-800",children:e.jsxs(z,{className:"p-4 text-center",children:[e.jsx(Ms,{className:"w-6 h-6 text-emerald-400 mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Conversões"}),e.jsx("p",{className:"text-2xl font-bold text-emerald-400",children:v.converted.toLocaleString()}),e.jsxs("p",{className:"text-xs text-slate-500",children:[v.clicked>0?(v.converted/v.clicked*100).toFixed(1):0,"%"]})]})}),e.jsx(M,{className:"bg-slate-900/50 border-slate-800",children:e.jsxs(z,{className:"p-4 text-center",children:[e.jsx(Ke,{className:"w-6 h-6 text-green-400 mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Receita Total"}),e.jsxs("p",{className:"text-2xl font-bold text-green-400",children:["$",v.revenue.toLocaleString()]})]})})]}),s.length>0&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[o.openRate&&e.jsx(M,{className:"bg-gradient-to-br from-amber-500/10 to-amber-600/5 border-amber-500/30",children:e.jsxs(z,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ye,{className:"w-5 h-5 text-amber-400"}),e.jsx("span",{className:"text-sm font-medium text-amber-400",children:"Melhor Taxa de Abertura"})]}),e.jsx("p",{className:"text-lg font-bold text-white truncate",children:o.openRate.subjectLine}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsxs(ce,{variant:"outline",className:"border-amber-500/50 text-amber-400",children:["Variante ",o.openRate.variant]}),e.jsxs("span",{className:"text-2xl font-bold text-amber-400",children:[o.openRate.openRate.toFixed(1),"%"]})]})]})}),o.clickRate&&e.jsx(M,{className:"bg-gradient-to-br from-orange-500/10 to-orange-600/5 border-orange-500/30",children:e.jsxs(z,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ye,{className:"w-5 h-5 text-orange-400"}),e.jsx("span",{className:"text-sm font-medium text-orange-400",children:"Melhor Taxa de Clique"})]}),e.jsx("p",{className:"text-lg font-bold text-white truncate",children:o.clickRate.subjectLine}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsxs(ce,{variant:"outline",className:"border-orange-500/50 text-orange-400",children:["Variante ",o.clickRate.variant]}),e.jsxs("span",{className:"text-2xl font-bold text-orange-400",children:[o.clickRate.clickRate.toFixed(1),"%"]})]})]})}),o.conversion&&e.jsx(M,{className:"bg-gradient-to-br from-emerald-500/10 to-emerald-600/5 border-emerald-500/30",children:e.jsxs(z,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ye,{className:"w-5 h-5 text-emerald-400"}),e.jsx("span",{className:"text-sm font-medium text-emerald-400",children:"Melhor Conversão"})]}),e.jsx("p",{className:"text-lg font-bold text-white truncate",children:o.conversion.subjectLine}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsxs(ce,{variant:"outline",className:"border-emerald-500/50 text-emerald-400",children:["Variante ",o.conversion.variant]}),e.jsxs("span",{className:"text-2xl font-bold text-emerald-400",children:[o.conversion.conversionRate.toFixed(1),"%"]})]})]})})]}),i.length>0&&e.jsxs(M,{className:"bg-slate-900/50 border-slate-800",children:[e.jsx(ke,{children:e.jsx(_e,{className:"text-white text-lg",children:"Comparação de Variantes"})}),e.jsx(z,{children:e.jsx("div",{className:"h-80",children:e.jsx(xs,{width:"100%",height:"100%",children:e.jsxs(Qs,{data:i,layout:"vertical",children:[e.jsx(ds,{strokeDasharray:"3 3",stroke:"#334155"}),e.jsx(ms,{type:"number",domain:[0,100],stroke:"#94a3b8"}),e.jsx(us,{type:"category",dataKey:"name",width:120,stroke:"#94a3b8",tick:{fontSize:12}}),e.jsx(hs,{contentStyle:{backgroundColor:"#1e293b",border:"1px solid #334155",borderRadius:"8px"},labelStyle:{color:"#fff"}}),e.jsx(Gs,{}),e.jsx(Ie,{dataKey:"Taxa Abertura",fill:"#f59e0b",radius:[0,4,4,0]}),e.jsx(Ie,{dataKey:"Taxa Clique",fill:"#f97316",radius:[0,4,4,0]}
1),e.jsx(Ie,{dataKey:"Taxa Conversão",fill:"#22c55e",radius:[0,4,4,0]})]})})})})]}),e.jsxs(M,{className:"bg-slate-900/50 border-slate-800",children:[e.jsx(ke,{children:e.jsx(_e,{className:"text-white text-lg",children:"Detalhes por Variante"})}),e.jsx(z,{children:s.length===0?e.jsxs("div",{className:"text-center py-8 text-slate-400",children:[e.jsx(ge,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"Nenhum dado de teste A/B disponÃvel"}),e.jsx("p",{className:"text-sm mt-1",children:"Os emails de onboarding populam automaticamente estes dados"})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-slate-700",children:[e.jsx("th",{className:"text-left py-3 px-2 text-slate-400 font-medium",children:"Variante"}),e.jsx("th",{className:"text-left py-3 px-2 text-slate-400 font-medium",children:"Tipo"}),e.jsx("th",{className:"text-left py-3 px-2 text-slate-400 font-medium max-w-xs",children:"Subject"}),e.jsx("th",{className:"text-right py-3 px-2 text-slate-400 font-medium",children:"Enviados"}),e.jsx("th",{className:"text-right py-3 px-2 text-slate-400 font-medium",children:"Abertos"}),e.jsx("th",{className:"text-right py-3 px-2 text-slate-400 font-medium",children:"Cliques"}),e.jsx("th",{className:"text-right py-3 px-2 text-slate-400 font-medium",children:"Conv."}),e.jsx("th",{className:"text-right py-3 px-2 text-slate-400 font-medium",children:"Receita"})]})}),e.jsx("tbody",{children:s.map((d,c)=>e.jsxs("tr",{className:"border-b border-slate-800 hover:bg-slate-800/50",children:[e.jsx("td",{className:"py-3 px-2",children:e.jsx(ce,{style:{backgroundColor:`${Z[c%Z.length]}20`,color:Z[c%Z.length],borderColor:`${Z[c%Z.length]}50`},variant:"outline",children:d.variant})}),e.jsx("td",{className:"py-3 px-2 text-slate-300 text-sm",children:d.emailType.replace("onboarding_","Onb ").replace("day","D")}),e.jsx("td",{className:"py-3 px-2 text-white text-sm max-w-xs truncate",title:d.subjectLine,children:d.subjectLine}),e.jsx("td",{className:"py-3 px-2 text-right text-slate-300",children:d.totalSent}),e.jsxs("td",{className:"py-3 px-2 text-right",children:[e.jsx("span",{className:"text-amber-400",children:d.opened}),e.jsxs("span",{className:"text-slate-500 text-xs ml-1",children:["(",d.openRate.toFixed(1),"%)"]})]}),e.jsxs("td",{className:"py-3 px-2 text-right",children:[e.jsx("span",{className:"text-orange-400",children:d.clicked}),e.jsxs("span",{className:"text-slate-500 text-xs ml-1",children:["(",d.clickRate.toFixed(1),"%)"]})]}),e.jsxs("td",{className:"py-3 px-2 text-right",children:[e.jsx("span",{className:"text-emerald-400",children:d.converted}),e.jsxs("span",{className:"text-slate-500 text-xs ml-1",children:["(",d.conversionRate.toFixed(1),"%)"]})]}),e.jsxs("td",{className:"py-3 px-2 text-right text-green-400 font-medium",children:["$",d.revenue.toLocaleString()]})]},`${d.variant}_${d.emailType}`))})]})})})]})]})};function Et(){const{user:s}=Us(),l=Xs(),[f,h]=r.useState(null);return r.useEffect(()=>{if(!s){l("/auth");return}N.rpc("has_role",{_user_id:s.id,_role:"admin"}).then(({data:u})=>h(u===!0))},[s,l]),!s||f===null?e.jsx(Me,{title:"Email Marketing",description:"Loadingâ¦",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{className:"h-10 w-72"}),e.jsx(pe,{className:"h-32"}),e.jsx(pe,{className:"h-64"})]})}):f?e.jsx(Me,{title:"Email Marketing",description:"Recovery campaigns, automation and deliverability",children:e.jsxs(cs,{defaultValue:"overview",className:"space-y-4",children:[e.jsxs(os,{children:[e.jsxs(ie,{value:"overview",className:"gap-1.5",children:[e.jsx(qs,{className:"h-4 w-4"})," Overview"]}),e.jsxs(ie,{value:"digest",className:"gap-1.5",children:[e.jsx(We,{className:"h-4 w-4"})," Digest"]}),e.jsxs(ie,{value:"composer",className:"gap-1.5",children:[e.jsx(Re,{className:"h-4 w-4"})," Composer"]}),e.jsxs(ie,{value:"automation",className:"gap-1.5",children:[e.jsx(Is,{className:"h-4 w-4"})," Automation"]}),e.jsxs(ie,{value:"health",className:"gap-1.5",children:[e.jsx(Bs,{className:"h-4 w-4"})," Health"]})]}),e.jsx(ue,{value:"overview",className:"space-y-4",children:e.jsx(Js,{})}),e.jsxs(ue,{value:"digest",className:"space-y-4",children:[e.jsx(dt,{}),e.jsx(ot,{})]}),e.jsxs(ue,{value:"composer",className:"space-y-4",children:[e.jsx(at,{}),e.jsx(nt,{})]}),e.jsx(ue,{value:"automation",className:"space-y-4",children:e.jsx(xt,{})}),e.jsxs(ue,{value:"health",className:"space-y-4",children:[e.jsx(rt,{}),e.jsx(lt,{})]})]})}):e.jsx(Me,{title:"Email Marketing",description:"Access denied",children:e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[60vh] text-center gap-3",children:[e.jsx(ns,{className:"h-12 w-12 text-destructive"}),e.jsx("h1",{className:"text-xl font-semibold",children:"Admin only"}),e.jsx(F,{onClick:()=>l("/"),variant:"outline",children:"Back home"})]})})}export{Et 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.