PageSourceSearch

https://facevideoai.com/assets/Admin-D1g07bCB.js

js facevideoai.com collected 2026-10-09 22:02:07 UTC 258,483 bytes, 137 lines download raw bytes

1import{t as Y,r as d,j as e,w as R,s as T,ah as we,ai as fe,B as $,b as Ae,K as ht,aj as me,L as V,ac as sr,ak as ss,W as ia,Q as la,R as ca,U as da,X as oa,al as as,am as rs,an as J,ao as ee,d as ua,ap as ar,aq as ma,V as wt,I as kt,e as Gt,ar as rr,as as nr,at as Ve,au as ir,aa as lr,av as cr,aw as ns,ax as Se,ay as dr,O as Ze,az as or,$ as ur,D as mr,_ as xr,T as xa,g as ha,u as hr,a as pr,N as Lt,Z as gr}from"./index-DpcRkzEJ.js";import{C as O,c as E,a as z,b as U}from"./card-CJakSgOC.js";import{B as A}from"./badge-CLIDEQN_.js";import{S as Ce,a as Pe,b as De,d as Le,e as q}from"./select-DqR0bC4U.js";import{t as ce,c as fr,d as jr,e as vr,a as br,b as yr,g as Ts,m as Os,f as Qe,h as Nr,T as qe,i as K,w as _r,j as Je,s as pa,k as Re,u as ga,r as St,l as wr,S as kr,n as is,o as Sr,p as fa,q as Cr,v as Pr,x as Dr,y as Lr,z as Ar,A as Tr,B as ja,C as Or,D as Es,E as va,F as ba,G as ya,H as Er,Z as ls,L as cs,I as ds,J as $r,K as Mr,M as Vt,N as Na,O as Ir,P as Rr,Q as os,R as _a,U as Fr,V as $s,W as zr,X as Ur,Y as wa,_ as ka,$ as Sa,a0 as Br,a1 as Wr,a2 as qr,a3 as Ca,a4 as Gr,a5 as Vr,a6 as Hr,a7 as Kr,a8 as Yr,a9 as Xr,aa as Zr,ab as Qr,ac as Pa,ad as Ms,ae as et,af as Jr,ag as en,ah as tn,ai as sn,aj as an,ak as rn,al as nn,am as us,an as ms,ao as pt,ap as xs,aq as hs,ar as Da,as as ln,at as La,au as Aa,av as Ta,aw as Oa,ax as tt,ay as cn,az as ze,aA as At,aB as Ht,aC as dn}from"./BarChart-C461JM8Z.js";import{A as on,a as un,u as Kt}from"./useQuery-CeUiP5c2.js";import{R as ve}from"./refresh-cw-CmrTENpi.js";import{C as Ct}from"./circle-alert-gVqSraD_.js";import{P as gt}from"./play-DQm9RfIK.js";import{S as mn}from"./shield-check-BlS2FfwO.js";import{S as Ea}from"./switch-CN-xraww.js";import"./vendor-supabase-XOXmZWMk.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const ps=Y("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const xn=Y("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/**
12 * @license lucide-react v0.462.0 - ISC
13 *
14 * This source code is licensed under the ISC license.
15 * See the LICENSE file in the root directory of this source tree.
16 */const hn=Y("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/**
17 * @license lucide-react v0.462.0 - ISC
18 *
19 * This source code is licensed under the ISC license.
20 * See the LICENSE file in the root directory of this source tree.
21 */const pn=Y("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.3V14",key:"akvzfd"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]]);/**
22 * @license lucide-react v0.462.0 - ISC
23 *
24 * This source code is licensed under the ISC license.
25 * See the LICENSE file in the root directory of this source tree.
26 */const Is=Y("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/**
27 * @license lucide-react v0.462.0 - ISC
28 *
29 * This source code is licensed under the ISC license.
30 * See the LICENSE file in the root directory of this source tree.
31 */const mt=Y("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
32 * @license lucide-react v0.462.0 - ISC
33 *
34 * This source code is licensed under the ISC license.
35 * See the LICENSE file in the root directory of this source tree.
36 */const He=Y("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/**
37 * @license lucide-react v0.462.0 - ISC
38 *
39 * This source code is licensed under the ISC license.
40 * See the LICENSE file in the root directory of this source tree.
41 */const gs=Y("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
42 * @license lucide-react v0.462.0 - ISC
43 *
44 * This source code is licensed under the ISC license.
45 * See the LICENSE file in the root directory of this source tree.
46 */const gn=Y("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/**
47 * @license lucide-react v0.462.0 - ISC
48 *
49 * This source code is licensed under the ISC license.
50 * See the LICENSE file in the root directory of this source tree.
51 */const fn=Y("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);/**
52 * @license lucide-react v0.462.0 - ISC
53 *
54 * This source code is licensed under the ISC license.
55 * See the LICENSE file in the root directory of this source tree.
56 */const jn=Y("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/**
57 * @license lucide-react v0.462.0 - ISC
58 *
59 * This source code is licensed under the ISC license.
60 * See the LICENSE file in the root directory of this source tree.
61 */const Rs=Y("HeartHandshake",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M12 5 9.04 7.96a2.17 2.17 0 0 0 0 3.08c.82.82 2.13.85 3 .07l2.07-1.9a2.82 2.82 0 0 1 3.79 0l2.96 2.66",key:"4oyue0"}],["path",{d:"m18 15-2-2",key:"60u0ii"}],["path",{d:"m15 18-2-2",key:"6p76be"}]]);/**
62 * @license lucide-react v0.462.0 - ISC
63 *
64 * This source code is licensed under the ISC license.
65 * See the LICENSE file in the root directory of this source tree.
66 */const vn=Y("Map",[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]]);/**
67 * @license lucide-react v0.462.0 - ISC
68 *
69 * This source code is licensed under the ISC license.
70 * See the LICENSE file in the root directory of this source tree.
71 */const Fs=Y("Megaphone",[["path",{d:"m3 11 18-5v12L3 14v-3z",key:"n962bs"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}]]);/**
72 * @license lucide-react v0.462.0 - ISC
73 *
74 * This source code is licensed under the ISC license.
75 * See the LICENSE file in the root directory of this source tree.
76 */const Tt=Y("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]);/**
77 * @license lucide-react v0.462.0 - ISC
78 *
79 * This source code is licensed under the ISC license.
80 * See the LICENSE file in the root directory of this source tree.
81 */const zs=Y("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/**
82 * @license lucide-react v0.462.0 - ISC
83 *
84 * This source code is licensed under the ISC license.
85 * See the LICENSE file in the root directory of this source tree.
86 */const Ot=Y("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]);/**
87 * @license lucide-react v0.462.0 - ISC
88 *
89 * This source code is licensed under the ISC license.
90 * See the LICENSE file in the root directory of this source tree.
91 */const bn=Y("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3
91kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]);/**
92 * @license lucide-react v0.462.0 - ISC
93 *
94 * This source code is licensed under the ISC license.
95 * See the LICENSE file in the root directory of this source tree.
96 */const ft=Y("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/**
97 * @license lucide-react v0.462.0 - ISC
98 *
99 * This source code is licensed under the ISC license.
100 * See the LICENSE file in the root directory of this source tree.
101 */const yn=Y("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
102 * @license lucide-react v0.462.0 - ISC
103 *
104 * This source code is licensed under the ISC license.
105 * See the LICENSE file in the root directory of this source tree.
106 */const Nn=Y("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/**
107 * @license lucide-react v0.462.0 - ISC
108 *
109 * This source code is licensed under the ISC license.
110 * See the LICENSE file in the root directory of this source tree.
111 */const _n=Y("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/**
112 * @license lucide-react v0.462.0 - ISC
113 *
114 * This source code is licensed under the ISC license.
115 * See the LICENSE file in the root directory of this source tree.
116 */const wn=Y("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/**
117 * @license lucide-react v0.462.0 - ISC
118 *
119 * This source code is licensed under the ISC license.
120 * See the LICENSE file in the root directory of this source tree.
121 */const Ge=Y("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/**
122 * @license lucide-react v0.462.0 - ISC
123 *
124 * This source code is licensed under the ISC license.
125 * See the LICENSE file in the root directory of this source tree.
126 */const $a=Y("Wallet",[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]),de=d.forwardRef(({className:t,...s},a)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:a,className:R("w-full caption-bottom text-sm",t),...s})}));de.displayName="Table";const oe=d.forwardRef(({className:t,...s},a)=>e.jsx("thead",{ref:a,className:R("[&_tr]:border-b",t),...s}));oe.displayName="TableHeader";const ue=d.forwardRef(({className:t,...s},a)=>e.jsx("tbody",{ref:a,className:R("[&_tr:last-child]:border-0",t),...s}));ue.displayName="TableBody";const kn=d.forwardRef(({className:t,...s},a)=>e.jsx("tfoot",{ref:a,className:R("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...s}));kn.displayName="TableFooter";const G=d.forwardRef(({className:t,...s},a)=>e.jsx("tr",{ref:a,className:R("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",t),...s}));G.displayName="TableRow";const k=d.forwardRef(({className:t,...s},a)=>e.jsx("th",{ref:a,className:R("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",t),...s}));k.displayName="TableHead";const N=d.forwardRef(({className:t,...s},a)=>e.jsx("td",{ref:a,className:R("p-4 align-middle [&:has([role=checkbox])]:pr-0",t),...s}));N.displayName="TableCell";const Sn=d.forwardRef(({className:t,...s},a)=>e.jsx("caption",{ref:a,className:R("mt-4 text-sm text-muted-foreground",t),...s}));Sn.displayName="TableCaption";function xt(t,s){const a=ce(t),r=ce(s),n=a.getTime()-r.getTime();return n<0?-1:n>0?1:n}function Cn(t){return fr(t,Date.now())}function Us(t,s){const a=ce(t),r=ce(s),n=Bs(a,r),o=Math.abs(jr(a,r));a.setDate(a.getDate()-n*o);const l=+(Bs(a,r)===-n),c=n*(o-l);return c===0?0:c}function Bs(t,s){const a=t.getFullYear()-s.getFullYear()||t.getMonth()-s.getMonth()||t.getDate()-s.getDate()||t.getHours()-s.getHours()||t.getMinutes()-s.getMinutes()||t.getSeconds()-s.getSeconds()||t.getMilliseconds()-s.getMilliseconds();return a<0?-1:a>0?1:a}function Pn(t){return s=>{const r=(t?Math[t]:Math.trunc)(s);return r===0?0:r}}function Dn(t,s){return+ce(t)-+ce(s)}function Ie(t){const s=ce(t);return s.setHours(23,59,59,999),s}function Ln(t){const s=ce(t);return+Ie(s)==+vr(s)}function An(t,s){const a=ce(t),r=ce(s),n=xt(a,r),o=Math.abs(br(a,r));let l;if(o<1)l=0;else{a.getMonth()===1&&a.getDate()>27&&a.setDate(30),a.setMonth(a.getMonth()-n*o);let c=xt(a,r)===-n;Ln(ce(t))&&o===1&&xt(t,r)===1&&(c=!1),l=n*(o-Number(c))}return l===0?0:l}function Tn(t,s,a){const r=Dn(t,s)/1e3;
126return Pn(a==null?void 0:a.roundingMethod)(r)}function On(t,s,a){const r=Nr(),n=(a==null?void 0:a.locale)??r.locale??yr,o=2520,l=xt(t,s);if(isNaN(l))throw new RangeError("Invalid time value");const c=Object.assign({},a,{addSuffix:a==null?void 0:a.addSuffix,comparison:l});let x,g;l>0?(x=ce(s),g=ce(t)):(x=ce(t),g=ce(s));const u=Tn(g,x),i=(Ts(g)-Ts(x))/1e3,h=Math.round((u-i)/60);let m;if(h<2)return a!=null&&a.includeSeconds?u<5?n.formatDistance("lessThanXSeconds",5,c):u<10?n.formatDistance("lessThanXSeconds",10,c):u<20?n.formatDistance("lessThanXSeconds",20,c):u<40?n.formatDistance("halfAMinute",0,c):u<60?n.formatDistance("lessThanXMinutes",1,c):n.formatDistance("xMinutes",1,c):h===0?n.formatDistance("lessThanXMinutes",1,c):n.formatDistance("xMinutes",h,c);if(h<45)return n.formatDistance("xMinutes",h,c);if(h<90)return n.formatDistance("aboutXHours",1,c);if(h<Os){const v=Math.round(h/60);return n.formatDistance("aboutXHours",v,c)}else{if(h<o)return n.formatDistance("xDays",1,c);if(h<Qe){const v=Math.round(h/Os);return n.formatDistance("xDays",v,c)}else if(h<Qe*2)return m=Math.round(h/Qe),n.formatDistance("aboutXMonths",m,c)}if(m=An(g,x),m<12){const v=Math.round(h/Qe);return n.formatDistance("xMonths",v,c)}else{const v=m%12,b=Math.trunc(m/12);return v<3?n.formatDistance("aboutXYears",b,c):v<9?n.formatDistance("overXYears",b,c):n.formatDistance("almostXYears",b+1,c)}}function Ke(t,s){return On(t,Cn(t),s)}function Ye(t){if(!t||typeof t!="string")return"—";const s=t.trim().toUpperCase();if(!/^[A-Z]{2}$/.test(s))return"—";const a=127462,r=65;return String.fromCodePoint(a+s.charCodeAt(0)-r)+String.fromCodePoint(a+s.charCodeAt(1)-r)}const st=t=>t===null?"—":`${Math.round(t*100)}%`,je=t=>`$${(t??0).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`,En=(t,s)=>{if(!t)return"—";const a=s||1,r={day:"day",week:"wk",month:"mo",year:"yr"}[t]||t;return a===1?`/${r}`:`/${a}${r}`};function $n({onCancellationCount:t}){const[s,a]=d.useState(null),[r,n]=d.useState(!0),[o,l]=d.useState(null),[c,x]=d.useState("just now"),[g,u]=d.useState("all"),[i,h]=d.useState("smart"),m=d.useCallback(async()=>{n(!0);try{const{data:{session:p}}=await T.auth.getSession();if(!(p!=null&&p.access_token))return;const{data:j,error:L}=await T.functions.invoke("admin-trial-stats",{headers:{Authorization:`Bearer ${p.access_token}`}});L||j!=null&&j.error?l((j==null?void 0:j.error)||(L==null?void 0:L.message)||"Failed"):(a(j),l(null),t==null||t(j.kpis.will_cancel))}finally{n(!1)}},[t]);d.useEffect(()=>{m()},[m]),d.useEffect(()=>{if(!(s!=null&&s.synced_at))return;const p=()=>x(Ke(new Date(s.synced_at),{addSuffix:!1}));p();const j=setInterval(p,5e3);return()=>clearInterval(j)},[s==null?void 0:s.synced_at]);const v=d.useMemo(()=>{const p=(s==null?void 0:s.rows)??[];return{all:p.length,active_paid:p.filter(j=>j.derived_status==="converted").length,will_cancel:p.filter(j=>j.derived_status==="will_cancel").length,zero_gen:p.filter(j=>(j.derived_status==="will_cancel"||j.derived_status==="on_track")&&j.generation_count===0).length,trials:p.filter(j=>j.derived_status==="on_track"||j.derived_status==="will_cancel").length,converted:p.filter(j=>j.derived_status==="converted").length,canceled:p.filter(j=>j.derived_status==="canceled").length,has_renewals:p.filter(j=>j.renewal_count>0).length}},[s]),b=d.useMemo(()=>{const p=(s==null?void 0:s.rows)??[];let j=p;switch(g){case"active_paid":j=p.filter(w=>w.derived_status==="converted");break;case"will_cancel":j=p.filter(w=>w.derived_status==="will_cancel");break;case"zero_gen":j=p.filter(w=>(w.derived_status==="will_cancel"||w.derived_status==="on_track")&&w.generation_count===0);break;case"trials":j=p.filter(w=>w.derived_status==="on_track"||w.derived_status==="will_cancel");break;case"converted":j=p.filter(w=>w.derived_status==="converted");break;case"canceled":j=p.filter(w=>w.derived_status==="canceled");break;case"has_renewals":j=p.filter(w=>w.renewal_count>0);break}const L=w=>w.derived_status==="will_cancel"?0:w.derived_status==="on_track"&&w.generation_count===0?1:w.derived_status==="on_track"?2:w.derived_status==="converted"?3:4;return[...j].sort((w,_)=>{if(i==="revenue")return _.total_paid_usd-w.total_paid_usd;
126if(i==="renewals")return _.renewal_count-w.renewal_count;if(i==="next_renewal"){const D=w.next_renewal_at?new Date(w.next_renewal_at).getTime():1/0,I=_.next_renewal_at?new Date(_.next_renewal_at).getTime():1/0;return D-I}const P=L(w)-L(_);return P!==0?P:new Date(_.created).getTime()-new Date(w.created).getTime()})},[g,i,s]);if(r&&!s)return e.jsx(O,{className:"border-border/50 bg-card/50",children:e.jsx(E,{className:"py-12 flex items-center justify-center",children:e.jsx("div",{className:"h-6 w-6 rounded-full border-2 border-primary border-t-transparent animate-spin"})})});if(o)return e.jsx(O,{className:"border-destructive/50 bg-destructive/5",children:e.jsx(E,{className:"py-6 text-center text-destructive text-sm",children:o})});const f=s.kpis;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(O,{className:"border-primary/30 bg-gradient-to-br from-primary/10 via-accent/5 to-transparent backdrop-blur-sm",children:e.jsxs(E,{className:"p-5 sm:p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-2",children:[e.jsx(qe,{className:"h-4 w-4 text-primary"}),e.jsx("span",{children:"Real MRR · active paid subs (normalized to monthly)"})]}),e.jsxs("div",{className:"text-3xl sm:text-4xl font-bold text-primary",children:[je(f.real_mrr_usd),e.jsx("span",{className:"text-sm font-normal text-muted-foreground ml-2",children:"/ mo"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1.5",children:[f.conversions_count," active paid · excludes scheduled cancels"]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-border/40 text-xs text-muted-foreground",children:["Trial-projected MRR (if all ",f.active_trials," trials convert):"," ",e.jsx("span",{className:"text-foreground font-medium",children:je(f.simulated_mrr_usd)})," · Likely"," ",e.jsx("span",{className:"text-foreground font-medium",children:je(f.projected_mrr_usd)})]})]})}),e.jsx(O,{className:"border-accent/30 bg-gradient-to-br from-accent/10 via-primary/5 to-transparent backdrop-blur-sm",children:e.jsxs(E,{className:"p-5 sm:p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-2",children:[e.jsx($a,{className:"h-4 w-4 text-accent"}),e.jsx("span",{children:"Subscription revenue collected (all time)"})]}),e.jsx("div",{className:"text-3xl sm:text-4xl font-bold text-accent",children:je(f.total_collected_usd)}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1.5",children:["Across ",s.rows.length," subscription",s.rows.length===1?"":"s"]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-border/40 text-xs text-muted-foreground flex items-center gap-3 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Ot,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"text-foreground font-medium",children:f.total_renewals})," renewals"]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:["Renewal revenue:"," ",e.jsx("span",{className:"text-foreground font-medium",children:je(f.total_renewal_revenue_usd)})]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:[f.subs_with_renewals," subs renewed ≥1×"]})]})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ke,{icon:e.jsx(Ge,{className:"h-4 w-4"}),label:"Active Trials",value:f.active_trials,subtitle:`+${f.trials_started_24h} started today`,tone:"primary"}),e.jsx(ke,{icon:e.jsx(we,{className:"h-4 w-4"}),label:"Active Paid Subs",value:f.conversions_count,subtitle:`${f.subs_with_renewals} have renewed`,tone:"accent"}),e.jsx(ke,{icon:e.jsx(fe,{className:"h-4 w-4"}),label:"Trials Will Cancel",value:f.will_cancel,subtitle:`${je(f.revenue_at_risk_usd)} at risk`,tone:f.will_cancel>0?"destructive":"muted",pulse:f.will_cancel>0}),e.jsx(ke,{icon:f.net_trial_change_24h>=0?e.jsx(on,{className:"h-4 w-4"}):e.jsx(un,{className:"h-4 w-4"}),label:"Net Trial Change (24h)",value:`${f.net_trial_change_24h>=0?"+":""}${f.net_trial_change_24h}`,subtitle:`${f.trials_started_24h} new · ${f.canceled_last_24h}
126 ended`,tone:f.net_trial_change_24h>=0?"primary":"destructive"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ke,{icon:e.jsx(qe,{className:"h-4 w-4"}),label:"Conversion (60d)",value:st(f.conversion_rate_60d),subtitle:`7d ${st(f.conversion_rate_7d)} · 30d ${st(f.conversion_rate_30d)}`,tone:"accent"}),e.jsx(ke,{icon:e.jsx(ps,{className:"h-4 w-4"}),label:"Trial Engagement",value:st(f.engagement_rate),subtitle:`${f.engaged_trials}/${f.active_trials} generated`,tone:"muted"}),e.jsx(ke,{icon:e.jsx(Ot,{className:"h-4 w-4"}),label:"Total Renewals Billed",value:f.total_renewals,subtitle:je(f.total_renewal_revenue_usd),tone:"primary"}),e.jsx(ke,{icon:e.jsx(He,{className:"h-4 w-4"}),label:"Avg Revenue / Active Sub",value:f.conversions_count>0?je(f.total_collected_usd/Math.max(1,f.conversions_count+f.canceled_last_24h)):"—",subtitle:"across all paid subs in view",tone:"muted"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last synced: ",e.jsxs("span",{className:"text-foreground",children:[c," ago"]})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:m,disabled:r,children:[e.jsx(ve,{className:R("h-3.5 w-3.5 mr-1.5",r&&"animate-spin")}),"Refresh"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Te,{active:g==="all",onClick:()=>u("all"),label:"All",count:v.all}),e.jsx(Te,{active:g==="active_paid",onClick:()=>u("active_paid"),label:"Active Paid",count:v.active_paid,tone:"primary"}),e.jsx(Te,{active:g==="has_renewals",onClick:()=>u("has_renewals"),label:"Has Renewed",count:v.has_renewals,tone:"primary"}),e.jsx(Te,{active:g==="trials",onClick:()=>u("trials"),label:"In Trial",count:v.trials}),e.jsx(Te,{active:g==="will_cancel",onClick:()=>u("will_cancel"),label:"Will Cancel",count:v.will_cancel,tone:"destructive"}),e.jsx(Te,{active:g==="zero_gen",onClick:()=>u("zero_gen"),label:"Zero Generations",count:v.zero_gen,tone:"warning"}),e.jsx(Te,{active:g==="canceled",onClick:()=>u("canceled"),label:"Canceled",count:v.canceled}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 text-xs",children:[e.jsx("span",{className:"text-muted-foreground mr-1",children:"Sort:"}),e.jsx(at,{active:i==="smart",onClick:()=>h("smart"),label:"Smart"}),e.jsx(at,{active:i==="revenue",onClick:()=>h("revenue"),label:"Revenue"}),e.jsx(at,{active:i==="renewals",onClick:()=>h("renewals"),label:"Renewals"}),e.jsx(at,{active:i==="next_renewal",onClick:()=>h("next_renewal"),label:"Next Renewal"})]})]}),e.jsxs(O,{className:"border-border/50 bg-card/50",children:[e.jsx(z,{children:e.jsxs(U,{className:"text-base",children:["Subscriptions (",b.length,")"]})}),e.jsx(E,{className:"overflow-x-auto",children:e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{children:[e.jsx(k,{children:"User"}),e.jsx(k,{children:"Status"}),e.jsx(k,{children:"Plan"}),e.jsx(k,{className:"text-right",children:"Renewals"}),e.jsx(k,{className:"text-right",children:"Total Paid"}),e.jsx(k,{children:"Next Renewal / Ends"}),e.jsx(k,{className:"text-right",children:"Gens"}),e.jsx(k,{className:"text-right",children:"Stripe"})]})}),e.jsxs(ue,{children:[b.length===0&&e.jsx(G,{children:e.jsx(N,{colSpan:8,className:"text-center text-muted-foreground text-sm py-8",children:"No subscriptions match this filter."})}),b.map(p=>{const j=p.derived_status==="will_cancel"||p.derived_status==="on_track",L=j&&p.generation_count===0,w=j&&p.trial_end?Math.max(0,Us(new Date(p.trial_end),new Date)):null,_=p.derived_status==="converted"&&p.next_renewal_at?Us(new Date(p.next_renewal_at),new Date):null;return e.jsxs(G,{className:R(p.derived_status==="will_cancel"&&"bg-destructive/5 hover:bg-destructive/10",L&&p.derived_status==="on_track"&&"bg-amber-500/5 hover:bg-amber-500/10",p.renewal_count>=2&&"bg-primary/5"),children:[e.jsxs(N,{children:[e.jsx("div",{className:"font-medium text-sm",children:p.full_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:p.email||"—"})]}),e.jsx(N,{children:e.jsxs("div",{className:"flex flex-col gap-1 items-start",children:[e.jsx(Mn,{status:p.derived_status}),L&&e.jsx(A,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-500",children:"Not engaged"}),p.cancel_at_period_end&&p.derived_status==="converted"&&e.jsx(A,{variant:"destructive",className:"text-[10px]",children:"Cancels at renewal"})]})}),e.jsxs(N,{className:"text-xs",children:[e.jsx("div",{className:"text-foreground",children:p.product_name||"—"}),e.jsx("div",{className:"text-muted-foreground",children:p.price_per_cycle_usd?`${je(p.price_per_cycle_usd)}${En(p.interval,p.interval_count)}`:"—"})]}),e.jsxs(N,{className:"text-right",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-sm",children:[e.jsx(Ot,{className:R("h-3.5 w-3.5",p.renewal_count>
1260?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:R("tabular-nums font-medium",p.renewal_count>0?"text-foreground":"text-muted-foreground"),children:p.renewal_count})]}),p.last_payment_at&&e.jsxs("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:["last ",K(new Date(p.last_payment_at),"MMM d")]})]}),e.jsxs(N,{className:"text-right",children:[e.jsx("div",{className:R("text-sm font-mono tabular-nums",p.total_paid_usd>0?"text-foreground":"text-muted-foreground"),children:je(p.total_paid_usd)}),p.renewal_revenue_usd>0&&e.jsxs("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:[je(p.renewal_revenue_usd)," from renewals"]})]}),e.jsx(N,{className:"text-xs",children:p.derived_status==="canceled"&&p.canceled_at?e.jsxs("span",{className:"text-muted-foreground",children:["Canceled ",K(new Date(p.canceled_at),"MMM d, yyyy")]}):p.derived_status==="converted"&&p.next_renewal_at?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(pn,{className:"h-3.5 w-3.5 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-foreground font-medium",children:K(new Date(p.next_renewal_at),"MMM d, yyyy")}),_!==null&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["in ",_,"d"]})]})]}):p.derived_status==="converted"&&p.cancel_at_period_end&&p.cancel_at?e.jsxs("span",{className:"text-destructive font-medium",children:["Ends ",K(new Date(p.cancel_at),"MMM d, yyyy")]}):p.cancel_at_period_end&&p.cancel_at?e.jsxs("span",{className:"text-destructive font-medium",children:["Cancels ",K(new Date(p.cancel_at),"MMM d")]}):p.trial_end?e.jsxs("div",{children:[e.jsxs("div",{className:"text-foreground",children:["Trial ends ",K(new Date(p.trial_end),"MMM d")]}),w!==null&&e.jsx("div",{className:R("text-[10px]",w===0?"text-destructive":w<=3?"text-amber-500":"text-muted-foreground"),children:w===0?"today":`${w}d left`})]}):"—"}),e.jsx(N,{className:"text-right text-sm",children:p.generation_count}),e.jsx(N,{className:"text-right",children:e.jsxs("a",{href:`https://dashboard.stripe.com/subscriptions/${p.subscription_id}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center text-xs text-muted-foreground hover:text-foreground",children:["View ",e.jsx(gs,{className:"h-3 w-3 ml-1"})]})})]},p.subscription_id)})]})]})})]})]})}function at({active:t,onClick:s,label:a}){return e.jsx("button",{onClick:s,className:R("px-2 py-0.5 rounded-md text-[11px] border transition-colors",t?"bg-foreground text-background border-foreground":"border-border/60 bg-card/40 text-muted-foreground hover:text-foreground"),children:a})}function Te({active:t,onClick:s,label:a,count:r,tone:n}){const o={destructive:"bg-destructive text-destructive-foreground border-destructive",warning:"bg-amber-500 text-background border-amber-500",primary:"bg-primary text-primary-foreground border-primary",undefined:"bg-foreground text-background border-foreground"}[n??"undefined"];return e.jsxs("button",{onClick:s,className:R("inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium border transition-colors",t?o:"border-border/60 bg-card/40 text-muted-foreground hover:text-foreground hover:border-border"),children:[a,e.jsx("span",{className:"text-[10px] opacity-80",children:r})]})}function ke({icon:t,label:s,value:a,subtitle:r,tone:n,pulse:o}){const l={primary:"border-primary/30 bg-primary/5",accent:"border-accent/30 bg-accent/5",destructive:"border-destructive/40 bg-destructive/10",muted:"border-border/50 bg-card/50"}[n],c={primary:"text-primary",accent:"text-accent",destructive:"text-destructive",muted:"text-muted-foreground"}[n];return e.jsx(O,{className:R("relative overflow-hidden backdrop-blur-sm",l),children:e.jsxs(E,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-2",children:[e.jsx("span",{className:c,children:t}),e.jsx("span",{children:s}),o&&e.jsxs("span",{className:"relative ml-auto flex h-2 w-2",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-destructive opacity-75 animate-ping"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-destructive"})]})]}),e.jsx("div",{className:R("text-2xl font-bold",n==="destructive"&&"text-destructive"),children:a}),r&&e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:r})]})})}function Mn({status:t}){switch(t){case"will_cancel":return e.jsx(A,{variant:"destructive",className:"text-xs",children:"Will Cancel"});case"on_track":return e.jsx(A,{className:"bg-primary/15 text-primary border-primary/30 hover:bg-primary/20 text-xs",children:"On Track"});case"converted":return e.jsx(A,{className:"bg-accent/15 text-accent border-accent/30 hover:bg-accent/20 text-xs",children:"Active Paid"});case"canceled":return e.jsx(A,{variant:"secondary",className:"text-xs",children:"Canceled"})}}const Ma="fv_replayed_conversions";function Yt(){try{return new Set(JSON.parse(localStorage.getItem(Ma)||"[]"))}catch{return new Set}}function In(t){const s=Yt();s.add(t);try{localStorage.setItem(Ma,JSON.stringify([...s]))}catch{}}function Rn(){const{toast:t}
126=Ae(),[s,a]=d.useState([]),[r,n]=d.useState(!0),[o,l]=d.useState(Yt()),[c,x]=d.useState({});d.useEffect(()=>{(async()=>{n(!0);const u=new Date(Date.now()-30*24*60*60*1e3).toISOString(),{data:i}=await T.from("credit_transactions").select("id, user_id, amount, description, stripe_session_id, created_at").eq("type","purchase").gte("created_at",u).order("created_at",{ascending:!1}),h=[...new Set((i||[]).map(b=>b.user_id))],{data:m}=await T.from("profiles").select("user_id, email, full_name").in("user_id",h.length?h:["00000000-0000-0000-0000-000000000000"]),v=new Map((m||[]).map(b=>[b.user_id,b]));a((i||[]).map(b=>{var f,p;return{id:b.id,user_id:b.user_id,amount:b.amount,description:b.description,stripe_session_id:b.stripe_session_id,created_at:b.created_at,email:((f=v.get(b.user_id))==null?void 0:f.email)??null,full_name:((p=v.get(b.user_id))==null?void 0:p.full_name)??null,amount_paid:null}})),n(!1)})()},[]);const g=u=>{if(!u.stripe_session_id){t({title:"No Stripe session",description:"Cannot replay without a Stripe session ID.",variant:"destructive"});return}const i=c[u.id];if(!i||i<=0){t({title:"Enter the paid amount",description:"Type the actual $ paid (after coupons) into the field first.",variant:"destructive"});return}const h=window;if(typeof h.gtag_report_conversion!="function"){t({title:"Google tag not loaded",description:"Refresh the page and try again.",variant:"destructive"});return}h.gtag_report_conversion(i,u.stripe_session_id,u.email||void 0,u.full_name||void 0),typeof h.fbq=="function"&&h.fbq("track","Purchase",{value:i,currency:"USD"},{eventID:u.stripe_session_id}),In(u.stripe_session_id),l(Yt()),t({title:"Conversion replayed",description:`Sent $${i.toFixed(2)} to Google Ads for ${u.email}`})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(O,{className:"border-border/50 bg-card/50",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center gap-2 text-base",children:[e.jsx(ft,{className:"h-4 w-4"}),"Replay Lost Google Ads Conversions"]})}),e.jsxs(E,{className:"space-y-3 text-sm text-muted-foreground",children:[e.jsxs("p",{children:["Manually re-fire Google Ads + Facebook Pixel conversion events for purchases that may not have reached Google (closed tab, ad-blocker, etc). Enter the ",e.jsx("strong",{children:"real $ paid"})," (after coupons — check Stripe dashboard) and click ",e.jsx("strong",{children:"Replay"}),"."]}),e.jsxs("div",{className:"flex gap-2 items-start text-xs bg-amber-500/10 border border-amber-500/30 rounded-md p-3",children:[e.jsx(Ct,{className:"h-4 w-4 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-amber-200 font-medium",children:"How this works:"}),e.jsxs("p",{className:"text-muted-foreground mt-1",children:["Google Ads attributes the conversion using the buyer's ",e.jsx("code",{className:"text-foreground",children:"gclid"})," ","cookie — set when they originally clicked your ad (valid ~90 days). Replays fire from"," ",e.jsx("em",{children:"your"})," browser but Google links them to the right user via the unique"," ",e.jsx("code",{className:"text-foreground",children:"transaction_id"})," = Stripe session ID. Already-replayed sessions are tracked in your browser to prevent double-firing."]})]})]})]})]}),e.jsx(O,{className:"border-border/50 bg-card/50",children:e.jsx(E,{className:"pt-6",children:r?e.jsx("p",{className:"text-muted-foreground text-sm",children:"Loading purchases…"}):s.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No purchases in the last 30 days."}):e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{children:[e.jsx(k,{children:"Date"}),e.jsx(k,{children:"User"}),e.jsx(k,{children:"Pack"}),e.jsx(k,{children:"Stripe Session"}),e.jsx(k,{className:"w-[140px]",children:"$ Paid"}),e.jsx(k,{className:"w-[140px]",children:"Action"})]})}),e.jsx(ue,{children:s.map(u=>{const i=u.stripe_session_id&&o.has(u.stripe_session_id);return e.jsxs(G,{children:[e.jsxs(N,{className:"text-xs whitespace-nowrap",children:[new Date(u.created_at).toLocaleDateString()," ",e.jsx("span",{className:"text-muted-foreground",children:new Date(u.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),e.jsxs(N,{className:"text-xs",children:[e.jsx("div",{className:"font-medium",children:u.email||"—"}),u.full_name&&e.jsx("div",{className:"text-muted-foreground",children:u.full_name})]}),e.jsx(N,{className:"text-xs",children:u.description||"—"}),e.jsx(N,{className:"text-xs font-mono",children:u.stripe_session_id?`${u.stripe_session_id.slice(0,16)}…`:e.jsx(A,{variant:"outline",children:"missing"})}),e.jsx(N,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"$"}),e.jsx("input",{type:"number",step:"0.01",placeholder:"0.00",disabled:!!i,value:c[u.id]??"",onChange:h=>x(m=>({...m,[u.id]:parseFloat(h.target.value)||0})),className:"w-20 h-8 px-2 text-xs rounded border bg-background border-border/50"})]})}),e.jsx(N,{children:i?e.jsxs(A,{className:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30 gap-1",children:[e.jsx(we,{className:"h-3 w-3"})," Replayed"]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>g(u),disabled:!u.stripe_session_id,children:[e.jsx(ft,{className:"h-3 w-3 mr-1"})," Replay"]})})]},u.id)})})]})})})]})}const Fn={"would-grant":"bg-cyan-500/15 text-cyan-300 border-cyan-500/30",granted:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30","already-granted":"bg-muted text-muted-foreground border-border","orphan-no-user":"bg-amber-500/15 text-amber-400 border-amber-500/30","unknown-price":"bg-amber-500/15 text-amber-400 border-amber-500/30",skipped:"bg-muted text-muted-foreground border-border",error:"bg-red-500/15 text-red-400 border-red-500/30"};function zn(){const{toast:t}
126=Ae(),[s,a]=d.useState(60),[r,n]=d.useState(""),[o,l]=d.useState(!1),[c,x]=d.useState(null),g=async u=>{l(!0),x(null);try{const{data:{session:i}}=await T.auth.getSession(),{data:h,error:m}=await T.functions.invoke("admin-reconcile-subscription-invoices",{body:{days:s,...r.trim()?{email:r.trim()}:{},dryRun:u},headers:i!=null&&i.access_token?{Authorization:`Bearer ${i.access_token}`}:{}});if(m)throw m;const v=h;x(v),t({title:u?"Approval list rebuilt":"Credits granted",description:u?`Scanned ${v.scanned} invoices, ${v.approvalCount} need review (${v.approvalCredits.toLocaleString()} credits)`:`Granted ${v.granted} invoices (${v.totalGrantedCredits.toLocaleString()} credits)`})}catch(i){t({title:"Reconcile failed",description:i instanceof Error?i.message:String(i),variant:"destructive"})}finally{l(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(O,{className:"border-border/50 bg-card/50",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center gap-2 text-base",children:[e.jsx(ft,{className:"h-4 w-4"}),"Reconcile Subscription Renewal Credits"]})}),e.jsxs(E,{className:"space-y-4 text-sm text-muted-foreground",children:[e.jsx("p",{children:"Rebuilds the missing-renewal list from live billing data, shows exactly which paid renewal invoices still need their cycle credit grant, and only grants after your explicit approval."}),e.jsxs("div",{className:"flex gap-2 items-start text-xs bg-amber-500/10 border border-amber-500/30 rounded-md p-3",children:[e.jsx(Ct,{className:"h-4 w-4 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-amber-200 font-medium",children:"Approval list is rebuilt from live invoice data"}),e.jsxs("p",{className:"text-muted-foreground mt-1",children:["Only paid ",e.jsx("code",{className:"text-[11px]",children:"subscription_cycle"})," invoices without an existing",e.jsx("code",{className:"text-[11px]",children:" cycle_<sub>_<periodStart>"})," credit record appear in the approval list, so proration rows and already-granted renewals stay excluded."]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ht,{htmlFor:"days",className:"text-xs",children:"Window (days)"}),e.jsx(me,{id:"days",type:"number",min:1,max:180,value:s,onChange:u=>a(parseInt(u.target.value)||60),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ht,{htmlFor:"email",className:"text-xs",children:"Filter by email (optional)"}),e.jsx(me,{id:"email",type:"email",placeholder:"[email protected]",value:r,onChange:u=>n(u.target.value),className:"h-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:o,onClick:()=>g(!0),children:[o?e.jsx(V,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Rebuild approval list"]}),e.jsxs($,{size:"sm",disabled:o,onClick:()=>g(!1),children:[o?e.jsx(V,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Grant approved renewals"]})]})]})]})]}),c&&e.jsxs(O,{className:"border-border/50 bg-card/50",children:[e.jsx(z,{children:e.jsxs(U,{className:"text-base",children:["Results · scanned ",c.scanned," · approval ",c.approvalCount," · granted ",c.granted,c.dryRun&&e.jsx(A,{variant:"outline",className:"ml-2",children:"Approval only"})]})}),e.jsxs(E,{children:[c.note&&e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:c.note}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[e.jsxs(A,{variant:"outline",children:["Need review: ",c.approvalCount]}),e.jsxs(A,{variant:"outline",children:["Approval credits: ",c.approvalCredits.toLocaleString()]}),e.jsxs(A,{variant:"outline",children:["Granted: ",c.granted]}),e.jsxs(A,{variant:"outline",children:["Granted credits: ",c.totalGrantedCredits.toLocaleString()]}),Object.entries(c.summary).map(([u,i])=>e.jsxs(A,{variant:"outline",children:[u,": ",i]},u))]}),c.results.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No invoices in this window."}):e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{children:[e.jsx(k,{children:"Status"}),e.jsx(k,{children:"Email"}),e.jsx(k,{children:"Invoice"}),e.jsx(k,{children:"Amount"}),e.jsx(k,{children:"Plan"}),e.jsx(k,{children:"Credits"}),e.jsx(k,{children:"Grant key"}),e.jsx(k,{children:"Note"})]})}),e.jsx(ue,{children:c.results.map(u=>e.jsxs(G,{children:[e.jsx(N,{children:e.jsx(A,{variant:"outline",className:Fn[u.status],children:u.status})}),e.jsx(N,{className:"text-xs",children:u.email??"—"}),e.jsxs(N,{className:"text-xs font-mono",children:[u.invoiceId.slice(0,18),"…"]}),e.jsx(N,{className:"text-xs",children:u.amount!=null?`$${u.amount.toFixed(2)}`:"—"}),e.jsx(N,{className:"text-xs",children:u.plan??"—"}),e.jsx(N,{className:"text-xs",children:u.credits!=null?u.credits.toLocaleStr
126ing():"—"}),e.jsx(N,{className:"text-[10px] font-mono text-muted-foreground",children:u.grantKey??"—"}),e.jsx(N,{className:"text-xs text-muted-foreground",children:u.reason??u.billingReason??""})]},u.invoiceId))})]})]})]})]})}const Ws={granted:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",recovered:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30","already-granted":"bg-muted text-muted-foreground border-border","orphan-no-user":"bg-amber-500/15 text-amber-400 border-amber-500/30","unknown-price":"bg-amber-500/15 text-amber-400 border-amber-500/30",skipped:"bg-muted text-muted-foreground border-border",error:"bg-red-500/15 text-red-400 border-red-500/30"};function Un(){var b;const{toast:t}=Ae(),[s,a]=d.useState(730),[r,n]=d.useState(""),[o,l]=d.useState(!1),[c,x]=d.useState(null),[g,u]=d.useState(null),i=d.useRef(null),h=async f=>{l(!0);try{const{data:{session:p}}=await T.auth.getSession(),{data:j,error:L}=await T.functions.invoke("admin-backfill-all-renewals",{body:{sinceDays:s,dryRun:f,...r.trim()?{email:r.trim()}:{}},headers:p!=null&&p.access_token?{Authorization:`Bearer ${p.access_token}`}:{}});if(L)throw L;j!=null&&j.run_id?(x(j.run_id),t({title:f?"Dry-run started":"Backfill started",description:`Run ${j.run_id.slice(0,8)}… processing in the background.`})):t({title:"No run started",description:(j==null?void 0:j.note)??"Unknown response",variant:"destructive"})}catch(p){t({title:"Start failed",description:p instanceof Error?p.message:String(p),variant:"destructive"})}finally{l(!1)}},m=async f=>{try{const{data:{session:p}}=await T.auth.getSession(),{data:j,error:L}=await T.functions.invoke("admin-backfill-status",{body:f?{run_id:f}:{},headers:p!=null&&p.access_token?{Authorization:`Bearer ${p.access_token}`}:{}});if(L)throw L;u(j),j!=null&&j.run_id&&!c&&x(j.run_id)}catch(p){console.error("status fetch failed",p)}};d.useEffect(()=>{if(c)return m(c),i.current=window.setInterval(()=>m(c),5e3),()=>{i.current&&window.clearInterval(i.current)}},[c]);const v=()=>{if(!g)return;const f=[...g.grantedSample??[],...g.tail??[]];if(!f.length)return;const p=["status","email","invoice_id","subscription_id","plan_tier","credits","amount_paid_cents","billing_reason","grant_key","reason","created_at"],j=[p.join(",")].concat(f.map(P=>p.map(D=>JSON.stringify(P[D]??"")).join(","))).join(`
127`),L=new Blob([j],{type:"text/csv"}),w=URL.createObjectURL(L),_=document.createElement("a");_.href=w,_.download=`renewal-backfill-${g.run_id}.csv`,_.click(),URL.revokeObjectURL(w)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(O,{className:"border-border/50 bg-card/50",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center gap-2 text-base",children:[e.jsx(ft,{className:"h-4 w-4"}),"Renewal Credit Recovery (Full History)"]})}),e.jsxs(E,{className:"space-y-4 text-sm text-muted-foreground",children:[e.jsxs("p",{children:["Scans every paid Stripe subscription invoice in the lookback window and grants any missing renewal credits idempotently. Safe to re-run — already-granted cycles are skipped via the ",e.jsx("code",{className:"text-[11px]",children:"cycle_<sub>_<periodStart>"})," key. Runs in the background; results stream into the audit table below."]}),e.jsxs("div",{className:"flex gap-2 items-start text-xs bg-amber-500/10 border border-amber-500/30 rounded-md p-3",children:[e.jsx(Ct,{className:"h-4 w-4 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-amber-200 font-medium",children:"Recommended workflow"}),e.jsxs("p",{className:"text-muted-foreground mt-1",children:["1) Run a ",e.jsx("strong",{children:"dry run"})," first to see counts. 2) Review the orphan / unknown-price tail. 3) Run the live backfill. Re-running is free — only missing grants get inserted."]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3 items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ht,{htmlFor:"sinceDays",className:"text-xs",children:"Lookback (days)"}),e.jsx(me,{id:"sinceDays",type:"number",min:1,max:3650,value:s,onChange:f=>a(parseInt(f.target.value)||730),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1 md:col-span-2",children:[e.jsx(ht,{htmlFor:"email",className:"text-xs",children:"Filter by customer email (optional)"}),e.jsx(me,{id:"email",type:"email",placeholder:"[email protected]",value:r,onChange:f=>n(f.target.value),className:"h-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:o,onClick:()=>h(!0),children:[o?e.jsx(V,{className:"h-3 w-3 mr-1 animate-spin"}):e.jsx(gt,{className:"h-3 w-3 mr-1"}),"Dry run"]}),e.jsxs($,{size:"sm",disabled:o,onClick:()=>h(!1),children:[o?e.jsx(V,{className:"h-3 w-3 mr-1 animate-spin"}):e.jsx(gt,{className:"h-3 w-3 mr-1"}),"Run live"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>m(c),children:"Refresh latest run"}),(g==null?void 0:g.run_id)&&e.jsx($,{variant:"ghost",size:"sm",onClick:v,children:"Export CSV"})]})]})]}),g&&e.jsxs(O,{className:"border-border/50 bg-card/50",children:[e.jsx(z,{children:e.jsxs(U,{className:"text-base",children:["Run ",((b=g.run_id)==null?void 0:b.slice(0,8))??"—","… · scanned ",g.totalScanned," · granted credits ",g.totalGrantedCredits.toLocaleStr
127ing()]})}),e.jsxs(E,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(g.summary).map(([f,p])=>e.jsxs(A,{variant:"outline",className:Ws[f]??"",children:[f,": ",p]},f)),e.jsxs(A,{variant:"outline",children:["amount paid: $",(g.totalAmountCents/100).toFixed(2)]})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium text-foreground mb-2",children:["Needs review (",g.tail.length,")"]}),g.tail.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No orphan / unknown-price / error rows. "}):e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{children:[e.jsx(k,{children:"Status"}),e.jsx(k,{children:"Email"}),e.jsx(k,{children:"Invoice"}),e.jsx(k,{children:"Subscription"}),e.jsx(k,{children:"Amount"}),e.jsx(k,{children:"Reason"})]})}),e.jsx(ue,{children:g.tail.map(f=>{var p,j;return e.jsxs(G,{children:[e.jsx(N,{children:e.jsx(A,{variant:"outline",className:Ws[f.status]??"",children:f.status})}),e.jsx(N,{className:"text-xs",children:f.email??"—"}),e.jsxs(N,{className:"text-xs font-mono",children:[(p=f.invoice_id)==null?void 0:p.slice(0,18),"…"]}),e.jsx(N,{className:"text-xs font-mono",children:((j=f.subscription_id)==null?void 0:j.slice(0,18))??"—"}),e.jsx(N,{className:"text-xs",children:f.amount_paid_cents!=null?`$${(f.amount_paid_cents/100).toFixed(2)}`:"—"}),e.jsx(N,{className:"text-xs text-muted-foreground",children:f.reason??""})]},f.id)})})]})]}),g.grantedSample.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Recently granted (latest 50)"}),e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{children:[e.jsx(k,{children:"Email"}),e.jsx(k,{children:"Plan"}),e.jsx(k,{children:"Credits"}),e.jsx(k,{children:"Invoice"}),e.jsx(k,{children:"Grant key"})]})}),e.jsx(ue,{children:g.grantedSample.map(f=>{var p;return e.jsxs(G,{children:[e.jsx(N,{className:"text-xs",children:f.email??"—"}),e.jsx(N,{className:"text-xs",children:f.plan_tier??"—"}),e.jsx(N,{className:"text-xs",children:f.credits??0}),e.jsxs(N,{className:"text-xs font-mono",children:[(p=f.invoice_id)==null?void 0:p.slice(0,18),"…"]}),e.jsx(N,{className:"text-[10px] font-mono text-muted-foreground",children:f.grant_key??"—"})]},f.id)})})]})]})]})]})]})}const Ue=t=>`$${(t/100).toFixed(2)}`;function Bn(){const[t,s]=d.useState(!1),[a,r]=d.useState([]),[n,o]=d.useState(14),l=async()=>{s(!0);try{const m=new Date(Date.now()-n*864e5).toISOString(),{data:v,error:b}=await T.from("payment_attempt_log").select("stripe_charge_id, email, amount_cents, status, failure_class, decline_reason, risk_score, risk_level, payment_method, card_last4, verified_customer, created_at").gte("created_at",m).order("created_at",{ascending:!1}).limit(1e3);if(b)throw b;r(v||[])}catch{r([])}finally{s(!1)}};d.useEffect(()=>{l()},[n]);const c=a.filter(m=>m.status==="failed"),x=c.filter(m=>m.failure_class==="blocked_by_stripe"),g=c.filter(m=>m.failure_class==="issuer_declined"),u=a.filter(m=>m.status==="succeeded"),i=m=>m.reduce((v,b)=>v+(b.amount_cents||0),0),h=x.filter(m=>m.verified_customer);return e.jsx(O,{children:e.jsxs(E,{className:"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(sr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-semibold",children:"Payment health"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["last ",n,"d"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>o(n===14?3:14),children:n===14?"3d":"14d"}),e.jsx($,{variant:"ghost",size:"sm",onClick:l,disabled:t,children:t?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(ve,{className:"h-4 w-4"})})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[u.length," succeeded (",Ue(i(u)),") ·"," ",x.length," blocked by Stripe (",Ue(i(x)),") ·"," ",g.length," bank declines (",Ue(i(g)),")"]}),h.length>0&&e.jsxs("div",{className:"rounded-lg border border-destructive/40 bg-destructive/10 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-destructive",children:[e.jsx(ss,{className:"h-4 w-4"}),h.length," verified customer",h.length>
1271?"s":""," blocked — reach out today"]}),h.slice(0,5).map(m=>e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.email??"unknown"," · ",Ue(m.amount_cents)," · risk ",m.risk_score??"?"," ·"," ",new Date(m.created_at).toLocaleString()]},m.stripe_charge_id))]}),e.jsxs("div",{className:"space-y-1",children:[a.length===0&&!t&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No payment telemetry in this window yet."}),c.slice(0,25).map(m=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm border-t border-border/50 pt-1",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"font-medium",children:m.email??"unknown"}),e.jsxs("span",{className:"text-muted-foreground",children:[" ","· ",Ue(m.amount_cents)," · ",m.payment_method??"?",m.card_last4?` …${m.card_last4}`:""," · ",new Date(m.created_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[m.risk_score!==null&&e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["risk ",m.risk_score]}),e.jsx(A,{variant:m.failure_class==="blocked_by_stripe"?"destructive":"secondary",className:"text-xs",children:m.failure_class==="blocked_by_stripe"?"Stripe block":m.failure_class==="issuer_declined"?`Bank: ${m.decline_reason??"declined"}`:m.failure_class??"failed"})]})]},m.stripe_charge_id))]})]})})}function Wn(){const t=new Date(Date.now()-2592e6).toISOString(),{data:s=[]}=Kt({queryKey:["admin-paypal-tx"],queryFn:async()=>{const{data:g,error:u}=await T.from("credit_transactions").select("id, user_id, amount, type, description, provider_ref, created_at").eq("provider","paypal").gte("created_at",t).order("created_at",{ascending:!1}).limit(200);if(u)throw u;return g??[]}}),{data:a=[]}=Kt({queryKey:["admin-paypal-events"],queryFn:async()=>{const{data:g,error:u}=await T.from("paypal_events").select("event_id, event_type, resource_id, handled, note, created_at").gte("created_at",t).order("created_at",{ascending:!1}).limit(200);if(u)throw u;return g??[]}}),r=s.filter(g=>g.type==="purchase"),n=s.filter(g=>g.type==="revoke"),o=a.filter(g=>g.event_type.startsWith("CUSTOMER.DISPUTE")),l=o.filter(g=>g.event_type==="CUSTOMER.DISPUTE.CREATED"),c=a.filter(g=>!g.handled&&g.event_type!=="SWEEP.RUN"),x=a.find(g=>g.event_type==="SWEEP.RUN");return e.jsxs(O,{className:"mb-6",children:[e.jsx(z,{className:"pb-3",children:e.jsxs(U,{className:"flex items-center gap-2 text-lg",children:[e.jsx($a,{className:"h-5 w-5"})," PayPal activity — last 30 days"]})}),e.jsxs(E,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-sm",children:[e.jsx(rt,{label:"Purchases",value:r.length}),e.jsx(rt,{label:"Credits granted",value:r.reduce((g,u)=>g+u.amount,0).toLocaleString()}),e.jsx(rt,{label:"Refunds / reversals",value:n.length}),e.jsx(rt,{label:"Disputes opened",value:l.length,tone:l.length?"bad":void 0})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[c.length," PayPal notification(s) arrived but were not processed — check the logs."]}),o.length>0&&e.jsx("div",{className:"space-y-1 border-t border-border/50 pt-2",children:o.slice(0,8).map(g=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[e.jsx("span",{className:"font-mono truncate",children:g.resource_id??g.event_id}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(A,{variant:g.event_type==="CUSTOMER.DISPUTE.CREATED"?"destructive":"secondary",className:"text-[10px]",children:g.event_type.replace("CUSTOMER.DISPUTE.","")}),e.jsx("span",{className:"text-muted-foreground",children:new Date(g.created_at).toLocaleDateString()})]})]},g.event_id))}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Daily dispute check last ran:"," ",x?new Date(x.created_at).toLocaleString():"never",". Disputes must be answered inside PayPal before their deadline."]})]})]})}function rt({label:t,value:s,tone:a}){return e.jsxs("div",{className:"rounded-lg border border-border/60 bg-card/40 p-2",children:[e.jsx("div",{className:`text-xl font-bold ${a==="bad"?"text-destructive":""}`,children:s}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:t})]})}const qn=[{label:"Last 24h",hours:24},{label:"Last 7 days",hours:24*7}];function Gn(){const{data:t,isError:s}=Kt({queryKey:["admin-checkout-attempts"],queryFn:async()=>{const i=new Date(Date.now()-6048e5).toISOString(),{data:h,error:m}=await T.from("checkout_attempts").select("id, email, pack_id, order_id, funding_source, device, stage, failure_reason, created_at, user_id, clicked_at, form_shown_at").gte("created_at",i).order("created_at",{ascending:!1}).limit(1e3);if(m)throw m;return h??[]},retry:!1}),a=t??[],r=i=>{const h=Date.now()-i*3600*1e3;return a.filter(m=>new Date(m.created_at).getTime()>=h)},n=i=>({started:i.length,approved:i.filter(h=>h.stage!=="started").length,completed:i.filter(h=>h.stage==="completed").length}),o=r(24*7).filter(i=>i.stage!=="completed"),l=r(24*7),c=l.filter(i=>i.stage==="failed"&&/DECLINED|card_declined/.test(i.failure_reason??"")),x=new Set(c.map(i=>
127i.user_id)),g=[...x].filter(i=>l.some(h=>h.user_id===i&&h.stage==="completed"&&c.some(m=>m.user_id===i&&h.created_at>m.created_at))).length,u=i=>{const h=l.filter(m=>m.device===i&&m.clicked_at&&m.form_shown_at).map(m=>(new Date(m.form_shown_at).getTime()-new Date(m.clicked_at).getTime())/1e3).filter(m=>m>=0&&m<120).sort((m,v)=>m-v);return h.length?{n:h.length,med:h[Math.floor(h.length/2)]}:null};return e.jsxs(O,{className:"mb-6",children:[e.jsx(z,{className:"pb-3",children:e.jsxs(U,{className:"flex items-center gap-2 text-lg",children:[e.jsx(gn,{className:"h-5 w-5"})," Checkout funnel"]})}),e.jsxs(E,{className:"space-y-4",children:[s&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Checkout tracking starts collecting once this update is live."}),qn.map(({label:i,hours:h})=>{const m=r(h),v=n(m),b=v.started?Math.round(v.completed/v.started*100):0,f=["paypal","card"].map(j=>{const L=m.filter(w=>w.funding_source===j);return{f:j,started:L.length,completed:L.filter(w=>w.stage==="completed").length}}),p=["desktop","mobile"].map(j=>{const L=m.filter(w=>w.device===j);return{d:j,started:L.length,completed:L.filter(w=>w.stage==="completed").length}});return e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:i}),e.jsxs(A,{variant:b<50&&v.started>3?"destructive":"secondary",children:[b,"% completed"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-sm",children:[e.jsx(Et,{label:"Started",value:v.started}),e.jsx(Et,{label:"Approved",value:v.approved}),e.jsx(Et,{label:"Completed",value:v.completed})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-[11px] text-muted-foreground",children:[e.jsx("div",{children:f.map(j=>e.jsxs("div",{children:[j.f==="card"?"Card button":"PayPal button",": ",j.completed,"/",j.started]},j.f))}),e.jsx("div",{children:p.map(j=>e.jsxs("div",{children:[j.d,": ",j.completed,"/",j.started]},j.d))})]})]},i)}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 text-[12px] space-y-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Declines & tap-to-form wait (7 days)"}),e.jsxs("div",{children:["Bank declines: ",c.length," attempts from ",x.size," customers · ",g," later bought"]}),["mobile","desktop"].map(i=>{const h=u(i);return e.jsxs("div",{className:"text-muted-foreground",children:[i," wait from tap to payment form: ",h?`${h.med.toFixed(1)}s median (${h.n} taps)`:"collecting…"]},i)})]}),o.length>0&&e.jsxs("div",{className:"space-y-1 border-t border-border/50 pt-2",children:[e.jsx("p",{className:"text-xs font-medium",children:"Abandoned orders (7 days)"}),o.slice(0,20).map(i=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px]",children:[e.jsx("span",{className:"font-mono truncate",children:i.order_id??i.id}),e.jsx("span",{className:"truncate text-muted-foreground",children:i.email??"—"}),e.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[i.funding_source??"?"," · ",i.device??"?"," · ",i.stage,i.failure_reason?` · ${i.failure_reason.slice(0,40)}`:""]})]},i.id))]})]})]})}function Et({label:t,value:s}){return e.jsxs("div",{className:"rounded-lg border border-border/60 bg-card/40 p-2",children:[e.jsx("div",{className:"text-xl font-bold",children:s}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:t})]})}const qs={granted:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30","dry-run":"bg-blue-500/15 text-blue-400 border-blue-500/30","already-granted":"bg-muted text-muted-foreground border-border",orphan:"bg-amber-500/15 text-amber-400 border-amber-500/30",error:"bg-red-500/15 text-red-400 border-red-500/30"};function Vn(){var i,h,m,v;const{toast:t}=Ae(),[s,a]=d.useState(!1),[r,n]=d.useState(null),[o,l]=d.useState(null),c=d.useRef(null),x=async b=>{if(!(!b&&!window.confirm("Live run will grant credits and send emails to every paying customer. Continue?"))){a(!0);try{const{data:{session:f}}=await T.auth.getSession(),{data:p,error:j}=await T.functions.invoke("admin-appreciation-drop",{body:{dryRun:b},headers:f!=null&&f.access_token?{Authorization:`Bearer ${f.access_token}`}:{}});if(j)throw j;
127p!=null&&p.run_id&&(n(p.run_id),t({title:b?"Dry-run started":"Live appreciation drop started",description:`Run ${p.run_id.slice(0,8)}… processing in the background.`}))}catch(f){t({title:"Start failed",description:f instanceof Error?f.message:String(f),variant:"destructive"})}finally{a(!1)}}},g=async b=>{try{const{data:{session:f}}=await T.auth.getSession(),{data:p,error:j}=await T.functions.invoke("admin-appreciation-status",{body:b?{run_id:b}:{},headers:f!=null&&f.access_token?{Authorization:`Bearer ${f.access_token}`}:{}});if(j)throw j;l(p),p!=null&&p.run_id&&!r&&n(p.run_id)}catch(f){console.error("status fetch failed",f)}};d.useEffect(()=>(g(r),c.current=window.setInterval(()=>g(r),5e3),()=>{c.current&&window.clearInterval(c.current)}),[r]);const u=()=>{if(!o)return;const b=[...o.grantedSample??[],...o.tail??[]];if(!b.length)return;const f=["status","tier","email","lifetime_cents","credits_granted","coupon_code","email_status","reason","created_at"],p=[f.join(",")].concat(b.map(_=>f.map(P=>JSON.stringify(_[P]??"")).join(","))).join(`
128`),j=new Blob([p],{type:"text/csv"}),L=URL.createObjectURL(j),w=document.createElement("a");w.href=L,w.download=`appreciation-drop-${o.run_id}.csv`,w.click(),URL.revokeObjectURL(L)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(O,{className:"border-border/50 bg-card/50",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center gap-2 text-base",children:[e.jsx(ia,{className:"h-4 w-4"}),"Customer Appreciation Drop (one-time)"]})}),e.jsxs(E,{className:"space-y-4 text-sm text-muted-foreground",children:[e.jsxs("p",{children:["Iterates every Stripe customer with lifetime spend > $0, classifies whales (≥ $200) vs paying, and grants credits. Idempotent via"," ",e.jsx("code",{className:"text-[11px]",children:"appreciation_2026_<userId>"})," — safe to re-run."]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{className:"rounded-md border border-blue-500/20 bg-blue-500/5 p-3",children:[e.jsx("p",{className:"text-blue-300 font-medium",children:"Paying tier (< $200 lifetime)"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"500 credits"})]}),e.jsxs("div",{className:"rounded-md border border-pink-500/20 bg-pink-500/5 p-3",children:[e.jsx("p",{className:"text-pink-300 font-medium",children:"Whale tier (≥ $200 lifetime)"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"2,500 credits"})]})]}),e.jsxs("div",{className:"flex gap-2 items-start text-xs bg-amber-500/10 border border-amber-500/30 rounded-md p-3",children:[e.jsx(Ct,{className:"h-4 w-4 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-amber-200 font-medium",children:"Recommended workflow"}),e.jsxs("p",{className:"text-muted-foreground mt-1",children:["1) Run a ",e.jsx("strong",{children:"dry run"})," first to see counts and orphan rows. 2) Spot-check the granted/orphan tail. 3) Run live — emails enqueue automatically."]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:s,onClick:()=>x(!0),children:[s?e.jsx(V,{className:"h-3 w-3 mr-1 animate-spin"}):e.jsx(gt,{className:"h-3 w-3 mr-1"}),"Dry run"]}),e.jsxs($,{size:"sm",disabled:s,onClick:()=>x(!1),children:[s?e.jsx(V,{className:"h-3 w-3 mr-1 animate-spin"}):e.jsx(gt,{className:"h-3 w-3 mr-1"}),"Run live"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(r),children:"Refresh"}),(o==null?void 0:o.run_id)&&e.jsx($,{variant:"ghost",size:"sm",onClick:u,children:"Export CSV"})]})]})]}),o&&e.jsxs(O,{className:"border-border/50 bg-card/50",children:[e.jsx(z,{children:e.jsxs(U,{className:"text-base",children:["Run ",((i=o.run_id)==null?void 0:i.slice(0,8))??"—","… · scanned ",o.totalScanned??0," · credits ",(o.totalCredits??0).toLocaleString()," · lifetime $",((o.totalLifetimeCents??0)/100).toLocaleString(void 0,{maximumFractionDigits:0})]})}),e.jsxs(E,{className:"space-y-4",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(o.summary??{}).map(([b,f])=>e.jsxs(A,{variant:"outline",className:qs[b]??"",children:[b,": ",f]},b))}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium text-foreground mb-2",children:["Needs review (",((h=o.tail)==null?void 0:h.length)??0,")"]}),(((m=o.tail)==null?void 0:m.length)??0)===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No orphan / error rows."}):e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{children:[e.jsx(k,{children:"Status"}),e.jsx(k,{children:"Email"}),e.jsx(k,{children:"Customer"}),e.jsx(k,{children:"Lifetime"}),e.jsx(k,{children:"Reason"})]})}),e.jsx(ue,{children:(o.tail??[]).map(b=>{var f;return e.jsxs(G,{children:[e.jsx(N,{children:e.jsx(A,{variant:"outline",className:qs[b.status]??"",children:b.status})}),e.jsx(N,{className:"text-xs",children:b.email??"—"}),e.jsxs(N,{className:"text-[11px] font-mono",children:[((f=b.stripe_customer_id)==null?void 0:f.slice(0,18))??"—","…"]}),e.jsxs(N,{className:"text-xs",children:["$",(b.lifetime_cents/100).toFixed(2)]}),e.jsx(N,{className:"text-xs text-muted-foreground",children:b.reason??""})]},b.id)})})]})]}),(((v=o.grantedSample)==null?void 0:v.length)??0)>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Granted sample (latest 50)"}),e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{children:[e.jsx(k,{children:"Tier"}),e.jsx(k,{children:"Email"}),e.jsx(k,{children:"Lifetime"}),e.jsx(k,{children:"Credits"}),e.jsx(k,{children:"Coupon"}),e.jsx(k,{children:"Email"})]})}),e.jsx(ue,{children:(o.grantedSample??[]).map(b=>e.jsxs(G,{children:[e.jsx(N,{children:e.jsx(A,{variant:"outline",className:b.tier==="whale"?"bg-pink-500/15 text-pink-400 border-pink-500/30":"bg-blue-500/15 text-blue-400 border-blue-500/30",children:b.tier})}),e.jsx(N,{className:"text-xs",children:b.email??"—"}),e.jsxs(N,{className:"text-xs",children:["$",(b.lifetime_cents/100).toFixed(2)]}),e.jsx(N,{className:"text-xs",children:b.credits_granted.toLocaleStr
128ing()}),e.jsx(N,{className:"text-[11px] font-mono",children:b.coupon_code??"—"}),e.jsx(N,{className:"text-[11px] text-muted-foreground truncate max-w-[160px]",children:b.email_status??"—"})]},b.id))})]})]})]})]})]})}function Hn({open:t,onOpenChange:s}){const[a,r]=d.useState(!1),[n,o]=d.useState(7),[l,c]=d.useState(null),[x,g]=d.useState(null),u=d.useCallback(async()=>{r(!0),g(null);try{const{data:b,error:f}=await T.functions.invoke("admin-a2e-audit",{body:{sinceDays:n}});if(f)throw f;c(b)}catch(b){g(b instanceof Error?b.message:String(b))}finally{r(!1)}},[n]),i=((l==null?void 0:l.summary.orphan_in_a2e.videos)??0)+((l==null?void 0:l.summary.orphan_in_a2e.images)??0),h=((l==null?void 0:l.summary.orphan_in_db.videos)??0)+((l==null?void 0:l.summary.orphan_in_db.images)??0),m=((l==null?void 0:l.buckets)??[]).filter(b=>b.bucket==="orphan_in_a2e"),v=((l==null?void 0:l.buckets)??[]).filter(b=>b.bucket==="orphan_in_db");return e.jsx(la,{open:t,onOpenChange:s,children:e.jsxs(ca,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(da,{children:e.jsx(oa,{children:"A2E ↔ Database Audit"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Window:"}),[1,7,30].map(b=>e.jsx($,{size:"sm",variant:n===b?"default":"outline",onClick:()=>o(b),children:b===1?"24h":`${b}d`},b)),e.jsxs($,{size:"sm",onClick:u,disabled:a,className:"ml-auto",children:[a?e.jsx(V,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(ve,{className:"h-4 w-4 mr-2"}),"Run audit"]})]}),x&&e.jsx("div",{className:"text-sm text-destructive bg-destructive/10 rounded p-3",children:x}),!l&&!a&&e.jsxs("div",{className:"text-sm text-muted-foreground py-8 text-center",children:["Click ",e.jsx("span",{className:"font-medium",children:"Run audit"})," to compare A2E history against your database."]}),a&&!l&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(V,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsx($t,{label:"In sync",videos:l.summary.in_sync.videos,images:l.summary.in_sync.images,tone:"ok"}),e.jsx($t,{label:"Orphan in A2E ⚠️",videos:l.summary.orphan_in_a2e.videos,images:l.summary.orphan_in_a2e.images,tone:i>0?"alert":"neutral"}),e.jsx($t,{label:"Orphan in DB",videos:l.summary.orphan_in_db.videos,images:l.summary.orphan_in_db.images,tone:"neutral"})]}),i>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 p-3",children:[e.jsx(fe,{className:"h-4 w-4 text-destructive mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium text-destructive",children:[i," A2E task(s) have NO matching row in your database."]}),e.jsx("div",{className:"text-muted-foreground mt-1",children:"This means generations ran on A2E (and used your credits with them) but no user got billed in your app, OR something is calling your A2E key from outside this project. Investigate before publishing."})]})]}):e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border bg-muted/30 p-3",children:[e.jsx(we,{className:"h-4 w-4 text-primary mt-0.5 flex-shrink-0"}),e.jsx("div",{className:"text-sm",children:"Every A2E task in this window is accounted for in your database. No leak detected."})]}),(l.summary.a2e_fetch_errors.videos||l.summary.a2e_fetch_errors.images)&&e.jsxs("div",{className:"text-xs text-muted-foreground bg-muted/30 rounded p-2",children:[e.jsx("div",{className:"font-medium mb-1",children:"A2E fetch warnings:"}),l.summary.a2e_fetch_errors.videos&&e.jsxs("div",{children:["Videos: ",l.summary.a2e_fetch_errors.videos]}),l.summary.a2e_fetch_errors.images&&e.jsxs("div",{children:["Images: ",l.summary.a2e_fetch_errors.images]})]}),e.jsxs(as,{defaultValue:"orphan_in_a2e",children:[e.jsxs(rs,{children:[e.jsxs(J,{value:"orphan_in_a2e",children:["Orphan in A2E (",i,")"]}),e.jsxs(J,{value:"orphan_in_db",children:["Orphan in DB (",h,")"]})]}),e.jsx(ee,{value:"orphan_in_a2e",children:e.jsx(Gs,{items:m})}),e.jsx(ee,{value:"orphan_in_db",children:e.jsx(Gs,{items:v})})]})]})]})]})})}function $t({label:t,videos:s,images:a,tone:r}){const n=r==="alert"?"border-destructive/50":r==="ok"?"border-primary/30":"border-border";return e.jsxs("div",{className:`rounded-md border ${n} bg-muted/20 p-3`,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:t}),e.jsxs("div",{className:"mt-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:s})," ",e.jsx("span",{className:"text-muted-foreground",children:"videos"})]}),e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:a})," ",e.jsx("span",{className:"text-muted-foreground",children:"images"})]})]})}function Gs({items:t}){return t.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"Nothing in this bucket. ✅"}):e.jsx("div",{className:"border rounded-md divide-y mt-2 max-h-96 overflow-y-auto",children:t.map(s=>e.jsxs("div",{className:"p-3 text-sm space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(A,{variant:"outline",className:"text-xs",children:s.type}),s.status&&e.jsx(A,{variant:"secondary",className:"text-xs",children:s.status}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground break-all",children:s.task_id}),s.created_at&&e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:new Date(s.created_at).toLocaleStr
128ing()})]}),s.prompt&&e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-2",children:s.prompt}),s.url&&e.jsx("a",{href:s.url,target:"_blank",rel:"noreferrer",className:"text-xs text-primary hover:underline break-all",children:s.url})]},`${s.type}-${s.task_id}`))})}const Kn=[{label:"24h",days:1},{label:"7d",days:7},{label:"30d",days:30},{label:"All",days:0}],Yn=[500,1e3,2e3];function Xn(t){const s=Math.max(1,Math.floor((Date.now()-new Date(t).getTime())/1e3));if(s<60)return`${s}s ago`;const a=Math.floor(s/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Vs(t){return t==="completed"?"default":t==="failed"?"destructive":t==="processing"||t==="pending"?"secondary":"outline"}function Zn({src:t,type:s,status:a}){const[r,n]=d.useState(!1);d.useEffect(()=>n(!1),[t]);const o=t&&!r,l=!o&&a==="completed";return e.jsx("div",{className:"w-14 h-14 rounded-md bg-muted overflow-hidden flex-shrink-0 flex flex-col items-center justify-center gap-0.5",children:o?e.jsx("img",{src:t,alt:"",className:"w-full h-full object-cover",loading:"lazy",onError:()=>n(!0)}):e.jsxs(e.Fragment,{children:[s==="video"?e.jsx(wt,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(kt,{className:"h-4 w-4 text-muted-foreground"}),l&&e.jsx("span",{className:"text-[9px] leading-none text-muted-foreground",children:"expired"})]})})}function Qn(){const[t,s]=d.useState([]),[a,r]=d.useState(null),[n,o]=d.useState(null),[l,c]=d.useState(!0),[x,g]=d.useState(""),[u,i]=d.useState("all"),[h,m]=d.useState("all"),[v,b]=d.useState(7),[f,p]=d.useState(500),[j,L]=d.useState(null),w=ua((j==null?void 0:j.image_url)??null),[_,P]=d.useState(!1),D=d.useCallback(async()=>{c(!0);try{const{data:y,error:B}=await T.functions.invoke("admin-live-feed",{body:{limit:f,sinceDays:v}});if(B)throw B;s((y==null?void 0:y.items)??[]),r((y==null?void 0:y.totals)??null),o((y==null?void 0:y.reconcile)??null)}catch(y){console.error("[LiveFeed] load failed",y)}finally{c(!1)}},[f,v]);d.useEffect(()=>{D()},[D]);const I=d.useMemo(()=>{const y=x.trim().toLowerCase();return t.filter(B=>{if(u!=="all"&&B.type!==u)return!1;if(h!=="all"){if(h==="processing"){if(B.status!=="processing"&&B.status!=="pending")return!1}else if(B.status!==h)return!1}if(y){const X=B.type==="video"?ar(B).label:"";if(!`${B.email??""} ${B.full_name??""} ${B.prompt??""} ${B.user_id} ${B.a2e_task_id??""} ${X}`.toLowerCase().includes(y))return!1}return!0})},[t,x,u,h]),Q=d.useMemo(()=>I.slice(0,150).map(y=>y.thumbnail_url??y.image_url),[I]),Z=ma(Q),te=((a==null?void 0:a.videos)??0)+((a==null?void 0:a.images)??0),S=te>0&&t.length>=f,C=n?(n.failed_no_task_id_videos_7d??0)+(n.failed_no_task_id_images_7d??0)+(n.stuck_processing_videos??0)+(n.stuck_processing_images??0):0;return e.jsxs("div",{className:"space-y-4",children:[n&&e.jsx(O,{children:e.jsxs(E,{className:"pt-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[C>0?e.jsx(fe,{className:"h-4 w-4 text-destructive"}):e.jsx(mn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Pipeline health"})]}),e.jsx(Hs,{label:"Failed before A2E (7d)",value:n.failed_no_task_id_videos_7d+n.failed_no_task_id_images_7d,tone:"warn"}),e.jsx(Hs,{label:"Stuck processing >30m",value:n.stuck_processing_videos+n.stuck_processing_images,tone:"warn"}),e.jsx($,{size:"sm",variant:"default",onClick:()=>P(!0),className:"ml-auto",children:"Reconcile with A2E"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-3",children:`"Failed before A2E" = we recorded a generation but A2E never accepted it. "Stuck processing" = we submitted but never heard back. Run the A2E reconcile to catch tasks billed by A2E that aren't in our DB.`})]})}),e.jsxs(O,{children:[e.jsxs(z,{className:"flex flex-row items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(U,{children:"Live Generation Feed"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Every generation, with the profile that owns it. Updates in real time."})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:D,disabled:l,children:[l?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(ve,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Refresh"})]})]}),e.jsxs(E,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Window:"}),Kn.map(y=>e.jsx($,{size:"sm",variant:v===y.days?"default":"outline",onClick:()=>b(y.days),children:y.label},y.days)),e.jsx("span",{className:"text-xs text-muted-foreground ml-4",children:"Limit:"}),Yn.map(y=>e.jsx($,{size:"sm",variant:f===y?"default":"outline",onClick:()=>p(y),children:y},y))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Loaded ",e.jsx("span",{className:"font-medium text-foreground",children:t.length})," ","of"," ",e.jsxs("span",{className:"font-medium text-foreground",children:["~",te.toLocaleStr
128ing()]})," ","in ",v===0?"all time":`last ${v}d`,S&&e.jsx("span",{className:"ml-2 text-destructive",children:"— increase limit or shorten window to see everything"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(me,{placeholder:"Search by email, name, prompt, user id, or A2E task id…",value:x,onChange:y=>g(y.target.value),className:"max-w-sm"}),e.jsx("div",{className:"flex gap-1",children:["all","video","image"].map(y=>e.jsx($,{size:"sm",variant:u===y?"default":"outline",onClick:()=>i(y),children:y==="all"?"All types":y==="video"?"Videos":"Images"},y))}),e.jsx("div",{className:"flex gap-1",children:["all","completed","processing","failed"].map(y=>e.jsx($,{size:"sm",variant:h===y?"default":"outline",onClick:()=>m(y),children:y==="all"?"All status":y.charAt(0).toUpperCase()+y.slice(1)},y))}),e.jsxs("div",{className:"ml-auto text-sm text-muted-foreground self-center",children:[I.length," shown"]})]}),l&&t.length===0?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(V,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):I.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:"No generations match the current filters."}):e.jsx("div",{className:"border rounded-lg divide-y overflow-hidden",children:I.map(y=>{const B=y.thumbnail_url??y.image_url,X=B?Z[B]??B:null;return e.jsxs("button",{onClick:()=>L(y),className:"w-full flex items-center gap-3 p-3 hover:bg-accent/50 text-left transition-colors",children:[e.jsx(Zn,{src:X,type:y.type,status:y.status}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(A,{variant:"outline",className:"text-xs",children:[y.type==="video"?e.jsx(wt,{className:"h-3 w-3 mr-1"}):e.jsx(kt,{className:"h-3 w-3 mr-1"}),y.type]}),e.jsx("span",{className:"text-sm font-medium truncate",children:y.email??e.jsx("span",{className:"text-muted-foreground italic",children:"no profile"})}),e.jsx(A,{variant:Vs(y.status),className:"text-xs",children:y.status}
128),y.type==="video"&&e.jsx(Gt,{model:y.model,quality:y.quality,target_duration:y.target_duration,credits_used:y.credits_used})]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate mt-0.5",children:y.prompt})]}),e.jsxs("div",{className:"text-right flex-shrink-0 text-xs text-muted-foreground space-y-0.5",children:[e.jsx("div",{children:Xn(y.created_at)}),e.jsxs("div",{children:["−",y.credits_used," cr"]}),e.jsxs("div",{className:"text-foreground/80",children:["After: ",y.balance_after??"—"]}),e.jsxs("div",{children:["Now: ",y.current_balance??"—"]})]})]},`${y.type}-${y.id}`)})})]})]}),e.jsx(la,{open:!!j,onOpenChange:y=>!y&&L(null),children:e.jsxs(ca,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(da,{children:e.jsx(oa,{children:"Generation details"})}),j&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-muted rounded-md overflow-hidden flex items-center justify-center max-h-96",children:j.type==="video"&&j.video_url?e.jsx("video",{src:j.video_url,controls:!0,className:"max-h-96 w-full"}):j.image_url||j.thumbnail_url?e.jsx("img",{src:w??j.thumbnail_url??"",alt:"",className:"max-h-96 w-auto"}):e.jsx("div",{className:"p-12 text-muted-foreground text-sm",children:j.status==="completed"?"Media expired — files are auto-deleted after 3 days":"No media yet"})}),e.jsxs("dl",{className:"grid grid-cols-[120px_1fr] gap-y-2 text-sm",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Type"}),e.jsx("dd",{children:j.type}),e.jsx("dt",{className:"text-muted-foreground",children:"Status"}),e.jsxs("dd",{children:[e.jsx(A,{variant:Vs(j.status),children:j.status}),j.type==="video"&&e.jsx(Gt,{model:j.model,quality:j.quality,target_duration:j.target_duration,credits_used:j.credits_used,className:"ml-2"})]}),e.jsx("dt",{className:"text-muted-foreground",children:"Email"}),e.jsx("dd",{className:"break-all",children:j.email??"—"}),e.jsx("dt",{className:"text-muted-foreground",children:"Name"}),e.jsx("dd",{children:j.full_name??"—"}),e.jsx("dt",{className:"text-muted-foreground",children:"User ID"}),e.jsx("dd",{className:"font-mono text-xs break-all",children:j.user_id}),e.jsx("dt",{className:"text-muted-foreground",children:"Generation ID"}),e.jsx("dd",{className:"font-mono text-xs break-all",children:j.id}),e.jsx("dt",{className:"text-muted-foreground",children:"A2E task ID"}),e.jsx("dd",{className:"font-mono text-xs break-all",children:j.a2e_task_id??e.jsx("span",{className:"text-muted-foreground",children:"— (never accepted by A2E)"})}),e.jsx("dt",{className:"text-muted-foreground",children:"Credits used"}),e.jsxs("dd",{children:["−",j.credits_used]}),e.jsx("dt",{className:"text-muted-foreground",children:"Balance after"}),e.jsx("dd",{children:j.balance_after??e.jsx("span",{className:"text-muted-foreground",children:"— (pre-snapshot row)"})}),e.jsx("dt",{className:"text-muted-foreground",children:"Current balance"}),e.jsx("dd",{children:j.current_balance??"—"}),e.jsx("dt",{className:"text-muted-foreground",children:"Created"}),e.jsx("dd",{children:new Date(j.created_at).toLocaleString()}),e.jsx("dt",{className:"text-muted-foreground",children:"Prompt"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:j.prompt}),j.error_message&&e.jsxs(e.Fragment,{children:[e.jsx("dt",{className:"text-muted-foreground",children:"Error"}),e.jsx("dd",{className:"text-destructive whitespace-pre-wrap",children:j.error_message})]})]})]})]})}),e.jsx(Hn,{open:_,onOpenChange:P})]})}function Hs({label:t,value:s,tone:a}){const n=s>0&&a==="warn"?"border-destructive/50 text-destructive":"border-border text-muted-foreground";return e.jsxs("div",{className:`text-xs border rounded-md px-2 py-1 ${n}`,children:[e.jsx("span",{className:"font-medium",children:s})," ",e.jsx("span",{children:t})]})}function Jn(){const[t,s]=d.useState(!1),[a,r]=d.useState([]),[n,o]=d.useState(14),l=async()=>{s(!0);try{const g=new Date(Date.now()-n*864e5).toISOString(),{data:u}=await T.from("videos").select("model, created_at, credits_used, a2e_task_id, error_message").eq("status","failed").in("error_message",["TIMEOUT","ABANDONED"]).gte("created_at",g).limit(1e3),i=new Map;for(const h of u||[]){const m=h.model||"unknown",v=i.get(m)||{model:m,kills:0,withTask:0,credits:0};v.kills+=1,v.credits+=h.credits_used||0,h.a2e_task_id&&(v.withTask+=1),i.set(m,v)}r([...i.values()].sort((h,m)=>m.kills-h.kills))}finally{s(!1)}};d.useEffect(()=>{l()},[n]);const c=a.reduce((g,u)=>g+u.kills,0),x=a.reduce((g,u)=>g+u.withTask,0);return e.jsx(O,{children:e.jsxs(E,{className:"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(_n,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-semibold",children:"Abandoned jobs by model"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["last ",n,"d"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>o(n===14?3:14),children:n===14?"3d":"14d"}),e.jsx($,{variant:"ghost",size:"sm",onClick:l,disabled:t,children:t?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(ve,{className:"h-4 w-4"})})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c," ended without a result · ",x," still had a provider task attached (we likely paid and refunded)."]}),e.jsxs("div",{className:"space-y-1",children:[a.length===0&&!t&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No abandoned jobs in this window."}),a.map(g=>e.jsxs("div",{className:"flex items-center justify-between text-sm border-t border-border/50 pt-1",children:[e.jsx("span",{className:"font-medium",children:g.model}),e.jsxs("span",{className:"text-muted-foreground",children:[g.kills," ended · ",g.withTask," with live task · ",g.credits.toLocaleStr
128ing()," cr refunded"]})]},g.model))]})]})})}const ei=24;function ti(){const{toast:t}=Ae(),[s,a]=d.useState(!1),[r,n]=d.useState(!1),[o,l]=d.useState(null),[c,x]=d.useState(new Set),g=`https://chpljoqmplgoykvryyug.supabase.co/functions/v1/admin-goodwill-policy-refunds?hours=${ei}`,u=async()=>{var f;a(!0);try{const{data:p}=await T.auth.getSession(),j=(f=p.session)==null?void 0:f.access_token;if(!j)throw new Error("Not authenticated");const L=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${j}`}}),w=await L.json();if(!L.ok)throw new Error(w.error||"Failed to load");l(w),x(new Set(w.clusters.filter(_=>!_.already_refunded).map(_=>_.refund_generation_id)))}catch(p){t({title:"Could not load goodwill refunds",description:p instanceof Error?p.message:String(p),variant:"destructive"})}finally{a(!1)}};d.useEffect(()=>{u()},[]);const h=((o==null?void 0:o.clusters)??[]).filter(f=>!f.already_refunded).filter(f=>c.has(f.refund_generation_id)),m=h.reduce((f,p)=>f+p.refund_credits,0),v=f=>{x(p=>{const j=new Set(p);return j.has(f)?j.delete(f):j.add(f),j})},b=async()=>{var p;if(h.length===0)return;const f=new Set(h.map(j=>j.user_id)).size;if(confirm(`Refund ${m} credits to ${f} user${f===1?"":"s"} (${h.length} rejections)?`)){n(!0);try{const{data:j}=await T.auth.getSession(),L=(p=j.session)==null?void 0:p.access_token;if(!L)throw new Error("Not authenticated");const w=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${L}`,"Content-Type":"application/json"},body:JSON.stringify({generationIds:h.map(P=>P.refund_generation_id)})}),_=await w.json();if(!w.ok)throw new Error(_.error||"Failed");t({title:`Refunded ${_.refunded} rejections`,description:`+${_.total_credits_refunded} credits to ${_.users_affected} users.`}),await u()}catch(j){t({title:"Refund failed",description:j instanceof Error?j.message:String(j),variant:"destructive"})}finally{n(!1)}}};return e.jsx(O,{className:"border-primary/30",children:e.jsxs(E,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rs,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Goodwill refunds · policy rejections"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 24h. One refund per image — the cheapest attempt. Retries never pay twice."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:u,disabled:s||r,children:[s?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(ve,{className:"h-4 w-4"}),"Refresh"]}),e.jsxs($,{size:"sm",onClick:b,disabled:r||s||h.length===0,children:[r?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(Rs,{className:"h-4 w-4"}),"Refund selected (",m.toLocaleString()," cr)"]})]})]}),o&&e.jsxs("div",{className:"flex flex-wrap gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:o.summary.clusters_eligible})," eligible"]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:o.summary.users_eligible})," users"]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:o.summary.credits_eligible.toLocaleString()})," credits if all refunded"]}),e.jsxs("span",{children:[o.summary.already_refunded," already refunded"]}),e.jsxs("span",{children:[o.summary.credits_spent_total.toLocaleString()," credits spent on rejections"]})]}),!s&&o&&o.clusters.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No policy rejections in the last 24 hours."}),o&&o.clusters.length>0&&e.jsx("div",{className:"max-h-80 overflow-y-auto rounded-md border divide-y",children:o.clusters.map(f=>e.jsxs("div",{className:`flex items-start gap-3 p-3 text-sm ${f.already_refunded?"opacity-50":""}`,children:[e.jsx(rr,{className:"mt-1",checked:c.has(f.refund_generation_id),disabled:f.already_refunded,onCheckedChange:()=>v(f.refund_generation_id)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:f.email??f.user_id.slice(0,8)}),e.jsx(A,{variant:"outline",className:"text-[10px]",children:f.bucket}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[f.attempts," attempt",f.attempts===1?"":"s"," · ",f.credits_spent.toLocaleStr
128ing()," cr spent"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ke(new Date(f.last_at),{addSuffix:!0})})]}),f.prompt&&e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-1",children:f.prompt})]}),e.jsx("div",{className:"text-right shrink-0",children:f.already_refunded?e.jsx("span",{className:"text-xs text-muted-foreground",children:"already refunded"}):e.jsxs("span",{className:"font-medium text-primary",children:["+",f.refund_credits.toLocaleString()]})})]},f.key))})]})})}function si(){const{toast:t}=Ae(),[s,a]=d.useState(!1),[r,n]=d.useState(!1),[o,l]=d.useState(5),[c,x]=d.useState(null),[g,u]=d.useState("all"),[i,h]=d.useState("all"),[m,v]=d.useState(""),[b,f]=d.useState("all"),p=async()=>{var P;a(!0);try{const{data:D}=await T.auth.getSession(),I=(P=D.session)==null?void 0:P.access_token;if(!I)throw new Error("Not authenticated");const Q=`https://chpljoqmplgoykvryyug.supabase.co/functions/v1/admin-failed-generations?days=${o}`,Z=await fetch(Q,{headers:{Authorization:`Bearer ${I}`}}),te=await Z.json();if(!Z.ok)throw new Error(te.error||"Failed");x(te)}catch(D){t({title:"Failed to load",description:D instanceof Error?D.message:String(D),variant:"destructive"})}finally{a(!1)}};d.useEffect(()=>{p()},[o]);const j=async()=>{var P;n(!0);try{const{data:D}=await T.auth.getSession(),I=(P=D.session)==null?void 0:P.access_token;if(!I)throw new Error("Not authenticated");const Z=`https://chpljoqmplgoykvryyug.supabase.co/functions/v1/admin-refund-recent-failures?hours=${o*24}`,te=await fetch(`${Z}&dry_run=1`,{method:"POST",headers:{Authorization:`Bearer ${I}`}}),S=await te.json();if(!te.ok)throw new Error(S.error||"Preview failed");const C=o===1?"last 24h":`last ${o} days`,y=`Refund ${S.eligible} failed generations from ${C} (${S.total_credits_eligible} credits) to ${S.users_affected} users?
129
130Scanned: ${S.scanned}
131Already refunded: ${S.already_refunded}
132No charge: ${S.no_charge}`;if(!confirm(y)){n(!1);return}const B=await fetch(Z,{method:"POST",headers:{Authorization:`Bearer ${I}`}}),X=await B.json();if(!B.ok)throw new Error(X.error||"Failed");t({title:`Refunded ${X.refunded} generations`,description:`+${X.total_credits_refunded} credits to ${X.users_recomputed} users.`}),await p()}catch(D){t({title:"Refund failed",description:D instanceof Error?D.message:String(D),variant:"destructive"})}finally{n(!1)}},L=d.useMemo(()=>{const P=(c==null?void 0:c.buckets)??{};return Object.entries(P).sort((D,I)=>I[1]-D[1])},[c]),w=d.useMemo(()=>{if(!c)return[];const P=m.trim().toLowerCase();return c.items.filter(D=>!(g!=="all"&&D.kind!==g||i!=="all"&&D.refund_status!==i||b!=="all"&&((D.error_message??"UNKNOWN").trim()||"UNKNOWN")!==b||P&&!`${D.email??""} ${D.a2e_task_id??""} ${D.id} ${D.prompt} ${D.failure_detail??""}`.toLowerCase().includes(P)))},[c,g,i,b,m]),_=P=>{navigator.clipboard.writeText(P),t({title:"Copied",description:P.length>40?P.slice(0,40)+"…":P})};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Jn,{}),e.jsx(ti,{}),e.jsx(O,{className:"bg-secondary/30 border-border/50",children:e.jsxs(E,{className:"p-4 flex flex-wrap items-center gap-3",children:[e.jsxs(Ce,{value:String(o),onValueChange:P=>l(parseInt(P,10)),children:[e.jsx(Pe,{className:"w-[140px]",children:e.jsx(De,{})}),e.jsxs(Le,{children:[e.jsx(q,{value:"1",children:"Last 24h"}),e.jsx(q,{value:"2",children:"Last 2 days"}),e.jsx(q,{value:"5",children:"Last 5 days"}),e.jsx(q,{value:"7",children:"Last 7 days"}),e.jsx(q,{value:"30",children:"Last 30 days"})]})]}),e.jsxs(Ce,{value:g,onValueChange:P=>u(P),children:[e.jsx(Pe,{className:"w-[130px]",children:e.jsx(De,{})}),e.jsxs(Le,{children:[e.jsx(q,{value:"all",children:"All types"}),e.jsx(q,{value:"video",children:"Videos"}),e.jsx(q,{value:"image",children:"Images"})]})]}),e.jsxs(Ce,{value:i,onValueChange:P=>h(P),children:[e.jsx(Pe,{className:"w-[180px]",children:e.jsx(De,{})}),e.jsxs(Le,{children:[e.jsx(q,{value:"all",children:"All charge states"}),e.jsx(q,{value:"refunded",children:"Refunded"}),e.jsx(q,{value:"charged_kept",children:"Charged, not refunded"}),e.jsx(q,{value:"never_charged",children:"Never charged"}),e.jsx(q,{value:"ledger_mismatch",children:"Ledger mismatch"})]})]}),e.jsxs(Ce,{value:b,onValueChange:f,children:[e.jsx(Pe,{className:"w-[220px]",children:e.jsx(De,{})}),e.jsxs(Le,{children:[e.jsx(q,{value:"all",children:"All error types"}),L.map(([P,D])=>e.jsxs(q,{value:P,children:[P," (",D,")"]},P))]})]}),e.jsx(me,{placeholder:"Search email, task ID, prompt…",value:m,onChange:P=>v(P.target.value),className:"max-w-sm"}),e.jsxs($,{variant:"outline",size:"sm",onClick:p,disabled:s,children:[s?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(ve,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Refresh"})]}),e.jsxs($,{size:"sm",onClick:j,disabled:r,className:"bg-emerald-600 hover:bg-emerald-700 text-white",children:[r?e.jsx(V,{className:"h-4 w-4 animate-spin"}):e.jsx(we,{className:"h-4 w-4"}),e.jsxs("span",{className:"ml-2",children:["Refund ",o===1?"last 24h":`last ${o}d`]})]}),c&&e.jsxs("div",{className:"ml-auto flex items-center gap-2 text-sm text-muted-foreground flex-wrap",children:[e.jsxs(A,{variant:"secondary",children:[c.counts.total," total"]}),e.jsxs(A,{className:"bg-emerald-500/20 text-emerald-300 border-emerald-500/30",children:[c.counts.refunded," refunded",c.counts.credits_refunded?` · ${c.counts.credits_refunded.toLocaleStr
132ing()} cr`:""]}),e.jsxs(A,{className:"bg-destructive/20 text-destructive border-destructive/30",children:[c.counts.charged_kept," charged, not refunded",c.counts.credits_kept?` · ${c.counts.credits_kept.toLocaleString()} cr kept`:""]}),c.counts.never_charged>0&&e.jsxs(A,{variant:"outline",children:[c.counts.never_charged," never charged"]}),c.counts.ledger_mismatch>0&&e.jsxs(A,{className:"bg-amber-500/20 text-amber-300 border-amber-500/30",children:[c.counts.ledger_mismatch," ledger mismatch"]}),e.jsxs(A,{variant:"outline",children:[c.counts.videos," vid"]}),e.jsxs(A,{variant:"outline",children:[c.counts.images," img"]}),typeof c.counts.failure_rate=="number"&&e.jsxs(A,{variant:"outline",children:[(c.counts.failure_rate*100).toFixed(1),"% of ",c.counts.total_volume??0," gens"]}),typeof c.counts.recovered=="number"&&e.jsxs(A,{className:"bg-blue-500/20 text-blue-300 border-blue-500/30",children:[c.counts.recovered," recovered on retry"]}),typeof c.counts.retried_failed=="number"&&c.counts.retried_failed>0&&e.jsxs(A,{variant:"outline",children:[c.counts.retried_failed," retried & failed again"]})]})]})}),s&&!c&&e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(V,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),c&&w.length===0&&e.jsx(O,{className:"bg-secondary/30 border-border/50",children:e.jsx(E,{className:"p-10 text-center text-muted-foreground",children:"No failed generations match these filters."})}),e.jsx("div",{className:"space-y-3",children:w.map(P=>e.jsx(ri,{item:P,onCopy:_},`${P.kind}-${P.id}`))})]})}const ai={AGE_RESTRICTED:"age-restricted — no refund per policy",CONTENT_POLICY:"content policy — no refund per policy"};function ri({item:t,onCopy:s}){var l;const a=ua(t.image_url??null),r=t.kind==="video",n=t.charged_amount??Math.abs(((l=t.usage_txn)==null?void 0:l.amount)??t.credits_used??0),o=(()=>{var c;switch(t.refund_status){case"refunded":return e.jsxs(A,{className:"bg-emerald-500/20 text-emerald-300 border-emerald-500/30 gap-1",children:[e.jsx(we,{className:"h-3 w-3"})," Refunded +",Math.abs(((c=t.refund_txn)==null?void 0:c.amount)??n)," credits"]});case"charged_kept":{const x=ai[t.failure_bucket??""]??"not refunded";return e.jsxs(A,{className:"bg-destructive/20 text-destructive border-destructive/30 gap-1",children:[e.jsx(nr,{className:"h-3 w-3"})," Charged ",n," credits · ",x]})}case"ledger_mismatch":return e.jsxs(A,{className:"bg-amber-500/20 text-amber-300 border-amber-500/30 gap-1",children:[e.jsx(fe,{className:"h-3 w-3"})," Ledger mismatch — record says ",t.credits_used,", no usage txn"]});default:return e.jsxs(A,{variant:"outline",className:"gap-1 opacity-70",children:[e.jsx(fe,{className:"h-3 w-3"})," Never charged"]})}})();return e.jsx(O,{className:"bg-secondary/30 border-border/50",children:e.jsx(E,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4",children:[e.jsx("div",{className:"shrink-0 w-full md:w-40",children:t.image_url?e.jsx("a",{href:a??void 0,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("div",{className:"aspect-[3/4] bg-black/40 rounded-md overflow-hidden border border-border/50",children:e.jsx("img",{src:a??void 0,alt:"source",className:"w-full h-full object-contain"})})}):e.jsx("div",{className:"aspect-[3/4] bg-black/40 rounded-md flex items-center justify-center text-muted-foreground text-xs",children:"No image"})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(A,{variant:"secondary",className:"gap-1",children:[r?e.jsx(wt,{className:"h-3 w-3"}):e.jsx(kt,{className:"h-3 w-3"}),r?`Video${t.target_duration?` ${t.target_duration}s`:""}`:"Image"]}),o,e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Ke(new Date(t.created_at),{addSuffix:!0})," · ",K(new Date(t.created_at),"MMM d, HH:mm:ss")]})]}),e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"User:"})," ",e.jsx("span",{className:"font-medium",children:t.email??"(no email)"})," ",e.jsxs("button",{onClick:()=>s(t.user_id),className:"text-xs text-primary hover:underline ml-1 inline-flex items-center gap-1",children:[e.jsx(mt,{className:"h-3 w-3"})," ",t.user_id.slice(0,8),"…"]})]}),e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Prompt:"})," ",e.jsx("span",{className:"whitespace-pre-wrap break-words",children:t.prompt||e.jsx("em",{className:"text-muted-foreground",children:"(empty)"})})]}),e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Error:"})," ",e.jsx("span",{className:"text-destructive break-words",children:t.error_message||"(no message)"})]}),t.failure_detail&&e.jsxs("div",{className:"text-xs bg-black/30 border border-border/50 rounded-md p-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Raw upstream detail:"})," ",e.jsx("span",{className:"break-words font-mono text-amber-300",children:t.failure_detail})]}),t.retry_outcome&&t.retry_outcome!=="no_retry"&&e.jsx("div",{className:"text-xs",children:t.retry_outcome==="recovered"?e.jsxs(A,{className:"bg-blue-500/20 text-blue-300 border-blue-500/30",children:["User retried and succeeded (",t.retry_attempts," attempt",t.retry_attempts===1?"":"s",")"]}):e.jsxs(A,{variant:"outline",children:["Retried ",t.retry_attempts,"× — still failing"]})}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground flex-wrap",children:[t.usage_txn&&e.jsxs("span",{children:["Usage txn: ",e.jsx("span",{className:"text-foreground",children:t.usage_txn.amount})," @ ",K(new Date(t.usage_txn.created_at),"HH:mm:ss")]}),t.refund_txn&&e.jsxs("span",{children:["Refund txn: ",e.jsxs("span",{className:"text-emerald-400",children:["+",t.refund_txn.amount]})," @ ",K(new Date(t.refund_txn.created_at),"HH:mm:ss")]}),t.a2e_task_id&&e.jsxs("button",{onClick:()=>s(t.a2e_task_id),className:"inline-flex items-center gap-1 hover:text-foreground",children:[e.jsx(mt,{className:"h-3 w-3"})," A2E: ",t.a2e_task_id.slice(0,10),"…"]}),e.jsxs("button",{onClick:()=>s(t.id),className:"inline-flex items-center gap-1 hover:text-foreground",children:[e.jsx(mt,{className:"h-3 w-3"})," ID: ",t.id.slice(0,8),"…"]}),t.image_url&&e.jsxs("a",{href:t.image_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 hover:text-foreground",children:[e.jsx(gs,{className:"h-3 w-3"})," Open image"]})]})]})]})})})}const Ia=Math.cos,jt=Math.sin,be=Math.sqrt,vt=Math.PI,Pt=2*vt,fs={draw(t,s){const a=be(s/vt);t.moveTo(a,0),t.arc(0,0,a,0,Pt)}},ni={draw(t,s){const a=be(s/5)/2;t.moveTo(-3*a,-a),t.lineTo(-a,-a),t.lineTo(-a,-3*a),t.lineTo(a,-3*a),t.lineTo(a,-a),t.lineTo(3*a,-a),t.lineTo(3*a,a),t.lineTo(a,a),t.lineTo(a,3*a),t.lineTo(-a,3*a),t.lineTo(-a,a),t.lineTo(-3*a,a),t.closePath()}},Ra=be(1/3),ii=Ra*2,li={draw(t,s){const a=be(s/ii),r=a*Ra;t.moveTo(0,-a),t.lineTo(r,0),t.lineTo(0,a),t.lineTo(-r,0),t.closePath()}},ci={draw(t,s){const a=be(s),r=-a/2;t.rect(r,r,a,a)}},di=.8908130915292852,Fa=jt(vt/10)/jt(7*vt/10),oi=jt(Pt/10)*Fa,ui=-Ia(Pt/10)*Fa,mi={draw(t,s){const a=be(s*di),r=oi*a,n=ui*a;t.moveTo(0,-a),t.lineTo(r,n);for(let o=1;o<5;++o){const l=Pt*o/5,c=Ia(l),x=jt(l);t.lineTo(x*a,-c*a),t.lineTo(c*r-x*n,x*r+c*n)}t.closePath()}},Mt=be(3),xi={draw(t,s){const a=-be(s/(Mt*3));t.moveTo(0,a*2),t.lineTo(-Mt*a,-a),t.lineTo(Mt*a,-a),t.closePath()}},xe=-.5,he=be(3)/2,Xt=1/be(12),hi=(Xt/2+1)*3,pi={draw(t,s){const a=be(s/hi),r=a/2,n=a
132*Xt,o=r,l=a*Xt+a,c=-o,x=l;t.moveTo(r,n),t.lineTo(o,l),t.lineTo(c,x),t.lineTo(xe*r-he*n,he*r+xe*n),t.lineTo(xe*o-he*l,he*o+xe*l),t.lineTo(xe*c-he*x,he*c+xe*x),t.lineTo(xe*r+he*n,xe*n-he*r),t.lineTo(xe*o+he*l,xe*l-he*o),t.lineTo(xe*c+he*x,xe*x-he*c),t.closePath()}};function gi(t,s){let a=null,r=_r(n);t=typeof t=="function"?t:Je(t||fs),s=typeof s=="function"?s:Je(s===void 0?64:+s);function n(){let o;if(a||(a=o=r()),t.apply(this,arguments).draw(a,+s.apply(this,arguments)),o)return a=null,o+""||null}return n.type=function(o){return arguments.length?(t=typeof o=="function"?o:Je(o),n):t},n.size=function(o){return arguments.length?(s=typeof o=="function"?o:Je(+o),n):s},n.context=function(o){return arguments.length?(a=o??null,n):a},n}var fi=["type","size","sizeType"];function Zt(){return Zt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},Zt.apply(null,arguments)}function Ks(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),a.push.apply(a,r)}return a}function Ys(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Ks(Object(a),!0).forEach(function(r){ji(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):Ks(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function ji(t,s,a){return(s=vi(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function vi(t){var s=bi(t,"string");return typeof s=="symbol"?s:s+""}function bi(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var r=a.call(t,s||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function yi(t,s){if(t==null)return{};var a,r,n=Ni(t,s);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)a=o[r],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(n[a]=t[a])}return n}function Ni(t,s){if(t==null)return{};var a={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(s.indexOf(r)!==-1)continue;a[r]=t[r]}return a}var za={symbolCircle:fs,symbolCross:ni,symbolDiamond:li,symbolSquare:ci,symbolStar:mi,symbolTriangle:xi,symbolWye:pi},_i=Math.PI/180,wi=t=>{var s="symbol".concat(ga(t));return za[s]||fs},ki=(t,s,a)=>{if(s==="area")return t;switch(a){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var r=18*_i;return 1.25*t*t*(Math.tan(r)-Math.tan(r*2)*Math.tan(r)**2)}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},Si=(t,s)=>{za["symbol".concat(ga(t))]=s},Ua=t=>{var s=t.type,a=s===void 0?"circle":s,r=t.size,n=r===void 0?64:r,o=t.sizeType,l=o===void 0?"area":o,c=yi(t,fi),x=Ys(Ys({},c),{},{type:a,size:n,sizeType:l}),g="circle";typeof a=="string"&&(g=a);var u=()=>{var b=wi(g),f=gi().type(b).size(ki(n,l,g)),p=f();if(p!==null)return p},i=x.className,h=x.cx,m=x.cy,v=pa(x);return Re(h)&&Re(m)&&Re(n)?d.createElement("path",Zt({}
132,v,{className:Ve("recharts-symbols",i),transform:"translate(".concat(h,", ").concat(m,")"),d:u()})):null};Ua.registerSymbol=Si;function bt(){return bt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},bt.apply(null,arguments)}function Xs(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),a.push.apply(a,r)}return a}function Ba(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Xs(Object(a),!0).forEach(function(r){Ci(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):Xs(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function Ci(t,s,a){return(s=Pi(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function Pi(t){var s=Di(t,"string");return typeof s=="symbol"?s:s+""}function Di(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var r=a.call(t,s||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}var ge=32,Li={align:"center",iconSize:14,inactiveColor:"#ccc",layout:"horizontal",verticalAlign:"middle",labelStyle:{}};function Ai(t){if(typeof t=="object"&&t!==null&&"strokeDasharray"in t)return String(t.strokeDasharray)}function Ti(t){var s=t.data,a=t.iconType,r=t.inactiveColor,n=ge/2,o=ge/6,l=ge/3,c=s.inactive?r:s.color,x=a??s.type;if(x==="none")return null;if(x==="plainline")return d.createElement("line",{strokeWidth:4,fill:"none",stroke:c,strokeDasharray:Ai(s.payload),x1:0,y1:n,x2:ge,y2:n,className:"recharts-legend-icon"});if(x==="line")return d.createElement("path",{strokeWidth:4,fill:"none",stroke:c,d:"M0,".concat(n,"h").concat(l,`
133            A`).concat(o,",").concat(o,",0,1,1,").concat(2*l,",").concat(n,`
134            H`).concat(ge,"M").concat(2*l,",").concat(n,`
135            A`).concat(o,",").concat(o,",0,1,1,").concat(l,",").concat(n),className:"recharts-legend-icon"});if(x==="rect")return d.createElement("path",{stroke:"none",fill:c,d:"M0,".concat(ge/8,"h").concat(ge,"v").concat(ge*3/4,"h").concat(-ge,"z"),className:"recharts-legend-icon"});if(d.isValidElement(s.legendIcon)){var g=Ba({},s);return delete g.legendIcon,d.cloneElement(s.legendIcon,g)}return d.createElement(Ua,{fill:c,cx:n,cy:n,size:ge,sizeType:"diameter",type:x})}function Oi(t){var s=t.payload,a=t.iconSize,r=t.layout,n=t.formatter,o=t.inactiveColor,l=t.iconType,c=t.labelStyle,x={x:0,y:0,width:ge,height:ge},g={display:r==="horizontal"?"inline-block":"block",marginRight:10},u={display:"inline-block",verticalAlign:"middle",marginRight:4};return s.map((i,h)=>{var m=i.formatter||n,v=Ve({"recharts-legend-item":!0,["legend-item-".concat(h)]:!0,inactive:i.inactive});if(i.type==="none")return null;var b=typeof c=="object"?Ba({},c):{};b.color=i.inactive?o:b.color||i.color;var f=m?m(i.value,i,h):i.value;return d.createElement("li",bt({className:v,style:g,key:"legend-item-".concat(h)},wr(t,i,h)),d.createElement(kr,{width:a,height:a,viewBox:x,style:u,"aria-label":"".concat(i.value," legend icon")},d.createElement(Ti,{data:i,iconType:l,inactiveColor:o})),d.createElement("span",{className:"recharts-legend-item-text",style:b},f))})}var Ei=t=>{var s=St(t,Li),a=s.payload,r=s.layout,n=s.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:r==="horizontal"?n:"left"};return d.createElement("ul",{className:"recharts-default-legend",style:o},d.createElement(Oi,bt({},s,{payload:a})))};function $i(){return is(Sr)}var Mi=["contextPayload"];function Qt(){return Qt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},Qt.apply(null,arguments)}function Ii(t,s){return Ui(t)||zi(t,s)||Fi(t,s)||Ri()}
135function Ri(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
136In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Fi(t,s){if(t){if(typeof t=="string")return Zs(t,s);var a={}.toString.call(t).slice(8,-1);return a==="Object"&&t.constructor&&(a=t.constructor.name),a==="Map"||a==="Set"?Array.from(t):a==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a)?Zs(t,s):void 0}}function Zs(t,s){(s==null||s>t.length)&&(s=t.length);for(var a=0,r=Array(s);a<s;a++)r[a]=t[a];return r}function zi(t,s){var a=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(a!=null){var r,n,o,l,c=[],x=!0,g=!1;try{if(o=(a=a.call(t)).next,s!==0)for(;!(x=(r=o.call(a)).done)&&(c.push(r.value),c.length!==s);x=!0);}catch(u){g=!0,n=u}finally{try{if(!x&&a.return!=null&&(l=a.return(),Object(l)!==l))return}finally{if(g)throw n}}return c}}function Ui(t){if(Array.isArray(t))return t}function Qs(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),a.push.apply(a,r)}return a}function Fe(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Qs(Object(a),!0).forEach(function(r){Bi(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):Qs(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function Bi(t,s,a){return(s=Wi(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function Wi(t){var s=qi(t,"string");return typeof s=="symbol"?s:s+""}function qi(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var r=a.call(t,s||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Gi(t,s){if(t==null)return{};var a,r,n=Vi(t,s);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)a=o[r],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(n[a]=t[a])}return n}function Vi(t,s){if(t==null)return{};var a={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(s.indexOf(r)!==-1)continue;a[r]=t[r]}return a}function Hi(t){return t.value}function Ki(t){var s=t.contextPayload,a=Gi(t,Mi),r=Tr(s,t.payloadUniqBy,Hi),n=Fe(Fe({},a),{},{payload:r});return d.isValidElement(t.content)?d.cloneElement(t.content,n):typeof t.content=="function"?d.createElement(t.content,n):d.createElement(Ei,n)}function Yi(t,s,a,r,n,o){var l=s.layout,c=s.align,x=s.verticalAlign,g,u;return(!t||(t.left===void 0||t.left===null)&&(t.right===void 0||t.right===null))&&(c==="center"&&l==="vertical"?g={left:((r||0)-o.width)/2}:g=c==="right"?{right:a&&a.right||0}:{left:a&&a.left||0}),(!t||(t.top===void 0||t.top===null)&&(t.bottom===void 0||t.bottom===null))&&(x==="middle"?u={top:((n||0)-o.height)/2}:u=x==="bottom"?{bottom:a&&a.bottom||0}:{top:a&&a.top||0}),Fe(Fe({},g),u)}function Xi(t){var s=t.align,a=t.layout,r=t.verticalAlign,n=t.itemSorter,o=ja();return d.useLayoutEffect(()=>{o(Or({align:s,layout:a,verticalAlign:r,itemSorter:n}))},[o,s,a,r,n]),null}function Zi(t){var s=t.width,a=t.height,r=ja();return d.useLayoutEffect(()=>{r(Es({width:s,height:a}))},[r,s,a]),d.useLayoutEffect(()=>()=>{r(Es({width:0,height:0}))},[r]),null}function Qi(t,s,a,r){return t==="vertical"&&s!=null?{height:s}:t==="horizontal"?{width:a||r}:null}var Ji={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",labelStyle:{},layout:"horizontal",verticalAlign:"bottom"};function el(t){var s=St(t,Ji),a=$i(),r=Cr(),n=Pr(),o=s.width,l=s.height,c=s.wrapperStyle,x=s.portal,g=Dr([a]),u=Ii(g,2),i=u[0],h=u[1],m=Lr(),v=Ar();if(m==null||v==null)return null;var b=m-((n==null?void 0:n.left)||0)-((n==null?void 0:n.right)||0),f=Qi(s.layout,l,o,b),p=x?c:Fe(Fe({position:"absolute",width:(f==null?void 0:f.width)||o||"auto",height:(f==null?void 0:f.height)||l||"auto"},Yi(c,s,n,m,v,i)),c),j=x??r;if(j==null||a==null)return null;var L=d.createElement("div",{className:"recharts-legend-wrapper",style:p,ref:h},d.createElement(Xi,{layout:s.layout,align:s.align,verticalAlign:s.verticalAlign,itemSorter:s.itemSorter}),!x&&d.createElement(Zi,{width:i.width,height:i.height}),d.createElement(Ki,Qt({},s,f,{margin:n,chartWidth:m,chartHeight:v,contextPayload:a})));return ir.createPortal(L,j)}var Wa=d.memo(el,fa);Wa.displayName="Legend";function Jt(){return Jt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},Jt.apply(null,arguments)}var qa=t=>{var s=t.cx,a=t.cy,r=t.r,n=t.className,o=Ve("recharts-dot",n);return Re(s)&&Re(a)&&Re(r)?d.createElement("circle",Jt({},ba(t),va(t),{className:o,cx:s,cy:a,r})):null},tl=["points"];function Js(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);
136s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),a.push.apply(a,r)}return a}function It(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Js(Object(a),!0).forEach(function(r){sl(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):Js(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function sl(t,s,a){return(s=al(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function al(t){var s=rl(t,"string");return typeof s=="symbol"?s:s+""}function rl(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var r=a.call(t,s||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function yt(){return yt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},yt.apply(null,arguments)}function nl(t,s){if(t==null)return{};var a,r,n=il(t,s);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)a=o[r],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(n[a]=t[a])}return n}function il(t,s){if(t==null)return{};var a={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(s.indexOf(r)!==-1)continue;a[r]=t[r]}return a}function ll(t){var s=t.option,a=t.dotProps,r=t.className;if(d.isValidElement(s))return d.cloneElement(s,a);if(typeof s=="function")return s(a);var n=Ve(r,typeof s!="boolean"?s.className:""),o=a??{};o.points;var l=nl(o,tl);return d.createElement(qa,yt({},l,{className:n}))}function cl(t,s){return t==null?!1:s?!0:t.length===1}function dl(t){var s=t.points,a=t.dot,r=t.className,n=t.dotClassName,o=t.dataKey,l=t.baseProps,c=t.needClip,x=t.clipPathId,g=t.zIndex,u=g===void 0?ds.scatter:g;if(!cl(s,a))return null;var i=ya(a),h=Er(a),m=s.map((b,f)=>{var p,j,L=It(It(It({r:3},l),h),{},{index:f,cx:(p=b.x)!==null&&p!==void 0?p:void 0,cy:(j=b.y)!==null&&j!==void 0?j:void 0,dataKey:o,value:b.value,payload:b.payload,points:s});return d.createElement(ll,{key:"dot-".concat(f),option:a,dotProps:L,className:n})}),v={};return c&&x!=null&&(v.clipPath="url(#clipPath-".concat(i?"":"dots-").concat(x,")")),d.createElement(ls,{zIndex:u},d.createElement(cs,yt({className:r},v),m))}function ea(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),a.push.apply(a,r)}return a}function Rt(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?ea(Object(a),!0).forEach(function(r){ol(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):ea(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function ol(t,s,a){return(s=ul(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function ul(t){var s=ml(t,"string");return typeof s=="symbol"?s:s+""}function ml(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var r=a.call(t,s||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}var xl=t=>{var s=t.point,a=t.childIndex,r=t.mainColor,n=t.activeDot,o=t.dataKey,l=t.clipPath;if(n===!1||s.x==null||s.y==null)return null;var c={index:a,dataKey:o,cx:s.x,cy:s.y,r:4,fill:r??"none",strokeWidth:2,stroke:"#fff",payload:s.payload,value:s.value},x=Rt(Rt(Rt({},c),Na(n)),va(n)),g;return d.isValidElement(n)?g=d.cloneElement(n,x):typeof n=="function"?g=n(x):g=d.createElement(qa,x),d.createElement(cs,{className:"recharts-active-dot",clipPath:l},g)};function hl(t){var s=t.points,a=t.mainColor,r=t.activeDot,n=t.itemDataKey,o=t.clipPath,l=t.zIndex,c=l===void 0?ds.activeDot:l,x=is($r),g=Mr();if(s==null||g==null)return null;var u=s.find(i=>g.includes(i.payload));return Vt(u)?null:d.createElement(ls,{zIndex:c},d.createElement(xl,{point:u,childIndex:Number(x),mainColor:a,dataKey:n,activeDot:r,clipPath:o}))}var pl=["animationElapsedTime","isAnimating","isEntrance","visibleLength","strokeDasharray","connectNulls"];function es(){return es=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},es.apply(null,arguments)}function gl(t,s){if(t==null)return{};var a,r,n=fl(t,s);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)a=o[r],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(n[a]=t[a])}return n}function fl(t,s){if(t==null)return{};var a={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(s.indexOf(r)!==-1)continue;a[r]=t[r]}return a}function jl(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function Ga(t,s){return"".concat(s,"px ").concat(t,"px")}function vl(t){return t.length%2!==0?[...t,...t]:t}function bl(t,s){for(var a=[],r=0;r<s;++r)a.push(...t);return a}function yl(t,s,a){var r=vl(a),n=r.reduce((m,v)=>m+v,0);if(!n)return Ga(s,t);for(var o=Math.floor(t/n),l=t%n,c=[],x=0,g=0;x<r.length;g+=(u=r[x])!==null&&u!==void 0?u:0,++x){var u,i=r[x];if(i!=null&&g+i>l){c=[...r.slice(0,x),l-g];break}}var h=c.length%2===0?[0,s]:[s];return[...bl(r,o),...c,...h].map(m=>"".concat(m,"px")).join(", ")}function Nl(t,s,a){if(t){var r="".concat(t).split(/[,\s]+/gim).map(n=>parseFloat(n));return yl(a,s,r)}return Ga(s,a)}function _l(t){t.animationElapsedTime,t.isAnimating,t.isEntrance;var s=t.visibleLength,a=t.strokeDasharray,r=t.connectNulls,n=gl(t,pl),o=r??!1,l;if(s!=null){var c,x=n.pathRef,g=jl((c=x==null?void 0:x.current)!==null&&c!==void 0?c:null);l=Nl(a,g,s)}else a!=null&&(l=String(a));return d.createElement(Ir,es({},n,{connectNulls:o,strokeDasharray:l}))}function wl(t){var s=d.useRef(0),a=d.useRef(0),r=d.useRef(!1),n=d.useRef(t);return n.current!==t&&(s.current=a.current,n.current=t),d.useCallback((o,l)=>{if(r.current)return null;var c=Math.min(Rr(s.current+o*l),l);return o>0&&l>0&&(a.current=Math.max(a.current,c),c>=l)?(r.current=!0,null):c},[])}var Va=(t,s,a,r)=>wa(t,"xAxis",s,r),Ha=(t,s,a,r)=>ka(t,"xAxis",s,r),Ka=(t,s,a,r)=>wa(t,"yAxis",a,r),Ya=(t,s,a,r)=>ka(t,"yAxis",a,r),kl=os([_a,Va,Ka,Ha,Ya],(t,s,a,r,n)=>Fr(t,"xAxis")?$s(s,r,!1):$s(a,n,!1)),Sl=(t,s,a,r,n)=>n;function Cl(t){return t.type==="line"}var Pl=os([zr,Sl],(t,s)=>t.filter(Cl).find(a=>a.id===s)),Dl=os([_a,Va,Ka,Ha,Ya,Pl,kl,Ur],(t,s,a,r,n,o,l,c)=>{var x=c.chartData,g=c.dataStartIndex,u=c.dataEndIndex;if(!(o==null||s==null||a==null||r==null||n==null||r.length===0||n.length===0||l==null||t!=="horizontal"&&t!=="vertical")){var i=o.dataKey,h=o.data,m;if(h!=null&&h.length>0?m=h:m=x==null?void 0:x.slice(g,u+1),m!=null)return Zl({layout:t,xAxis:s,yAxis:a,xAxisTicks:r,yAxisTicks:n,dataKey:i,bandSize:l,displayedData:m})}});function Ll(t){var s=Na(t),a=3,r=2;if(s!=null){var n=s.r,o=s.strokeWidth,l=Number(n),c=Number(o);return(Number.isNaN(l)||l<0)&&(l=a),(Number.isNaN(c)||c<0)&&(c=r),{r:l,strokeWidth:c}}return{r:a,strokeWidth:r}}var Al=["id"],Tl=["type","layout","connectNulls","needClip","shape","strokeDasharray"],Ol=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function Nt(){return Nt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},Nt.apply(null,arguments)}function js(t,s){if(t==null)return{};var a,r,n=El(t,s);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)a=o[r],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(n[a]=t[a])}return n}function El(t,s){if(t==null)return{};var a={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(s.indexOf(r)!==-1)continue;a[r]=t[r]}return a}function ta(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);
136s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),a.push.apply(a,r)}return a}function ye(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?ta(Object(a),!0).forEach(function(r){$l(t,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):ta(Object(a)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(a,r))})}return t}function $l(t,s,a){return(s=Ml(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function Ml(t){var s=Il(t,"string");return typeof s=="symbol"?s:s+""}function Il(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var r=a.call(t,s||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Rl(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function Fl(t){var s=0,a=0;for(var r of t)r.status==="matched"&&r.prev.x!=null&&r.next.x!=null&&(s+=r.next.x-r.prev.x,a++);return a>0?s/a:0}var zl=(t,s)=>{if(t==null)return[];if(s===1)return t.flatMap(c=>c.status==="removed"?[]:[c.next]);var a=Fl(t),r=[];for(var n of t)if(n.status==="matched")r.push(ye(ye({},n.next),{},{x:et(n.prev.x,n.next.x,s),y:et(n.prev.y,n.next.y,s)}));else if(n.status==="added")if(n.next.x!=null){var o=n.next.x-a;r.push(ye(ye({},n.next),{},{x:et(o,n.next.x,s),y:n.next.y}))}else r.push(n.next);else if(n.status==="removed"&&n.prev.x!=null){var l=n.prev.x+a;r.push(ye(ye({},n.prev),{},{x:et(n.prev.x,l,s),y:n.prev.y}))}return r},vs={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",animationInterpolateFn:zl,animationMatchBy:Yr,connectNulls:!1,dot:!0,fill:"#fff",hide:!1,isAnimationActive:"auto",label:!1,legendType:"line",shape:_l,stroke:"#3182bd",strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:ds.line,type:"linear"},Ul=t=>{var s=t.dataKey,a=t.name,r=t.stroke,n=t.legendType,o=t.hide;return[{inactive:o,dataKey:s,type:n,color:r,value:Ca(a,s),payload:t}]},Bl=d.memo(t=>{var s=t.dataKey,a=t.data,r=t.stroke,n=t.strokeWidth,o=t.fill,l=t.name,c=t.hide,x=t.unit,g=t.tooltipType,u=t.id,i={dataDefinedOnItem:a,getPosition:Xr,settings:{stroke:r,strokeWidth:n,fill:o,dataKey:s,nameKey:void 0,name:Ca(l,s),hide:c,type:g,color:r,unit:x,graphicalItemId:u}};return d.createElement(Gr,{tooltipEntrySettings:i})});function Wl(t){var s=t.clipPathId,a=t.points,r=t.props,n=r.dot,o=r.dataKey,l=r.needClip;r.id;var c=js(r,Al),x=ba(c);return d.createElement(dl,{points:a,dot:n,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:o,baseProps:x,needClip:l,clipPathId:s})}function ql(t){var s=t.showLabels,a=t.children,r=t.points,n=d.useMemo(()=>r==null?void 0:r.map(o=>{var l,c,x={x:(l=o.x)!==null&&l!==void 0?l:0,y:(c=o.y)!==null&&c!==void 0?c:0,width:0,lowerWidth:0,upperWidth:0,height:0};return ye(ye({},x),{},{value:o.value,payload:o.payload,viewBox:x,parentViewBox:void 0,fill:void 0})}),[r]);return d.createElement(sn,{value:s?n:void 0},a)}function Gl(t){var s=t.clipPathId,a=t.pathRef,r=t.points,n=t.props,o=t.animationElapsedTime,l=t.isAnimating,c=t.isEntrance,x=t.visibleLength,g=n.type,u=n.layout,i=n.connectNulls,h=n.needClip,m=n.shape,v=n.strokeDasharray,b=js(n,Tl),f=ye(ye({},pa(b)),{},{fill:"none",className:"recharts-line-curve",clipPath:h?"url(#clipPath-".concat(s,")"):void 0,points:r,type:g,layout:u,connectNulls:i,strokeDasharray:v??n.strokeDasharray,pathRef:a,animationElapsedTime:o,isAnimating:l,isEntrance:n.animateNewValues?c:!1,visibleLength:x});return d.createElement(d.Fragment,null,(r==null?void 0:r.length)>1&&d.createElement(an,{option:m,DefaultShape:vs.shape,shapeProps:f}),d.createElement(Wl,{points:r,clipPathId:s,props:n}))}function Vl(t){var s=t.clipPathId,a=t.props,r=t.pathRef,n=t.previousPointsRef,o=a.points,l=a.isAnimationActive,c=a.animationBegin,x=a.animationDuration,g=a.animationEasing,u=a.animationMatchBy,i=a.animationInterpolateFn,h=a.layout,m=Rl(r.current),v=Jr(a.onAnimationStart,a.onAnimationEnd),b=v.isAnimating,f=v.handleAnimationStart,p=v.handleAnimationEnd,j=!b,L=wl(o),w=d.useCallback(_=>_>0&&m>0,[m]);return d.createElement(ql,{points:o,showLabels:j},a.children,d.createElement(en,{animationInput:o,animationIdPrefix:"recharts-line-",items:o,previousItemsRef:n,isAnimationActive:l,animationBegin:c,animationDuration:x,animationEasing:g,onAnimationStart:f,onAnimationEnd:p,animationInterpolateFn:i,animationMatchBy:u,shouldUpdatePreviousRef:w,layout:h},(_,P,D)=>{var I=b||P<1,Q=I?L(P,m):null;return d.createElement(Gl,{props:a,points:_,clipPathId:s,pathRef:r,animationElapsedTime:P,isAnimating:
136I,isEntrance:D,visibleLength:Q})}),d.createElement(tn,{label:a.label}))}function Hl(t){var s=t.clipPathId,a=t.props,r=d.useRef(null),n=d.useRef(null);return d.createElement(Vl,{props:a,clipPathId:s,previousPointsRef:r,pathRef:n})}var Kl=(t,s)=>{var a,r;return{x:(a=t.x)!==null&&a!==void 0?a:void 0,y:(r=t.y)!==null&&r!==void 0?r:void 0,value:t.value,errorVal:Pa(t.payload,s)}};class Yl extends d.Component{render(){var s=this.props,a=s.hide,r=s.dot,n=s.points,o=s.className,l=s.xAxisId,c=s.yAxisId,x=s.top,g=s.left,u=s.width,i=s.height,h=s.id,m=s.needClip,v=s.zIndex;if(a)return null;var b=Ve("recharts-line",o),f=h,p=Ll(r),j=p.r,L=p.strokeWidth,w=ya(r),_=j*2+L,P=m?"url(#clipPath-".concat(w?"":"dots-").concat(f,")"):void 0;return d.createElement(ls,{zIndex:v},d.createElement(cs,{className:b},m&&d.createElement("defs",null,d.createElement(Zr,{clipPathId:f,xAxisId:l,yAxisId:c}),!w&&d.createElement("clipPath",{id:"clipPath-dots-".concat(f)},d.createElement("rect",{x:g-_/2,y:x-_/2,width:u+_,height:i+_}))),d.createElement(Qr,{xAxisId:l,yAxisId:c,data:n,dataPointFormatter:Kl,errorBarOffset:0},d.createElement(Hl,{props:this.props,clipPathId:f}))),d.createElement(hl,{activeDot:this.props.activeDot,points:n,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:P}))}}function Xl(t){var s=St(t,vs),a=s.activeDot,r=s.animateNewValues,n=s.animationBegin,o=s.animationDuration,l=s.animationEasing,c=s.connectNulls,x=s.dot,g=s.hide,u=s.isAnimationActive,i=s.label,h=s.legendType,m=s.xAxisId,v=s.yAxisId,b=s.id,f=js(s,Ol),p=Vr(m,v),j=p.needClip,L=Hr(),w=Kr(),_=Sa(),P=is(te=>Dl(te,m,v,_,b));if(w!=="horizontal"&&w!=="vertical"||P==null||L==null)return null;var D=L.height,I=L.width,Q=L.x,Z=L.y;return d.createElement(Yl,Nt({},f,{id:b,connectNulls:c,dot:x,activeDot:a,animateNewValues:r,animationBegin:n,animationDuration:o,animationEasing:l,isAnimationActive:u,hide:g,label:i,legendType:h,xAxisId:m,yAxisId:v,points:P,layout:w,height:D,width:I,left:Q,top:Z,needClip:j}))}function Zl(t){var s=t.layout,a=t.xAxis,r=t.yAxis,n=t.xAxisTicks,o=t.yAxisTicks,l=t.dataKey,c=t.bandSize,x=t.displayedData;return x.map((g,u)=>{var i=Pa(g,l);if(s==="horizontal"){var h=Ms({axis:a,ticks:n,bandSize:c,entry:g,index:u}),m=Vt(i)?null:r.scale.map(i);return{x:h,y:m??null,value:i,payload:g}}var v=Vt(i)?null:a.scale.map(i),b=Ms({axis:r,ticks:o,bandSize:c,entry:g,index:u});return v==null||b==null?null:{x:v,y:b,value:i,payload:g}}).filter(Boolean)}function Ql(t){var s=St(t,vs),a=Sa();return d.createElement(Br,{id:s.id,type:"line"},r=>d.createElement(d.Fragment,null,d.createElement(Wr,{legendPayload:Ul(s)}),d.createElement(Bl,{dataKey:s.dataKey,data:s.data,stroke:s.stroke,strokeWidth:s.strokeWidth,fill:s.fill,name:s.name,hide:s.hide,unit:s.unit,tooltipType:s.tooltipType,id:r}),d.createElement(qr,{type:"line",id:r,data:s.data,xAxisId:s.xAxisId,yAxisId:s.yAxisId,zAxisId:0,dataKey:s.dataKey,hide:s.hide,isPanorama:a}),d.createElement(Xl,Nt({},s,{id:r}))))}var We=d.memo(Ql,fa);We.displayName="Line";var Jl=["axis"],ec=d.forwardRef((t,s)=>d.createElement(rn,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:Jl,tooltipPayloadSearcher:nn,categoricalChartProps:t,ref:s}));
136const tc="America/New_York",sc=t=>{if(!t)return"never";try{return new Date(t).toLocaleString("en-US",{timeZone:tc,month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})+" ET"}catch{return t}},ac=t=>t?(Date.now()-new Date(t).getTime())/6e4:Number.POSITIVE_INFINITY;function rc(){const[t,s]=d.useState(null);d.useEffect(()=>{let r=!1;return(async()=>{var u,i,h,m,v;const[o,l,c,x,g]=await Promise.all([T.from("credit_transactions").select("created_at").eq("type","purchase").order("created_at",{ascending:!1}).limit(1).maybeSingle(),T.from("profiles").select("created_at").order("created_at",{ascending:!1}).limit(1).maybeSingle(),T.from("videos").select("created_at").order("created_at",{ascending:!1}).limit(1).maybeSingle(),T.from("page_events").select("created_at").eq("event","health_check").order("created_at",{ascending:!1}).limit(1).maybeSingle(),T.from("page_events").select("created_at").eq("event","landing_view").order("created_at",{ascending:!1}).limit(1).maybeSingle()]);r||s({lastPurchase:((u=o.data)==null?void 0:u.created_at)??null,lastSignup:((i=l.data)==null?void 0:i.created_at)??null,lastVideo:((h=c.data)==null?void 0:h.created_at)??null,lastHealthCheck:((m=x.data)==null?void 0:m.created_at)??null,lastLandingView:((v=g.data)==null?void 0:v.created_at)??null})})(),()=>{r=!0}},[]);const a=[{label:"Last purchase",iso:(t==null?void 0:t.lastPurchase)??null,warnAfterMin:360},{label:"Last signup",iso:(t==null?void 0:t.lastSignup)??null,warnAfterMin:120},{label:"Last video generated",iso:(t==null?void 0:t.lastVideo)??null,warnAfterMin:120},{label:"Last landing view",iso:(t==null?void 0:t.lastLandingView)??null,warnAfterMin:60},{label:"Backend heartbeat",iso:(t==null?void 0:t.lastHealthCheck)??null,warnAfterMin:20}];return e.jsxs(O,{children:[e.jsx(z,{className:"pb-3",children:e.jsx(U,{className:"text-base",children:"Site health (Eastern Time)"})}),e.jsx(E,{children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-3",children:a.map(r=>{const n=ac(r.iso)>r.warnAfterMin;return e.jsxs("div",{className:"rounded-md border p-3 flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[n?e.jsx(fe,{className:"w-3 h-3 text-destructive"}):e.jsx(we,{className:"w-3 h-3 text-green-500"}),e.jsx("span",{children:r.label})]}),e.jsx("div",{className:`text-sm font-medium ${n?"text-destructive":""}`,children:sc(r.iso)})]},r.label)})})})]})}function nc(){const[t,s]=d.useState(null),[a,r]=d.useState(null),[n,o]=d.useState(!1),[l,c]=d.useState(null),x=async()=>{o(!0),c(null);const[{data:u,error:i},h]=await Promise.all([T.rpc("admin_credit_drift"),T.from("sweeper_runs").select("mode, scanned, backfilled, refunded, credits_refunded, rail_tripped, rail_reason, created_at").order("created_at",{ascending:!1}).limit(1).maybeSingle()]);i&&c(i.message),s(u??[]),r(h.data??null),o(!1)};d.useEffect(()=>{x()},[]);const g=t!==null&&t.length===0;return e.jsxs(O,{children:[e.jsxs(z,{className:"pb-3 flex flex-row items-center justify-between space-y-0",children:[e.jsxs(U,{className:"text-base flex items-center gap-2",children:[g?e.jsx(we,{className:"w-4 h-4 text-green-500"}):e.jsx(fe,{className:"w-4 h-4 text-destructive"}),"Credit balance vs ledger"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:x,disabled:n,children:e.jsx(ve,{className:`w-4 h-4 ${n?"animate-spin":""}`})})]}),e.jsxs(E,{children:[l&&e.jsx("p",{className:"text-sm text-destructive",children:l}),!l&&t===null&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Checking…"}),!l&&g&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every wallet matches its credit history. No drift."}),!l&&t!==null&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm text-destructive font-medium",children:[t.length," account",t.length===1?"":"s"," out of sync"]}),e.jsx("div",{className:"max-h-64 overflow-auto rounded-md border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-2",children:"Email"}),e.jsx("th",{className:"text-right p-2",children:"Balance"}),e.jsx("th",{className:"text-right p-2",children:"Ledger"}),e.jsx("th",{className:"text-right p-2",children:"Owed"})]})}),e.jsx("tbody",{children:t.map(u=>e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"p-2 truncate max-w-[220px]",children:u.email??u.user_id}),e.jsx("td",{className:"p-2 text-right",children:u.balance.toLocaleStr
136ing()}),e.jsx("td",{className:"p-2 text-right",children:u.ledger.toLocaleString()}),e.jsx("td",{className:"p-2 text-right font-medium",children:u.diff.toLocaleString()})]},u.user_id))})]})})]})]})]})}const ic={sent:"bg-green-500/15 text-green-500 border-green-500/30",failed:"bg-red-500/15 text-red-500 border-red-500/30",dlq:"bg-red-500/15 text-red-500 border-red-500/30",suppressed:"bg-yellow-500/15 text-yellow-500 border-yellow-500/30",pending:"bg-blue-500/15 text-blue-500 border-blue-500/30",bounced:"bg-orange-500/15 text-orange-500 border-orange-500/30"};function lc(t,s){const a=new Date;switch(t){case"today":return{start:ze(a),end:Ie(a)};case"24h":return{start:At(a,1),end:a};case"7d":return{start:ze(At(a,6)),end:Ie(a)};case"30d":return{start:ze(At(a,29)),end:Ie(a)};case"custom":return{start:s?ze(s.from):ze(a),end:Ie(s?s.to:a)}}}function cc(){const[t,s]=d.useState("today"),[a,r]=d.useState(void 0),[n,o]=d.useState(null),[l,c]=d.useState(!0),[x,g]=d.useState("all"),[u,i]=d.useState("all"),[h,m]=d.useState(""),[v,b]=d.useState(1),f=25,p=d.useMemo(()=>lc(t,a),[t,a]),j=async()=>{c(!0);try{const{data:C,error:y}=await T.functions.invoke("admin-emails",{body:{startDate:p.start.toISOString(),endDate:p.end.toISOString()}});if(y)throw y;o(C),b(1)}catch(C){console.error("admin-emails error",C),Se.error("Failed to load email stats")}finally{c(!1)}};d.useEffect(()=>{j()},[t,a==null?void 0:a.from,a==null?void 0:a.to]);const L=(n==null?void 0:n.status_counts.sent)||0,w=((n==null?void 0:n.status_counts.dlq)||0)+((n==null?void 0:n.status_counts.failed)||0),_=(n==null?void 0:n.status_counts.suppressed)||0;n!=null&&n.status_counts.pending;const P=(n==null?void 0:n.total_unique_emails)||0,D=L+w>0?Math.round(L/(L+w)*1e3)/10:null,I=d.useMemo(()=>{const C=new Set;return n==null||n.recent_sends.forEach(y=>C.add(y.template_name)),Array.from(C).sort()},[n]),Q=d.useMemo(()=>n?n.recent_sends.filter(C=>!(x!=="all"&&C.template_name!==x||u!=="all"&&(u==="failed"&&!["failed","dlq"].includes(C.status)||u!=="failed"&&C.status!==u)||h&&!C.recipient_email.toLowerCase().includes(h.toLowerCase()))):[],[n,x,u,h]),Z=Math.max(1,Math.ceil(Q.length/f)),te=Q.slice((v-1)*f,v*f),S=d.useMemo(()=>n!=null&&n.buckets?Object.entries(n.buckets).sort(([C],[y])=>C.localeCompare(y)).map(([C,y])=>({label:n.bucket_granularity==="hour"?K(new Date(C),"MMM d HH:mm"):K(new Date(C),"MMM d"),sent:y.sent||0,failed:(y.failed||0)+(y.dlq||0),suppressed:y.suppressed||0,pending:y.pending||0})):[],[n]);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(rc,{}),e.jsx(nc,{}),e.jsx(O,{children:e.jsxs(E,{className:"pt-6",children:[e.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[e.jsxs("div",{className:"flex gap-1 bg-muted/50 rounded-md p-1",children:[[["today","Today"],["24h","24h"],["7d","7 days"],["30d","30 days"]].map(([C,y])=>e.jsx($,{size:"sm",variant:t===C?"default":"ghost",onClick:()=>s(C),className:"h-8",children:y},C)),e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsxs($,{size:"sm",variant:t==="custom"?"default":"ghost",className:"h-8",children:[e.jsx(pt,{className:"w-3.5 h-3.5 mr-1.5"}),t==="custom"&&a?`${K(a.from,"MMM d")} – ${K(a.to,"MMM d")}`:"Custom"]})}),e.jsx(xs,{className:"w-auto p-0 pointer-events-auto",align:"start",children:e.jsx(hs,{mode:"range",selected:a?{from:a.from,to:a.to}:void 0,onSelect:C=>{C!=null&&C.from&&(C!=null&&C.to)&&(r({from:C.from,to:C.to}),s("custom"))},numberOfMonths:2,className:"pointer-events-auto"})})]})]}),e.jsxs(Ce,{value:x,onValueChange:g,children:[e.jsx(Pe,{className:"w-[200px] h-9",children:e.jsx(De,{placeholder:"All templates"})}),e.jsxs(Le,{children:[e.jsx(q,{value:"all",children:"All templates"}),I.map(C=>e.jsx(q,{value:C,children:C},C))]})]}),e.jsxs(Ce,{value:u,onValueChange:i,children:[e.jsx(Pe,{className:"w-[160px] h-9",children:e.jsx(De,{})}),e.jsxs(Le,{children:[e.jsx(q,{value:"all",children:"All statuses"}),e.jsx(q,{value:"sent",children:"Sent"}),e.jsx(q,{value:"failed",children:"Failed"}),e.jsx(q,{value:"suppressed",children:"Suppressed"}),e.jsx(q,{value:"pending",children:"Pending"})]})]}),e.jsx(me,{placeholder:"Search recipient…",value:h,onChange:C=>m(C.target.value),className:"w-[220px] h-9"}),e.jsx("div",{className:"ml-auto flex gap-2",children:e.jsxs($,{variant:"outline",size:"sm",onClick:j,disabled:l,children:[e.jsx(ve,{className:`w-4 h-4 mr-2 ${l?"animate-spin":""}`})," Refresh"]})})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-3",children:[K(p.start,"PPp")," → ",K(p.end,"PPp")]})]})}
136),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsx(Be,{icon:lr,label:"Total",value:P}),e.jsx(Be,{icon:we,label:"Sent",value:L,tone:"green"}),e.jsx(Be,{icon:fe,label:"Failed",value:w,tone:"red"}),e.jsx(Be,{icon:hn,label:"Suppressed",value:_,tone:"yellow"}),e.jsx(Be,{icon:cr,label:"Delivery rate",value:D===null?"—":`${D}%`,tone:D===null?void 0:D>=95?"green":"yellow"})]}),e.jsxs(O,{children:[e.jsx(z,{className:"pb-2",children:e.jsxs(U,{className:"text-base",children:["Sends over time (",(n==null?void 0:n.bucket_granularity)==="hour"?"per hour":"per day",")"]})}),e.jsx(E,{children:S.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-8 text-center",children:"No emails in this range."}):e.jsx(Da,{width:"100%",height:220,children:e.jsxs(ln,{data:S,children:[e.jsx(La,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Aa,{dataKey:"label",tick:{fontSize:11}}),e.jsx(Ta,{allowDecimals:!1,tick:{fontSize:11}}),e.jsx(Oa,{contentStyle:{background:"hsl(var(--background))",border:"1px solid hsl(var(--border))"}}),e.jsx(tt,{dataKey:"sent",stackId:"a",fill:"hsl(142 71% 45%)"}),e.jsx(tt,{dataKey:"failed",stackId:"a",fill:"hsl(0 72% 51%)"}),e.jsx(tt,{dataKey:"suppressed",stackId:"a",fill:"hsl(45 93% 47%)"}),e.jsx(tt,{dataKey:"pending",stackId:"a",fill:"hsl(217 91% 60%)"})]})})})]}),(n==null?void 0:n.welcome_health)&&n.welcome_health.signups_total>0&&(()=>{const C=n.welcome_health,y=C.signups_total>5&&(C.coverage_pct??0)<80;return e.jsxs(O,{className:y?"border-destructive/50":"",children:[e.jsx(z,{className:"pb-2",children:e.jsxs(U,{className:"text-base flex items-center gap-2",children:[y?e.jsx(fe,{className:"w-4 h-4 text-destructive"}):e.jsx(we,{className:"w-4 h-4 text-green-500"}),"Welcome email coverage"]})}),e.jsx(E,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(nt,{label:"Signups",value:C.signups_total}),e.jsx(nt,{label:"Welcome sent",value:C.welcome_sent,tone:"green"}),e.jsx(nt,{label:"Missing",value:C.welcome_missing,tone:C.welcome_missing>0?"red":void 0}),e.jsx(nt,{label:"Coverage",value:C.coverage_pct===null?"—":`${C.coverage_pct}%`,tone:y?"red":"green"})]})})]})})(),e.jsxs(O,{children:[e.jsxs(z,{className:"pb-2 flex flex-row items-center justify-between",children:[e.jsxs(U,{className:"text-base",children:["Email log (",Q.length.toLocaleString(),")"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{size:"icon",variant:"outline",className:"h-8 w-8",disabled:v<=1,onClick:()=>b(C=>C-1),children:e.jsx(cn,{className:"w-4 h-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Page ",v," of ",Z]}),e.jsx($,{size:"icon",variant:"outline",className:"h-8 w-8",disabled:v>=Z,onClick:()=>b(C=>C+1),children:e.jsx(ns,{className:"w-4 h-4"})})]})]}),e.jsx(E,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{children:[e.jsx(k,{className:"w-[160px]",children:"Time"}),e.jsx(k,{children:"Template"}),e.jsx(k,{children:"Recipient"}),e.jsx(k,{className:"w-[110px]",children:"Status"}),e.jsx(k,{children:"Details"})]})}),e.jsx(ue,{children:te.length===0?e.jsx(G,{children:e.jsx(N,{colSpan:5,className:"text-center text-sm text-muted-foreground py-8",children:l?"Loading…":"No emails match your filters."})}):te.map(C=>e.jsxs(G,{children:[e.jsxs(N,{className:"text-xs whitespace-nowrap",children:[e.jsx("div",{children:K(new Date(C.created_at),"MMM d, HH:mm")}),e.jsx("div",{className:"text-muted-foreground",children:Ke(new Date(C.created_at),{addSuffix:!0})})]}),e.jsx(N,{className:"text-sm font-medium",children:C.template_name}),e.jsx(N,{className:"text-xs font-mono",children:C.recipient_email}),e.jsx(N,{children:e.jsx(A,{variant:"outline",className:ic[C.status]||"",children:C.status})}),e.jsx(N,{className:"text-xs text-muted-foreground max-w-[360px] truncate",title:C.error_message||C.resend_id||"",children:C.error_message||(C.resend_id?`Resend: ${C.resend_id}`:"—")})]},C.message_id))})]})})})]})]})}function Be({icon:t,label:s,value:a,tone:r}){const n=r==="green"?"text-green-500":r==="red"?"text-red-500":r==="yellow"?"text-yellow-500":"text-foreground";return e.jsx(O,{children:e.jsxs(E,{className:"pt-5 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(t,{className:"w-3.5 h-3.5"})," ",s]}),e.jsx("div",{className:`text-2xl font-bold ${n}
136`,children:typeof a=="number"?a.toLocaleString():a})]})})}function nt({label:t,value:s,tone:a}){const r=a==="green"?"text-green-500":a==="red"?"text-red-500":"";return e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:t}),e.jsx("div",{className:`text-xl font-bold ${r}`,children:typeof s=="number"?s.toLocaleString():s})]})}function dc(){const[t,s]=d.useState([]),[a,r]=d.useState(!0),[n,o]=d.useState("pending"),[l,c]=d.useState(null),[x,g]=d.useState({}),u=d.useCallback(async()=>{r(!0);let m=T.from("review_submissions").select("*").order("created_at",{ascending:!1}).limit(200);n!=="all"&&(m=m.eq("status",n));const{data:v,error:b}=await m;b?Se.error("Failed to load reviews"):s(v??[]),r(!1)},[n]);d.useEffect(()=>{u()},[u]);const i=async m=>{const v=x[m.id]??"200",b=parseInt(v,10);if(!Number.isFinite(b)||b<=0||b>5e3){Se.error("Enter a credit amount between 1 and 5000");return}c(m.id);try{const{data:{session:f}}=await T.auth.getSession();if(!(f!=null&&f.access_token))throw new Error("Not authenticated");const{data:p,error:j}=await T.functions.invoke("admin-grant-review-credits",{headers:{Authorization:`Bearer ${f.access_token}`},body:{reviewId:m.id,credits:b}});if(j)throw j;if(p&&p.error)throw new Error(p.error);Se.success(`Granted ${b} credits to ${m.email}`),await u()}catch(f){console.error(f),Se.error(f instanceof Error?f.message:"Failed to grant credits")}finally{c(null)}},h=async m=>{c(m.id);try{const{error:v}=await T.from("review_submissions").update({status:"dismissed"}).eq("id",m.id);if(v)throw v;await u()}catch{Se.error("Failed to dismiss")}finally{c(null)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(O,{children:e.jsxs(E,{className:"pt-6 flex flex-wrap items-center gap-3",children:[e.jsx(dr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"User reviews queued for credits"}),e.jsxs(Ce,{value:n,onValueChange:m=>o(m),children:[e.jsx(Pe,{className:"w-[160px] h-9 ml-auto",children:e.jsx(De,{})}),e.jsxs(Le,{children:[e.jsx(q,{value:"pending",children:"Pending"}),e.jsx(q,{value:"credited",children:"Credited"}),e.jsx(q,{value:"dismissed",children:"Dismissed"}),e.jsx(q,{value:"all",children:"All"})]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:u,disabled:a,children:[e.jsx(ve,{className:`h-4 w-4 mr-2 ${a?"animate-spin":""}`}),"Refresh"]})]})}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:"Loading…"}):t.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground text-sm",children:["No ",n==="all"?"":n," reviews."]}):e.jsx("div",{className:"space-y-3",children:t.map(m=>e.jsxs(O,{children:[e.jsxs(z,{className:"pb-2 flex flex-row items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(U,{className:"text-sm flex items-center gap-2",children:[m.name||"Anonymous",e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:m.email})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[Ke(new Date(m.created_at),{addSuffix:!0}),m.user_id?" · linked account":" · no account match"]})]}),e.jsxs(A,{variant:"outline",className:m.status==="credited"?"bg-green-500/15 text-green-500 border-green-500/30":m.status==="dismissed"?"bg-muted text-muted-foreground":"bg-yellow-500/15 text-yellow-500 border-yellow-500/30",children:[m.status,m.credits_granted?` · +${m.credits_granted}`:""]})]}),e.jsxs(E,{children:[e.jsx("pre",{className:"whitespace-pre-wrap text-sm text-foreground/90 font-sans bg-muted/30 rounded p-3 border border-border/50",children:m.message}),m.status==="pending"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-4",children:[e.jsx(me,{type:"number",className:"w-28 h-9",placeholder:"200",value:x[m.id]??"200",onChange:v=>g(b=>({...b,[m.id]:v.target.value})),disabled:l===m.id,min:1,max:5e3}),e.jsxs($,{size:"sm",onClick:()=>i(m),disabled:l===m.id,children:[l===m.id?e.jsx(V,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Grant credits"]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>h(m),disabled:l===m.id,children:"Dismiss"})]})]})]},m.id))})]})}const oc=["new","escalated","resolved"];function uc(t){const s=Date.now()-new Date(t).getTime(),a=Math.round(s/6e4);if(a<1)return"just now";if(a<60)return`${a}m ago`;const r=Math.round(a/60);return r<24?`${r}h ago`:`${Math.round(r/24)}d ago`}function Ft(t){return t?t.replace(/_/g," "):"unclassified"}async function zt(t){const{data:s,error:a}=await T.functions.invoke("admin-support-tickets",{body:t});if(a)throw a;if(s!=null&&s.error)throw new Error(s.error);return s}
136function mc(){const[t,s]=d.useState("new"),[a,r]=d.useState([]),[n,o]=d.useState({}),[l,c]=d.useState(null),[x,g]=d.useState(null),[u,i]=d.useState(null),[h,m]=d.useState(!1),[v,b]=d.useState(""),[f,p]=d.useState(!1),j=d.useCallback(async()=>{m(!0);try{const D=await zt({action:"list",status:t});r(D.tickets??[]),o(D.counts??{})}catch(D){Ze({title:"Could not load tickets",description:String(D),variant:"destructive"})}finally{m(!1)}},[t]);d.useEffect(()=>{j(),c(null),g(null),i(null)},[j]);const L=d.useCallback(async D=>{c(D),b(""),p(!1);try{const I=await zt({action:"detail",ticket_id:D});g(I.ticket),i(I.account??null)}catch(I){Ze({title:"Could not load ticket",description:String(I),variant:"destructive"})}},[]),w=async D=>{if(x)try{await zt({action:D,ticket_id:x.id,note:v||void 0}),Ze({title:D==="resolve"?"Marked resolved":"Escalated"}),c(null),g(null),i(null),j()}catch(I){Ze({title:"Action failed",description:String(I),variant:"destructive"})}},_=async()=>{x!=null&&x.ai_draft&&(await navigator.clipboard.writeText(x.ai_draft),p(!0),setTimeout(()=>p(!1),2e3))},P=(x==null?void 0:x.category)==="safety_report";return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[380px_1fr]",children:[e.jsxs(O,{className:"h-fit",children:[e.jsxs(z,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(U,{className:"text-base",children:"Support inbox"}),e.jsx($,{variant:"ghost",size:"icon",onClick:j,"aria-label":"Refresh tickets",children:e.jsx(ve,{className:R("h-4 w-4",h&&"animate-spin")})})]}),e.jsx(as,{value:t,onValueChange:D=>s(D),className:"mt-2",children:e.jsx(rs,{className:"w-full",children:oc.map(D=>e.jsxs(J,{value:D,className:"flex-1 capitalize text-xs",children:[D,n[D]?e.jsx("span",{className:"ml-1 opacity-60",children:n[D]}):null]},D))})})]}),e.jsxs(E,{className:"space-y-2 max-h-[70vh] overflow-y-auto",children:[a.length===0&&e.jsxs("p",{className:"py-6 text-center text-sm text-muted-foreground",children:["No ",t," tickets."]}),a.map(D=>{const I=D.category==="safety_report";return e.jsxs("button",{onClick:()=>L(D.id),className:R("w-full rounded-lg border p-3 text-left transition-colors hover:bg-muted/50",l===D.id&&"border-primary bg-muted/40",I&&"border-destructive/60 bg-destructive/5"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:D.from_email}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:uc(D.received_at)})]}),e.jsx("p",{className:"mt-1 truncate text-sm text-muted-foreground",children:D.subject||"(no subject)"}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsxs(A,{variant:I?"destructive":"secondary",className:"text-[10px] capitalize",children:[I&&e.jsx(ss,{className:"mr-1 h-3 w-3"}),Ft(D.category)]}),!D.matched_user_id&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"no account"})]})]},D.id)})]})]}),e.jsxs("div",{className:"space-y-4",children:[!x&&e.jsx(O,{children:e.jsx(E,{className:"py-16 text-center text-sm text-muted-foreground",children:"Select a ticket to view it."})}),x&&e.jsxs(e.Fragment,{children:[e.jsxs(O,{children:[e.jsx(z,{className:"pb-3",children:e.jsx(U,{className:"text-base",children:"The message"})}),e.jsxs(E,{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"text-muted-foreground",children:[x.from_name?`${x.from_name} · `:"",x.from_email," · ",new Date(x.received_at).toLocaleString()]}),e.jsx("div",{className:"font-medium",children:x.subject||"(no subject)"}),e.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-md bg-muted/40 p-3 font-sans text-sm",children:x.body})]})]}),e.jsxs(O,{children:[e.jsx(z,{className:"pb-3",children:e.jsx(U,{className:"text-base",children:"Account snapshot"})}),e.jsx(E,{className:"text-sm",children:u?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Email: "}),u.email]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Signed up: "}),u.created_at?new Date(u.created_at).toLocaleDateString():"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Credits: "}
136),(u.credits??0).toLocaleString()]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Subscription: "}),u.subscription_status??"none",u.subscription_tier?` (${u.subscription_tier})`:""]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Generations: "}),u.total_generations.toLocaleString()]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Last active: "}),u.last_generation_at?new Date(u.last_generation_at).toLocaleDateString():"—"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1 text-muted-foreground",children:"Purchase history"}),u.purchases.length===0?e.jsx("p",{className:"text-muted-foreground",children:"No purchases."}):e.jsx("ul",{className:"space-y-1",children:u.purchases.map((D,I)=>e.jsxs("li",{className:"flex justify-between gap-3 border-b border-border/50 py-1",children:[e.jsxs("span",{className:"truncate",children:[new Date(D.created_at).toLocaleDateString()," · ",D.description??D.type]}),e.jsxs("span",{className:"shrink-0",children:[D.amount.toLocaleString()," cr"]})]},I))})]})]}):e.jsx("p",{className:"text-muted-foreground",children:"No account found for this email address."})})]}),e.jsxs(O,{className:R(P&&"border-destructive/60"),children:[e.jsx(z,{className:"pb-3",children:e.jsx(U,{className:"text-base",children:"AI analysis"})}),e.jsx(E,{className:"space-y-3 text-sm",children:P?e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-destructive/10 p-3 text-destructive",children:[e.jsx(fe,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:"Safety report — requires manual review. No AI draft generated."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{variant:"secondary",className:"capitalize",children:Ft(x.category)}),e.jsx(A,{variant:"outline",className:"capitalize",children:Ft(x.ai_suggested_action)})]}),x.ai_reasoning&&e.jsx("p",{className:"text-muted-foreground",children:x.ai_reasoning}),e.jsx(or,{readOnly:!0,value:x.ai_draft??"No draft was generated.",className:"min-h-[180px] font-sans"}),e.jsxs($,{variant:"secondary",size:"sm",onClick:_,disabled:!x.ai_draft,children:[f?e.jsx(ur,{className:"mr-2 h-4 w-4"}):e.jsx(mt,{className:"mr-2 h-4 w-4"}),f?"Copied":"Copy draft"]})]})})]}),e.jsx(O,{children:e.jsxs(E,{className:"flex flex-col gap-3 pt-6 sm:flex-row sm:items-center",children:[e.jsx(me,{placeholder:"Optional note when resolving",value:v,onChange:D=>b(D.target.value),className:"sm:max-w-xs"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{onClick:()=>w("resolve"),disabled:x.status==="resolved",children:"Mark resolved"}),e.jsx($,{variant:"outline",onClick:()=>w("escalate"),disabled:x.status==="escalated",children:"Escalate"})]})]})})]})]})]})}const re=t=>t==null?"—":`${t<0?"-":""}$${Math.abs(t).toFixed(2)}`,Ne=t=>(t??0).toLocaleString();function xc({activeDates:t}){const[s,a]=d.useState(!0),[r,n]=d.useState(null),[o,l]=d.useState([]),[c,x]=d.useState(null),[g,u]=d.useState(0),[i,h]=d.useState(null),[m,v]=d.useState(null),[b,f]=d.useState(null),[p,j]=d.useState(null),[L,w]=d.useState({}),_=d.useRef({}),P=d.useCallback(async()=>{a(!0),n(null);const{data:{session:S}}=await T.auth.getSession();if(!(S!=null&&S.access_token)){n("Not authenticated"),a(!1);return}const{data:C,error:y}=await T.functions.invoke("admin-profitability",{headers:{Authorization:`Bearer ${S.access_token}`},body:{start_date:t.start,end_date:t.end,timezone_offset:new Date().getTimezoneOffset()}});if(y||C!=null&&C.error){n((C==null?void 0:C.error)||(y==null?void 0:y.message)||"Failed to load"),a(!1);return}l(C.daily||[]),x(C.totals||null),u(C.paying_users||0),h(C.cost_per_paying_user??null),v(C.avg_order_value??null),f(C.avg_profit_per_order??null),j(C.revenue_error||null);const B={};for(const X of C.daily||[])B[X.date]=String(X.ads_usd??0);w(B),a(!1)},[t.start,t.end]);d.useEffect(()=>{P()},[P]);const D=d.useCallback(async(S,C)=>{const y=Number(C);if(!Number.isFinite(y)||y<0)return;const{data:{session:B}}=await T.auth.getSession();B!=null&&B.access_token&&(await T.functions.invoke("admin-set-ad-spend",{headers:{Authorization:`Bearer ${B.access_token}`},body:{date:S,google_ads_usd:y}}),l(X=>X.map(ie=>{if(ie.date!==S)return ie;const M=+(ie.revenue_usd-ie.cogs_usd-ie.free_cogs_usd-y).toFixed(2),Dt=ie.revenue_usd>0?+(M/ie.revenue_usd*100).toFixed(1):null;return{...ie,ads_usd:y,profit_usd:M,margin_pct:Dt}})))},[]);d.useEffect(()=>{if(!o.length)return;const S={orders:0,starter:0,pro:0,elite:0,subs:0,other:0,credits_sold:0,revenue_usd:0,subs_revenue_usd:0,cogs_usd:0,free_cogs_usd:0,free_credits_used:0,ads_usd:0,profit_usd:0,margin_pct:null};for(const y of o)S.orders+=y.orders,S.starter+=y.starter,S.pro+=y.pro,S.elite+=y.elite,S.subs+=y.subs,S.other+=y.other,S.credits_sold+=y.credits_sold,S.revenue_usd+=y.revenue_usd,S.subs_revenue_usd+=y.subs_revenue_usd,S.cogs_usd+=y.cogs_usd,S.free_cogs_usd+=y.free_cogs_usd,S.free_credits_used+=y.free_credits_used,S.ads_usd+=y.ads_usd,S.profit_usd+=y.profit_usd;S.revenue_usd=+S.revenue_usd.toFixed(2),S.cogs_usd=+S.cogs_usd.toFixed(2),S.free_cogs_usd=+S.free_cogs_usd.toFixed(2),S.ads_usd=+S.ads_usd.toFixed(2),S.profit_usd=+S.profit_usd.toFixed(2),S.margin_pct=S.revenue_usd>0?+(S.profit_usd/S.revenue_usd*100).toFixed(1):null,x(S);const C=S.cogs_usd+S.free_cogs_usd+S.ads_usd;h(g>0?+(C/g).toFixed(2):null),v(S.orders>0?+(S.revenue_usd/S.orders).toFixed(2):null),f(S.orders>0?+(S.profit_usd/S.orders).toFixed(2):null)},[o,g]);const I=(S,C)=>{w(y=>({...y,[S]:C})),_.current[S]&&window.clearTimeout(_.current[S]),_.current[S]=window.setTimeout(()=>D(S,C),500)},Q=()=>
136{if(!o.length)return;const S=["Date","Orders","Starter","Pro","Elite","Subs","Other","Credits Sold","Revenue","Subs Revenue","Pack COGS","Free Credits Used","Free COGS","Ads","Profit","Margin %"],C=o.map(M=>[M.date,M.orders,M.starter,M.pro,M.elite,M.subs,M.other,M.credits_sold,M.revenue_usd.toFixed(2),M.subs_revenue_usd.toFixed(2),M.cogs_usd.toFixed(2),M.free_credits_used,M.free_cogs_usd.toFixed(2),M.ads_usd.toFixed(2),M.profit_usd.toFixed(2),M.margin_pct??""]),y=[S,...C].map(M=>M.join(",")).join(`
137`),B=new Blob([y],{type:"text/csv"}),X=URL.createObjectURL(B),ie=document.createElement("a");ie.href=X,ie.download=`profitability_${t.start}_to_${t.end}.csv`,ie.click(),URL.revokeObjectURL(X)},Z=d.useMemo(()=>{if(!c)return null;const S=c.profit_usd>=0;return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:[e.jsx(pe,{icon:e.jsx(He,{className:"h-4 w-4"}),label:"Revenue",value:re(c.revenue_usd),accent:"primary"}),e.jsx(pe,{icon:e.jsx(zs,{className:"h-4 w-4"}),label:"Pack COGS (sold)",value:re(c.cogs_usd),accent:"muted"}),e.jsx(pe,{icon:e.jsx(zs,{className:"h-4 w-4"}),label:"Free Credits COGS",value:re(c.free_cogs_usd),accent:"muted"}),e.jsx(pe,{icon:e.jsx(Ht,{className:"h-4 w-4"}),label:"Ads Spend",value:re(c.ads_usd),accent:"muted"}),e.jsx(pe,{icon:S?e.jsx(qe,{className:"h-4 w-4"}):e.jsx(Ht,{className:"h-4 w-4"}),label:"Net Profit",value:re(c.profit_usd),accent:S?"success":"destructive"}),e.jsx(pe,{icon:e.jsx(qe,{className:"h-4 w-4"}),label:"Margin",value:c.margin_pct===null?"—":`${c.margin_pct.toFixed(1)}%`,accent:S?"success":"destructive"})]})},[c]),te=d.useMemo(()=>c?e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:[e.jsx(pe,{icon:e.jsx(Nn,{className:"h-4 w-4"}),label:"Orders / AOV",value:`${Ne(c.orders)} · ${m!==null?re(m):"—"}`,accent:"primary"}),e.jsx(pe,{icon:e.jsx(Tt,{className:"h-4 w-4"}),label:"Starter",value:Ne(c.starter),accent:"muted"}),e.jsx(pe,{icon:e.jsx(Tt,{className:"h-4 w-4"}),label:"Pro",value:Ne(c.pro),accent:"muted"}),e.jsx(pe,{icon:e.jsx(Tt,{className:"h-4 w-4"}),label:"Elite",value:Ne(c.elite),accent:"muted"}),e.jsx(pe,{icon:e.jsx(Ge,{className:"h-4 w-4"}),label:"Free Credits Used",value:Ne(c.free_credits_used),accent:"muted"}),e.jsx(pe,{icon:e.jsx(Ge,{className:"h-4 w-4"}),label:"Avg Profit / Order",value:b!==null?re(b):"—",accent:(b??0)>=0?"success":"destructive"})]}):null,[c,m,b]);return s?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 rounded-full border-2 border-primary border-t-transparent animate-spin"})}):r?e.jsx(O,{children:e.jsx(E,{className:"pt-6 text-destructive text-sm",children:r})}):e.jsxs("div",{className:"space-y-4",children:[Z,te,p&&e.jsx(O,{className:"border-amber-500/30 bg-amber-500/5",children:e.jsxs(E,{className:"pt-4 pb-4 flex items-start gap-2 text-sm",children:[e.jsx(fe,{className:"h-4 w-4 text-amber-500 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-amber-500",children:"Revenue source unavailable"}),e.jsxs("p",{className:"text-muted-foreground",children:["Stripe error: ",p]})]})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("strong",{children:"Hybrid model:"})," Pack COGS is locked in at the moment of purchase (assumes 100% redemption). Free Credits COGS (welcome 300, free trial 1,000, admin grants) is consumption-based — counted only when actually spent on a video/image, FIFO per user. Cost basis: $0.0015 per our credit. Pack COGS — Starter $2.40 · Pro $15.90 · Elite $75.00.",g>0&&` ${g} unique paying customers in range.`]}),e.jsx(O,{children:e.jsxs(E,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Daily breakdown"}),e.jsxs($,{size:"sm",variant:"outline",onClick:Q,className:"h-8 gap-1.5",children:[e.jsx(mr,{className:"h-3.5 w-3.5"})," Export CSV"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{children:[e.jsx(k,{className:"whitespace-nowrap",children:"Date"}),e.jsx(k,{className:"text-right",children:"Orders"}),e.jsx(k,{className:"text-right",children:"Starter"}),e.jsx(k,{className:"text-right",children:"Pro"}),e.jsx(k,{className:"text-right",children:"Elite"}),e.jsx(k,{className:"text-right",children:"Subs"}),e.jsx(k,{className:"text-right",children:"Other"}),e.jsx(k,{className:"text-right",children:"Credits Sold"}),e.jsx(k,{className:"text-right",children:"Revenue"}),e.jsx(k,{className:"text-right",children:"Pack COGS"}),e.jsx(k,{className:"text-right",children:"Free Used"}),e.jsx(k,{className:"text-right",children:"Free COGS"}),e.jsx(k,{className:"text-right w-32",children:"Ads $"}),e.jsx(k,{className:"text-right",children:"Profit"}),e.jsx(k,{className:"text-right",children:"Margin"})]})}),e.jsxs(ue,{children:[o.map(S=>e.jsxs(G,{children:[e.jsx(N,{className:"font-mono text-xs whitespace-nowrap",children:S.date}),e.jsx(N,{className:"text-right tabular-nums",children:S.orders}),e.jsx(N,{className:"text-right tabular-nums",children:S.starter}),e.jsx(N,{className:"text-right tabular-nums",children:S.pro}),e.jsx(N,{className:"text-right tabular-nums",children:S.elite}),e.jsx(N,{className:"text-right tabular-nums",children:S.subs}),e.jsx(N,{className:"text-right tabular-nums",children:S.other}),e.jsx(N,{className:"text-right tabular-nums",children:Ne(S.credits_sold)}),e.jsx(N,{className:"text-right tabular-nums",children:re(S.revenue_usd)}),e.jsx(N,{className:"text-right tabular-nums",children:re(S.cogs_usd)}),e.jsx(N,{className:"text-right tabular-nums",children:Ne(S.free_credits_used)}),e.jsx(N,{className:"text-right tabular-nums",children:re(S.free_cogs_usd)}),e.jsx(N,{className:"text-right",children:e.jsx(me,{type:"number",step:"0.01",min:"0",value:L[S.date]??"0",onChange:C=>I(S.date,C.target.value),className:"h-7 text-right tabular-nums w-28 ml-auto"})}),e.jsx(N,{className:R("text-right tabular-nums font-medium",S.profit_usd>0&&"text-emerald-500",S.profit_usd<0&&"text-destructive"),children:re(S.profit_usd)}),e.jsx(N,{className:R("text-right tabular-nums",(S.margin_pct??0)>0&&"text-emerald-500",(S.margin_pct??0)<0&&"text-destructive"),children:S.margin_pct===null?"—":`${S.margin_pct.toFixed(1)}%`})]},S.date)),c&&e.jsxs(G,{className:"border-t-2 font-medium bg-muted/30",children:[e.jsx(N,{children:"Total"}),e.jsx(N,{className:"text-right tabular-nums",children:c.orders}),e.jsx(N,{className:"text-right tabular-nums",children:c.starter}),e.jsx(N,{className:"text-right tabular-nums",children:c.pro}),e.jsx(N,{className:"text-right tabular-nums",children:c.elite}),e.jsx(N,{className:"text-right tabular-nums",children:c.subs}),e.jsx(N,{className:"text-right tabular-nums",children:c.other}),e.jsx(N,{className:"text-right tabular-nums",children:Ne(c.credits_sold)}),e.jsx(N,{className:"text-right tabular-nums",children:re(c.revenue_usd)}),e.jsx(N,{className:"text-right tabular-nums",children:re(c.cogs_usd)}),e.jsx(N,{className:"text-right tabular-nums",children:Ne(c.free_credits_used)}),e.jsx(N,{className:"text-right tabular-nums",children:re(c.free_cogs_usd)}),e.jsx(N,{className:"text-right tabular-nums",children:re(c.ads_usd)}),e.jsx(N,{className:R("text-right tabular-nums",c.profit_usd>0&&"text-emerald-500",c.profit_usd<0&&"text-destructive"),children:re(c.profit_usd)}),e.jsx(N,{className:R("text-right tabular-nums",(c.margin_pct??0)>0&&"text-emerald-500",(c.margin_pct??0)<0&&"text-destructive"),children:c.margin_pct===null?"—":`${c.margin_pct.toFixed(1)}%`})]})]})]})})]})})]})}function pe({icon:t,label:s,value:a,accent:r}){const n=r==="success"?"text-emerald-500":r==="destructive"?"text-destructive":r==="muted"?"text-muted-foreground":"text-primary";return e.jsx(O,{children:e.jsxs(E,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:R("flex items-center gap-1.5 text-xs",n),children:[t,e.jsx("span",{className:"text-muted-foreground",children:s})]}),e.jsx("p",{className:R("text-xl font-semibold mt-1 tabular-nums",n),children:a})]})})}const _t=(t,s)=>s>0?t/s*100:0,_e=(t,s)=>`${_t(t,s).toFixed(1)}%`,Ut=t=>t==null?"—":t<1?`${Math.round(t*60)}m`:t<48?`${t.toFixed(1)}h`:`${(t/24).toFixed(1)}d`;function hc({funnel:t,campaigns:s,trafficSources:a}){if(!t)return e.jsx(O,{className:"border-border/50 bg-card/50",children:e.jsx(E,{className:"py-12 text-center text-sm text-muted-foreground",children:"Loading funnel…"})});const r=[{key:"visitors",label:"Visitors",sublabel:`${t.visitors_from_ads.toLocaleStr
137ing()} from ads`,value:t.visitors,prev:null,icon:Ge,color:"from-blue-500/30 to-blue-500/10",barColor:"bg-blue-500/70"},{key:"signups",label:"Signed Up",sublabel:"Google OAuth",value:t.signups,prev:t.visitors,icon:wn,color:"from-purple-500/30 to-purple-500/10",barColor:"bg-purple-500/70"},{key:"trials",label:"Started Free Trial",sublabel:`Median signup→trial: ${Ut(t.median_signup_to_trial_hours)}`,value:t.trials_started,prev:t.signups,icon:xr,color:"from-pink-500/30 to-pink-500/10",barColor:"bg-pink-500/70"},{key:"purchases",label:"Purchased",sublabel:`${t.purchased_after_trial} after trial · ${t.purchased_without_trial} skipped trial`,value:t.purchasers,prev:t.trials_started,icon:He,color:"from-green-500/30 to-green-500/10",barColor:"bg-green-500/70"}],n=t.purchasers>0?t.revenue_total/t.purchasers:0,o=_t(t.purchasers,t.visitors);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center justify-between text-lg",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Ht,{className:"h-4 w-4 text-primary"})}),"Conversion Funnel — Ad → Signup → Trial → Purchase"]}),e.jsxs(A,{variant:"outline",className:"text-xs",children:["Overall: ",o.toFixed(2),"% visitor → paid"]})]})}),e.jsx(E,{className:"space-y-4",children:r.map((l,c)=>{const x=l.icon,g=t.visitors>0?l.value/t.visitors*100:0,u=l.prev!=null?_t(l.value,l.prev):100,i=l.prev!=null?Math.max(0,l.prev-l.value):0;return e.jsxs("div",{children:[c>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground my-1.5 ml-4",children:[e.jsx(xn,{className:"h-3 w-3"}),e.jsxs("span",{className:u<20?"text-rose-400 font-medium":"text-foreground/70",children:[u.toFixed(1),"% conv"]}),e.jsxs("span",{className:"text-rose-400/80",children:["· ",i.toLocaleString()," dropped off"]})]}),e.jsxs("div",{className:`rounded-lg bg-gradient-to-r ${l.color} border border-border/40 p-4`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(x,{className:"h-5 w-5 text-foreground/80 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold text-sm",children:l.label}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:l.sublabel})]})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:l.value.toLocaleString()}),e.jsxs("div",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:[_e(l.value,t.visitors)," of visitors"]})]})]}),e.jsx("div",{className:"mt-3 h-1.5 rounded-full bg-background/40 overflow-hidden",children:e.jsx("div",{className:`h-full ${l.barColor} transition-all`,style:{width:`${Math.max(2,g)}%`}})})]})]},l.key)})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(it,{label:"Visitor → Signup",value:_e(t.signups,t.visitors),sub:`${t.signups} of ${t.visitors}`}),e.jsx(it,{label:"Signup → Trial",value:_e(t.trials_started,t.signups),sub:`Median: ${Ut(t.median_signup_to_trial_hours)}`}),e.jsx(it,{label:"Trial → Purchase",value:_e(t.purchased_after_trial,t.trials_started),sub:`Median: ${Ut(t.median_trial_to_purchase_hours)}`}),e.jsx(it,{label:"Avg Order Value",value:`$${(n/100).toFixed(2)}`,sub:`Total: $${(t.revenue_total/100).toFixed(0)}`})]}),e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsx(z,{children:e.jsx(U,{className:"text-base",children:"Daily Funnel"})}),e.jsx(E,{children:t.daily.length===0?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"No data in this date range."}):e.jsx(Da,{width:"100%",height:280,children:e.jsxs(ec,{data:t.daily,children:[e.jsx(La,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(Aa,{dataKey:"date",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Ta,{tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Oa,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12}}),e.jsx(Wa,{wrapperStyle:{fontSize:12}}),e.jsx(We,{type:"monotone",dataKey:"visitors",stroke:"#60a5fa",strokeWidth:2,dot:!1}),e.jsx(We,{type:"monotone",dataKey:"signups",stroke:"#a78bfa",strokeWidth:2,dot:!1}),e.jsx(We,{type:"monotone",dataKey:"trials",stroke:"#f472b6",strokeWidth:2,dot:!1}),e.jsx(We,{type:"monotone",dataKey:"purchases",stroke:"#34d399",strokeWidth:2,dot:!1})]})})})]}),e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center gap-2 text-base",children:[e.jsx(Fs,{className:"h-4 w-4 text-primary"}),"Funnel by Traffic Source"]})}),e.jsx(E,{className:"overflow-x-auto",children:s.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:["No UTM-tagged traffic in range. Tag ads with ",e.jsx("code",{className:"bg-secondary/60 px-1.5 py-0.5 rounded text-[11px]",children:"?utm_source=facebook&utm_campaign=propack"}),"."]}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50 text-xs uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Source / Campaign"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Visitors"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Signups"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Trials"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Paid"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Sign%"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Trial%"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Paid%"})]})}),e.jsx("tbody",{children:s.map((l,c)=>e.jsxs("tr",{className:"border-b border-border/30 hover:bg-muted/20",children:[e.jsxs("td",{className:"py-2 px-2",children:[e.jsx("div",{className:"font-medium",children:l.source}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l.campaign})]}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:l.visitors.toLocaleStr
137ing()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:l.signups.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:(l.trials??0).toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums font-semibold",children:l.purchasers.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right text-xs text-muted-foreground",children:_e(l.signups,l.visitors)}),e.jsx("td",{className:"py-2 px-2 text-right text-xs text-muted-foreground",children:_e(l.trials??0,l.signups)}),e.jsx("td",{className:"py-2 px-2 text-right text-xs text-muted-foreground",children:_e(l.purchasers,l.visitors)})]},c))})]})})]}),e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsx(z,{children:e.jsx(U,{className:"text-base",children:"Drop-off Diagnostics"})}),e.jsxs(E,{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(Bt,{stage:"Visitor → Signup",count:t.dropoff_visited_no_signup,total:t.visitors,hint:`${(t.signup_view_sessions??0).toLocaleString()} sessions reached the signup page`}),e.jsx(Bt,{stage:"Signup → Trial",count:t.dropoff_signup_no_trial,total:t.signups,hint:`${(t.pricing_view_sessions??0).toLocaleString()} sessions viewed pricing or clicked trial`}),e.jsx(Bt,{stage:"Trial → Purchase",count:t.dropoff_trial_no_purchase,total:t.trials_started,hint:"Trialers who never converted to a paid pack"})]})]}),a&&a.length>0&&e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsxs(z,{children:[e.jsxs(U,{className:"text-base flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4 text-primary"})," Traffic Sources"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Where users come from (referrer + UTMs). ChatGPT, Google Organic, Reddit etc. — not just paid ads."})]}),e.jsx(E,{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/40 text-xs uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Channel"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Signups"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Trials"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Generators"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Paid"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Trial %"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Paid %"})]})}),e.jsx("tbody",{children:a.map(l=>e.jsxs("tr",{className:"border-b border-border/20 hover:bg-background/30",children:[e.jsx("td",{className:"py-2 px-2 font-medium capitalize",children:l.channel.replace(/_/g," ")}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:l.signups.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:l.trials.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:l.generators.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums text-emerald-400",children:l.purchasers.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums text-muted-foreground",children:_e(l.trials,l.signups)}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums text-muted-foreground",children:_e(l.purchasers,l.signups)})]},l.channel))})]})})]})]})}function it({label:t,value:s,sub:a}){return e.jsx(O,{className:"border-border/50 bg-card/50",children:e.jsxs(E,{className:"p-4",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium",children:t}),e.jsx("div",{className:"text-2xl font-bold mt-1 tabular-nums",children:s}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 truncate",children:a})]})})}function Bt({stage:t,count:s,total:a,hint:r}){const n=_t(s,a);return e.jsxs("div",{className:"rounded-lg border border-border/40 bg-background/30 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:t}),e.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[e.jsx("span",{className:"text-xl font-bold tabular-nums text-rose-400",children:s.toLocaleStr
137ing()}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",n.toFixed(1),"% lost)"]})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground mt-2 leading-snug",children:r})]})}const pc={lt1s:"< 1s",lt3s:"1–3s",lt8s:"3–8s",gte8s:"8s+",unknown:"No CTA click recorded"};function gc({range:t}){var u;const[s,a]=d.useState([]),[r,n]=d.useState([]),[o,l]=d.useState(!0),[c,x]=d.useState(null);d.useEffect(()=>{const i=t.from,h=t.to??t.from;if(!i||!h)return;let m=!1;return l(!0),x(null),(async()=>{const v=new Date(i);v.setHours(0,0,0,0);const b=new Date(h);b.setHours(23,59,59,999);const f={_start:v.toISOString(),_end:b.toISOString()},[p,j]=await Promise.all([T.rpc("admin_signup_funnel_stats",f),T.rpc("admin_signup_arrival_timing",f)]);m||(p.error?x(p.error.message):(a((p.data??[]).map(L=>({step:L.step,ord:Number(L.ord),sessions:Number(L.sessions)}))),n((j.data??[]).map(L=>({bucket:L.bucket,sessions:Number(L.sessions)})))),l(!1))})(),()=>{m=!0}},[t]);const g=((u=s[0])==null?void 0:u.sessions)??0;return e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center gap-2 text-lg",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(fn,{className:"h-4 w-4 text-primary"})}),"Signup Funnel — CTA → Page → OAuth → Account"]})}),e.jsx(E,{children:o?e.jsxs("div",{className:"flex items-center gap-2 py-8 text-muted-foreground",children:[e.jsx(V,{className:"h-4 w-4 animate-spin"})," Loading…"]}):c?e.jsx("p",{className:"text-sm text-destructive",children:c}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-2",children:s.map(i=>{const h=g?i.sessions/g*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-muted-foreground",children:i.step}),e.jsxs("span",{className:"font-medium tabular-nums",children:[i.sessions.toLocaleString(),g?e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:[h.toFixed(1),"%"]}):null]})]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${Math.min(h,100)}%`}})})]},i.ord)})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Time from CTA click to signup page"}),r.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No arrivals recorded in this range yet."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(i=>e.jsxs("span",{className:"rounded-full border border-border/60 px-3 py-1 text-xs",children:[pc[i.bucket]??i.bucket,": ",e.jsx("span",{className:"font-medium",children:i.sessions.toLocaleString()})]},i.bucket))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Counts are unique sessions. Data only exists from the moment this tracking shipped."})]})})]})}function fc(){const[t,s]=d.useState(null),[a,r]=d.useState(0),[n,o]=d.useState(!0),[l,c]=d.useState(!1),[x,g]=d.useState(!1),{toast:u}=Ae(),i=d.useCallback(async()=>{const[{data:v,error:b},f]=await Promise.all([T.rpc("admin_signup_region_gate_status"),T.rpc("admin_region_gated_accounts")]);if(!b&&Array.isArray(v)&&v[0]){const p=v[0];s({enabled:!!p.enabled,updated_at:p.updated_at??null,stalls_24h:Number(p.stalls_24h??0),withheld_total:Number(p.withheld_total??0)})}f.error||r(Number(f.data??0)),o(!1)},[]);d.useEffect(()=>{i()},[i]);const h=async v=>{c(!0);const{error:b}=await T.rpc("admin_set_signup_region_gate",{_enabled:v});if(c(!1),b){u({title:"Could not update",description:b.message,variant:"destructive"});return}u({title:v?"Canada region gate ON":"Canada region gate OFF",description:v?"New Canadian signups fail silently and can't log in.":"Everything is back to normal for Canada."}),i()},m=async()=>{g(!0);const{data:v,error:b}=await T.rpc("admin_restore_region_withheld_credits");if(g(!1),b){u({title:"Restore failed",description:b.message,variant:"destructive"});return}u({title:"Credits restored",description:`${Number(v??0)} account(s) had their withheld welcome credits granted back.`}),i()};return e.jsxs(O,{children:[e.jsx(z,{className:"pb-3",children:e.jsxs(U,{className:"flex items-center gap-2 text-base",children:[e.jsx(ss,{className:"h-4 w-4"}
137),"Signup region gate (Canada)"]})}),e.jsx(E,{children:n?e.jsx(V,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t!=null&&t.enabled?"Locking out new Canadian accounts":"Off — everything normal"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"While on: Canadian signups stall silently, accounts created since the toggle can't log in or check out, and welcome credits are withheld. Accounts created before the toggle are untouched."})]}),e.jsx(Ea,{checked:!!(t!=null&&t.enabled),disabled:l,onCheckedChange:h,"aria-label":"Toggle Canada region gate"})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-1 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Accounts locked out: ",e.jsx("strong",{className:"text-foreground",children:a})]}),e.jsxs("span",{children:["Stalls (24h): ",e.jsx("strong",{className:"text-foreground",children:(t==null?void 0:t.stalls_24h)??0})]}),e.jsxs("span",{children:["Welcome bonuses withheld: ",e.jsx("strong",{className:"text-foreground",children:(t==null?void 0:t.withheld_total)??0})]}),(t==null?void 0:t.updated_at)&&e.jsxs("span",{children:["Changed ",new Date(t.updated_at).toLocaleString()]})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:m,disabled:x,children:[x&&e.jsx(V,{className:"h-3 w-3 animate-spin"}),"Restore withheld credits"]})]})})]})}const Wt=[{path:"/free-ai-video",label:"Free and Uncensored Video"},{path:"/photo-to-video",label:"Photo to Video + Free AI"},{path:"/ai-image-editor",label:"AI Image"},{path:"/welcome",label:"Brand Welcome"},{path:"/image-to-video",label:"Image to Video (text-only)"},{path:"/dollarsubscription",label:"FB Search Purchase #5"},{path:"/start",label:"Lander Max Value"},{path:"/freetrial",label:"Free Trial"},{path:"/freetrial1",label:"Free Trial v5 (Apr 23)"},{path:"/freetrial2",label:"Free Trial v9 (May 7)"},{path:"/freecredits",label:"Free Credits"},{path:"/propack",label:"Pro Pack"},{path:"/reviews",label:"Reviews"},{path:"/credits",label:"Credits"},{path:"/imagealt",label:"Image Alt"},{path:"/alt",label:"Alt"}];function jc(t){const s=new Date,a=s,r=t==="24h"?1:t==="7d"?7:30;return{from:new Date(s.getTime()-r*24*60*60*1e3),to:a}}function Me(t,s){return s?`${(t/s*100).toFixed(1)}%`:"—"}function vc(){const[t,s]=d.useState("7d"),[a,r]=d.useState(),[n,o]=d.useState([]),[l,c]=d.useState(!0),[x,g]=d.useState(null),u=d.useMemo(()=>t==="custom"&&(a!=null&&a.from)?a:jc(t),[t,a]);d.useEffect(()=>{const m=u.from,v=u.to??u.from;if(!m||!v)return;let b=!1;return c(!0),g(null),(async()=>{const f=new Date(m);f.setHours(0,0,0,0);const p=new Date(v);p.setHours(23,59,59,999);const{data:j,error:L}=await T.rpc("admin_landing_page_stats",{_paths:Wt.map(w=>w.path),_start:f.toISOString(),_end:p.toISOString()});if(!b){if(L)g(L.message),o([]);else{const w=Wt.map(_=>{const P=j==null?void 0:j.find(D=>D.path===_.path);return{path:_.path,sessions:Number((P==null?void 0:P.sessions)??0),signups:Number((P==null?void 0:P.signups)??0),paid:Number((P==null?void 0:P.paid)??0)}});o(w)}c(!1)}})(),()=>{b=!0}},[u]);const i=d.useMemo(()=>n.reduce((m,v)=>({sessions:m.sessions+v.sessions,signups:m.signups+v.signups,paid:m.paid+v.paid}),{sessions:0,signups:0,paid:0}),[n]),h=u.from?`${K(u.from,"MMM d")} – ${K(u.to??u.from,"MMM d, yyyy")}`:"";return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsxs(z,{children:[e.jsxs(U,{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 text-lg",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(bn,{className:"h-4 w-4 text-primary"})}),"Landing Pages — Sessions → Signup → Paid"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[["24h","7d","30d"].map(m=>e.jsx($,{variant:t===m?"default":"outline",size:"sm",className:"h-8 text-xs",onClick:()=>s(m),children:m==="24h"?"Last 24h":m==="7d"?"7 days":"30 days"},m)),e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsxs($,{variant:t==="custom"?"default":"outline",size:"sm",className:R("h-8 text-xs justify-start font-normal gap-2"),children:[e.jsx(pt,{className:"h-3.5 w-3.5"}),t==="custom"&&(a!=null&&a.from)?h:"Custom"]})}),e.jsx(xs,{className:"w-auto p-0",align:"end",children:e.jsx(hs,{mode:"range",selected:a,onSelect:m=>{r(m),m!=null&&m.from&&s("custom")},numberOfMonths:2,disabled:m=>m>new Date,className:R("p-3 pointer-events-auto")})})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Showing ",h,". Sessions = unique visits to the URL (may include logged-in revisits). Signups/Paid = users whose captured landing page was this path (falls back to earliest tracked pageview for pre-fix legacy signups)."]})]}),e.jsx(E,{className:"overflow-x-auto",children:l?e.jsxs("div",{className:"flex items-center gap-2 py-8 text-sm text-muted-foreground",children:[e.jsx(V,{className:"h-4 w-4 animate-spin"})," Loading…"]}):x?e.jsx("div",{className:"text-sm text-destructive py-8",children:x}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50 text-xs uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Landing page"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Sessions"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Signups"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Sign %"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Paid"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Sign → Paid"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Sess → Paid"})]})}),e.jsxs("tbody",{children:[n.map(m=>{const v=Wt.find(b=>b.path===m.path);return e.jsxs("tr",{className:"border-b border-border/30 hover:bg-muted/20",children:[e.jsxs("td",{className:"py-2 px-2",children:[e.jsx("div",{className:"font-mono text-sm text-primary",children:m.path}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v==null?void 0:v.label})]}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:m.sessions.toLocaleStr
137ing()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:m.signups.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums text-muted-foreground",children:Me(m.signups,m.sessions)}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums font-semibold text-emerald-400",children:m.paid.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums text-muted-foreground",children:Me(m.paid,m.signups)}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums text-muted-foreground",children:Me(m.paid,m.sessions)})]},m.path)}),e.jsxs("tr",{className:"border-t-2 border-border/60 bg-muted/10 font-semibold",children:[e.jsx("td",{className:"py-2 px-2",children:"Totals"}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:i.sessions.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:i.signups.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:Me(i.signups,i.sessions)}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums text-emerald-400",children:i.paid.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:Me(i.paid,i.signups)}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums",children:Me(i.paid,i.sessions)})]})]})]})})]}),e.jsx(gc,{range:u}),e.jsx(fc,{})]})}function bc(){const[t,s]=d.useState(null),[a,r]=d.useState(!0);d.useEffect(()=>{let o=!1;return(async()=>{const l=new Date(Date.now()-6048e5).toISOString(),c=T.from("profiles").select("user_id",{count:"exact",head:!0}).gte("created_at",l),x=T.from("profiles").select("user_id",{count:"exact",head:!0}).gte("created_at",l).not("utm_source","is",null),g=T.from("profiles").select("user_id",{count:"exact",head:!0}).gte("created_at",l).not("gclid","is",null),u=T.from("profiles").select("user_id",{count:"exact",head:!0}).gte("created_at",l).not("landing_page","is",null),i=T.from("profiles").select("signup_url_raw").gte("created_at",l).not("signup_url_raw","is",null).order("created_at",{ascending:!1}).limit(5),[h,m,v,b,f]=await Promise.all([c,x,g,u,i]);o||(s({total:h.count??0,withUtm:m.count??0,withGclid:v.count??0,withLanding:b.count??0,sampleUrls:(f.data||[]).map(p=>p.signup_url_raw).filter(Boolean)}),r(!1))})(),()=>{o=!0}},[]);const n=(o,l)=>l>0?(o/l*100).toFixed(1)+"%":"—";return e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center gap-2 text-lg",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-accent/10 flex items-center justify-center",children:e.jsx(ps,{className:"h-4 w-4 text-accent"})}),"Attribution Capture Health (last 7d)"]})}),e.jsx(E,{className:"space-y-4",children:a||!t?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(V,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(lt,{label:"New signups",value:t.total.toLocaleString()}),e.jsx(lt,{label:"With utm_source",value:`${t.withUtm.toLocaleString()} (${n(t.withUtm,t.total)})`,tone:t.total>0&&t.withUtm/t.total>=.4?"good":"bad"}),e.jsx(lt,{label:"With gclid",value:`${t.withGclid.toLocaleString()} (${n(t.withGclid,t.total)})`,tone:t.total>0&&t.withGclid/t.total>=.2?"good":"bad"}),e.jsx(lt,{label:"With landing_page",value:`${t.withLanding.toLocaleString()} (${n(t.withLanding,t.total)})`})]}),t.sampleUrls.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-2",children:"Recent signup URLs (debug)"}),e.jsx("div",{className:"space-y-1",children:t.sampleUrls.map((o,l)=>e.jsx("div",{className:"text-xs font-mono text-muted-foreground truncate p-2 rounded bg-muted/40",title:o,children:o},l))}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Look for ",e.jsx("code",{className:"text-foreground",children:"gclid="})," in these. If it's missing, Google auto-tagging isn't reaching the browser at signup time (likely OAuth redirect stripping it)."]})]})]})})]})}function lt({label:t,value:s,tone:a}){return e.jsxs("div",{className:"p-3 rounded-lg border border-border/40 bg-background/40",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:t}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"text-lg font-semibold",children:s}),a==="good"&&e.jsx(A,{variant:"outline",className:"text-green-500 border-green-500/40 text-[10px]",children:"OK"}),a==="bad"&&e.jsx(A,{variant:"outline",className:"text-red-500 border-red-500/40 text-[10px]",children:"LOW"})]})]})}const yc=[{label:"24h",hours:24},{label:"7d",hours:168},{label:"30d",hours:720}];
137function Nc(){const[t,s]=d.useState(24),[a,r]=d.useState([]),[n,o]=d.useState(!0),l=d.useCallback(async()=>{o(!0);const{data:i,error:h}=await T.rpc("admin_signup_sources",{_hours:t});!h&&Array.isArray(i)&&r(i.map(m=>({country_code:String(m.country_code??"??"),source:String(m.source??"Direct / app"),signups:Number(m.signups??0),credited:Number(m.credited??0),paid:Number(m.paid??0)}))),o(!1)},[t]);d.useEffect(()=>{l()},[l]);const c=a.reduce((i,h)=>i+h.signups,0),x=a.filter(i=>i.country_code==="US").reduce((i,h)=>i+h.signups,0),g=Object.values(a.reduce((i,h)=>{var v;const m=i[v=h.country_code]||(i[v]={code:h.country_code,signups:0,paid:0});return m.signups+=h.signups,m.paid+=h.paid,i},{})).sort((i,h)=>h.signups-i.signups).slice(0,12),u=Object.values(a.reduce((i,h)=>{var v;const m=i[v=h.source]||(i[v]={source:h.source,signups:0,paid:0});return m.signups+=h.signups,m.paid+=h.paid,i},{})).sort((i,h)=>h.signups-i.signups).slice(0,10);return e.jsxs(O,{children:[e.jsx(z,{className:"pb-3",children:e.jsxs(U,{className:"flex items-center justify-between gap-2 text-base",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-4 w-4"}),"Where signups are coming from"]}),e.jsx("span",{className:"flex gap-1",children:yc.map(i=>e.jsx($,{size:"sm",variant:t===i.hours?"default":"outline",onClick:()=>s(i.hours),children:i.label},i.hours))})]})}),e.jsx(E,{children:n?e.jsx(V,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-1 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Total signups: ",e.jsx("strong",{className:"text-foreground",children:c})]}),e.jsxs("span",{children:["US: ",e.jsx("strong",{className:"text-foreground",children:x})]}),e.jsxs("span",{children:["Outside US: ",e.jsx("strong",{className:"text-foreground",children:c-x})]})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"By country"}),e.jsxs("div",{className:"space-y-1",children:[g.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{children:[Ye(i.code)," ",i.code==="??"?"Unknown":i.code]}),e.jsxs("span",{className:"text-muted-foreground",children:[i.signups,i.paid>0&&e.jsxs("span",{className:"ml-2 text-foreground",children:["· ",i.paid," paid"]})]})]},i.code)),g.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No signups in this window."})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"By source"}),e.jsxs("div",{className:"space-y-1",children:[u.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"truncate pr-2",children:i.source}),e.jsxs("span",{className:"text-muted-foreground",children:[i.signups,i.paid>0&&e.jsxs("span",{className:"ml-2 text-foreground",children:["· ",i.paid," paid"]})]})]},i.source)),u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No signups in this window."})]})]})]})]})})]})}const _c=[{label:"30d",days:30},{label:"90d",days:90},{label:"All time",days:3650}];function wc(){const[t,s]=d.useState(3650),[a,r]=d.useState([]),[n,o]=d.useState(!0),[l,c]=d.useState(!1),x=d.useCallback(async()=>{o(!0);const{data:h,error:m}=await T.rpc("admin_country_performance",{_days:t});!m&&Array.isArray(h)&&r(h.map(v=>({country_code:String(v.country_code??"??"),accounts:Number(v.accounts??0),buyers:Number(v.buyers??0),purchase_txns:Number(v.purchase_txns??0),buyer_pct:Number(v.buyer_pct??0),free_burn:Number(v.free_burn??0),gated:!!v.gated}))),o(!1)},[t]);d.useEffect(()=>{x()},[x]);const g=a.find(h=>h.country_code==="??"),u=a.filter(h=>h.country_code!=="??"),i=l?u:u.slice(0,20);return e.jsxs(O,{children:[e.jsx(z,{className:"pb-3",children:e.jsxs(U,{className:"flex items-center justify-between gap-2 text-base",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-4 w-4"}),"Who buys, by country"]}),e.jsx("span",{className:"flex gap-1",children:_c.map(h=>e.jsx($,{size:"sm",variant:t===h.days?"default":"outline",onClick:()=>s(h.days),children:h.label},h.days))})]})}),e.jsx(E,{children:n?e.jsx(V,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Buyers are distinct accounts that ever paid — orders are shown separately. Free burn is credits used by accounts that never paid. A red tag means that country currently gets no welcome credits."}),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:"border-b border-border text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"py-2 text-left font-medium",children:"Country"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Accounts"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Buyers"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Orders"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Buyer %"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Free burn"})]})}),e.jsx("tbody",{children:i.map(h=>e.jsxs("tr",{className:"border-b border-border/40",children:[e.jsxs("td",{className:"py-1.5",children:[e.jsx("span",{className:"mr-1",children:Ye(h.country_code)}),h.country_code,h.gated&&e.jsx(A,{variant:"destructive",className:"ml-2 px-1.5 py-0 text-[10px]",children:"no free credits"})]}),e.jsx("td",{className:"py-1.5 text-right tabular-nums",children:h.accounts.toLocaleStr
137ing()}),e.jsx("td",{className:"py-1.5 text-right tabular-nums",children:h.buyers.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right tabular-nums text-muted-foreground",children:h.purchase_txns.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right tabular-nums",children:[h.buyer_pct,"%"]}),e.jsx("td",{className:"py-1.5 text-right tabular-nums text-muted-foreground",children:h.free_burn.toLocaleString()})]},h.country_code))})]})}),u.length>20&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>c(h=>!h),children:l?"Show top 20":`Show all ${u.length} countries`}),g&&e.jsxs("div",{className:"rounded-md border border-border/60 bg-muted/30 p-3 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Unknown country"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.accounts.toLocaleString()," accounts · ",g.buyers.toLocaleString()," buyers (",g.buyer_pct,"%) · ",g.free_burn.toLocaleString()," free credits burned. These are VPNs and failed lookups, some of them real US customers, so they still get their welcome credits."]})]})]})})]})}function kc(){const[t,s]=d.useState(null),[a,r]=d.useState(""),[n,o]=d.useState([]),[l,c]=d.useState(""),[x,g]=d.useState(!0),[u,i]=d.useState(!1),{toast:h}=Ae(),m=d.useCallback(async()=>{const[{data:p,error:j},L]=await Promise.all([T.rpc("admin_welcome_geo_gate_status"),T.from("signup_block_list").select("id, value").eq("block_type","email_domain").order("value")]);if(!j&&Array.isArray(p)&&p[0]){const w=p[0],_={enabled:!!w.enabled,countries:String(w.countries??""),updated_at:w.updated_at??null,withheld_7d:Number(w.withheld_7d??0)};s(_),r(_.countries)}!L.error&&Array.isArray(L.data)&&o(L.data.map(w=>({id:String(w.id),value:String(w.value)}))),g(!1)},[]);d.useEffect(()=>{m()},[m]);const v=async(p,j)=>{i(!0);const{error:L}=await T.rpc("admin_set_welcome_geo_gate",{_enabled:p,_countries:(j??a).toUpperCase().replace(/\s+/g,"")});if(i(!1),L){h({title:"Could not update",description:L.message,variant:"destructive"});return}h({title:p?"Welcome credits limited by country":"Welcome credits open to everyone",description:p?"New accounts outside the list start with no free credits.":"Every new account gets the 300 free credits again."}),m()},b=async()=>{const p=l.trim().toLowerCase().replace(/^@/,"");if(!p)return;i(!0);const{error:j}=await T.rpc("admin_add_signup_block",{_block_type:"email_domain",_value:p,_reason:"disposable email provider"});if(i(!1),j){h({title:"Could not add",description:j.message,variant:"destructive"});return}c(""),m()},f=async p=>{i(!0);const{error:j}=await T.rpc("admin_remove_signup_block",{_id:p});if(i(!1),j){h({title:"Could not remove",description:j.message,variant:"destructive"});return}m()};return e.jsxs(O,{children:[e.jsx(z,{className:"pb-3",children:e.jsxs(U,{className:"flex items-center gap-2 text-base",children:[e.jsx(ia,{className:"h-4 w-4"}),"Free welcome credits"]})}),e.jsx(E,{children:x?e.jsx(V,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t!=null&&t.enabled?"Limited to the countries listed below":"Off — every new account gets 300 credits"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"While on, new accounts from other countries are still created and can still buy credits — they just don't get the free 300. Existing accounts are never touched."})]}),e.jsx(Ea,{checked:!!(t!=null&&t.enabled),disabled:u,onCheckedChange:p=>v(p),"aria-label":"Toggle welcome credit country limit"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Countries that keep free credits"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{value:a,onChange:p=>r(p.target.value),placeholder:"US,CA,GB,AU",className:"font-mono text-xs"}),e.jsx($,{size:"sm",variant:"outline",disabled:u||a===(t==null?void 0:t.countries),onClick:()=>v(!!(t!=null&&t.enabled),a),children:"Save"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Two-letter codes, comma separated. Bonuses withheld in the last 7 days:"," ",e.jsx("strong",{className:"text-foreground",children:(t==null?void 0:t.withheld_7d)??0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:["Blocked disposable inbox domains (",n.length,")"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{value:l,onCh
137ange:p=>c(p.target.value),onKeyDown:p=>{p.key==="Enter"&&b()},placeholder:"temp-mail.org",className:"font-mono text-xs"}),e.jsx($,{size:"sm",variant:"outline",disabled:u||!l.trim(),onClick:b,children:"Add"})]}),e.jsxs("div",{className:"max-h-40 space-y-1 overflow-y-auto pr-1",children:[n.map(p=>e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"font-mono",children:p.value}),e.jsx($,{size:"icon",variant:"ghost",className:"h-6 w-6",disabled:u,onClick:()=>f(p.id),"aria-label":`Remove ${p.value}`,children:e.jsx(xa,{className:"h-3 w-3"})})]},p.id)),n.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No domains blocked."})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signups on these domains keep the account but lose the free credits."})]})]})})]})}function Sc(){const[t,s]=d.useState(null),[a,r]=d.useState(null),[n,o]=d.useState(null),[l,c]=d.useState(!0);d.useEffect(()=>{let u=!1;return(async()=>{const i=new Date(Date.now()-2592e5).toISOString(),h=T.from("videos").select("id",{count:"exact",head:!0}).lt("created_at",i).is("purged_at",null),m=T.from("generated_images").select("id",{count:"exact",head:!0}).lt("created_at",i).is("purged_at",null),v=T.from("purge_job_log").select("ran_at, videos_purged, images_purged").order("ran_at",{ascending:!1}).limit(1).maybeSingle(),[b,f,p]=await Promise.all([h,m,v]);u||(s(b.count??0),r(f.count??0),o(p.data??null),c(!1))})(),()=>{u=!0}},[]);const x=(t??0)+(a??0),g=x>0;return e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center gap-2 text-lg",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-accent/10 flex items-center justify-center",children:e.jsx(xa,{className:"h-4 w-4 text-accent"})}),"3-Day Deletion Health"]})}),e.jsx(E,{className:"space-y-4",children:l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(V,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ct,{label:"Videos overdue",value:(t??0).toLocaleString(),tone:(t??0)>0?"bad":"good"}),e.jsx(ct,{label:"Images overdue",value:(a??0).toLocaleString(),tone:(a??0)>0?"bad":"good"}),e.jsx(ct,{label:"Purged (last run)",value:`${((n==null?void 0:n.videos_purged)??0).toLocaleString()} / ${((n==null?void 0:n.images_purged)??0).toLocaleString()}`}),e.jsx(ct,{label:"Last run",value:n!=null&&n.ran_at?Cc(n.ran_at):"never"})]}),g?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["The Privacy Policy promises permanent erasure 3 days after generation. The hourly purge job is behind by ",x.toLocaleString()," rows — it needs to drain the backlog."]}):e.jsx("p",{className:"text-xs text-emerald-500/80",children:"Backlog clear — everything older than 72 hours has been purged."})]})})]})}function Cc(t){const s=new Date(t),a=Date.now(),r=Math.round((a-s.getTime())/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const n=Math.round(r/60);return n<24?`${n}h ago`:s.toLocaleDateString()}function ct({label:t,value:s,tone:a}){return e.jsxs("div",{className:"p-3 rounded-lg border border-border/40 bg-background/40",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:t}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"text-lg font-semibold",children:s}),a==="good"&&e.jsx(A,{variant:"outline",className:"text-green-500 border-green-500/40 text-[10px]",children:"OK"}),a==="bad"&&e.jsx(A,{variant:"outline",className:"text-red-500 border-red-500/40 text-[10px]",children:"LOW"})]})]})}function Pc({userId:t}){const[s,a]=d.useState(null),[r,n]=d.useState(null),o=async()=>{const{data:c,error:x}=await T.functions.invoke("admin-refund-pack",{body:{mode:"list",userId:t}});if(x){a([]);return}a((c==null?void 0:c.candidates)??[])};d.useEffect(()=>{o()},[t]);const l=async c=>{var u,i;if(!confirm(`Refund this pack at PayPal and remove ${c.credits} credits?`))return;n(c.capture_id);const{data:x,error:g}=await T.functions.invoke("admin-refund-pack",{body:{mode:"refund",userId:t,captureId:c.capture_id}});if(n(null),g||x!=null&&x.error){let h=x==null?void 0:x.error;try{h=h??((i=await((u=g==null?void 0:g.context)==null?void 0:u.json()))==null?void 0:i.error)}catch{}Se.error(String(h??"Refund failed"))}else Se.success(x!=null&&x.alreadyRefunded?"Already refunded":`Refunded — ${x==null?void 0:x.creditsRemoved} credits removed`);o()};return!s||s.length===0?null:e.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-2",children:[e.jsx("div",{className:"text-sm font-semibold",children:"Unused pack refunds (14 days)"}),s.map(c=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-xs",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"text-foreground",children:[c.description," · ",new Date(c.purchased_at).toLocaleDateString()," · ",c.days_since,"d ago"]}),!c.eligible&&e.jsx("div",{className:"text-muted-foreground",children:c.reasons.join(" · ")})]}),c.already_refunded?e.jsx(A,{variant:"secondary",children:"Refunded"}):e.jsx($,{size:"sm",variant:"destructive",disabled:!c.eligible||r===c.capture_id,onClick:()=>l(c),children:r===c.capture_id?"Refunding…":"Refund unused pack"})]},c.capture_id))]})}const Dc={region_not_selling:"US-only",ip_reuse:"IP reuse",ip_already_used:"IP reuse",ip_cluster:"IP cluster",ip_subnet_abuse:"IP cluster",blocklist:"Blocklist",email_already_used:"Dup email",region_blocked:"Region"};function ts(t){return t?Dc[t]||t:"flagged"}const Lc={whale:"bg-purple-500/10 text-purple-300 border-purple-500/30",big:"bg-indigo-500/10 text-indigo-300 border-indigo-500/30",medium:"bg-teal-500/10 text-teal-300 border-teal-500/30",small:"bg-slate-500/10 text-slate-300 border-slate-500/30",dollar:"bg-amber-500/10 text-amber-300 border-amber-500/30"},Ac={whale:"Whale",big:"Big",medium:"Medium",small:"Small",dollar:"$1 only"};function Xa({tier:t,usd:s,inRange:a}){const r=t||"free";if(r==="free")return e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"});const n=typeof s=="number"?s:0;return e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(A,{variant:"outline",className:R("text-[10px] font-medium",Lc[r]),children:Ac[r]||r}),e.jsxs("span",{className:"font-mono text-xs text-foreground",children:["$",n.toLocaleStr
137ing(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]}),a&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400",title:"bought in this date range"})]})}const Tc={click_id:"click id",lander:"lander",utm:"UTM",referrer:"referrer"};function Za({channel:t,evidence:s,referrerHost:a}){const r=t||null;if(!r)return e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"});if(r==="google_ads"){const l=Tc[s||""]||null;return e.jsx(A,{variant:"outline",className:"text-[10px] bg-blue-500/10 text-blue-300 border-blue-500/30",children:l?`Google · ${l}`:"Google Ads"})}const o=r==="organic_other"?a||"Other organic":{google_organic:"Google organic",reddit:"Reddit",facebook:"Facebook",direct:"Direct",tiktok:"TikTok",youtube:"YouTube",twitter:"X",bing:"Bing",duckduckgo:"DuckDuckGo",chatgpt:"ChatGPT",perplexity:"Perplexity"}[r]||r;return e.jsx(A,{variant:"outline",className:"text-[10px] font-normal text-muted-foreground",children:o})}function Oc({status:t,reason:s,detail:a}){return t==="granted"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium text-emerald-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400"}),"Granted"]}):t==="withheld"?e.jsx("span",{className:"inline-flex flex-col text-xs",title:a||s||"withheld",children:e.jsxs("span",{className:"inline-flex items-center gap-1 font-medium text-rose-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-rose-400"}),"Withheld · ",ts(s)]})}):t==="unclaimed"?e.jsx("span",{className:"text-xs text-muted-foreground",title:"never loaded the app",children:"Unclaimed"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}function sa({status:t}){const s={completed:"bg-emerald-500/10 text-emerald-400 border-emerald-500/20",processing:"bg-amber-500/10 text-amber-400 border-amber-500/20",pending:"bg-primary/10 text-primary border-primary/20",failed:"bg-destructive/10 text-destructive border-destructive/20"};return e.jsx(A,{variant:"outline",className:R("text-xs",s[t]),children:t})}function dt({label:t,value:s}){return e.jsxs("div",{className:"rounded-lg border border-border/50 bg-background/50 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:t}),e.jsx("div",{className:"mt-1 text-sm font-semibold text-foreground",children:s.toLocaleString()})]})}function ot({title:t,children:s}){return e.jsxs("div",{className:"rounded-lg border border-border/50 bg-background/50 p-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground mb-2",children:t}),e.jsx("div",{className:"space-y-1 text-xs",children:s})]})}function ne({label:t,value:s}){return s==null||s===""?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-muted-foreground shrink-0 w-24",children:t}),e.jsx("span",{className:"text-foreground break-all min-w-0",children:s})]})}function Ec(t){if(!t)return null;const s=/iPhone|iPad/i.test(t)?"iOS":/Android/i.test(t)?"Android":/Mac OS X/i.test(t)?"Mac":/Windows/i.test(t)?"Windows":/Linux/i.test(t)?"Linux":"Unknown",a=/Edg\//i.test(t)?"Edge":/Chrome\//i.test(t)?"Chrome":/Firefox\//i.test(t)?"Firefox":/Safari\//i.test(t)?"Safari":"";return a?`${s} · ${a}`:s}const ut=t=>`$${t.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`,qt=t=>t?new Date(t).toLocaleDateString():"—";function Qa({user:t,loading:s=!1,onOpenLinked:a}){const[r,n]=d.useState("videos"),o=ma(t.videos.map(i=>i.image_url));if(s)return e.jsx("div",{className:"p-5",children:e.jsxs("div",{className:"flex items-center justify-center gap-3 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"h-5 w-5 rounded-full border-2 border-primary border-t-transparent animate-spin"}),"Loading lifetime activity..."]})});const l=t.attribution,c=t.spend,x=t.bonus,g=t.linked_accounts||[],u=t.linked_totals;return e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsx(Pc,{userId:t.user_id}),e.jsxs("div",{className:"flex flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:[e.jsx("span",{className:"font-semibold text-foreground",children:t.email}),e.jsxs("span",{className:"text-muted-foreground",children:["ID: ",e.jsxs("code",{className:"text-xs bg-secondary/50 px-1.5 py-0.5 rounded",children:[t.user_id.slice(0,8),"..."]})]}),e.jsx(A,{variant:"secondary",className:"text-xs",children:"Lifetime"}),t.utm_campaign&&e.jsxs(A,{variant:"outline",className:"text-xs",children:["Campaign: ",t.utm_campaign]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This panel shows full account history, not the current date filter."})]}),e.jsxs("div",{className:"grid gap-2 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs(ot,{title:"Identity",children:[e.jsx("div",{className:"mb-2",children:e.jsx(Xa,{tier:c==null?void 0:c.tier,usd:c==null?void 0:c.lifetime_usd})}),e.jsx(ne,{label:"Lifetime",value:c?ut(c.lifetime_usd):"—"}),e.jsx(ne,{label:"Purchases",value:(c==null?void 0:c.purchases)??0}),e.jsx(ne,{label:"First paid",value:qt(c==null?void 0:c.first_paid_at)}),e.jsx(ne,{label:"Last paid",value:qt(c==null?void 0:c.last_paid_at)}),(c==null?void 0:c.estimated)&&e.jsx("p",{className:"pt-1 text-[10px] text-muted-foreground",children:"Some older charges are estimated from the product name."})]}),e.jsxs(ot,{title:"Where they came from",children:[e.jsx("div",{className:"mb-2",children:e.jsx(Za,{channel:l==null?void 0:l.acquisition_channel,evidence:l==null?void 0:l.channel_evidence})}),e.jsx(ne,{label:"Landing",value:l==null?void 0:l.landing_page}),e.jsx(ne,{label:"Referrer",value:l==null?void 0:l.landing_referrer}),e.jsx(ne,{label:"Campaign",value:l==null?void 0:l.utm_campaign}),e.jsx(ne,{label:"Content",value:l==null?void 0:l.utm_content}),e.jsx(ne,{label:"Term",value:l==null?void 0:l.utm_term}),e.jsx(ne,{label:"Click id",value:l?l.gclid_present?"Yes":"No":null}),e.jsx(ne,{label:"Signup URL",value:l==null?void 0:l.signup_url_raw}),e.jsx(ne,{label:"Device",value:Ec(l==null?void 0:l.user_agent)}),e.jsx(ne,{label:"Language",value:l==null?void 0:l.language}),e.jsx(ne,{label:"ISP",value:l!=null&&l.isp?`${l.isp}${l.asn?` (${l.asn})`:""}`:l==null?void 0:l.asn}),e.jsx(ne,{label:"Location",value:l&&(l.city||l.region||l.country_code)?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[l.country_code&&e.jsx("span",{className:"text-base leading-none",children:Ye(l.country_code)}
137),e.jsx("span",{children:[l.city,l.region,l.country_code].filter(Boolean).join(", ")})]}):null}),(l==null?void 0:l.is_vpn)&&e.jsx(A,{variant:"outline",className:"mt-1 text-[10px] bg-amber-500/10 text-amber-300 border-amber-500/30",children:"VPN"})]}),e.jsxs(ot,{title:"Welcome bonus",children:[e.jsxs("div",{className:"mb-2",children:[(x==null?void 0:x.status)==="granted"&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium text-emerald-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400"}),"Granted"]}),(x==null?void 0:x.status)==="withheld"&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium text-rose-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-rose-400"}),"Withheld"]}),(x==null?void 0:x.status)==="unclaimed"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Unclaimed — never loaded the app"}),(x==null?void 0:x.status)==="none"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"No bonus on record"})]}),(x==null?void 0:x.bonus_tx_at)&&e.jsx(ne,{label:"Granted at",value:new Date(x.bonus_tx_at).toLocaleString()}),((x==null?void 0:x.rows)||[]).map((i,h)=>e.jsxs("div",{className:"mt-2 rounded border border-border/40 p-2 space-y-0.5",children:[e.jsx("div",{className:"font-medium text-rose-300",children:ts(i.reason)}),i.details&&typeof i.details=="object"&&Object.entries(i.details).map(([m,v])=>e.jsxs("div",{className:"text-[11px] text-muted-foreground break-all",children:[m,": ",typeof v=="object"?JSON.stringify(v):String(v)]},m)),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["denied_at: ",new Date(i.created_at).toLocaleString()]}),i.revoked&&e.jsx("div",{className:"text-[11px] text-amber-300",children:"revoked"})]},h))]}),e.jsx(ot,{title:"Linked accounts",children:g.length===0?e.jsx("p",{className:"text-muted-foreground",children:"No linked accounts found."}):e.jsx("div",{className:"max-h-48 overflow-y-auto -mx-1",children:e.jsxs("table",{className:"w-full text-[11px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-muted-foreground",children:[e.jsx("th",{className:"text-left font-normal px-1",children:"Email"}),e.jsx("th",{className:"text-left font-normal px-1",children:"Match"}),e.jsx("th",{className:"text-right font-normal px-1",children:"Used"}),e.jsx("th",{className:"text-right font-normal px-1",children:"$"})]})}),e.jsx("tbody",{children:g.map(i=>e.jsxs("tr",{className:R("border-t border-border/30",a&&"cursor-pointer hover:bg-secondary/30"),onClick:()=>a==null?void 0:a(i.user_id),title:[`joined ${qt(i.created_at)}`,i.country_code||"",`bonus ${i.bonus_status}${i.bonus_reason?` (${ts(i.bonus_reason)})`:""}`,i.abuse_flag_reason?`flag ${i.abuse_flag_reason}`:""].filter(Boolean).join(" · "),children:[e.jsx("td",{className:"px-1 py-1 font-mono truncate max-w-[130px]",children:i.email||i.user_id.slice(0,8)}),e.jsx("td",{className:"px-1 py-1 text-muted-foreground",children:i.match_type}),e.jsx("td",{className:"px-1 py-1 text-right font-mono",children:i.credits_used.toLocaleString()}),e.jsx("td",{className:"px-1 py-1 text-right font-mono",children:i.lifetime_usd?ut(i.lifetime_usd):"—"})]},i.user_id))}),u&&e.jsx("tfoot",{children:e.jsxs("tr",{className:"border-t border-border/50 font-medium",children:[e.jsxs("td",{className:"px-1 py-1",children:[u.accounts," total"]}),e.jsx("td",{}),e.jsx("td",{className:"px-1 py-1 text-right font-mono",children:u.credits_used.toLocaleString()}),e.jsx("td",{className:"px-1 py-1 text-right font-mono",children:ut(u.lifetime_usd)})]})})]})})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsx(dt,{label:"Videos",value:t.video_count}),e.jsx(dt,{label:"Images",value:t.image_count}),e.jsx(dt,{label:"Credits Used",value:t.total_credits_used}),e.jsx(dt,{label:"Transactions",value:t.transactions.length})]}),e.jsx("div",{className:"flex gap-2",children:["videos","images","transactions"].map(i=>{const h={videos:t.videos.length,images:t.images.length,transactions:t.transactions.length};return e.jsxs($,{variant:r===i?"default":"secondary",size:"sm",className:"h-7 text-xs",onClick:()=>n(i),children:[i.charAt(0).toUpperCase()+i.slice(1)," (",h[i],")"]},i)})}),r==="videos"&&(t.videos.length===0?e.jsx("p",{className:"text-xs text-muted-foreground py-4 text-center",children:"No videos generated yet."}):e.jsx("div",{className:"grid gap-2 max-h-80 overflow-y-auto pr-1",children:t.videos.map(i=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/50 p-3 bg-background/50 hover:bg-background/80 transition-colors",children:[i.thumbnail_url||i.image_url?e.jsx("img",{src:i.thumbnail_url||o[i.image_url]||void 0,alt:"",className:"w-16 h-12 rounded-md object-cover flex-shrink-0"}):e.jsx("div",{className:"w-16 h-12 rounded-md bg-muted flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs text-foreground truncate",children:i.prompt}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[e.jsx(sa,{status:i.status}),e.jsx(Gt,{model:i.model,quality:i.quality,target_duration:i.target_duration,credits_used:i.credits_used}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[i.credits_used," credits"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(i.created_at).toLocaleStr
137ing()})]})]}),i.video_url&&e.jsx("a",{href:i.video_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80 transition-colors",onClick:h=>h.stopPropagation(),children:e.jsx(gs,{className:"h-4 w-4"})})]},i.id))})),r==="images"&&(t.images.length===0?e.jsx("p",{className:"text-xs text-muted-foreground py-4 text-center",children:"No images generated yet."}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 max-h-80 overflow-y-auto pr-1",children:t.images.map(i=>e.jsxs("div",{className:"rounded-lg border border-border/50 p-2 bg-background/50 space-y-1.5 hover:bg-background/80 transition-colors",children:[i.image_url?e.jsx("img",{src:i.image_url,alt:"",className:"w-full aspect-square rounded-md object-cover"}):e.jsx("div",{className:"w-full aspect-square rounded-md bg-muted"}),e.jsx("p",{className:"text-xs text-foreground truncate",children:i.prompt}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(sa,{status:i.status}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[i.credits_used,"cr"]})]})]},i.id))})),r==="transactions"&&(t.transactions.length===0?e.jsx("p",{className:"text-xs text-muted-foreground py-4 text-center",children:"No transactions yet."}):e.jsx("div",{className:"max-h-60 overflow-y-auto",children:e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{className:"border-border/30 hover:bg-transparent",children:[e.jsx(k,{className:"text-xs uppercase tracking-wider",children:"Type"}),e.jsx(k,{className:"text-xs uppercase tracking-wider",children:"Amount"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-right",children:"USD"}),e.jsx(k,{className:"text-xs uppercase tracking-wider",children:"Description"}),e.jsx(k,{className:"text-xs uppercase tracking-wider",children:"Date"})]})}),e.jsx(ue,{children:t.transactions.map((i,h)=>e.jsxs(G,{className:"border-border/30",children:[e.jsx(N,{children:e.jsx(A,{variant:i.type==="purchase"||i.type==="topup"?"default":"secondary",className:"text-xs",children:i.type})}),e.jsxs(N,{className:R("font-mono text-sm",i.amount>0?"text-emerald-400":"text-destructive"),children:[i.amount>0?"+":"",i.amount]}),e.jsx(N,{className:"text-right font-mono text-xs text-foreground",children:typeof i.usd=="number"&&i.usd>0?ut(i.usd):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(N,{className:"text-xs text-muted-foreground",children:i.description||"—"}),e.jsx(N,{className:"text-xs text-muted-foreground",children:new Date(i.created_at).toLocaleString()})]},h))})]})}))]})}function aa({options:t,value:s,onChange:a}){return e.jsx("div",{className:"inline-flex rounded-md border border-border/50 overflow-hidden",children:t.map(r=>e.jsx("button",{type:"button",onClick:()=>a(r.value),className:R("px-2.5 py-1 text-xs transition-colors",s===r.value?"bg-primary text-primary-foreground":"bg-secondary/40 text-muted-foreground hover:bg-secondary"),children:r.label},r.value))})}function $c({users:t,userDetails:s,loadingUserId:a,searchQuery:r,onSearchQueryChange:n,searchingDb:o,onOpenUser:l}){const[c,x]=d.useState(null),[g,u]=d.useState("all"),[i,h]=d.useState(!1),[m,v]=d.useState(!1),[b,f]=d.useState("all"),[p,j]=d.useState(!1),L=_=>{x(_),l(_),setTimeout(()=>{var P;(P=document.getElementById(`user-row-${_}`))==null||P.scrollIntoView({behavior:"smooth",block:"center"})},120)},w=d.useMemo(()=>{let _=t.filter(P=>!(g==="google"&&P.acquisition_channel!=="google_ads"||g==="organic"&&P.acquisition_channel==="google_ads"||i&&P.bonus_status!=="withheld"||m&&!["whale","big"].includes(P.spend_tier||"")||b==="us"&&P.country_code!=="US"||b==="non_us"&&(!P.country_code||P.country_code==="US")));return p&&(_=[..._].sort((P,D)=>(D.lifetime_usd||0)-(P.lifetime_usd||0))),_},[t,g,i,m,b,p]);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(yn,{className:"h-4 w-4 text-muted-foreground absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(me,{placeholder:"Search by email, name, or source...",value:r,onChange:_=>n(_.target.value),className:"h-9 pl-9 bg-secondary/50 border-border/50"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsxs(A,{variant:"secondary",className:"whitespace-nowrap",children:[w.length," accounts"]}),o&&e.jsx(A,{variant:"outline",className:"whitespace-nowrap",children:"Searching all users…"}),e.jsxs(A,{variant:"outline",className:"whitespace-nowrap font-mono",children:[new Set(w.map(_=>
137_.signup_ip).filter(Boolean)).size," unique IPs"]}),e.jsxs(A,{variant:"outline",className:"whitespace-nowrap font-mono",children:[new Set(w.map(_=>_.country_code).filter(Boolean)).size," countries"]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(aa,{value:g,onChange:u,options:[{value:"all",label:"All traffic"},{value:"google",label:"Google"},{value:"organic",label:"Organic"}]}),e.jsx(aa,{value:b,onChange:f,options:[{value:"all",label:"All countries"},{value:"us",label:"US"},{value:"non_us",label:"Non-US"}]}),e.jsx($,{variant:i?"default":"secondary",size:"sm",className:"h-7 text-xs",onClick:()=>h(_=>!_),children:"Withheld only"}),e.jsx($,{variant:m?"default":"secondary",size:"sm",className:"h-7 text-xs",onClick:()=>v(_=>!_),children:"Whale + Big"}),e.jsx($,{variant:p?"default":"secondary",size:"sm",className:"h-7 text-xs",onClick:()=>j(_=>!_),children:"Sort by lifetime $"})]}),e.jsx(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:e.jsx(E,{className:"overflow-x-auto p-0",children:e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{className:"border-border/50 hover:bg-transparent",children:[e.jsx(k,{className:"w-8"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Email"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Name"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Credits"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Videos"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Images"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Used"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Bonus"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Country"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Source"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Trial"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Paid"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Joined"})]})}),e.jsx(ue,{children:w.map(_=>{const P=c===_.user_id,D=s[_.user_id]??_,I=a===_.user_id&&!s[_.user_id];return e.jsxs(d.Fragment,{children:[e.jsxs(G,{id:`user-row-${_.user_id}`,className:R("cursor-pointer border-border/30 transition-colors",P?"bg-secondary/40":"hover:bg-secondary/20"),onClick:()=>{if(P){x(null);return}x(_.user_id),l(_.user_id)},children:[e.jsx(N,{className:"px-2",children:P?e.jsx(ha,{className:"h-4 w-4 text-primary"}):e.jsx(ns,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(N,{className:"font-mono text-xs",children:_.email}),e.jsx(N,{className:"text-sm",children:_.full_name||"—"}),e.jsx(N,{className:"text-right",children:e.jsx(A,{variant:_.credits>0?"default":"secondary",className:"font-mono text-xs",children:_.credits.toLocaleString()})}),e.jsxs(N,{className:"text-right font-mono text-sm",children:[_.video_count," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",_.video_completed,"✓)"]})]}),e.jsx(N,{className:"text-right font-mono text-sm",children:_.image_count}),e.jsx(N,{className:"text-right font-mono text-sm",children:_.total_credits_used.toLocaleString()}),e.jsx(N,{children:e.jsx(Oc,{status:_.bonus_status,reason:_.bonus_reason,detail:_.bonus_detail})}),e.jsx(N,{className:"text-base",title:_.country_code||"Unknown",children:_.country_code?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"text-lg leading-none",children:Ye(_.country_code)}),e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:_.country_code}),_.is_vpn&&e.jsx("span",{className:"rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[9px] font-medium text-amber-300",title:"VPN or datacenter IP",children:"VPN"})]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(N,{className:"text-xs",children:e.jsx(Za,{channel:_.acquisition_channel,evidence:_.channel_evidence,referrerHost:_.first_referrer_host})}),e.jsx(N,{children:(()=>{const Q=_.subscription_status||"none";if(Q==="trialing"){const Z=_.trial_ends_at?new Date(_.trial_ends_at).toLocaleDateString():null;return e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium text-blue-400",title:Z?`Trial ends ${Z}`:"Trialing",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-blue-400"}),"Trial"]}
137)}return Q==="active"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium text-emerald-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400"}),"Active"]}):Q==="cancelled"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium text-amber-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-400"}),"Cancelled"]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})})()}),e.jsx(N,{children:e.jsx(Xa,{tier:_.spend_tier,usd:_.lifetime_usd,inRange:_.purchased_in_range})}),e.jsx(N,{className:"text-xs text-muted-foreground",children:new Date(_.created_at).toLocaleDateString()})]}),P&&e.jsx(G,{children:e.jsx(N,{colSpan:13,className:"bg-secondary/20 p-0 border-border/30",children:e.jsx(Qa,{user:D,loading:I,onOpenLinked:L})})})]},_.user_id)})})]})})})]})}function ra(t){return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function Mc(t){const s=new Date,a=ra(s),r=n=>ra(new Date(s.getTime()-n*24*60*60*1e3));switch(t){case"today":return{start:a,end:a};case"yesterday":{const n=r(1);return{start:n,end:n}}case"7d":return{start:r(6),end:a};case"30d":return{start:r(29),end:a};case"90d":return{start:r(89),end:a};default:return{start:r(29),end:a}}}const Ic={today:"Today",yesterday:"Yesterday","7d":"Last 7 Days","30d":"Last 30 Days","90d":"Last 90 Days",custom:"Custom Range"};function Qc(){var Ns,_s,ws,ks;const{user:t,loading:s}=hr(),a=pr(),r=t==null?void 0:t.id,[n,o]=d.useState(null),[l,c]=d.useState([]),[x,g]=d.useState({}),[u,i]=d.useState(null),[h,m]=d.useState(null),[v,b]=d.useState([]),[f,p]=d.useState([]),[j,L]=d.useState([]),[w,_]=d.useState([]),[P,D]=d.useState(null),[I,Q]=d.useState(!0),[Z,te]=d.useState(""),[S,C]=d.useState([]),[y,B]=d.useState(!1);d.useState(null);const[X,ie]=d.useState("today"),[M,Dt]=d.useState(void 0),[Ee,bs]=d.use
137State(null),[$e,Ja]=d.useState(null),Xe=d.useMemo(()=>X==="custom"&&(M!=null&&M.from)?{start:K(M.from,"yyyy-MM-dd"),end:K(M.to||M.from,"yyyy-MM-dd")}:Mc(X),[X,M]),ys=d.useCallback(async F=>{if(!x[F]){i(F);try{const{data:{session:W}}=await T.auth.getSession();if(!(W!=null&&W.access_token))return;const{data:le,error:H}=await T.functions.invoke("admin-user-detail",{headers:{Authorization:`Bearer ${W.access_token}`},body:{user_id:F}});if(H||le!=null&&le.error||!(le!=null&&le.user))return;g(se=>({...se,[F]:le.user}))}finally{i(W=>W===F?null:W)}}},[x]);d.useEffect(()=>{if(s)return;if(!r){a("/login");return}(async()=>{Q(!0),D(null);let{data:{session:W}}=await T.auth.getSession();const le=(W==null?void 0:W.expires_at)??0;if(!(W!=null&&W.access_token)||le*1e3-Date.now()<6e4){const{data:ae}=await T.auth.refreshSession();W=ae.session??W}if(!(W!=null&&W.access_token)){a("/login");return}const{data:H,error:se}=await T.functions.invoke("admin-stats",{headers:{Authorization:`Bearer ${W.access_token}`},body:{start_date:Xe.start,end_date:Xe.end,timezone_offset:new Date().getTimezoneOffset()}});if(se||H!=null&&H.error){D((H==null?void 0:H.error)||(se==null?void 0:se.message)||"Unauthorized"),Q(!1);return}o(H.summary),c(H.userStats),m(H.funnel),b(H.campaigns),p(H.traffic_sources||[]),L(H.dailySignups),_(H.dailyRevenue),bs(H.trialCancelCount??null),Ja(H.paidUserCount??null),Q(!1)})()},[r,s,a,Xe]),d.useEffect(()=>{const F=Z.trim();if(F.length<2){C([]),B(!1);return}let W=!1;B(!0);const le=setTimeout(async()=>{try{const{data:{session:H}}=await T.auth.getSession();if(!(H!=null&&H.access_token))return;const{data:se,error:ae}=await T.functions.invoke("admin-user-search",{headers:{Authorization:`Bearer ${H.access_token}`},body:{query:F}});if(W)return;ae||se!=null&&se.error?C([]):C((se==null?void 0:se.users)||[])}finally{W||B(!1)}},350);return()=>{W=!0,clearTimeout(le)}},[Z]);const er=d.useMemo(()=>{const F=Z.trim().toLowerCase(),W=ae=>{var Ss,Cs,Ps,Ds,Ls,As;return!F||((Ss=ae.email)==null?void 0:Ss.toLowerCase().includes(F))||((Cs=ae.full_name)==null?void 0:Cs.toLowerCase().includes(F))||((Ps=ae.utm_source)==null?void 0:Ps.toLowerCase().includes(F))||((Ds=ae.acquisition_channel)==null?void 0:Ds.toLowerCase().includes(F))||((Ls=ae.bonus_reason)==null?void 0:Ls.toLowerCase().includes(F))||((As=ae.user_id)==null?void 0:As.toLowerCase().includes(F))},le=l.filter(W);if(!F)return le;const H=new Set(le.map(ae=>ae.user_id)),se=[...le];for(const ae of S)H.has(ae.user_id)||(H.add(ae.user_id),se.push(ae));return se},[l,Z,S]);if(s||I)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(Lt,{}),e.jsx("div",{className:"flex items-center justify-center h-[60vh]",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full border-2 border-primary border-t-transparent animate-spin"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Loading dashboard..."})]})})]});if(P)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(Lt,{}),e.jsx("div",{className:"flex items-center justify-center h-[60vh]",children:e.jsx(O,{className:"max-w-md",children:e.jsxs(E,{className:"pt-6 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-destructive/10 flex items-center justify-center mx-auto mb-4",children:e.jsx(gr,{className:"h-6 w-6 text-destructive"})}),e.jsx("p",{className:"text-destructive font-semibold",children:P==="Unauthorized"?"You don't have admin access.":P})]})})})]});const tr=X==="custom"&&(M!=null&&M.from)?`${K(M.from,"MMM d")} – ${K(M.to||M.from,"MMM d")}`:Ic[X]||"Last 30 Days";return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(Lt,{}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 pt-24 pb-12",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground tracking-tight",children:"Admin Dashboard"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Showing data for ",e.jsx("span",{className:"text-foreground font-medium",children:tr})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",className:"h-9 bg-secondary/50 border-border/50",onClick:()=>a("/admin/insights"),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-2 text-muted-foreground"}),"Revenue Insights"]}),e.jsxs(Ce,{value:X,onValueChange:F=>ie(F),children:[e.jsxs(Pe,{className:"w-[160px] h-9 bg-secondary/50 border-border/50",children:[e.jsx(pt,{className:"h-3.5 w-3.5 mr-2 text-muted-foreground"}),e.jsx(De,{})]}),e.jsxs(Le,{children:[e.jsx(q,{value:"today",children:"Today"}),e.jsx(q,{value:"yesterday",children:"Yesterday"}),e.jsx(q,{value:"7d",children:"Last 7 Days"}),e.jsx(q,{value:"30d",children:"Last 30 Days"}),e.jsx(q,{value:"90d",children:"Last 90 Days"}),e.jsx(q,{value:"custom",children:"Custom Range"})]})]}),X==="custom"&&e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:R("h-9 justify-start text-left font-normal bg-secondary/50 border-border/50",!(M!=null&&M.from)&&"text-muted-foreground"),children:[e.jsx(pt,{className:"mr-2 h-3.5 w-3.5"}),M!=null&&M.from?M.to?`${K(M.from,"MMM d")} – ${K(M.to,"MMM d")}`:K(M.from,"MMM d, yyyy"):"Pick dates"]})}),e.jsx(xs,{className:"w-auto p-0",align:"end",children:e.jsx(hs,{mode:"range",selected:M,onSelect:Dt,numberOfMonths:2,disabled:F=>F>new Date,className:R("p-3 pointer-events-auto")})})]})]})]}),e.jsxs(as,{defaultValue:"live",className:"space-y-6",children:[e.jsxs(rs,{className:"bg-secondary/50 border border-border/50 p-1 h-auto flex-wrap",children:[e.jsxs(J,{value:"live",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm relative",children:[e.jsxs("span",{className:"relative mr-1.5 inline-flex h-2 w-2",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-500 opacity-75"}),e.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-emerald-500"})]}),"Live Feed"]}),e.jsx(J,{value:"failed",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Failed Gens"}),e.jsx(J,{value:"overview",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Overview"}),e.jsx(J,{value:"funnel",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Funnel"}),e.jsx(J,{value:"landing-pages",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Landing Pages"}),e.jsx(J,{value:"campaigns",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Campaigns"}),e.jsxs(J,{value:"users",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm relative",children:["Users",$e!==null&&$e>0&&e.jsx("span",{className:"ml-2 inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-emerald-500 text-white text-[10px] font-bold",children:$e})]}),e.jsxs(J,{value:"paid",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm relative",children:["Paid Users",$e!==null&&$e>0&&e.jsx("span",{className:"ml-2 inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-emerald-500 text-white text-[10px] font-bold",children:$e})]}),e.jsxs(J,{value:"trials",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm relative",children:["Trials",Ee!==null&&Ee>0&&e.jsx("span",{className:"ml-2 inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-destructive text-destructive-foreground text-[10px] font-bold",children:Ee})]}),e.jsx(J,{value:"replay",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Replay Conversions"}),e.jsx(J,{value:"reconcile",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Reconcile Renewals"}),e.jsx(J,{value:"recovery",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Renewal Recovery"}),e.jsx(J,{value:"appreciation",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Appreciation Drop"}),e.jsx(J,{value:"payments",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Payments"}),e.jsx(J,{value:"support",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Support"}),e.jsx(J,{value:"reviews",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Reviews"}),e.jsx(J,{value:"emails",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Emails"}),e.jsx(J,{value:"profitability",className:"data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2 text-sm",children:"Profitability"})]}),e.jsxs(ee,{value:"payments",className:"space-y-4",children:[e.jsx(Bn,{}),e.jsx(Wn,{}),e.jsx(Gn,{})]}),e.jsx(ee,{value:"support",className:"space-y-4",children:e.jsx(mc,{})}),e.jsx(ee,{value:"reviews",className:"space-y-4",children:e.jsx(dc,{})}),e.jsx(ee,{value:"appreciation",className:"space-y-4",children:e.jsx(Vn,{})}),e.jsx(ee,{value:"emails",className:"space-y-4",children:e.jsx(cc,{})}),e.jsx(ee,{value:"profitability",className:"space-y-4",children:e.jsx(xc,{activeDates:Xe})}),e.jsx(ee,{value:"live",className:"space-y-4",children:e.jsx(Qn,{})}),e.jsx(ee,{value:"failed",className:"space-y-4",children:e.jsx(si,{})}),e.jsxs(ee,{value:"overview",className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:[e.jsx(Oe,{icon:e.jsx(Ge,{className:"h-4 w-4"}),label:"Total Users",value:(n==null?void 0:n.total_users)??0,accent:"primary"}),e.jsx(Oe,{icon:e.jsx(qe,{className:"h-4 w-4"}),label:"Today",value:(n==null?void 0:n.signups_today)??0,accent:"primary"}),e.jsx(Oe,{icon:e.jsx(ps,{className:"h-4 w-4"}),label:"This Week",value:(n==null?void 0:n.signups_this_week)??0,accent:"primary"}),e.jsx(Oe,{icon:e.jsx(wt,{className:"h-4 w-4"}),label:"Videos",value:(n==null?void 0:n.total_videos)??0,accent:"accent"}),e.jsx(Oe,{icon:e.jsx(kt,{className:"h-4 w-4"}),label:"Images",value:(n==null?void 0:n.total_images)??0,accent:"accent"}),e.jsx(Oe,{icon:e.jsx(He,{className:"h-4 w-4"}),label:"Credits Used",value:(n==null?void 0:n.total_credits_used)??0,accent:"accent"}),Ee!==null&&e.jsx(Oe,{icon:e.jsx(fe,{className:"h-4 w-4"}),label:"Trial Cancels",value:Ee,accent:Ee>
1370?"destructive":"primary"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm overflow-hidden",children:[e.jsx(z,{className:"pb-2",children:e.jsx(U,{className:"text-sm font-medium text-muted-foreground",children:"Daily Signups"})}),e.jsxs(E,{children:[e.jsx(na,{data:j.map(F=>F.count||0),color:"hsl(var(--primary))"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground mt-3",children:[e.jsx("span",{children:(Ns=j[0])==null?void 0:Ns.date}),e.jsxs("span",{className:"text-foreground font-medium",children:["Total: ",j.reduce((F,W)=>F+(W.count||0),0)]}),e.jsx("span",{children:(_s=j[j.length-1])==null?void 0:_s.date})]})]})]}),e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm overflow-hidden",children:[e.jsx(z,{className:"pb-2",children:e.jsx(U,{className:"text-sm font-medium text-muted-foreground",children:"Daily Revenue Credits"})}),e.jsxs(E,{children:[e.jsx(na,{data:w.map(F=>F.amount||0),color:"hsl(var(--accent))"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground mt-3",children:[e.jsx("span",{children:(ws=w[0])==null?void 0:ws.date}),e.jsxs("span",{className:"text-foreground font-medium",children:["Total: ",w.reduce((F,W)=>F+(W.amount||0),0).toLocaleString()]}),e.jsx("span",{children:(ks=w[w.length-1])==null?void 0:ks.date})]})]})]})]}),e.jsx(Sc,{})]}),e.jsxs(ee,{value:"funnel",className:"space-y-6",children:[e.jsx(bc,{}),e.jsx(Nc,{}),e.jsx(wc,{}),e.jsx(kc,{}),e.jsx(hc,{funnel:h,campaigns:v,trafficSources:f})]}),e.jsx(ee,{value:"landing-pages",className:"space-y-6",children:e.jsx(vc,{})}),e.jsx(ee,{value:"campaigns",className:"space-y-6",children:e.jsxs(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:[e.jsx(z,{children:e.jsxs(U,{className:"flex items-center gap-2 text-lg",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-accent/10 flex items-center justify-center",children:e.jsx(Is,{className:"h-4 w-4 text-accent"})}),"UTM Campaigns"]})}),e.jsx(E,{className:"overflow-x-auto",children:v.length===0?e.jsxs("div",{className:"text-center py-12 max-w-md mx-auto",children:[e.jsx(Is,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-3"}),e.jsx("p",{className:"text-foreground text-sm font-medium",children:"No campaign data yet"}),e.jsxs("p",{className:"text-muted-foreground text-xs mt-2",children:["Tag your ad URLs with ",e.jsx("code",{className:"bg-secondary/60 px-1.5 py-0.5 rounded text-[11px]",children:"?utm_source=facebook&utm_campaign=propack"})," to see attribution here. Visitors, signups, and purchases will be grouped by source + campaign."]})]}):e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{className:"border-border/50 hover:bg-transparent",children:[e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Source"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Campaign"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Visitors"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Signups"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Generators"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Purchasers"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Conv."})]})}),e.jsx(ue,{children:v.map((F,W)=>e.jsxs(G,{className:"border-border/30 hover:bg-secondary/30",children:[e.jsx(N,{className:"font-mono text-sm text-primary",children:F.source}),e.jsx(N,{className:"text-sm",children:F.campaign}),e.jsx(N,{className:"text-right font-mono text-sm",children:F.visitors}),e.jsx(N,{className:"text-right font-mono text-sm",children:F.signups}),e.jsx(N,{className:"text-right font-mono text-sm",children:F.generators}),e.jsx(N,{className:"text-right font-mono text-sm",children:F.purchasers}),e.jsx(N,{className:"text-right",children:e.jsx(A,{variant:"secondary",className:"font-mono text-xs",children:F.visitors>0?`${(F.signups/F.visitors*100).toFixed(1)}%`:"—"})})]},W))})]})})]})}),e.jsx(ee,{value:"users",className:"space-y-4",children:e.jsx($c,{users:er,userDetails:x,loadingUserId:u,searchQuery:Z,onSearchQueryChange:te,searchingDb:y,onOpenUser:ys})}),e.jsx(ee,{value:"paid",className:"space-y-4",children:e.jsx(Fc,{users:l,onOpenUser:ys,userDetails:x,loadingUserId:u})}),e.jsx(ee,{value:"trials",className:"space-y-4",children:e.jsx($n,{onCancellationCount:bs})}),e.jsx(ee,{value:"replay",className:"space-y-4",children:e.jsx(Rn,{})}),e.jsx(ee,{value:"reconcile",className:"space-y-4",children:e.jsx(zn,{})}),e.jsx(ee,{value:"recovery",className:"space-y-4",children:e.jsx(Un,{})})]})]})]})}function Oe({icon:t,label:s,value:a,accent:r}){const n=r==="primary"?"bg-primary/[0.02]":r==="accent"?"bg-accent/[0.02]":"bg-destructive/[0.04]",o=r==="primary"?"text-primary/60":r==="accent"?"text-accent/60":"text-destructive",l=r==="destructive"?"text-destructive":"text-foreground";return e.jsxs(O,{className:R("border-border/50 bg-card/50 backdrop-blur-sm overflow-hidden relative group hover:border-border transition-colors",r==="destructive"&&"border-destructive/40 bg-destructive/5"),children:[e.jsx("div",{className:R("absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity",n)}),e.jsxs(E,{className:"pt-5 pb-4 px-4 relative",children:[e.jsxs("div",{className:R("flex items-center gap-1.5 mb-2",o),children:[t,e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:s})]}),e.jsx("p",{className:R("text-2xl font-bold tracking-tight",l),children:a.toLocaleStr
137ing()})]})]})}function na({data:t,color:s}){if(t.length===0)return null;const a=Math.max(...t,1),r=80,n=400,o=n/(t.length-1||1),l=t.map((x,g)=>`${g*o},${r-x/a*r}`).join(" "),c=`0,${r} ${l} ${(t.length-1)*o},${r}`;return e.jsxs("svg",{viewBox:`0 0 ${n} ${r}`,className:"w-full h-20",preserveAspectRatio:"none",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:`grad-${s.replace(/[^a-z0-9]/gi,"")}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:s,stopOpacity:"0.2"}),e.jsx("stop",{offset:"100%",stopColor:s,stopOpacity:"0.02"})]})}),e.jsx("polygon",{points:c,fill:`url(#grad-${s.replace(/[^a-z0-9]/gi,"")})`}),e.jsx("polyline",{points:l,fill:"none",stroke:s,strokeWidth:"2",vectorEffect:"non-scaling-stroke",strokeLinecap:"round",strokeLinejoin:"round"})]})}const Rc=t=>{const a=(t.description||"").toLowerCase().includes("trial");return t.type==="purchase"||t.type==="topup"?!a:t.type==="subscription"?!a&&t.amount>0:!1};function Fc({users:t,onOpenUser:s,userDetails:a,loadingUserId:r}){const[n,o]=d.useState(null),l=d.useMemo(()=>t.filter(u=>u.has_purchased).map(u=>{const i=u.transactions.filter(Rc),h=i.reduce((v,b)=>v+(b.amount>0?b.amount:0),0),m=i.length?i.reduce((v,b)=>new Date(b.created_at)>new Date(v)?b.created_at:v,i[0].created_at):null;return{...u,_purchaseCount:i.length,_creditsPurchased:h,_lastPurchase:m}}).sort((u,i)=>{const h=u._lastPurchase?new Date(u._lastPurchase).getTime():0;return(i._lastPurchase?new Date(i._lastPurchase).getTime():0)-h}),[t]),c=l.reduce((u,i)=>u+i._creditsPurchased,0),x=l.reduce((u,i)=>u+i._purchaseCount,0),g=l.length?(x/l.length).toFixed(1):"0";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsxs(A,{variant:"secondary",className:"whitespace-nowrap",children:[l.length," paid users"]}),e.jsxs(A,{variant:"outline",className:"whitespace-nowrap font-mono",children:[c.toLocaleString()," credits sold"]}),e.jsxs(A,{variant:"outline",className:"whitespace-nowrap font-mono",children:[g," avg purchases/user"]})]}),e.jsx(O,{className:"border-border/50 bg-card/50 backdrop-blur-sm",children:e.jsx(E,{className:"overflow-x-auto p-0",children:l.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(He,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"No paid users in this date range yet."})]}):e.jsxs(de,{children:[e.jsx(oe,{children:e.jsxs(G,{className:"border-border/50 hover:bg-transparent",children:[e.jsx(k,{className:"w-8"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Email"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Country"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Signup"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Last Purchase"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"# Purchases"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Credits Bought"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Videos"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Images"}),e.jsx(k,{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium text-right",children:"Credits Left"})]})}),e.jsx(ue,{children:l.map(u=>{const i=n===u.user_id,h=a[u.user_id]??u,m=r===u.user_id&&!a[u.user_id];return e.jsxs(d.Fragment,{children:[e.jsxs(G,{className:R("cursor-pointer border-border/30 transition-colors",i?"bg-secondary/40":"hover:bg-secondary/20"),onClick:()=>{if(i){o(null);return}o(u.user_id),s(u.user_id)},children:[e.jsx(N,{className:"px-2",children:i?e.jsx(ha,{className:"h-4 w-4 text-primary"}):e.jsx(ns,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(N,{className:"font-mono text-xs",children:u.email}),e.jsx(N,{title:u.country_code||"Unknown",children:u.country_code?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"text-lg leading-none",children:Ye(u.country_code)}),e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:u.country_code})]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(N,{className:"text-xs text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()}),e.jsx(N,{className:"text-xs text-foreground font-medium",children:u._lastPurchase?new Date(u._lastPurchase).toLocaleDateString():"—"}),e.jsx(N,{className:"text-right font-mono text-sm",children:u._purchaseCount}),e.jsx(N,{className:"text-right font-mono text-sm",children:u._creditsPurchased.toLocaleStr
137ing()}),e.jsx(N,{className:"text-right font-mono text-sm",children:u.video_count}),e.jsx(N,{className:"text-right font-mono text-sm",children:u.image_count}),e.jsx(N,{className:"text-right",children:e.jsx(A,{variant:u.credits>0?"default":"secondary",className:"font-mono text-xs",children:u.credits.toLocaleString()})})]}),i&&e.jsx(G,{children:e.jsx(N,{colSpan:10,className:"bg-secondary/20 p-0 border-border/30",children:e.jsx(Qa,{user:h,loading:m})})})]},u.user_id)})})]})})})]})}export{Qc 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.