PageSourceSearch

https://taskhuddle.io/assets/InternalAdmin-Be0WfyFl.js

js taskhuddle.io collected 2026-10-07 19:56:16 UTC 130,242 bytes, 42 lines download raw bytes

1import{j as e}from"./vendor-ui-1jIxplIL.js";import{r as y,R as Gs}from"./vendor-react-DTP8y_xJ.js";import{ac as Ee,b8 as Ws,b9 as Js,ba as Ys,bb as qe,m as G,B as O,C as _,E as U,G as L,U as Ne,i as b,aI as Ae,z as xs,a3 as Ze,H as le,y as $e,I as Y,p as ue,q as je,r as pe,t as ge,v as R,a7 as Ps,aJ as Ve,j as $,as as rs,D as we,c as _e,d as be,e as Ce,f as Se,g as ke,aG as ns,a as Xs,Q as ls,ah as hs,ai as us,aj as Ue,ak as oe,o as ze,P as Zs,L as J,T as Je,a1 as ea,aH as js,bc as sa,s as k,bd as is,S as cs,k as Qe,a4 as Oe,a6 as aa,F as ta,ap as Es,be as Ds,bf as Ts,bg as Rs,bh as zs,N as ra,ag as De,K as me,af as Fe,J as Us,ad as Fs,bi as na,bj as la,aE as ia,bk as ca,Y as da,aF as Ls,Z as oa,bl as ma,bm as xa}from"./index-tQjrzw8f.js";import{A as ne,C as ha,a as ua,b as ja}from"./collapsible-CFlSkv4I.js";import{R as fe}from"./refresh-cw-D-gskVIN.js";import{T as ve}from"./trending-up-CyIspDM5.js";import{T as Ye,g as pa,a as ga,b as fa,c as Na,d as as,e as xe,f as vs}from"./command-Ckj-DYsB.js";import{f as X}from"./format-CyYVy0Vs.js";import{T as ie,a as ce,b as z,c as v,d as de,e as l}from"./table-Cv1ICAQe.js";import{D as ds}from"./download-DS6Apxdn.js";import{C as es}from"./calendar-CLj9hr4t.js";import{A as ts}from"./arrow-up-right-DqVu6FPD.js";import{C as Me}from"./credit-card--qk9ytR1.js";import{S as va}from"./square-pen-BXFni1NG.js";import{S as Xe}from"./shield-CNpJYrbt.js";import{A as ys}from"./arrow-left-DAq_FC9k.js";import{R as Be,A as ya,X as os,Y as ms,T as Ie,a as wa,B as Os,b as Bs,C as ss,P as ps,d as gs,L as Is}from"./charts-DQW1wu31.js";import{A as Ge}from"./arrow-right-dKV0Slbp.js";import{T as _a}from"./target-BRwY2jxU.js";import{G as qs}from"./gift-DDEOCtKg.js";import{P as ba}from"./pin-BC-ArCZu.js";import{W as Ca,a as Sa,P as ka}from"./wifi-BwRKXT5K.js";import{P as Aa}from"./play-D5r3Goao.js";import{P as Ma}from"./progress-D_bDjb3l.js";import{M as Pa}from"./moon-BIfSttQj.js";import{S as $s,G as ws}from"./share-2-aJhxjB9C.js";import{S as Ea}from"./skip-forward-DKDqabAC.js";import{C as Hs}from"./clipboard-list-BxErd5g7.js";import"./vendor-supabase-BIoz4D0x.js";import"./startOfDay-D_1RImCA.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 _s=Ee("ArrowDownRight",[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]]);/**
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 Da=Ee("Command",[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]]);/**
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 Le=Ee("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"}]]);/**
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 Ta=Ee("FilePen",[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5",key:"1couwa"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/**
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 Ra=Ee("Percent",[["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5",key:"4mh3h7"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5",key:"1mdrzq"}]]);/**
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 za=Ee("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/**
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 Ks=Ee("StickyNote",[["path",{d:"M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z",key:"qazsjp"}],["path",{d:"M15 3v4a2 2 0 0 0 2 2h4",key:"40519r"}]]);function Ua(a,c,m){const g=Ws(a,c)/Js;return Ys(m==null?void 0:m.roundingMethod)(g)}const Fa=()=>{const{metrics:a,loadingMetrics:c,refetchMetrics:m,users:g,billingEvents:h}=qe();if(c)return e.jsx("div",{className:"space-y-6",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[...Array(8)].map((o,n)=>e.jsx(G,{className:"h-32"},n))})});const x=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}
36).format(o),j=(g==null?void 0:g.slice(0,5))||[],d=(h==null?void 0:h.filter(o=>o.event_type==="payment").slice(0,5))||[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Business Overview"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Real-time metrics and KPIs"})]}),e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>m(),children:[e.jsx(fe,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs(_,{className:"bg-gradient-to-br from-blue-500/10 to-blue-600/5 border-blue-500/20",children:[e.jsxs(U,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(L,{className:"text-sm font-medium text-muted-foreground",children:"Total Users"}),e.jsx(Ne,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:(a==null?void 0:a.total_users)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["+",(a==null?void 0:a.new_users_this_month)||0," this month"]})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-purple-500/10 to-purple-600/5 border-purple-500/20",children:[e.jsxs(U,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(L,{className:"text-sm font-medium text-muted-foreground",children:"Organizations"}),e.jsx(Ae,{className:"h-4 w-4 text-purple-500"})]}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:(a==null?void 0:a.total_orgs)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(a==null?void 0:a.active_orgs)||0," active (30d)"]})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-green-500/10 to-green-600/5 border-green-500/20",children:[e.jsxs(U,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(L,{className:"text-sm font-medium text-muted-foreground",children:"Paying Orgs"}),e.jsx(xs,{className:"h-4 w-4 text-green-500"})]}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:(a==null?void 0:a.paying_orgs)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(a==null?void 0:a.free_orgs)||0," on free plan"]})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-orange-500/10 to-orange-600/5 border-orange-500/20",children:[e.jsxs(U,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(L,{className:"text-sm font-medium text-muted-foreground",children:"User Growth"}),((a==null?void 0:a.user_growth_rate)||0)>=0?e.jsx(ve,{className:"h-4 w-4 text-green-500"}):e.jsx(Ye,{className:"h-4 w-4 text-red-500"})]}),e.jsxs(b,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[((a==null?void 0:a.user_growth_rate)||0)>=0?"+":"",(a==null?void 0:a.user_growth_rate)||0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"vs last month"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(_,{className:"bg-gradient-to-br from-emerald-500/10 to-emerald-600/5 border-emerald-500/20",children:[e.jsxs(U,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(L,{className:"text-sm font-medium text-muted-foreground",children:"MRR"}),e.jsx(Le,{className:"h-4 w-4 text-emerald-500"})]}),e.jsxs(b,{children:[e.jsx("div",{className:"text-3xl font-bold",children:x((a==null?void 0:a.mrr)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Monthly Recurring Revenue"})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-emerald-500/10 to-emerald-600/5 border-emerald-500/20",children:[e.jsxs(U,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(L,{className:"text-sm font-medium text-muted-foreground",children:"ARR"}),e.jsx(Le,{className:"h-4 w-4 text-emerald-500"})]}),e.jsxs(b,{children:[e.jsx("div",{className:"text-3xl font-bold",children:x((a==null?void 0:a.arr)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Annual Recurring Revenue"})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-red-500/10 to-red-600/5 border-red-500/20",children:[e.jsxs(U,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(L,{className:"text-sm font-medium text-muted-foreground",children:"Churn (This Month)"}),e.jsx(Ye,{className:"h-4 w-4 text-red-500"})]}),e.jsxs(b,{children:[e.jsx("div",{className:"text-3xl font-bold",children:(a==null?void 0:a.churned_this_month)||0}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Customers churned"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-4 w-4"}),"Recent Signups"]}),e.jsx(le,{children:"Latest user registrations"})]}),e.jsx(b,{children:e.jsx("div",{className:"space-y-3",children:j.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recent signups"}):j.map(o=>{var f,N,t,s,u;const n=((f=o.organizations)==null?void 0:f.find(M=>M.is_current))||((N=o.organizations)==null?void 0:N[0]),p=((t=o.organizations)==null?void 0:t.reduce((M,Q)=>{const B={enterprise:4,business:3,pro:2,free:1};return(B[Q.plan]||0)>(B[M]||0)?Q.plan:M},"free"))||"free";return e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o.email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(n==null?void 0:n.org_name)||"No org",(((s=o.organizations)==null?void 0:s.length)||0)>1&&` +${(((u=o.organizations)==null?void 0:u.length)||1)-1} more`]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${p==="enterprise"?"bg-purple-500/20 text-purple-400":p==="business"?"bg-blue-500/20 text-blue-400":p==="pro"?"bg-green-500/20 text-green-400":"bg-muted text-muted-foreground"}`,children:p}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:X(new Date(o.created_at),"MMM d, yyyy")})]})]}
36,o.user_id)})})})]}),e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(Le,{className:"h-4 w-4"}),"Recent Payments"]}),e.jsx(le,{children:"Latest payment events"})]}),e.jsx(b,{children:e.jsx("div",{className:"space-y-3",children:d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recent payments"}):d.map(o=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium capitalize",children:o.event_type.replace("_"," ")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.to_plan&&`→ ${o.to_plan}`})]}),e.jsxs("div",{className:"text-right",children:[o.amount&&e.jsxs("p",{className:"font-medium text-green-500",children:["+",x(o.amount)]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:X(new Date(o.created_at),"MMM d, yyyy")})]})]},o.id))})})]})]})]})},bs=a=>!a.organizations||a.organizations.length===0?null:a.organizations.find(c=>c.is_current)||a.organizations[0],We=a=>{if(!a.organizations||a.organizations.length===0)return"free";const c={enterprise:4,business:3,pro:2,free:1};return a.organizations.reduce((m,g)=>{const h=c[g.plan]||0,x=c[m]||0;return h>x?g.plan:m},"free")},La=()=>{var V,q;const{users:a,loadingUsers:c,refetchUsers:m,updateUserPlan:g}=qe(),[h,x]=y.useState(""),[j,d]=y.useState("all"),[o,n]=y.useState("all"),[p,f]=y.useState(null),[N,t]=y.useState(null),[s,u]=y.useState(""),[M,Q]=y.useState(new Set),B=y.useMemo(()=>a?a.filter(i=>{var K,H,D,F,he,P;bs(i);const w=h===""||((K=i.email)==null?void 0:K.toLowerCase().includes(h.toLowerCase()))||((H=i.first_name)==null?void 0:H.toLowerCase().includes(h.toLowerCase()))||((D=i.last_name)==null?void 0:D.toLowerCase().includes(h.toLowerCase()))||((F=i.organizations)==null?void 0:F.some(te=>{var re;return(re=te.org_name)==null?void 0:re.toLowerCase().includes(h.toLowerCase())})),C=We(i),E=j==="all"||C===j||((he=i.organizations)==null?void 0:he.some(te=>te.plan===j)),T=((P=i.organizations)==null?void 0:P.length)||0,W=o==="all"||o==="1"&&T===1||o==="2+"&&T>=2||o==="3+"&&T>=3;return w&&E&&W}):[],[a,h,j,o]),se=y.useMemo(()=>a?{total:a.length,multiOrg:a.filter(i=>{var w;return(((w=i.organizations)==null?void 0:w.length)||0)>=2}).length,noOrg:a.filter(i=>{var w;return(((w=i.organizations)==null?void 0:w.length)||0)===0}).length}:{total:0,multiOrg:0,noOrg:0},[a]),ae=()=>{if(!B.length)return;const i=["Email","First Name","Last Name","Org Count","Organizations","Highest Plan","Referred By","Signup Date","Last Seen"],w=B.map(K=>{var H,D;return[K.email,K.first_name||"",K.last_name||"",((H=K.organizations)==null?void 0:H.length)||0,((D=K.organizations)==null?void 0:D.map(F=>`${F.org_name} (${F.role}/${F.plan})`).join("; "))||"",We(K),K.referred_by||"",X(new Date(K.created_at),"yyyy-MM-dd"),K.last_seen_at?X(new Date(K.last_seen_at),"yyyy-MM-dd HH:mm"):""]}),C=[i,...w].map(K=>K.map(H=>`"${H}"`).join(",")).join(`
37`),E=new Blob([C],{type:"text/csv"}),T=URL.createObjectURL(E),W=document.createElement("a");W.href=T,W.download=`taskhuddle-users-${X(new Date,"yyyy-MM-dd")}.csv`,W.click()},Z=async()=>{!(N!=null&&N.org_id)||!s||(await g.mutateAsync({orgId:N.org_id,plan:s}),f(null),t(null),u(""))},ee=i=>{Q(w=>{const C=new Set(w);return C.has(i)?C.delete(i):C.add(i),C})},S=i=>{const w={enterprise:"bg-purple-500/20 text-purple-400 border-purple-500/30",business:"bg-blue-500/20 text-blue-400 border-blue-500/30",pro:"bg-green-500/20 text-green-400 border-green-500/30",free:""};return e.jsxs($,{variant:i==="enterprise"?"default":i==="business"||i==="pro"?"outline":"secondary",className:w[i]||"",children:[i==="enterprise"&&e.jsx(xs,{className:"h-3 w-3 mr-1"}),i]})};return c?e.jsxs("div",{className:"space-y-4",children:[e.jsx(G,{className:"h-10 w-full"}),e.jsx(G,{className:"h-[500px] w-full"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Y,{placeholder:"Search by email, name, or organization...",value:h,onChange:i=>x(i.target.value),className:"pl-9"})]}),e.jsxs(ue,{value:j,onValueChange:d,children:[e.jsx(je,{className:"w-[140px]",children:e.jsx(pe,{placeholder:"Plan"})}),e.jsxs(ge,{children:[e.jsx(R,{value:"all",children:"All Plans"}),e.jsx(R,{value:"free",children:"Free"}),e.jsx(R,{value:"pro",children:"Pro"}),e.jsx(R,{value:"business",children:"Business"}),e.jsx(R,{value:"enterprise",children:"Enterprise"})]})]}),e.jsxs(ue,{value:o,onValueChange:n,children:[e.jsx(je,{className:"w-[140px]",children:e.jsx(pe,{placeholder:"Org count"})}),e.jsxs(ge,{children:[e.jsx(R,{value:"all",children:"All Users"}),e.jsx(R,{value:"1",children:"Single Org"}),e.jsx(R,{value:"2+",children:"2+ Orgs"}),e.jsx(R,{value:"3+",children:"3+ Orgs"})]})]}),e.jsx(O,{variant:"outline",size:"icon",onClick:()=>m(),children:e.jsx(fe,{className:"h-4 w-4"})}),e.jsxs(O,{variant:"outline",onClick:ae,children:[e.jsx(ds,{className:"h-4 w-4 mr-2"}),"Export"]})]}),e.jsxs("div",{className:"flex gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",B.length," of ",se.total," users"]}),e.jsxs("span",{className:"text-primary",children:["• ",se.multiOrg," multi-org users"]}),se.noOrg>0&&e.jsxs("span",{className:"text-destructive",children:["• ",se.noOrg," without org"]})]}),e.jsx(_,{children:e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{className:"w-[30px]"}),e.jsx(v,{children:"User"}),e.jsx(v,{children:"Organizations"}
37),e.jsx(v,{children:"Highest Plan"}),e.jsx(v,{children:"Referred By"}),e.jsx(v,{children:"Signup Date"}),e.jsx(v,{children:"Last Seen"}),e.jsx(v,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(de,{children:B.length===0?e.jsx(z,{children:e.jsx(l,{colSpan:8,className:"text-center text-muted-foreground py-8",children:"No users found"})}):B.map(i=>{var W,K;const w=((W=i.organizations)==null?void 0:W.length)||0,C=M.has(i.user_id),E=bs(i),T=We(i);return e.jsxs(Gs.Fragment,{children:[e.jsxs(z,{className:w>1?"cursor-pointer hover:bg-muted/50":"",onClick:()=>w>1&&ee(i.user_id),children:[e.jsx(l,{className:"p-2",children:w>1?e.jsx(O,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:H=>{H.stopPropagation(),ee(i.user_id)},children:C?e.jsx(Ps,{className:"h-4 w-4"}):e.jsx(Ve,{className:"h-4 w-4"})}):null}),e.jsx(l,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:i.email}),(i.first_name||i.last_name)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[i.first_name," ",i.last_name]})]})}),e.jsx(l,{children:e.jsx("div",{className:"flex items-center gap-2",children:w===0?e.jsx("span",{className:"text-muted-foreground text-sm",children:"No organization"}):w===1?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ae,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:E==null?void 0:E.org_name}),e.jsx($,{variant:"outline",className:"text-[10px] px-1 py-0 ml-1",children:E==null?void 0:E.role})]}):e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ne,{className:"h-3 w-3 text-primary"}),e.jsxs("span",{className:"text-sm font-medium text-primary",children:[w," organizations"]})]})})}),e.jsx(l,{children:S(T)}),e.jsx(l,{children:i.referred_by?e.jsx($,{variant:"outline",className:"text-xs",children:i.referred_by}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(l,{children:e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(es,{className:"h-3 w-3 text-muted-foreground"}),X(new Date(i.created_at),"MMM d, yyyy")]})}),e.jsx(l,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:i.last_seen_at?X(new Date(i.last_seen_at),"MMM d, HH:mm"):"Never"})}),e.jsx(l,{children:e.jsx(O,{variant:"ghost",size:"sm",onClick:H=>{H.stopPropagation(),f(i),t(E),u((E==null?void 0:E.plan)||"free")},children:e.jsx(rs,{className:"h-4 w-4"})})})]}),w>1&&C&&e.jsx(z,{className:"bg-muted/30",children:e.jsx(l,{colSpan:8,className:"p-0",children:e.jsxs("div",{className:"p-4 pl-12 space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"All Organizations:"}),(K=i.organizations)==null?void 0:K.map(H=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-background border",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ae,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:H.org_name}),H.is_current&&e.jsx($,{variant:"default",className:"text-[10px] px-1 py-0 bg-primary/20 text-primary",children:"current"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Joined ",X(new Date(H.joined_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",className:"text-xs",children:H.role}),S(H.plan),e.jsx(O,{variant:"ghost",size:"sm",onClick:()=>{f(i),t(H),u(H.plan)},children:e.jsx(rs,{className:"h-4 w-4"})})]})]},H.org_id))]})})},`${i.user_id}-orgs`)]},i.user_id)})})]})})})}),e.jsx(we,{open:!!p,onOpenChange:()=>{f(null),t(null)},children:e.jsxs(_e,{children:[e.jsxs(be,{children:[e.jsx(Ce,{children:"User Details"}),e.jsx(Se,{children:"View and manage user settings"})]}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Email"}),e.jsx("p",{className:"font-medium",children:p.email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Name"}),e.jsxs("p",{className:"font-medium",children:[p.first_name," ",p.last_name]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Total Organizations"}),e.jsx("p",{className:"font-medium",children:((V=p.organizations)==null?void 0:V.length)||0})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Highe
37st Plan"}),e.jsx("p",{className:"font-medium capitalize",children:We(p)})]})]}),N&&e.jsxs("div",{className:"border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx(Ae,{className:"h-4 w-4"}),N.org_name]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",children:N.role}),S(N.plan)]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Change Plan for this Organization"}),e.jsxs(ue,{value:s,onValueChange:i=>u(i),children:[e.jsx(je,{children:e.jsx(pe,{})}),e.jsxs(ge,{children:[e.jsx(R,{value:"free",children:"Free"}),e.jsx(R,{value:"pro",children:"Pro ($12/mo)"}),e.jsx(R,{value:"business",children:"Business ($29/mo)"}),e.jsx(R,{value:"enterprise",children:"Enterprise ($99/mo)"})]})]})]})]}),(((q=p.organizations)==null?void 0:q.length)||0)>1&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Tip: Click on different organizations above to manage their plans individually."})]}),e.jsxs(ke,{children:[e.jsx(O,{variant:"outline",onClick:()=>{f(null),t(null)},children:"Cancel"}),e.jsx(O,{onClick:Z,disabled:!s||!N||s===N.plan||g.isPending,children:g.isPending?"Updating...":"Update Plan"})]})]})})]})},Oa=()=>{const{billingEvents:a,loadingBillingEvents:c,refetchBillingEvents:m,metrics:g}=qe(),[h,x]=y.useState(""),[j,d]=y.useState("all"),o=y.useMemo(()=>a?a.filter(t=>{var M;const s=h===""||((M=t.stripe_event_id)==null?void 0:M.toLowerCase().includes(h.toLowerCase()))||t.event_type.toLowerCase().includes(h.toLowerCase()),u=j==="all"||t.event_type===j;return s&&u}):[],[a,h,j]),n=y.useMemo(()=>{if(!a)return{payments:0,upgrades:0,downgrades:0,churn:0,totalRevenue:0};const t=a.filter(s=>new Date(s.created_at).getMonth()===new Date().getMonth()&&new Date(s.created_at).getFullYear()===new Date().getFullYear());return{payments:t.filter(s=>s.event_type==="payment").length,upgrades:t.filter(s=>s.event_type==="upgrade").length,downgrades:t.filter(s=>s.event_type==="downgrade").length,churn:t.filter(s=>s.event_type==="churn").length,totalRevenue:t.filter(s=>s.event_type==="payment"&&s.amount).reduce((s,u)=>s+(u.amount||0),0)}},[a]),p=t=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(t),f=t=>{switch(t){case"payment":return e.jsx(Le,{className:"h-4 w-4 text-green-500"});case"upgrade":return e.jsx(ts,{className:"h-4 w-4 text-blue-500"});case"downgrade":return e.jsx(_s,{className:"h-4 w-4 text-orange-500"});case"churn":return e.jsx(ns,{className:"h-4 w-4 text-red-500"});case"refund":return e.jsx(Ye,{className:"h-4 w-4 text-red-500"});case"reactivation":return e.jsx(ve,{className:"h-4 w-4 text-green-500"});default:return e.jsx(Me,{className:"h-4 w-4 text-muted-foreground"})}},N=t=>{switch(t){case"payment":return"bg-green-500/20 text-green-400 border-green-500/30";case"upgrade":return"bg-blue-500/20 text-blue-400 border-blue-500/30";case"downgrade":return"bg-orange-500/20 text-orange-400 border-orange-500/30";case"churn":return"bg-red-500/20 text-red-400 border-red-500/30";case"refund":return"bg-red-500/20 text-red-400 border-red-500/30";case"reactivation":return"bg-green-500/20 text-green-400 border-green-500/30";default:return""}};return c?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[...Array(4)].map((t,s)=>e.jsx(G,{className:"h-24"},s))}),e.jsx(G,{className:"h-[400px]"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[e.jsxs(_,{className:"bg-gradient-to-br from-green-500/10 to-green-600/5 border-green-500/20",children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Le,{className:"h-4 w-4 text-green-500"}),"Payments (This Month)"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.payments}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p(n.totalRevenue)," total"]})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-blue-500/10 to-blue-600/5 border-blue-500/20",children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ts,{className:"h-4 w-4 text-blue-500"}),"Upgrades"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.upgrades}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This month"})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-orange-500/10 to-orange-600/5 border-orange-500/20",children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(_s,{className:"h-4 w-4 text-orange-500"}),"Downgrades"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.downgrades}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This month"})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-red-500/10 to-red-600/5 border-red-500/20",children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ns,{className:"h-4 w-4 text-red-500"}),"Churn"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.churn}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This month"})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-emerald-500/10 to-emerald-600/5 border-emerald-500/20",children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ve,{className:"h-4 w-4 text-emerald-500"}),"MRR"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:p((g==null?void 0:g.mrr)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Current"})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Y,{placeholder:"Search billing events...",value:h,onChange:t=>x(t.target.value),className:"pl-9"})]}),e.jsxs(ue,{value:j,onValueChange:d,children:[e.jsx(je,{className:"w-[180px]",children:e.jsx(pe,{placeholder:"Filter by type"})}),e.jsxs(ge,{children:[e.jsx(R,{value:"all",children:"All Events"}),e.jsx(R,{value:"payment",children:"Payments"}),e.jsx(R,{value:"upgrade",children:"Upgrades"}),e.jsx(R,{value:"downgrade",children:"Downgrades"}),e.jsx(R,{value:"churn",children:"Churn"}),e.jsx(R,{value:"refund",children:"Refunds"}),e.jsx(R,{value:"reactivation",children:"Reactivations"})]})]}),e.jsx(O,{variant:"outline",size:"icon",onClick:()=>m(),children:e.jsx(fe,{className:"h-4 w-4"})})]}),e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsx(L,{children:"Billing Events"}),e.jsx(le,{children:"All payment and subscription changes"})]}),e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Event"}),e.jsx(v,{children:"Plan Change"}),e.jsx(v,{children:"Amount"}),e.jsx(v,{children:"Stripe Event"}),e.jsx(v,{children:"Date"})]})}),e.jsx(de,{children:o.length===0?e.jsx(z,{children:e.jsx(l,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No billing events found"})}):o.map(t=>e.jsxs(z,{children:[e.jsx(l,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[f(t.event_type),e.jsx($,{variant:"outline",className:N(t.event_type),children:t.event_type.replace("_"," ")})]})}),e.jsx(l,{children:t.from_plan||t.to_plan?e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[t.from_plan&&e.jsx("span",{className:"capitalize",children:t.from_plan}),t.from_plan&&t.to_plan&&e.jsx(ts,{className:"h-3 w-3 text-muted-foreground"}),t.to_plan&&e.jsx("span",{className:"capitalize font-medium",children:t.to_plan})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(l,{children:t.amount?e.jsxs("span",{className:t.event_type==="refund"?"text-red-500":"text-green-500",children:[t.event_type==="refund"?"-":"+",p(t.amount)]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(l,{children:t.stripe_event_id?e.jsxs("code",{className:"text-xs bg-muted px-1.5 py-0.5 rounded",children:[t.stripe_event_id.slice(0,20),"..."]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(l,{children:e.jsx("span",{className:"text-sm",children:X(new Date(t.created_at),"MMM d, yyyy HH:mm")}
37)})]},t.id))})]})})})]})]})},Ba=()=>{const{toast:a}=Xs(),{affiliates:c,loadingAffiliates:m,refetchAffiliates:g,affiliateStats:h,loadingAffiliateStats:x,refetchAffiliateStats:j,referrals:d,loadingReferrals:o,payouts:n,loadingPayouts:p,refetchPayouts:f,createAffiliate:N,updateAffiliate:t,createPayout:s,updatePayoutStatus:u}=qe(),M=r=>`${window.location.origin}/login?ref=${r}`,Q=r=>{navigator.clipboard.writeText(r),a({title:"Copied!",description:"Affiliate link copied to clipboard"})},[B,se]=y.useState(""),[ae,Z]=y.useState(!1),[ee,S]=y.useState(!1),[V,q]=y.useState(!1);y.useState(null);const[i,w]=y.useState({name:"",email:"",affiliate_code:"",commission_rate:20,payment_email:"",notes:""}),[C,E]=y.useState(null),[T,W]=y.useState({affiliate_id:"",amount:0,period_start:"",period_end:"",notes:""}),K=y.useMemo(()=>c?c.filter(r=>B===""||r.name.toLowerCase().includes(B.toLowerCase())||r.email.toLowerCase().includes(B.toLowerCase())||r.affiliate_code.toLowerCase().includes(B.toLowerCase())):[],[c,B]),H=y.useMemo(()=>h?h.reduce((r,I)=>({totalReferrals:r.totalReferrals+Number(I.total_referrals),paidReferrals:r.paidReferrals+Number(I.paid_referrals),pendingCommissions:r.pendingCommissions+Number(I.pending_commission),totalPaid:r.totalPaid+Number(I.total_paid)}),{totalReferrals:0,paidReferrals:0,pendingCommissions:0,totalPaid:0}):{totalReferrals:0,paidReferrals:0,pendingCommissions:0,totalPaid:0},[h]),D=r=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(r),F=async()=>{await N.mutateAsync({name:i.name,email:i.email,affiliate_code:i.affiliate_code||i.name.toLowerCase().replace(/\s+/g,"-"),commission_rate:i.commission_rate,payment_email:i.payment_email||i.email,payment_method:"manual",notes:i.notes||null,status:"active",user_id:null}),Z(!1),w({name:"",email:"",affiliate_code:"",commission_rate:20,payment_email:"",notes:""})},he=async()=>{if(!T.period_start||!T.period_end){a({title:"Error",description:"Please select period start and end dates",variant:"destructive"});return}await s.mutateAsync({affiliate_id:T.affiliate_id,amount:T.amount,period_start:T.period_start,period_end:T.period_end,status:"pending",payment_reference:null,notes:T.notes||null}),S(!1),W({affiliate_id:"",amount:0,period_start:"",period_end:"",notes:""})},P=async()=>{C&&(await t.mutateAsync({id:C.id,name:C.name,email:C.email,commission_rate:C.commission_rate,status:C.status,payment_email:C.payment_email||null,notes:C.notes||null}),q(!1),E(null))},te=r=>{E({id:r.id,name:r.name,email:r.email,commission_rate:r.commission_rate,status:r.status,payment_email:r.payment_email||"",notes:r.notes||""}),q(!0)},re=r=>{switch(r){case"active":return e.jsx($,{className:"bg-green-500/20 text-green-400 border-green-500/30",children:"Active"});case"inactive":return e.jsx($,{className:"bg-gray-500/20 text-gray-400 border-gray-500/30",children:"Inactive"});case"suspended":return e.jsx($,{className:"bg-red-500/20 text-red-400 border-red-500/30",children:"Suspended"});case"pending":return e.jsxs($,{className:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",children:[e.jsx(ls,{className:"h-3 w-3 mr-1"}),"Pending"]});case"processing":return e.jsx($,{className:"bg-blue-500/20 text-blue-400 border-blue-500/30",children:"Processing"});case"paid":return e.jsxs($,{className:"bg-green-500/20 text-green-400 border-green-500/30",children:[e.jsx(js,{className:"h-3 w-3 mr-1"}),"Paid"]});case"failed":return e.jsxs($,{className:"bg-red-500/20 text-red-400 border-red-500/30",children:[e.jsx(ns,{className:"h-3 w-3 mr-1"}),"Failed"]});default:return e.jsx($,{variant:"outline",children:r})}},A=r=>h==null?void 0:h.find(I=>I.affiliate_id===r);return m||x?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[...Array(4)].map((r,I)=>e.jsx(G,{className:"h-24"},I))}),e.jsx(G,{className:"h-[400px]"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs(_,{className:"bg-gradient-to-br from-blue-500/10 to-blue-600/5 border-blue-500/20",children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ne,{className:"h-4 w-4 text-blue-500"}),"Total Affiliates"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:(c==null?void 0:c.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(c==null?void 0:c.filter(r=>r.status==="active").length)||0," active"]})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-purple-500/10 to-purple-600/5 border-purple-500/20",children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ze,{className:"h-4 w-4 text-purple-500"}),"Total Referrals"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:H.totalReferrals}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[H.paidReferrals," converted to paid"]})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-orange-500/10 to-orange-600/5 border-orange-500/20",children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ls,{className:"h-4 w-4 text-orange-500"}),"Pending Commissions"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:D(H.pendingCommissions)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting payout"})]})]}),e.jsxs(_,{className:"bg-gradient-to-br from-green-500/10 to-green-600/5 border-green-500/20",children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Le,{className:"h-4 w-4 text-green-500"}),"Total Paid Out"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"text-2xl font-bold",children:D(H.totalPaid)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]})]}),e.jsxs(hs,{defaultValue:"affiliates",className:"w-full",children:[e.jsxs(us,{children:[e.jsx(Ue,{value:"affiliates",children:"Affiliates"}),e.jsx(Ue,{value:"referrals",children:"Referrals"}),e.jsx(Ue,{value:"payouts",children:"Payouts"})]}),e.jsxs(oe,{value:"affiliates",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Y,{placeholder:"Search affiliates...",value:B,onChange:r=>se(r.target.value),className:"pl-9"})]}),e.jsx(O,{variant:"outline",size:"icon",onClick:()=>g(),children:e.jsx(fe,{className:"h-4 w-4"})}),e.jsxs(we,{open:ae,onOpenChange:Z,children:[e.jsx(ze,{asChild:!0,children:e.jsxs(O,{children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Add Affiliate"]})}),e.jsxs(_e,{children:[e.jsxs(be,{children:[e.jsx(Ce,{children:"Add New Affiliate"}),e.jsx(Se,{children:"Create a new affiliate partner"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Name"}),e.jsx(Y,{value:i.name,onChange:r=>w({...i,name:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Email"}),e.jsx(Y,{type:"email",value:i.email,onChange:r=>w({...i,email:r.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Affiliate Code"}),e.jsx(Y,{value:i.affiliate_code,onChange:r=>w({...i,affiliate_code:r.target.value}),placeholder:"auto-generated if empty"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Commission Rate (%)"}),e.jsx(Y,{type:"number",value:i.commission_rate,onChange:r=>w({...i,commission_rate:Number(r.target.value)})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Payment Email (PayPal)"}),e.jsx(Y,{type:"email",value:i.payment_email,onChange:r=>w({...i,payment_email:r.target.value}),placeholder:"Same as email if empty"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Notes"}),e.jsx(Je,{value:i.notes,onChange:r=>w({...i,notes:r.target.value})})]})]}),e.jsxs(ke,{children:[e.jsx(O,{variant:"outline",onClick:()=>Z(!1),children:"Cancel"}),e.jsx(O,{onClick:F,disabled:!i.name||!i.email||N.isPending,children:N.isPending?"Creating...":"Create Affiliate"})]})]})]}),e.jsx(we,{open:V,onOpenChange:q,children:e.jsxs(_e,{children:[e.jsxs(be,{children:[e.jsx(Ce,{children:"Edit Affiliate"}),e.jsx(Se,{children:"Update affiliate details"})]}),C&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Name"}),e.jsx(Y,{value:C.name,onChange:r=>E({...C,name:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Email"}),e.jsx(Y,{type:"email",value:C.email,onChange:r=>E({...C,email:r.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Commission Rate (%)"}),e.jsx(Y,{type:"number",value:C.commission_rate,onChange:r=>E({...C,commission_rate:Number(r.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Status"}),e.jsxs(ue,{value:C.status,onValueChange:r=>E({...C,status:r}),children:[e.jsx(je,{children:e.jsx(pe,{})}),e.jsxs(ge,{children:[e.jsx(R,{value:"active",children:"Active"}),e.jsx(R,{value:"inactive",children:"Inactive"}),e.jsx(R,{value:"suspended",children:"Suspended"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Payment Email"}),e.jsx(Y,{type:"email",value:C.payment_email,onChange:r=>E({...C,payment_email:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Notes"}),e.jsx(Je,{value:C.notes,onChange:r=>E({...C,notes:r.target.value})})]})]}),e.jsxs(ke,{children:[e.jsx(O,{variant:"outline",onClick:()=>q(!1),children:"Cancel"}),e.jsx(O,{onClick:P,disabled:!(C!=null&&C.name)||!(C!=null&&C.email)||t.isPending,children:t.isPending?"Saving...":"Save Changes"})]})]})})]}),e.jsx(_,{children:e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Affiliate"}),e.jsx(v,{children:"Referral Link"}),e.jsx(v,{children:"Commission"}),e.jsx(v,{children:"Referrals"}),e.jsx(v,{children:"Paid Referrals"}),e.jsx(v,{children:"Pending"}),e.jsx(v,{children:"Total Paid"}),e.jsx(v,{children:"Status"}),e.jsx(v,{className:"w-[60px]",children:"Actions"})]})}),e.jsx(de,{children:K.length===0?e.jsx(z,{children:e.jsx(l,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No affiliates found"})}):K.map(r=>
37{const I=A(r.id),ye=M(r.affiliate_code);return e.jsxs(z,{children:[e.jsx(l,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.email})]})}),e.jsx(l,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-xs bg-muted px-1.5 py-0.5 rounded max-w-[200px] truncate",children:ye}),e.jsx(O,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Q(ye),children:e.jsx(ea,{className:"h-3 w-3"})})]})}),e.jsx(l,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ra,{className:"h-3 w-3 text-muted-foreground"}),r.commission_rate,"%"]})}),e.jsx(l,{children:(I==null?void 0:I.total_referrals)||0}),e.jsx(l,{children:(I==null?void 0:I.paid_referrals)||0}),e.jsx(l,{children:e.jsx("span",{className:"text-orange-500",children:D(Number(I==null?void 0:I.pending_commission)||0)})}),e.jsx(l,{children:e.jsx("span",{className:"text-green-500",children:D(Number(I==null?void 0:I.total_paid)||0)})}),e.jsx(l,{children:re(r.status)}),e.jsx(l,{children:e.jsx(O,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>te(r),children:e.jsx(va,{className:"h-3.5 w-3.5"})})})]},r.id)})})]})})})})]}),e.jsx(oe,{value:"referrals",className:"mt-4",children:e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsx(L,{children:"Referral History"}),e.jsx(le,{children:"All users referred by affiliates"})]}),e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Email"}),e.jsx(v,{children:"Affiliate"}),e.jsx(v,{children:"Signup Date"}),e.jsx(v,{children:"Converted"}),e.jsx(v,{children:"First Payment"}),e.jsx(v,{children:"Lifetime Value"})]})}),e.jsx(de,{children:o?e.jsx(z,{children:e.jsx(l,{colSpan:6,children:e.jsx(G,{className:"h-10"})})}):(d==null?void 0:d.length)===0?e.jsx(z,{children:e.jsx(l,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals yet"})}):d==null?void 0:d.map(r=>{const I=c==null?void 0:c.find(ye=>ye.id===r.affiliate_id);return e.jsxs(z,{children:[e.jsx(l,{className:"font-medium",children:r.referred_email}),e.jsx(l,{children:(I==null?void 0:I.name)||"Unknown"}),e.jsx(l,{children:X(new Date(r.signup_date),"MMM d, yyyy")}),e.jsx(l,{children:r.converted_to_paid?e.jsx($,{className:"bg-green-500/20 text-green-400",children:"Yes"}):e.jsx($,{variant:"outline",children:"No"})}),e.jsx(l,{children:r.first_payment_amount?D(r.first_payment_amount):"—"}),e.jsx(l,{children:D(r.lifetime_value)})]},r.id)})})]})})})]})}),e.jsxs(oe,{value:"payouts",className:"mt-4 space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(we,{open:ee,onOpenChange:S,children:[e.jsx(ze,{asChild:!0,children:e.jsxs(O,{children:[e.jsx(Me,{className:"h-4 w-4 mr-2"}),"Create Payout"]})}),e.jsxs(_e,{children:[e.jsxs(be,{children:[e.jsx(Ce,{children:"Create Payout"}),e.jsx(Se,{children:"Schedule a commission payout for an affiliate"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Affiliate"}),e.jsxs(ue,{value:T.affiliate_id,onValueChange:r=>W({...T,affiliate_id:r}),children:[e.jsx(je,{children:e.jsx(pe,{placeholder:"Select affiliate"})}),e.jsx(ge,{children:c==null?void 0:c.filter(r=>r.status==="active").map(r=>e.jsx(R,{value:r.id,children:r.name},r.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Amount ($)"}),e.jsx(Y,{type:"number",value:T.amount,onChange:r=>W({...T,amount:Number(r.target.value)})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Period Start"}),e.jsx(Y,{type:"date",value:T.period_start,onChange:r=>W({...T,period_start:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Period End"}),e.jsx(Y,{type:"date",value:T.period_end,onChange:r=>W({...T,period_end:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Notes"}),e.jsx(Je,{value:T.notes,onChange:r=>W({...T,notes:r.target.value})})]})]}),e.jsxs(ke,{children:[e.jsx(O,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx(O,{onClick:he,disabled:!T.affiliate_id||!T.amount||s.isPending,children:s.isPending?"Creating...":"Create Payout"})]})]})]})}),e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsx(L,{children:"Payout History"}),e.jsx(le,{children:"All commission payouts"})]}),e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Affiliate"}),e.jsx(v,{children:"Amount"}),e.jsx(v,{children:"Period"}),e.jsx(v,{children:"Status"}),e.jsx(v,{children:"Reference"}),e.jsx(v,{children:"Created"}),e.jsx(v,{children:"Actions"})]})}),e.jsx(de,{children:p?e.jsx(z,{children:e.jsx(l,{colSpan:7,children:e.jsx(G,{className:"h-10"})})}):(n==null?void 0:n.length)===0?e.jsx(z,{children:e.jsx(l,{colSpan:7,className:"text-center text-muted-foreground py-8",children:"No payouts yet"})}):n==null?void 0:n.map(r=>{const I=c==null?void 0:c.find(ye=>ye.id===r.affiliate_id);return e.jsxs(z,{children:[e.jsx(l,{className:"font-medium",children:(I==null?void 0:I.name)||"Unknown"}),e.jsx(l,{children:D(r.amount)}),e.jsxs(l,{className:"text-sm",children:[X(new Date(r.period_start),"MMM d")," - ",X(new Date(r.period_end),"MMM d, yyyy")]}),e.jsx(l,{children:re(r.status)}),e.jsx(l,{children:r.payment_reference?e.jsx("code",{className:"text-xs bg-muted px-1.5 py-0.5 rounded",children:r.payment_reference}):"—"}),e.jsx(l,{children:X(new Date(r.created_at),"MMM d, yyyy")}),e.jsx(l,{children:r.status==="pending"&&e.jsx(O,{size:"sm",variant:"outline",onClick:()=>u.mutate({id:r.id,status:"paid"}),children:"Mark Paid"})})]},r.id)})})]})})})]})]})]})]})},Ia=()=>{const{adminLogs:a,loadingAdminLogs:c,refetchAdminLogs:m,billingEvents:g,loadingBillingEvents:h,users:x}=qe(),[j,d]=y.useState(""),[o,n]=y.useState("all"),p=y.useMemo(()=>{const s=[];return a==null||a.forEach(u=>{s.push({id:`admin-${u.id}`,type:"admin",action:u.action,details:`${u.entity_type}${u.entity_id?` (${u.entity_id.slice(0,8)}...)`:""}`,metadata:u.details,created_at:u.created_at,icon:"shield"})}),g==null||g.forEach(u=>{s.push({id:`billing-${u.id}`,type:"billing",action:u.event_type,details:u.from_plan&&u.to_plan?`${u.from_plan} → ${u.to_plan}`:u.amount?`$${u.amount}`:"",metadata:u.metadata,created_at:u.created_at,icon:"card"})}
37),x==null||x.slice(0,50).forEach(u=>{var B,se,ae;const M=((B=u.organizations)==null?void 0:B.find(Z=>Z.is_current))||((se=u.organizations)==null?void 0:se[0]),Q=((ae=u.organizations)==null?void 0:ae.reduce((Z,ee)=>{const S={enterprise:4,business:3,pro:2,free:1};return(S[ee.plan]||0)>(S[Z]||0)?ee.plan:Z},"free"))||"free";s.push({id:`signup-${u.user_id}`,type:"signup",action:"user_signup",details:u.email,metadata:{plan:Q,org:(M==null?void 0:M.org_name)||"No org",referred_by:u.referred_by},created_at:u.created_at,icon:"user"})}),s.sort((u,M)=>new Date(M.created_at).getTime()-new Date(u.created_at).getTime())},[a,g,x]),f=y.useMemo(()=>p.filter(s=>{const u=j===""||s.action.toLowerCase().includes(j.toLowerCase())||s.details.toLowerCase().includes(j.toLowerCase()),M=o==="all"||s.type===o||s.action===o;return u&&M}),[p,j,o]),N=s=>{switch(s){case"shield":return e.jsx(Xe,{className:"h-4 w-4 text-blue-500"});case"card":return e.jsx(Me,{className:"h-4 w-4 text-green-500"});case"user":return e.jsx(Ze,{className:"h-4 w-4 text-purple-500"});case"settings":return e.jsx(sa,{className:"h-4 w-4 text-orange-500"});case"edit":return e.jsx(Ta,{className:"h-4 w-4 text-yellow-500"});default:return e.jsx(ne,{className:"h-4 w-4 text-muted-foreground"})}},t=s=>{switch(s){case"admin":return"bg-blue-500/20 text-blue-400 border-blue-500/30";case"billing":return"bg-green-500/20 text-green-400 border-green-500/30";case"signup":return"bg-purple-500/20 text-purple-400 border-purple-500/30";default:return""}};return c||h?e.jsxs("div",{className:"space-y-4",children:[e.jsx(G,{className:"h-10 w-full"}),e.jsx(G,{className:"h-[500px] w-full"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Y,{placeholder:"Search activity logs...",value:j,onChange:s=>d(s.target.value),className:"pl-9"})]}),e.jsxs(ue,{value:o,onValueChange:n,children:[e.jsx(je,{className:"w-[180px]",children:e.jsx(pe,{placeholder:"Filter by type"})}),e.jsxs(ge,{children:[e.jsx(R,{value:"all",children:"All Activity"}),e.jsx(R,{value:"admin",children:"Admin Actions"}),e.jsx(R,{value:"billing",children:"Billing Events"}),e.jsx(R,{value:"signup",children:"User Signups"})]})]}),e.jsx(O,{variant:"outline",size:"icon",onClick:()=>m(),children:e.jsx(fe,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex gap-4 text-sm text-muted-foreground",children:e.jsxs("span",{children:["Showing ",f.length," activities"]})}),e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"h-5 w-5"}),"Activity Log"]}),e.jsx(le,{children:"Complete audit trail of all admin actions, billing events, and signups"})]}),e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{className:"w-[50px]"}),e.jsx(v,{children:"Type"}),e.jsx(v,{children:"Action"}),e.jsx(v,{children:"Details"}),e.jsx(v,{children:"Metadata"}),e.jsx(v,{children:"Time"})]})}),e.jsx(de,{children:f.length===0?e.jsx(z,{children:e.jsx(l,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No activity found"})}):f.slice(0,100).map(s=>e.jsxs(z,{children:[e.jsx(l,{children:N(s.icon)}),e.jsx(l,{children:e.jsx($,{variant:"outline",className:t(s.type),children:s.type})}),e.jsx(l,{children:e.jsx("span",{className:"font-medium capitalize",children:s.action.replace(/_/g," ")})}),e.jsx(l,{children:e.jsx("span",{className:"text-sm",children:s.details||"—"})}),e.jsx(l,{children:s.metadata?e.jsxs("details",{className:"cursor-pointer",children:[e.jsxs("summary",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(rs,{className:"h-3 w-3"}),"View"]}),e.jsx("pre",{className:"text-xs mt-2 p-2 bg-muted rounded overflow-x-auto max-w-[300px]",children:JSON.stringify(s.metadata,null,2)})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(l,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:X(new Date(s.created_at),"MMM d, yyyy HH:mm")}
37)})]},s.id))})]})})})]}),e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"h-5 w-5"}),"Internal Admin Actions"]}),e.jsx(le,{children:"Actions performed by TaskHuddle team members"})]}),e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Action"}),e.jsx(v,{children:"Entity Type"}),e.jsx(v,{children:"Entity ID"}),e.jsx(v,{children:"Details"}),e.jsx(v,{children:"Time"})]})}),e.jsx(de,{children:(a==null?void 0:a.length)===0?e.jsx(z,{children:e.jsx(l,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No admin actions recorded yet"})}):a==null?void 0:a.slice(0,50).map(s=>e.jsxs(z,{children:[e.jsx(l,{children:e.jsx("span",{className:"font-medium capitalize",children:s.action.replace(/_/g," ")})}),e.jsx(l,{children:e.jsx($,{variant:"outline",children:s.entity_type})}),e.jsx(l,{children:s.entity_id?e.jsxs("code",{className:"text-xs bg-muted px-1.5 py-0.5 rounded",children:[s.entity_id.slice(0,8),"..."]}):"—"}),e.jsx(l,{children:s.details?e.jsx("pre",{className:"text-xs max-w-[300px] overflow-x-auto",children:JSON.stringify(s.details,null,2)}):"—"}),e.jsx(l,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:X(new Date(s.created_at),"MMM d, yyyy HH:mm")})})]},s.id))})]})})})]})]})},qa=()=>{const[a,c]=y.useState(!0),[m,g]=y.useState(null),[h,x]=y.useState([]),[j,d]=y.useState([]),[o,n]=y.useState([]),[p,f]=y.useState([]),[N,t]=y.useState([]),[s,u]=y.useState(0),M=y.useCallback(async()=>{const[{count:S},{data:V},{data:q},{data:i},{data:w}]=await Promise.all([k.from("organizations").select("*",{count:"exact",head:!0}),k.from("projects").select("org_id").not("org_id","is",null),k.from("tasks").select("org_id").not("org_id","is",null),k.from("behavior_events").select("org_id").eq("event_name","ai_run_completed"),k.from("behavior_events").select("org_id, session_number, time_since_signup_hours").gte("session_number",2).lte("time_since_signup_hours",48)]);g({orgsCreated:S||0,orgsWithProject:new Set((V==null?void 0:V.map(C=>C.org_id))||[]).size,orgsWithTask:new Set((q==null?void 0:q.map(C=>C.org_id))||[]).size,orgsUsedAI:new Set((i==null?void 0:i.map(C=>C.org_id))||[]).size,orgsReturnedIn48h:new Set((w==null?void 0:w.map(C=>C.org_id))||[]).size})},[]),Q=y.useCallback(async S=>{const V=new Date;V.setDate(V.getDate()-S);const{data:q}=await k.from("behavior_events").select("event_name, plan").gte("created_at",V.toISOString()).in("event_name",["project_created","task_created","ai_run_completed","field_capture_completed","message_sent","file_uploaded"]);if(!q)return[];const i={};return["free","pro","business","enterprise"].forEach(C=>{i[C]={plan:C,projectsCreated:0,tasksCreated:0,aiRunsCompleted:0,fieldCapturesCompleted:0,messagesSent:0,filesUploaded:0}}),q.forEach(C=>{const E=C.plan||"free";switch(i[E]||(i[E]={plan:E,projectsCreated:0,tasksCreated:0,aiRunsCompleted:0,fieldCapturesCompleted:0,messagesSent:0,filesUploaded:0}),C.event_name){case"project_created":i[E].projectsCreated++;break;case"task_created":i[E].tasksCreated++;break;case"ai_run_completed":i[E].aiRunsCompleted++;break;case"field_capture_completed":i[E].fieldCapturesCompleted++;break;case"message_sent":i[E].messagesSent++;break;case"file_uploaded":i[E].filesUploaded++;break}}),Object.values(i)},[]),B=y.useCallback(async()=>{const{data:S}=await k.from("behavior_events").select("event_name, feature_name, metadata").in("event_name",["paywall_shown","ai_limit_reached","upgrade_clicked","upgrade_completed"]);if(!S)return;const V={};S.forEach(q=>{var w;const i=q.feature_name||((w=q.metadata)==null?void 0:w.feature)||"general";switch(V[i]||(V[i]={feature:i,paywallHits:0,limitReached:0,upgradeClicks:0,upgradeCompleted:0}),q.event_name){case"paywall_shown":V[i].paywallHits++;break;case"ai_limit_reached":V[i].limitReached++;break;case"upgrade_clicked":V[i].upgradeClicks++;break;case"upgrade_completed":V[i].upgradeCompleted++;break}}),n(Object.values(V).sort((q,i)=>i.paywallHits-q.paywallHits))},[]),se=y.useCallback(async()=>{const[{data:S},{data:V},{data:q},{data:i},{data:w},{data:C}]=await Promise.all([k.from("organizations").select("id, name, created_at").limit(100),k.from("subscriptions").select("org_id, plan, status").eq("status","active"),k.from("organization_members").select("org_id"),k.from("projects").select("org_id"),k.from("tasks").select("org_id"),k.from("behavior_events").select("org_id, event_name, created_at").in("event_name",["ai_run_completed","field_capture_completed"]).order("created_at",{ascending:!1}).limit(5e3)]);if(!S)return;const E=new Map;
37(V||[]).forEach(P=>E.set(P.org_id,P.plan));const T=new Map;(q||[]).forEach(P=>{T.set(P.org_id,(T.get(P.org_id)||0)+1)});const W=new Map;(i||[]).forEach(P=>{P.org_id&&W.set(P.org_id,(W.get(P.org_id)||0)+1)});const K=new Map;(w||[]).forEach(P=>{P.org_id&&K.set(P.org_id,(K.get(P.org_id)||0)+1)});const H=new Map,D=new Map,F=new Map;(C||[]).forEach(P=>{P.org_id&&(P.event_name==="ai_run_completed"?H.set(P.org_id,(H.get(P.org_id)||0)+1):P.event_name==="field_capture_completed"&&D.set(P.org_id,(D.get(P.org_id)||0)+1),F.has(P.org_id)||F.set(P.org_id,P.created_at))});const he=S.map(P=>({orgId:P.id,orgName:P.name,plan:E.get(P.id)||"free",teamSize:T.get(P.id)||0,projectsCount:W.get(P.id)||0,tasksCount:K.get(P.id)||0,aiRuns:H.get(P.id)||0,fieldCaptures:D.get(P.id)||0,lastActive:F.get(P.id)||P.created_at}));he.sort((P,te)=>te.projectsCount+te.tasksCount+te.aiRuns-(P.projectsCount+P.tasksCount+P.aiRuns)),f(he.slice(0,20))},[]),ae=y.useCallback(async()=>{const[{data:S},{data:V},{data:q},{data:i},{data:w}]=await Promise.all([k.from("organizations").select("id, name, created_at").limit(100),k.from("subscriptions").select("org_id, plan, status").eq("status","active"),k.from("projects").select("org_id"),k.from("behavior_events").select("org_id, created_at").order("created_at",{ascending:!1}).limit(5e3),k.from("behavior_events").select("org_id, created_at").eq("event_name","paywall_shown").order("created_at",{ascending:!1}).limit(1e3)]);if(!S)return;const C=new Date,E=new Map;(V||[]).forEach(D=>E.set(D.org_id,D.plan));const T=new Map;(q||[]).forEach(D=>{D.org_id&&T.set(D.org_id,(T.get(D.org_id)||0)+1)});const W=new Map;(i||[]).forEach(D=>{D.org_id&&!W.has(D.org_id)&&W.set(D.org_id,D.created_at)});const K=new Map;(w||[]).forEach(D=>{D.org_id&&!K.has(D.org_id)&&K.set(D.org_id,D.created_at)});const H=[];for(const D of S){const F=E.get(D.id)||"free",he=T.get(D.id)||0,P=W.get(D.id)||D.created_at,te=Math.floor((C.getTime()-new Date(P).getTime())/(1e3*60*60*24));let re=null;if(he===0?re="No projects created":te>14?re="Inactive for 14+ days":F!=="free"&&te>7&&(re="Paid org inactive 7+ days"),!re&&K.has(D.id)){const A=new Date(K.get(D.id));new Date(P)<=A&&te>3&&(re="Dropped after paywall")}re&&H.push({orgId:D.id,orgName:D.name,plan:F,issue:re,lastActivity:P,daysSinceActivity:te})}H.sort((D,F)=>F.daysSinceActivity-D.daysSinceActivity),t(H.slice(0,20))},[]),Z=y.useCallback(async()=>{const{count:S}=await k.from("behavior_events").select("*",{count:"exact",head:!0});u(S||0)},[]),ee=y.useCallback(async()=>{c(!0);try{await Promise.all([M(),Q(7).then(x),Q(30).then(d),B(),se(),ae(),Z()])}catch(S){console.error("[BehaviorAnalytics] Error fetching:",S)}finally{c(!1)}},[M,Q,B,se,ae,Z]);return y.useEffect(()=>{ee()},[ee]),{loading:a,activationFunnel:m,featureUsage7d:h,featureUsage30d:j,upgradePressure:o,powerOrgs:p,atRiskOrgs:N,totalEvents:s,refetch:ee}},$a=({onSelectOrg:a})=>{const[c,m]=y.useState(!0),[g,h]=y.useState([]),[x,j]=y.useState([]),[d,o]=y.useState(""),[n,p]=y.useState("all"),[f,N]=y.useState("all"),t=async()=>{m(!0);try{const{data:s}=await k.from("organizations").select("id, name, created_at").order("created_at",{ascending:!1});if(!s){h([]),j([]),m(!1);return}const{data:u}=await k.from("subscriptions").select("org_id, plan").eq("status","active"),M=new Map((u||[]).map(w=>[w.org_id,w.plan])),{data:Q}=await k.from("profiles").select("org_id"),B=new Map;(Q||[]).forEach(w=>{w.org_id&&B.set(w.org_id,(B.get(w.org_id)||0)+1)});const{data:se}=await k.from("projects").select("org_id"),ae=new Map;(se||[]).forEach(w=>{w.org_id&&ae.set(w.org_id,(ae.get(w.org_id)||0)+1)});const{data:Z}=await k.from("tasks").select("org_id"),ee=new Map;(Z||[]).forEach(w=>{w.org_id&&ee.set(w.org_id,(ee.get(w.org_id)||0)+1)});const{data:S}=await k.from("behavior_events").select("org_id, created_at").order("created_at",{ascending:!1}),V=new Map,q=new Map;(S||[]).forEach(w=>{w.org_id&&(V.set(w.org_id,(V.get(w.org_id)||0)+1),q.has(w.org_id)||q.set(w.org_id,w.created_at))});const i=s.map(w=>({orgId:w.id,orgName:w.name,plan:M.get(w.id)||"free",userCount:B.get(w.id)||0,projectCount:ae.get(w.id)||0,taskCount:ee.get(w.id)||0,totalEvents:V.get(w.id)||0,lastActivity:q.get(w.id)||null,createdAt:w.created_at}));h(i),j(i)}catch(s){console.error("[OrgBrowser] Error:",s)}finally{m(!1)}};return y.useEffect(()=>{t()},[]),y.useEffect(()=>{let s=[...g];if(d.trim()){const u=d.toLowerCase();s=s.filter(M=>M.orgName.toLowerCase().includes(u))}if(n!=="all"&&(s=s.filter(u=>u.plan===n)),f!=="all"){const u=new Date,M=new Date(u.getTime()-7*24*60*60*1e3),Q=new Date(u.getTime()-30*24*60*60*1e3);
37f==="active"?s=s.filter(B=>B.lastActivity&&new Date(B.lastActivity)>=M):f==="dormant"?s=s.filter(B=>!B.lastActivity||new Date(B.lastActivity)<Q):f==="no-events"&&(s=s.filter(B=>B.totalEvents===0))}j(s)},[g,d,n,f]),c?e.jsxs(_,{children:[e.jsx(U,{children:e.jsx(G,{className:"h-6 w-48"})}),e.jsx(b,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((s,u)=>e.jsx(G,{className:"h-16"},u))})})]}):e.jsxs(_,{children:[e.jsx(U,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(Ae,{className:"h-4 w-4"}),"All Organizations"]}),e.jsxs(O,{variant:"outline",size:"sm",onClick:t,children:[e.jsx(fe,{className:"h-4 w-4 mr-2"}),"Refresh"]})]})}),e.jsxs(b,{children:[e.jsxs("div",{className:"flex flex-wrap gap-3 mb-4",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Y,{placeholder:"Search organizations...",value:d,onChange:s=>o(s.target.value),className:"pl-9"})]}),e.jsxs(ue,{value:n,onValueChange:p,children:[e.jsx(je,{className:"w-[140px]",children:e.jsx(pe,{placeholder:"Plan"})}),e.jsxs(ge,{children:[e.jsx(R,{value:"all",children:"All Plans"}),e.jsx(R,{value:"free",children:"Free"}),e.jsx(R,{value:"pro",children:"Pro"}),e.jsx(R,{value:"business",children:"Business"}),e.jsx(R,{value:"enterprise",children:"Enterprise"})]})]}),e.jsxs(ue,{value:f,onValueChange:N,children:[e.jsx(je,{className:"w-[160px]",children:e.jsx(pe,{placeholder:"Activity"})}),e.jsxs(ge,{children:[e.jsx(R,{value:"all",children:"All Activity"}),e.jsx(R,{value:"active",children:"Active (7d)"}),e.jsx(R,{value:"dormant",children:"Dormant (30d+)"}),e.jsx(R,{value:"no-events",children:"No Events"})]})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:[x.length," of ",g.length," organizations"]}),e.jsxs("div",{className:"space-y-2 max-h-[500px] overflow-y-auto",children:[x.map(s=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors cursor-pointer group",onClick:()=>a(s.orgId,s.orgName),children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Ae,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:s.orgName}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($,{variant:"outline",className:"text-xs capitalize",children:s.plan}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",title:"Members",children:[e.jsx(Ne,{className:"h-3 w-3"}),s.userCount]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",title:"Projects",children:[e.jsx(is,{className:"h-3 w-3"}),s.projectCount]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",title:"Tasks",children:[e.jsx(cs,{className:"h-3 w-3"}),s.taskCount]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",title:"Events",children:[e.jsx(ne,{className:"h-3 w-3"}),s.totalEvents]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx("div",{className:"text-right text-xs text-muted-foreground hidden sm:block",children:s.lastActivity?e.jsx("span",{children:Qe(new Date(s.lastActivity),{addSuffix:!0})}):e.jsx("span",{className:"text-yellow-500",children:"No activity"})}),e.jsx(Ve,{className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})]})]},s.orgId)),x.length===0&&e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No organizations match your filters"})]})]})]})},Ha=a=>{const[c,m]=y.useState(!0),[g,h]=y.useState({overview:null,usageMetrics:null,dailyActivity:[],eventBreakdown:[],userActivity:[],monetization:null}),x=y.useCallback(async()=>{var j;if(!a){m(!1);return}m(!0);try{const{data:d}=await k.from("organizations").select("id, name, created_at").eq("id",a).single(),{data:o}=await k.from("subscriptions").select("plan").eq("org_id",a).eq("status","active").single(),{data:n}=await k.from("behavior_events").select("*").eq("org_id",a).order("created_at",{ascending:!1}),{count:p}=await k.from("profiles").select("*",{count:"exact",head:!0}).eq("org_id",a),{count:f}=await k.from("projects").select("*",{count:"exact",head:!0}).eq("org_id",a),{count:N}=await k.from("tasks").select("*",{count:"exact",head:!0}).eq("org_id",a),t=new Date,s=new Date(t.getTime()-30*24*60*60*1e3),u=new Date(t.getTime()-7*24*60*60*1e3),M=n||[],Q=((j=M[0])==null?void 0:j.created_at)||null,B=d?Math.floor((t.getTime()-new Date(d.created_at).getTime())/(1e3*60*60*24)):0,se=Q?Math.floor((t.getTime()-new Date(Q).getTime())/(1e3*60*60*24)):-1,ae=new Set(M.filter(A=>new Date(A.created_at)>=u).map(A=>A.user_id)).size,Z=new Set(M.filter(A=>new Date(A.created_at)>=s).map(A=>A.user_id)).size,ee={orgId:a,orgName:(d==null?void 0:d.name)||"Unknown",plan:(o==null?void 0:o.plan)||"free",totalEvents:M.length,totalUsers:p||0,totalProjects:f||0,totalTasks:N||0,activeUsers7d:ae,activeUsers30d:Z,daysSinceSignup:B,daysSinceLastActivity:se,lastActivityAt:Q,createdAt:(d==null?void 0:d.created_at)||""},S=(A,r)=>M.filter(I=>I.event_name===A&&(!r||new Date(I.created_at)>=r)).length,V={projectsCreated:{allTime:S("project_created"),last30d:S("project_created",s),last7d:S("project_created",u)},tasksCreated:{allTime:S("task_created"),last30d:S("task_created",s),last7d:S("task_created",u)},aiRunsCompleted:{allTime:S("ai_run_completed"),last30d:S("ai_run_completed",s),last7d:S("ai_run_completed",u)},messagesSent:{allTime:S("message_sent"),last30d:S("message_sent",s),last7d:S("message_sent",u)},filesUploaded:{allTime:S("file_uploaded"),last30d:S("file_uploaded",s),last7d:S("file_uploaded",u)},fieldCapturesCompleted:{allTime:S("field_capture_completed"),last30d:S("field_capture_completed",s),last7d:S("field_capture_completed",u)},logins:{allTime:S("login"),last30d:S("login",s),last7d:S("login",u)}},q=new Map;for(let A=29;A>=0;A--){const r=new Date(t.getTime()-A*24*60*60*1e3);q.set(r.toISOString().split("T")[0],0)}M.filter(A=>new Date(A.created_at)>
37=s).forEach(A=>{const r=new Date(A.created_at).toISOString().split("T")[0];q.has(r)&&q.set(r,(q.get(r)||0)+1)});const i=Array.from(q.entries()).map(([A,r])=>({date:A,events:r})),w=new Map;M.forEach(A=>{w.set(A.event_name,(w.get(A.event_name)||0)+1)});const C=Array.from(w.entries()).map(([A,r])=>({eventName:A,count:r})).sort((A,r)=>r.count-A.count).slice(0,15),E=new Map;M.forEach(A=>{if(!A.user_id)return;const r=E.get(A.user_id)||{count:0,lastActive:A.created_at,features:new Map};r.count++,new Date(A.created_at)>new Date(r.lastActive)&&(r.lastActive=A.created_at),A.feature_name?r.features.set(A.feature_name,(r.features.get(A.feature_name)||0)+1):r.features.set(A.event_name,(r.features.get(A.event_name)||0)+1),E.set(A.user_id,r)});const T=Array.from(E.keys()),{data:W}=await k.from("profiles").select("user_id, first_name, last_name, email").in("user_id",T),K=new Map((W||[]).map(A=>[A.user_id,A])),H=Array.from(E.entries()).map(([A,r])=>{var Ns;const I=K.get(A),ye=((Ns=Array.from(r.features.entries()).sort((Vs,Qs)=>Qs[1]-Vs[1])[0])==null?void 0:Ns[0])||"N/A";return{userId:A,userName:I&&`${I.first_name||""} ${I.last_name||""}`.trim()||"Unknown",email:(I==null?void 0:I.email)||"",totalEvents:r.count,lastActive:r.lastActive,topFeature:ye}}).sort((A,r)=>r.totalEvents-A.totalEvents).slice(0,20),D=S("paywall_shown"),F=S("ai_limit_reached"),he=S("upgrade_clicked"),P=S("upgrade_completed"),te=new Map;M.filter(A=>A.event_name==="paywall_shown").forEach(A=>{const r=A.feature_name||"unknown";te.set(r,(te.get(r)||0)+1)});const re={paywallsHit:D,limitsReached:F,upgradeClicks:he,upgradeCompleted:P,paywallsByFeature:Array.from(te.entries()).map(([A,r])=>({feature:A,count:r})).sort((A,r)=>r.count-A.count)};h({overview:ee,usageMetrics:V,dailyActivity:i,eventBreakdown:C,userActivity:H,monetization:re})}catch(d){console.error("[useOrgBehaviorAnalytics] Error:",d)}finally{m(!1)}},[a]);return y.useEffect(()=>{x()},[x]),{loading:c,analytics:g,refetch:x}},Ka=({orgId:a,onBack:c})=>{const{loading:m,analytics:g,refetch:h}=Ha(a),{overview:x,usageMetrics:j,dailyActivity:d,eventBreakdown:o,userActivity:n,monetization:p}=g;if(m)return e.jsxs("div",{className:"space-y-6 p-1",children:[e.jsx(G,{className:"h-10 w-48"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(4)].map((N,t)=>e.jsx(G,{className:"h-24"},t))}),e.jsx(G,{className:"h-64"}),e.jsx(G,{className:"h-64"})]});if(!x)return e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Organization not found"}),e.jsxs(O,{variant:"outline",className:"mt-4",onClick:c,children:[e.jsx(ys,{className:"h-4 w-4 mr-2"}),"Go Back"]})]});const f=["hsl(var(--primary))","hsl(var(--secondary))","#22c55e","#f59e0b","#8b5cf6","#ec4899","#06b6d4","#f97316"];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(O,{variant:"ghost",size:"icon",onClick:c,children:e.jsx(ys,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold",children:x.orgName}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($,{variant:"outline",className:"capitalize",children:x.plan}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Since ",X(new Date(x.createdAt),"MMM d, yyyy")]})]})]})]}),e.jsxs(O,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(fe,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4",children:[e.jsx(_,{children:e.jsxs(b,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Ne,{className:"h-4 w-4"}),"Members"]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:x.totalUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[x.activeUsers7d," active (7d)"]})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(is,{className:"h-4 w-4"}),"Projects"]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:x.totalProjects})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(cs,{className:"h-4 w-4"}),"Tasks"]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:x.totalTasks})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(ne,{className:"h-4 w-4"}),"Total Events"]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:x.totalEvents.toLocaleStr
37ing()})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(es,{className:"h-4 w-4"}),"Days Active"]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:x.daysSinceSignup}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"days since signup"})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(ve,{className:"h-4 w-4"}),"Last Activity"]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:x.daysSinceLastActivity>=0?`${x.daysSinceLastActivity}d`:"N/A"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x.lastActivityAt?Qe(new Date(x.lastActivityAt),{addSuffix:!0}):"No activity"})]})})]}),j&&e.jsxs(_,{children:[e.jsx(U,{children:e.jsxs(L,{className:"text-base flex items-center gap-2",children:[e.jsx(Oe,{className:"h-4 w-4"}),"Usage Metrics"]})}),e.jsx(b,{children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Metric"}),e.jsx(v,{className:"text-right",children:"All Time"}),e.jsx(v,{className:"text-right",children:"Last 30d"}),e.jsx(v,{className:"text-right",children:"Last 7d"})]})}),e.jsxs(de,{children:[e.jsxs(z,{children:[e.jsxs(l,{className:"font-medium flex items-center gap-2",children:[e.jsx(is,{className:"h-3 w-3 text-muted-foreground"}),"Projects"]}),e.jsx(l,{className:"text-right",children:j.projectsCreated.allTime}),e.jsx(l,{className:"text-right",children:j.projectsCreated.last30d}),e.jsx(l,{className:"text-right",children:j.projectsCreated.last7d})]}),e.jsxs(z,{children:[e.jsxs(l,{className:"font-medium flex items-center gap-2",children:[e.jsx(cs,{className:"h-3 w-3 text-muted-foreground"}),"Tasks"]}),e.jsx(l,{className:"text-right",children:j.tasksCreated.allTime}),e.jsx(l,{className:"text-right",children:j.tasksCreated.last30d}),e.jsx(l,{className:"text-right",children:j.tasksCreated.last7d})]}),e.jsxs(z,{children:[e.jsxs(l,{className:"font-medium flex items-center gap-2",children:[e.jsx(Oe,{className:"h-3 w-3 text-muted-foreground"}),"AI Runs"]}),e.jsx(l,{className:"text-right",children:j.aiRunsCompleted.allTime}),e.jsx(l,{className:"text-right",children:j.aiRunsCompleted.last30d}),e.jsx(l,{className:"text-right",children:j.aiRunsCompleted.last7d})]}),e.jsxs(z,{children:[e.jsxs(l,{className:"font-medium flex items-center gap-2",children:[e.jsx(aa,{className:"h-3 w-3 text-muted-foreground"}),"Messages"]}),e.jsx(l,{className:"text-right",children:j.messagesSent.allTime}),e.jsx(l,{className:"text-right",children:j.messagesSent.last30d}),e.jsx(l,{className:"text-right",children:j.messagesSent.last7d})]}),e.jsxs(z,{children:[e.jsxs(l,{className:"font-medium flex items-center gap-2",children:[e.jsx(ta,{className:"h-3 w-3 text-muted-foreground"}),"Files Uploaded"]}),e.jsx(l,{className:"text-right",children:j.filesUploaded.allTime}),e.jsx(l,{className:"text-right",children:j.filesUploaded.last30d}),e.jsx(l,{className:"text-right",children:j.filesUploaded.last7d})]}),e.jsxs(z,{children:[e.jsxs(l,{className:"font-medium flex items-center gap-2",children:[e.jsx(ne,{className:"h-3 w-3 text-muted-foreground"}),"Field Captures"]}),e.jsx(l,{className:"text-right",children:j.fieldCapturesCompleted.allTime}),e.jsx(l,{className:"text-right",children:j.fieldCapturesCompleted.last30d}),e.jsx(l,{className:"text-right",children:j.fieldCapturesCompleted.last7d})]}),e.jsxs(z,{children:[e.jsxs(l,{className:"font-medium flex items-center gap-2",children:[e.jsx(Ne,{className:"h-3 w-3 text-muted-foreground"}),"Logins"]}),e.jsx(l,{className:"text-right",children:j.logins.allTime}),e.jsx(l,{className:"text-right",children:j.logins.last30d}),e.jsx(l,{className:"text-right",children:j.logins.last7d})]})]})]})})]}),e.jsxs(_,{children:[e.jsx(U,{children:e.jsxs(L,{className:"text-base flex items-center gap-2",children:[e.jsx(ve,{className:"h-4 w-4"}),"Activity Timeline (Last 30 Days)"]})}),e.jsx(b,{children:e.jsx("div",{className:"h-64",children:e.jsx(Be,{width:"100%",height:"100%",children:e.jsxs(ya,{data:d,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorEvents",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",
37stopColor:"hsl(var(--primary))",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"hsl(var(--primary))",stopOpacity:0})]})}),e.jsx(os,{dataKey:"date",tickFormatter:N=>X(new Date(N),"M/d"),tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),e.jsx(ms,{tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Ie,{labelFormatter:N=>X(new Date(N),"MMM d, yyyy"),contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(wa,{type:"monotone",dataKey:"events",stroke:"hsl(var(--primary))",fillOpacity:1,fill:"url(#colorEvents)"})]})})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(_,{children:[e.jsx(U,{children:e.jsxs(L,{className:"text-base flex items-center gap-2",children:[e.jsx(ne,{className:"h-4 w-4"}),"Event Breakdown"]})}),e.jsx(b,{children:e.jsx("div",{className:"h-64",children:e.jsx(Be,{width:"100%",height:"100%",children:e.jsxs(Os,{data:o.slice(0,8),layout:"vertical",children:[e.jsx(os,{type:"number",tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),e.jsx(ms,{type:"category",dataKey:"eventName",tick:{fontSize:10},width:120,stroke:"hsl(var(--muted-foreground))"}),e.jsx(Ie,{contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(Bs,{dataKey:"count",radius:[0,4,4,0],children:o.slice(0,8).map((N,t)=>e.jsx(ss,{fill:f[t%f.length]},`cell-${t}`))})]})})})})]}),p&&e.jsxs(_,{children:[e.jsx(U,{children:e.jsxs(L,{className:"text-base flex items-center gap-2",children:[e.jsx(Me,{className:"h-4 w-4"}),"Monetization Signals"]})}),e.jsxs(b,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20",children:[e.jsx("p",{className:"text-2xl font-bold text-yellow-400",children:p.paywallsHit}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paywalls Hit"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-red-500/10 border border-red-500/20",children:[e.jsx("p",{className:"text-2xl font-bold text-red-400",children:p.limitsReached}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Limits Reached"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/10 border border-blue-500/20",children:[e.jsx("p",{className:"text-2xl font-bold text-blue-400",children:p.upgradeClicks}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upgrade Clicks"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-green-500/10 border border-green-500/20",children:[e.jsx("p",{className:"text-2xl font-bold text-green-400",children:p.upgradeCompleted}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upgrades Completed"})]})]}),p.paywallsByFeature.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Paywalls by Feature:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:p.paywallsByFeature.map(({feature:N,count:t})=>e.jsxs($,{variant:"outline",className:"text-xs",children:[N,": ",t]},N))})]})]})]})]}),e.jsxs(_,{children:[e.jsx(U,{children:e.jsxs(L,{className:"text-base flex items-center gap-2",children:[e.jsx(Ne,{className:"h-4 w-4"}),"User Activity"]})}),e.jsx(b,{children:n.length>0?e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"User"}),e.jsx(v,{children:"Email"}),e.jsx(v,{className:"text-right",children:"Events"}),e.jsx(v,{className:"text-right",children:"Last Active"}),e.jsx(v,{className:"text-right",children:"Top Feature"})]})}),e.jsx(de,{children:n.map(N=>e.jsxs(z,{children:[e.jsx(l,{className:"font-medium",children:N.userName}),e.jsx(l,{className:"text-muted-foreground text-sm",children:N.email}),e.jsx(l,{className:"text-right",children:N.totalEvents}),e.jsx(l,{className:"text-right text-sm text-muted-foreground",children:Qe(new Date(N.lastActive),{addSuffix:!0})}),e.jsx(l,{className:"text-right",children:e.jsx($,{variant:"secondary",className:"text-xs capitalize",children:N.topFeature.replace(/_/g," ")})})]},N.userId))})]}):e.jsx("p",{className:"text-muted-foreground text-sm text-center py-8",children:"No user activity data"})})]})]})},Va=({onSelectOrg:a})=>{const{loading:c,activationFunnel:m,featureUsage7d:g,featureUsage30d:h,upgradePressure:x,powerOrgs:j,atRiskOrgs:d,totalEvents:o,refetch:n}=qa(),[p,f]=y.useState(null),N=(s,u)=>{f(s),a==null||a(s,u)};if(c)return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-5 ga
37p-4",children:[...Array(5)].map((s,u)=>e.jsx(G,{className:"h-24"},u))}),e.jsx(G,{className:"h-96"})]});const t=(s,u)=>s===0?0:Math.round(u/s*100);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-semibold flex items-center gap-2",children:[e.jsx(ne,{className:"h-5 w-5 text-primary"}),"Behavior Analytics"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.toLocaleString()," total events tracked"]})]}),e.jsxs(O,{variant:"outline",size:"sm",onClick:()=>n(),children:[e.jsx(fe,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),e.jsx($a,{onSelectOrg:N}),e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(ve,{className:"h-4 w-4"}),"Activation Funnel"]}),e.jsx(le,{children:"Organization-based activation metrics"})]}),e.jsx(b,{children:m?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(He,{label:"Orgs Created",value:m.orgsCreated,color:"bg-blue-500/20 text-blue-400"}),e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground hidden sm:block"}),e.jsx(He,{label:"With Project",value:m.orgsWithProject,rate:t(m.orgsCreated,m.orgsWithProject),color:"bg-purple-500/20 text-purple-400"}),e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground hidden sm:block"}),e.jsx(He,{label:"With Task",value:m.orgsWithTask,rate:t(m.orgsWithProject,m.orgsWithTask),color:"bg-green-500/20 text-green-400"}),e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground hidden sm:block"}),e.jsx(He,{label:"Used AI",value:m.orgsUsedAI,rate:t(m.orgsWithTask,m.orgsUsedAI),color:"bg-orange-500/20 text-orange-400"}),e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground hidden sm:block"}),e.jsx(He,{label:"Returned 48h",value:m.orgsReturnedIn48h,rate:t(m.orgsCreated,m.orgsReturnedIn48h),color:"bg-emerald-500/20 text-emerald-400"})]}):e.jsx("p",{className:"text-muted-foreground text-sm",children:"No data available"})})]}),e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"h-4 w-4"}),"Core Feature Usage"]}),e.jsx(le,{children:"Usage counts segmented by plan"})]}),e.jsx(b,{children:e.jsxs(hs,{defaultValue:"7d",className:"w-full",children:[e.jsxs(us,{children:[e.jsx(Ue,{value:"7d",children:"Last 7 Days"}),e.jsx(Ue,{value:"30d",children:"Last 30 Days"})]}),e.jsx(oe,{value:"7d",className:"mt-4",children:e.jsx(Cs,{data:g})}),e.jsx(oe,{value:"30d",className:"mt-4",children:e.jsx(Cs,{data:h})})]})})]}),e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(_a,{className:"h-4 w-4"}),"Upgrade Pressure"]}),e.jsx(le,{children:"Paywall hits and upgrade signals by feature"})]}),e.jsx(b,{children:x.length>0?e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Feature"}),e.jsx(v,{className:"text-right",children:"Paywall Hits"}),e.jsx(v,{className:"text-right",children:"Limits Reached"}),e.jsx(v,{className:"text-right",children:"Upgrade Clicks"}),e.jsx(v,{className:"text-right",children:"Completed"}),e.jsx(v,{className:"text-right",children:"Conversion"})]})}),e.jsx(de,{children:x.map(s=>e.jsxs(z,{children:[e.jsx(l,{className:"font-medium capitalize",children:s.feature}),e.jsx(l,{className:"text-right",children:s.paywallHits}),e.jsx(l,{className:"text-right",children:s.limitReached}),e.jsx(l,{className:"text-right",children:s.upgradeClicks}),e.jsx(l,{className:"text-right text-green-400",children:s.upgradeCompleted}),e.jsx(l,{className:"text-right",children:s.upgradeClicks>0?`${Math.round(s.upgradeCompleted/s.upgradeClicks*100)}%`:"-"})]},s.feature))})]}):e.jsx("p",{className:"text-muted-foreground text-sm",children:"No upgrade pressure data yet"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"h-4 w-4 text-yellow-500"}),"Power Organizations"]}),e.jsx(le,{children:"Top active organizations by engagement"})]}),e.jsx(b,{children:j.length>0?e.jsx("div",{className:"space-y-3 max-h-96 overflow-y-auto",children:j.map(s=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors cursor-pointer group",onClick:()=>N(s.orgId,s.orgName),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ae,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:s.orgName}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($,{variant:"outline",className:"text-xs",children:s.plan}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.teamSize," users"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"text-right text-xs",children:[e.jsxs("p",{children:[s.projectsCount," projects • ",s.tasksCount," tasks"]}),e.jsxs("p",{className:"text-muted-foreground",children:[s.aiRuns," AI • ",s.fieldCaptures," captures"]})]}),e.jsx(Ve,{className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})]})]},s.orgId))}):e.jsx("p",{className:"text-muted-foreground text-sm",children:"No data available"})})]}),e.jsxs(_,{children:[e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"h-4 w-4 text-red-500"}),"At-Risk Organizations"]}),e.jsx(le,{children:"Organizations showing signs of churn"})]}),e.jsx(b,{children:d.length>0?e.jsx("div",{className:"space-y-3 max-h-96 overflow-y-auto",children:d.map(s=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-red-500/5 border border-red-500/20 hover:bg-red-500/10 transition-colors cursor-pointer group",onClick:()=>N(s.orgId,s.orgName),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ae,{className:"h-4 w-4 text-red-400"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:s.orgName}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($,{variant:"outline",className:"text-xs border-red-500/30 text-red-400",children:s.plan}),e.jsx("span",{className:"text-xs text-red-400",children:s.issue})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"text-right text-xs text-muted-foreground",children:[e.jsxs("p",{children:[s.daysSinceActivity,"d inactive"]}),e.jsx("p",{children:X(new Date(s.lastActivity),"MMM d")})]}),e.jsx(Ve,{className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})]})]},s.orgId))}):e.jsx("p",{className:"text-muted-foreground text-sm",children:"No at-risk organizations detected"})})]})]}),e.jsx(Ds,{open:!!p,onOpenChange:()=>f(null),children:e.jsxs(Ts,{className:"w-full sm:max-w-2xl lg:max-w-4xl overflow-y-auto",children:[e.jsx(Rs,{className:"sr-only",children:e.jsx(zs,{children:"Organization Analytics"})}),p&&e.jsx(Ka,{orgId:p,onBack:()=>f(null)})]})})]})},He=({label:a,value:c,rate:m,color:g})=>e.jsxs("div",{className:`px-4 py-3 rounded-lg ${g} flex flex-col items-center min-w-[100px]`,children:[e.jsx("span",{className:"text-2xl font-bold",children:c}),e.jsx("span",{className:"text-xs opacity-80",children:a}),m!==void 0&&e.jsxs("span",{className:"text-xs mt-1 opacity-60",children:[m,"%"]})]}),Cs=({data:a})=>e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Plan"}),e.jsx(v,{className:"text-right",children:"Projects"}),e.jsx(v,{className:"text-right",children:"Tasks"}),e.jsx(v,{className:"text-right",children:"AI Runs"}),e.jsx(v,{className:"text-right",children:"Captures"}),e.jsx(v,{className:"text-right",children:"Messages"}),e.jsx(v,{className:"text-right",children:"Files"})]})}),e.jsxs(de,{children:[a.map(c=>e.jsxs(z,{children:[e.jsx(l,{children:e.jsx($,{variant:"outline",className:"capitalize",children:c.plan})}),e.jsx(l,{className:"text-right",children:c.projectsCreated}),e.jsx(l,{className:"text-right",children:c.tasksCreated}),e.jsx(l,{className:"text-right",children:c.aiRunsCompleted}),e.jsx(l,{className:"text-right",children:c.fieldCapturesCompleted}),e.jsx(l,{className:"text-right",children:c.messagesSent}),e.jsx(l,{className:"text-right",children:c.filesUploaded})]},c.plan)),a.length===0&&e.jsx(z,{children:e.jsx(l,{colSpan:7,className:"text-center text-muted-foreground",children:"No usage data available"})})]})]}),fs=()=>{const a=ra(),c=async(n,p,f,N)=>{const{data:{user:t}}=await k.auth.getUser();t&&await k.from("internal_admin_logs").insert([{admin_user_id:t.id,action:n,entity_type:p,entity_id:f,details:N?JSON.parse(JSON.stringify(N)):null}])},m=De({mutationFn:async({orgId:n,days:p})=>{const{data:f}=await k.from("subscriptions").select("trial_end, plan").eq("org_id",n).maybeSingle(),N=f!=null&&f.trial_end?new Date(f.trial_end):new Date,t=new Date(N);t.setDate(t.getDate()+p);const{error:s}
37=await k.from("subscriptions").upsert({org_id:n,trial_end:t.toISOString(),status:"trialing",plan:(f==null?void 0:f.plan)||"free"},{onConflict:"org_id"});if(s)throw s;return await c("extend_trial","org",n,{days:p,new_end:t.toISOString()}),{orgId:n,newEnd:t}},onSuccess:()=>{me.success("Trial extended successfully"),a.invalidateQueries({queryKey:["admin-users"]})},onError:n=>{me.error(`Failed to extend trial: ${n.message}`)}}),g=De({mutationFn:async({orgId:n,credits:p,reason:f})=>{const{data:N}=await k.from("ai_credits").select("balance").eq("org_id",n).maybeSingle();if(N){const{error:s}=await k.from("ai_credits").update({balance:N.balance+p}).eq("org_id",n);if(s)throw s}else{const{error:s}=await k.from("ai_credits").insert({org_id:n,balance:p});if(s)throw s}const{data:{user:t}}=await k.auth.getUser();return await k.from("ai_credit_transactions").insert({org_id:n,user_id:t==null?void 0:t.id,amount:p,transaction_type:"admin_grant",description:f}),await c("grant_credits","org",n,{credits:p,reason:f}),{orgId:n,credits:p}},onSuccess:n=>{me.success(`Granted ${n.credits} credits successfully`),a.invalidateQueries({queryKey:["admin-users"]})},onError:n=>{me.error(`Failed to grant credits: ${n.message}`)}}),h=De({mutationFn:async({orgId:n,newPlan:p})=>{const{data:f}=await k.from("subscriptions").select("plan").eq("org_id",n).maybeSingle(),N=(f==null?void 0:f.plan)||"free";await k.from("billing_events").insert([{org_id:n,event_type:"admin_plan_change",from_plan:N,to_plan:p}]);const{error:t}=await k.from("subscriptions").upsert({org_id:n,plan:p,status:"active"},{onConflict:"org_id"});if(t)throw t;return await c("update_plan","org",n,{old_plan:N,new_plan:p}),{orgId:n,oldPlan:N,newPlan:p}},onSuccess:n=>{me.success(`Plan updated to ${n.newPlan}`),a.invalidateQueries({queryKey:["admin-users"]})},onError:n=>{me.error(`Failed to update plan: ${n.message}`)}}),x=De({mutationFn:async({entityType:n,entityId:p,note:f,isPinned:N})=>{const{data:{user:t}}=await k.auth.getUser();if(!t)throw new Error("Not authenticated");const{data:s,error:u}=await k.from("internal_admin_notes").insert({entity_type:n,entity_id:p,note:f,created_by:t.id,is_pinned:N||!1}).select().single();if(u)throw u;return await c("add_note",n,p,{note_preview:f.substring(0,100)}),s},onSuccess:()=>{me.success("Note added successfully"),a.invalidateQueries({queryKey:["admin-notes"]})},onError:n=>{me.error(`Failed to add note: ${n.message}`)}}),j=De({mutationFn:async()=>{const{data:n,error:p}=await k.rpc("refresh_all_engagement_scores");if(p)throw p;return await c("refresh_engagement_scores","system",void 0,{count:n}),n},onSuccess:n=>{me.success(`Refreshed ${n} engagement scores`),a.invalidateQueries({queryKey:["engagement-scores"]})},onError:n=>{me.error(`Failed to refresh scores: ${n.message}`)}}),d=n=>Fe({queryKey:["admin-notes",n],queryFn:async()=>{if(!n)return[];const{data:p,error:f}=await k.from("internal_admin_notes").select("*").eq("entity_type","org").eq("entity_id",n).order("is_pinned",{ascending:!1}).order("created_at",{ascending:!1});if(f)throw f;return p||[]},enabled:!!n}),o=De({mutationFn:async n=>{const{error:p}=await k.from("internal_admin_notes").delete().eq("id",n);if(p)throw p},onSuccess:()=>{me.success("Note deleted"),a.invalidateQueries({queryKey:["admin-notes"]})},onError:n=>{me.error(`Failed to delete note: ${n.message}`)}});return{extendTrial:m.mutate,isExtendingTrial:m.isPending,grantCredits:g.mutate,isGrantingCredits:g.isPending,updatePlan:h.mutate,isUpdatingPlan:h.isPending,addNote:x.mutate,isAddingNote:x.isPending,refreshEngagementScores:j.mutate,isRefreshingScores:j.isPending,useOrgNotes:d,deleteNote:o.mutate,isDeletingNote:o.isPending}},Ss=({selectedOrgId:a,selectedOrgName:c})=>{const{extendTrial:m,isExtendingTrial:g,grantCredits:h,isGrantingCredits:x,updatePlan:j,isUpdatingPlan:d,addNote:o,isAddingNote:n,refreshEngagementScores:p,isRefreshingScores:f,useOrgNotes:N,deleteNote:t,isDeletingNote:s}=fs(),{data:u=[],isLoading:M}=N(a),[Q,B]=y.useState("7"),[se,ae]=y.useState("100"),[Z,ee]=y.useState(""),[S,V]=y.useState(""),[q,i]=y.useState(""),[w,C]=y.useState(!1),[E,T]=y.useState(null),W=()=>{a&&(m({orgId:a,days:parseInt(Q)}),T(null),B("7"))},K=()=>{a&&(h({orgId:a,credits:parseInt(se),reason:Z}),T(null),ae("100"),ee(""))},H=()=>{!a||!S||(j({orgId:a,newPlan:S}),T(null),V(""))},D=()=>{!a||!q.trim()||(o({entityType:"org",entityId:a,note:q,isPinned:w}),T(null),i(""),C(!1))};return e.jsxs(_,{className:"border-primary/20 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(U,{className:"pb-2 md:pb-3 px-3 md:px-6 pt-3 md:pt-6",children:e.jsxs(L,{className:"text-xs md:text-sm font-medium flex items-center gap-2",children:[e.jsx(Oe,{className:"h-3.5 w-3.5 md:h-4 md:w-4 text-primary"}),"Quick Actions",c?e.jsx("span",{className:"text-[10px] md:text-xs text-muted-foreground ml-auto truncate max-w-[150px]",children:c}):e.jsx("span",{className:"text-[10px] md:text-xs text-muted-foreground ml-auto",children:"Select an org from Engagement or Behavior tab"})]})}),e.jsxs(b,{className:"space-y-3 px-3 md:px-6 pb-3 md:pb-6",children:[e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-3 lg:grid-cols-5 ga
37p-1.5 md:gap-2",children:[e.jsxs(we,{open:E==="trial",onOpenChange:F=>T(F?"trial":null),children:[e.jsx(ze,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"h-auto py-1.5 md:py-2 px-2 md:px-3 flex-col gap-0.5 md:gap-1",disabled:!a,children:[e.jsx(es,{className:"h-3.5 w-3.5 md:h-4 md:w-4"}),e.jsx("span",{className:"text-[10px] md:text-xs leading-tight",children:"Trial"})]})}),e.jsxs(_e,{children:[e.jsxs(be,{children:[e.jsx(Ce,{children:"Extend Trial"}),e.jsxs(Se,{children:["Extend trial period for ",c]})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Days to Add"}),e.jsx(Y,{type:"number",value:Q,onChange:F=>B(F.target.value),min:"1",max:"365"})]})}),e.jsx(ke,{children:e.jsx(O,{onClick:W,disabled:g,children:g?"Extending...":"Extend Trial"})})]})]}),e.jsxs(we,{open:E==="credits",onOpenChange:F=>T(F?"credits":null),children:[e.jsx(ze,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"h-auto py-1.5 md:py-2 px-2 md:px-3 flex-col gap-0.5 md:gap-1",disabled:!a,children:[e.jsx(qs,{className:"h-3.5 w-3.5 md:h-4 md:w-4"}),e.jsx("span",{className:"text-[10px] md:text-xs leading-tight",children:"Credits"})]})}),e.jsxs(_e,{children:[e.jsxs(be,{children:[e.jsx(Ce,{children:"Grant AI Credits"}),e.jsxs(Se,{children:["Add credits to ",c]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Credits Amount"}),e.jsx(Y,{type:"number",value:se,onChange:F=>ae(F.target.value),min:"1"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Reason"}),e.jsx(Y,{value:Z,onChange:F=>ee(F.target.value),placeholder:"e.g., Customer success gift"})]})]}),e.jsx(ke,{children:e.jsx(O,{onClick:K,disabled:x,children:x?"Granting...":"Grant Credits"})})]})]}),e.jsxs(we,{open:E==="plan",onOpenChange:F=>T(F?"plan":null),children:[e.jsx(ze,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"h-auto py-1.5 md:py-2 px-2 md:px-3 flex-col gap-0.5 md:gap-1",disabled:!a,children:[e.jsx(Me,{className:"h-3.5 w-3.5 md:h-4 md:w-4"}),e.jsx("span",{className:"text-[10px] md:text-xs leading-tight",children:"Plan"})]})}),e.jsxs(_e,{children:[e.jsxs(be,{children:[e.jsx(Ce,{children:"Update Plan"}),e.jsxs(Se,{children:["Change plan for ",c]})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"New Plan"}),e.jsxs(ue,{value:S,onValueChange:V,children:[e.jsx(je,{children:e.jsx(pe,{placeholder:"Select plan"})}),e.jsxs(ge,{children:[e.jsx(R,{value:"free",children:"Free"}),e.jsx(R,{value:"pro",children:"Pro"}),e.jsx(R,{value:"business",children:"Business"}),e.jsx(R,{value:"enterprise",children:"Enterprise"})]})]})]})}),e.jsx(ke,{children:e.jsx(O,{onClick:H,disabled:d||!S,children:d?"Updating...":"Update Plan"})})]})]}),e.jsxs(we,{open:E==="note",onOpenChange:F=>T(F?"note":null),children:[e.jsx(ze,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"h-auto py-1.5 md:py-2 px-2 md:px-3 flex-col gap-0.5 md:gap-1",disabled:!a,children:[e.jsx(Ks,{className:"h-3.5 w-3.5 md:h-4 md:w-4"}),e.jsx("span",{className:"text-[10px] md:text-xs leading-tight",children:"Note"})]})}),e.jsxs(_e,{children:[e.jsxs(be,{children:[e.jsx(Ce,{children:"Add Internal Note"}),e.jsxs(Se,{children:["Add a note to ",c]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(J,{children:"Note"}),e.jsx(Je,{value:q,onChange:F=>i(F.target.value),placeholder:"Enter your note...",rows:4})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",id:"pinned",checked:w,onChange:F=>C(F.target.checked),className:"rounded"}),e.jsx(J,{htmlFor:"pinned",className:"text-sm font-normal",children:"Pin this note"})]})]}),e.jsx(ke,{children:e.jsx(O,{onClick:D,disabled:n||!q.trim(),children:n?"Adding...":"Add Note"})})]})]}),e.jsxs(O,{variant:"outline",size:"sm",className:"h-auto py-1.5 md:py-2 px-2 md:px-3 flex-col gap-0.5 md:gap-1",onClick:()=>p(),disabled:f,children:[e.jsx(fe,{className:`h-3.5 w-3.5 md:h-4 md:w-4 ${f?"animate-spin":""}`}),e.jsx("span",{className:"text-[10px] md:text-xs leading-tight",children:"Refresh"})]})]}),a&&e.jsx("div",{className:"space-y-1.5",children:M?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading notes..."}):u.length>0?u.map(F=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border/50 bg-muted/30 px-2.5 py-2 text-xs",children:[F.is_pinned&&e.jsx(ba,{className:"h-3 w-3 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-foreground whitespace-pre-wrap break-words",children:F.note}),e.jsx("p",{className:"text-muted-foreground mt-0.5 text-[10px]",children:F.created_at?Qe(new Date(F.created_at),{addSuffix:!0}):""})]}),e.jsx(O,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>t(F.id),disabled:s,children:e.jsx(Us,{className:"h-3 w-3"})})]},F.id)):e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"No notes for this org yet."})})]})]})},Qa=(a=!0,c=50)=>{const[m,g]=y.useState([]),[h,x]=y.useState(!1),[j,d]=y.useState(!1),o=y.useCallback(f=>{h||g(N=>[f,...N].slice(0,c))},[h,c]),n=y.useCallback(()=>{g([])},[]),p=y.useCallback(()=>{x(f=>!f)},[]);return y.useEffect(()=>{if(!a)return;let f;return(async()=>
37{f=k.channel("admin-live-activity").on("postgres_changes",{event:"INSERT",schema:"public",table:"behavior_events"},t=>{var M,Q;const s=t.new;let u="feature_use";s.event_name==="signup"?u="signup":s.event_name==="login"?u="login":(M=s.event_name)!=null&&M.includes("project")?u="project_create":(Q=s.event_name)!=null&&Q.includes("task")&&(u="task_create"),o({id:s.id,type:u,eventName:s.event_name,userId:s.user_id,orgId:s.org_id,metadata:s.metadata,timestamp:new Date(s.created_at)})}).on("postgres_changes",{event:"INSERT",schema:"public",table:"billing_events"},t=>{const s=t.new;let u="payment";s.event_type==="upgrade"?u="upgrade":s.event_type==="downgrade"&&(u="downgrade"),o({id:s.id,type:u,eventName:s.event_type,userId:s.user_id,orgId:s.org_id,metadata:{amount:s.amount,from_plan:s.from_plan,to_plan:s.to_plan},timestamp:new Date(s.created_at)})}).on("postgres_changes",{event:"INSERT",schema:"public",table:"profiles"},t=>{const s=t.new;o({id:s.user_id,type:"signup",eventName:"New User Signup",userId:s.user_id,userEmail:s.email,orgId:s.org_id,timestamp:new Date(s.created_at)})}).subscribe(t=>{d(t==="SUBSCRIBED")})})(),()=>{f&&k.removeChannel(f)}},[a,o]),{events:m,isPaused:h,isConnected:j,togglePause:p,clearEvents:n}},Ga=a=>{switch(a){case"signup":return e.jsx(Ze,{className:"h-4 w-4 text-green-500"});case"login":return e.jsx(ne,{className:"h-4 w-4 text-blue-500"});case"upgrade":return e.jsx(ve,{className:"h-4 w-4 text-primary"});case"downgrade":return e.jsx(Ye,{className:"h-4 w-4 text-orange-500"});case"payment":return e.jsx(Me,{className:"h-4 w-4 text-green-500"});case"feature_use":return e.jsx(Oe,{className:"h-4 w-4 text-yellow-500"});case"project_create":return e.jsx(ca,{className:"h-4 w-4 text-purple-500"});case"task_create":return e.jsx(ia,{className:"h-4 w-4 text-cyan-500"});default:return e.jsx(ne,{className:"h-4 w-4 text-muted-foreground"})}},Wa=a=>{switch(a){case"signup":case"upgrade":case"payment":return"default";case"downgrade":return"destructive";default:return"secondary"}},ks=()=>{const{events:a,isPaused:c,isConnected:m,togglePause:g,clearEvents:h}=Qa(!0,30);return e.jsxs(_,{className:"h-full border-0 md:border shadow-none md:shadow-sm",children:[e.jsx(U,{className:"pb-2 md:pb-3 px-4 pt-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(L,{className:"text-xs md:text-sm font-medium flex items-center gap-2",children:[e.jsx(ne,{className:"h-3.5 w-3.5 md:h-4 md:w-4"}),e.jsx("span",{children:"Live Activity"}),e.jsx($,{variant:m?"default":"destructive",className:"text-[10px] md:text-xs px-1.5 py-0",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"h-2.5 w-2.5 md:h-3 md:w-3 mr-0.5 md:mr-1"}),e.jsx("span",{className:"hidden xs:inline",children:"Live"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{className:"h-2.5 w-2.5 md:h-3 md:w-3 mr-0.5 md:mr-1"}),e.jsx("span",{className:"hidden xs:inline",children:"Off"})]})})]}),e.jsxs("div",{className:"flex items-center gap-0.5 md:gap-1",children:[e.jsx(O,{variant:"ghost",size:"icon",className:"h-6 w-6 md:h-7 md:w-7",onClick:g,children:c?e.jsx(Aa,{className:"h-3 w-3 md:h-3.5 md:w-3.5"}):e.jsx(ka,{className:"h-3 w-3 md:h-3.5 md:w-3.5"})}),e.jsx(O,{variant:"ghost",size:"icon",className:"h-6 w-6 md:h-7 md:w-7",onClick:h,children:e.jsx(Us,{className:"h-3 w-3 md:h-3.5 md:w-3.5"})})]})]})}),e.jsx(b,{className:"p-0",children:e.jsx(Fs,{className:"h-[50vh] md:h-[300px]",children:e.jsx("div",{className:"px-4 pb-4 space-y-2",children:e.jsx(na,{mode:"popLayout",children:a.length===0?e.jsxs("div",{className:"text-center text-muted-foreground py-8",children:[e.jsx(ne,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"Waiting for activity..."}),c&&e.jsx("p",{className:"text-xs mt-1",children:"Feed is paused"})]}):a.map(x=>e.jsxs(la.div,{initial:{opacity:0,x:-20,height:0},animate:{opacity:1,x:0,height:"auto"},exit:{opacity:0,x:20,height:0},transition:{duration:.2},className:"flex items-start gap-3 p-2 rounded-lg bg-muted/50 hover:bg-muted transition-colors",children:[e.jsx("div",{className:"mt-0.5",children:Ga(x.type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx($,{variant:Wa(x.type),className:"text-xs",children:x.type.replace("_"," ")}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Qe(x.timestamp,{addSuffix:!0})})]}),e.jsx("p",{className:"text-sm font-medium truncate mt-0.5",children:x.eventName}),x.userEmail&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:x.userEmail}),x.metadata&&Object.keys(x.metadata).length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[x.metadata.amount&&e.jsxs($,{variant:"outline",className:"text-xs",children:["$",(x.metadata.amount/100).toFixed(2)]}),x.metadata.to_plan&&e.jsxs($,{variant:"outline",className:"text-xs",children:["→ ",x.metadata.to_plan]})]})]})]},x.id))})})})})]})},Ja=()=>{const a=Fe({queryKey:["engagement-scores"],queryFn:async()=>{const{data:g,error:h}=await k.from("org_engagement_scores").select(`
38          *,
39          organizations:org_id (
40            name
41          )
42        `).order("score",{ascending:!1});if(h)throw h;const x=g.map(o=>o.org_id),{data:j}=await k.from("subscriptions").select("org_id, plan").in("org_id",x),d=new Map;
42return j==null||j.forEach(o=>{d.set(o.org_id,o.plan)}),g.map(o=>{var n,p;return{...o,organization:{name:Array.isArray(o.organizations)?(n=o.organizations[0])==null?void 0:n.name:((p=o.organizations)==null?void 0:p.name)||"Unknown",plan:d.get(o.org_id)||"free"}}})}}),c=Fe({queryKey:["engagement-distribution"],queryFn:async()=>{const{data:g,error:h}=await k.from("org_engagement_scores").select("health_status");if(h)throw h;const x={healthy:0,at_risk:0,critical:0,dormant:0};return g.forEach(j=>{const d=j.health_status;d in x&&x[d]++}),x}}),m=Fe({queryKey:["engagement-average"],queryFn:async()=>{const{data:g,error:h}=await k.from("org_engagement_scores").select("score");if(h)throw h;if(g.length===0)return 0;const x=g.reduce((j,d)=>j+(d.score||0),0);return Math.round(x/g.length)}});return{scores:a.data||[],loadingScores:a.isLoading,distribution:c.data||{healthy:0,at_risk:0,critical:0,dormant:0},loadingDistribution:c.isLoading,averageScore:m.data||0,loadingAverage:m.isLoading,refetch:()=>{a.refetch(),c.refetch(),m.refetch()}}},Pe={healthy:"hsl(var(--primary))",at_risk:"hsl(45, 93%, 47%)",critical:"hsl(0, 84%, 60%)",dormant:"hsl(var(--muted-foreground))"},Ya={healthy:e.jsx(ve,{className:"h-4 w-4"}),at_risk:e.jsx(Es,{className:"h-4 w-4"}),critical:e.jsx(da,{className:"h-4 w-4"}),dormant:e.jsx(Pa,{className:"h-4 w-4"})},Xa=({onSelectOrg:a})=>{const{scores:c,loadingScores:m,distribution:g,averageScore:h,refetch:x}=Ja(),{refreshEngagementScores:j,isRefreshingScores:d}=fs(),[o,n]=y.useState("all"),p=o==="all"?c:c.filter(t=>t.health_status===o),f=[{name:"Healthy",value:g.healthy,color:Pe.healthy},{name:"At Risk",value:g.at_risk,color:Pe.at_risk},{name:"Critical",value:g.critical,color:Pe.critical},{name:"Dormant",value:g.dormant,color:Pe.dormant}].filter(t=>t.value>0),N=()=>{j(),setTimeout(()=>x(),2e3)};return m?e.jsxs(_,{children:[e.jsx(U,{children:e.jsx(G,{className:"h-6 w-48"})}),e.jsxs(b,{className:"space-y-4",children:[e.jsx(G,{className:"h-40 w-full"}),e.jsx(G,{className:"h-64 w-full"})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsx(_,{className:"col-span-2 md:col-span-1",children:e.jsx(b,{className:"pt-4",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl font-bold",children:h}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Avg Score"})]})})}),Object.entries(g).map(([t,s])=>e.jsx(_,{className:`cursor-pointer transition-all ${o===t?"ring-2 ring-primary":""}`,onClick:()=>n(t===o?"all":t),children:e.jsx(b,{className:"pt-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:s}),e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:t.replace("_"," ")})]}),e.jsx("div",{style:{color:Pe[t]},children:Ya[t]})]})})},t))]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-4",children:[e.jsxs(_,{children:[e.jsx(U,{className:"pb-2",children:e.jsxs(L,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ne,{className:"h-4 w-4"}),"Health Distribution"]})}),e.jsxs(b,{children:[e.jsx("div",{className:"h-[200px]",children:e.jsx(Be,{width:"100%",height:"100%",children:e.jsxs(ps,{children:[e.jsx(gs,{data:f,cx:"50%",cy:"50%",innerRadius:50,outerRadius:80,paddingAngle:2,dataKey:"value",children:f.map((t,s)=>e.jsx(ss,{fill:t.color},`cell-${s}`))}),e.jsx(Ie,{formatter:t=>[`${t} orgs`,""],contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}})]})})}),e.jsx("div",{className:"flex flex-wrap justify-center gap-3 mt-2",children:f.map(t=>e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:t.color}}),e.jsx("span",{children:t.name})]},t.name))})]})]}),e.jsxs(_,{className:"lg:col-span-2",children:[e.jsx(U,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(L,{className:"text-sm font-medium",children:"Organization Scores"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ue,{value:o,onValueChange:n,children:[e.jsx(je,{className:"w-[130px] h-8",children:e.jsx(pe,{})}),e.jsxs(ge,{children:[e.jsx(R,{value:"all",children:"All Status"}),e.jsx(R,{value:"healthy",children:"Healthy"}),e.jsx(R,{value:"at_risk",children:"At Risk"}),e.jsx(R,{value:"critical",children:"Critical"}),e.jsx(R,{value:"dormant",children:"Dormant"})]})]}),e.jsx(O,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:N,disabled:d,children:e.jsx(fe,{className:`h-4 w-4 ${d?"animate-spin":""}`})})]})]})}),e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"max-h-[350px] overflow-auto",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Organization"}),e.jsx(v,{children:"Plan"}),e.jsx(v,{className:"text-center",children:"Score"}),e.jsx(v,{className:"text-center",children:"Status"}),e.jsx(v,{})]})}),e.jsx(de,{children:p.length===0?e.jsx(z,{children:e.jsx(l,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No organizations foun
42d"})}):p.slice(0,20).map(t=>{var s,u;return e.jsxs(z,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>{var M;return a==null?void 0:a(t.org_id,((M=t.organization)==null?void 0:M.name)||"Unknown")},children:[e.jsx(l,{className:"font-medium",children:((s=t.organization)==null?void 0:s.name)||"Unknown"}),e.jsx(l,{children:e.jsx($,{variant:"outline",className:"capitalize text-xs",children:((u=t.organization)==null?void 0:u.plan)||"free"})}),e.jsx(l,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{value:t.score,className:"h-2 w-16"}),e.jsx("span",{className:"text-sm font-medium w-8",children:t.score})]})}),e.jsx(l,{className:"text-center",children:e.jsx($,{variant:"secondary",className:"capitalize text-xs",style:{backgroundColor:`${Pe[t.health_status]}20`,color:Pe[t.health_status]},children:t.health_status.replace("_"," ")})}),e.jsx(l,{children:e.jsx(Ve,{className:"h-4 w-4 text-muted-foreground"})})]},t.id)})})]})})})]})]})]})},Za=({onNavigateTab:a,onAction:c})=>{const[m,g]=y.useState(!1);y.useEffect(()=>{const j=d=>{d.key==="k"&&(d.metaKey||d.ctrlKey)&&(d.preventDefault(),g(o=>!o))};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[]);const h=y.useCallback(j=>{g(!1),c==null||c(j)},[c]),x=y.useCallback(j=>{g(!1),a(j)},[a]);return e.jsxs(pa,{open:m,onOpenChange:g,children:[e.jsx(ga,{placeholder:"Type a command or search..."}),e.jsxs(fa,{children:[e.jsx(Na,{children:"No results found."}),e.jsxs(as,{heading:"Navigation",children:[e.jsxs(xe,{onSelect:()=>
42x("dashboard"),children:[e.jsx(ve,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dashboard"})]}),e.jsxs(xe,{onSelect:()=>x("engagement"),children:[e.jsx(Ls,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Engagement Scores"})]}),e.jsxs(xe,{onSelect:()=>x("users"),children:[e.jsx(Ne,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Users"})]}),e.jsxs(xe,{onSelect:()=>x("billing"),children:[e.jsx(Me,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Billing"})]}),e.jsxs(xe,{onSelect:()=>x("affiliates"),children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Affiliates"})]}),e.jsxs(xe,{onSelect:()=>x("logs"),children:[e.jsx(ne,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Logs"})]})]}),e.jsx(vs,{}),e.jsxs(as,{heading:"Quick Actions",children:[e.jsxs(xe,{onSelect:()=>h("extend_trial"),children:[e.jsx(es,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Extend Trial"})]}),e.jsxs(xe,{onSelect:()=>h("grant_credits"),children:[e.jsx(qs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Grant AI Credits"})]}),e.jsxs(xe,{onSelect:()=>h("add_note"),children:[e.jsx(Ks,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Add Note"})]}),e.jsxs(xe,{onSelect:()=>h("refresh_scores"),children:[e.jsx(fe,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Refresh Engagement Scores"})]})]}),e.jsx(vs,{}),e.jsxs(as,{heading:"Data",children:[e.jsxs(xe,{onSelect:()=>h("export_users"),children:[e.jsx(ds,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Export Users CSV"})]}),e.jsxs(xe,{onSelect:()=>h("export_billing"),children:[e.jsx(ds,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Export Billing CSV"})]})]})]})]})},As=["hsl(var(--primary))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))"],et=()=>{const{data:a,isLoading:c}=Fe({queryKey:["internal-admin-walkthrough-completions"],queryFn:async()=>{const{data:h,error:x}=await k.from("walkthrough_completions").select("*").order("completed_at",{ascending:!1});if(x)throw x;const j=(h||[]).map(n=>n.user_id);if(j.length===0)return[];const{data:d}=await k.from("profiles").select("user_id, email, first_name, last_name").in("user_id",j),o=new Map((d||[]).map(n=>[n.user_id,n]));return(h||[]).map(n=>{var p,f,N;return{...n,email:((p=o.get(n.user_id))==null?void 0:p.email)??null,first_name:((f=o.get(n.user_id))==null?void 0:f.first_name)??null,last_name:((N=o.get(n.user_id))==null?void 0:N.last_name)??null}})}}),m=y.useMemo(()=>{if(!a)return null;const h=a.filter(j=>!j.skipped),x=a.filter(j=>j.skipped);return{total:a.length,completed:h.length,skipped:x.length}},[a]),g=y.useMemo(()=>m?[{name:"Completed",value:m.completed},{name:"Skipped",value:m.skipped}].filter(h=>h.value>0):[],[m]);return c?e.jsx(G,{className:"h-48 w-full"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(ws,{className:"h-4 w-4"}),"Tutorial Completions"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(_,{children:e.jsxs(b,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(ws,{className:"h-3.5 w-3.5"})," Total"]}),e.jsx("p",{className:"text-2xl font-bold",children:(m==null?void 0:m.total)??0})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(js,{className:"h-3.5 w-3.5"})," Completed"]}),e.jsx("p",{className:"text-2xl font-bold",children:(m==null?void 0:m.completed)??0})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(Ea,{className:"h-3.5 w-3.5"})," Skipped"]}),e.jsx("p",{className:"text-2xl font-bold",children:(m==null?void 0:m.skipped)??0})]})})]}),g.length>0&&e.jsxs(_,{children:[e.jsx(U,{className:"pb-2",children:e.jsx(L,{className:"text-sm",children:"Completion vs Skipped"})}),e.jsx(b,{className:"pb-3",children:e.jsx(Be,{width:"100%",height:180,children:e.jsxs(ps,{children:[e.jsx(gs,{data:g,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,dataKey:"value",paddingAngle:2,children:g.map((h,x)=>e.jsx(ss,{fill:As[x%As.length]},x))}),e.jsx(Ie,{}),e.jsx(Is,{wrapperStyle:{fontSize:"11px"}})]})})})]}),a&&a.length>0&&e.jsxs(_,{children:[e.jsx(U,{className:"pb-3",children:e.jsx(L,{className:"text-sm",children:"Individual Tutorial Results"})}),e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"overflow-auto max-h-[300px]",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"User"}),e.jsx(v,{children:"Status"}),e.jsx(v,{children:"Steps"}),e.jsx(v,{children:"Date"})]})}),e.jsx(de,{children:a.map(h=>e.jsxs(z,{children:[e.jsx(l,{className:"text-xs font-medium max-w-[180px] truncate",children:h.email??h.user_id.slice(0,8)}),e.jsx(l,{children:e.jsx($,{variant:h.skipped?"destructive":"default",className:"text-[10px]",children:h.skipped?"Skipped":"Completed"})}),e.jsxs(l,{className:"text-xs",children:[h.steps_completed,"/",h.total_steps]}),e.jsx(l,{className:"text-xs text-muted-foreground",children:X(new Date(h.c
42ompleted_at),"MMM d, yyyy")})]},h.id))})]})})})]}),(!a||a.length===0)&&e.jsx(_,{children:e.jsx(b,{className:"py-8 text-center text-muted-foreground text-sm",children:"No tutorial completions recorded yet"})})]})},Ms=["hsl(var(--primary))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))","#6366f1","#f59e0b","#10b981","#ef4444","#8b5cf6"],Re=a=>(a==null?void 0:a.replace(/-/g," ").replace(/\b\w/g,c=>c.toUpperCase()))??"—";function Te(a){const c={};return a.forEach(m=>{const g=m||"Not specified";c[g]=(c[g]||0)+1}),Object.entries(c).map(([m,g])=>({name:Re(m),value:g})).sort((m,g)=>g.value-m.value)}const st=()=>{const[a,c]=y.useState(""),{data:m,isLoading:g}=Fe({queryKey:["internal-admin-onboarding"],queryFn:async()=>{const{data:d,error:o}=await k.from("onboarding_profiles").select("user_id, role, team_size, industry, work_style, priorities, referral_source, onboarding_completed, onboarding_step, created_at, updated_at").order("created_at",{ascending:!1});if(o)throw o;const n=(d||[]).map(N=>N.user_id),{data:p}=await k.from("profiles").select("user_id, email, first_name, last_name").in("user_id",n),f=new Map((p||[]).map(N=>[N.user_id,N]));return(d||[]).map(N=>{var t,s,u;return{...N,email:((t=f.get(N.user_id))==null?void 0:t.email)??null,first_name:((s=f.get(N.user_id))==null?void 0:s.first_name)??null,last_name:((u=f.get(N.user_id))==null?void 0:u.last_name)??null}})}}),h=y.useMemo(()=>{if(!m)return null;const d=m.filter(p=>p.onboarding_completed),o=m.filter(p=>!p.onboarding_completed),n=d.length>0?d.reduce((p,f)=>p+Ua(new Date(f.updated_at),new Date(f.created_at)),0)/d.length:0;return{total:m.length,completed:d.length,incomplete:o.length,completionRate:m.length>0?Math.round(d.length/m.length*100):0,avgMinutes:Math.round(n)}},[m]),x=y.useMemo(()=>{if(!m)return null;const d=m.filter(n=>n.onboarding_completed),o=d.flatMap(n=>n.priorities||[]);return{roles:Te(d.map(n=>n.role)),teamSizes:Te(d.map(n=>n.team_size)),industries:Te(d.map(n=>n.industry)),workStyles:Te(d.map(n=>n.work_style)),referrals:Te(d.map(n=>n.referral_source)),priorities:Te(o)}},[m]),j=y.useMemo(()=>{if(!m)return[];if(!a)return m;const d=a.toLowerCase();return m.filter(o=>{var n,p,f,N;return((n=o.email)==null?void 0:n.toLowerCase().includes(d))||((p=o.role)==null?void 0:p.toLowerCase().includes(d))||((f=o.industry)==null?void 0:f.toLowerCase().includes(d))||((N=o.referral_source)==null?void 0:N.toLowerCase().includes(d))})},[m,a]);return g?e.jsxs("div",{className:"space-y-4",children:[e.jsx(G,{className:"h-24 w-full"}),e.jsx(G,{className:"h-64 w-full"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(_,{children:e.jsxs(b,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(Ne,{className:"h-3.5 w-3.5"})," Total Signups"]}),e.jsx("p",{className:"text-2xl font-bold",children:(h==null?void 0:h.total)??0})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(js,{className:"h-3.5 w-3.5"})," Completed"]}),e.jsx("p",{className:"text-2xl font-bold",children:(h==null?void 0:h.completed)??0})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(Hs,{className:"h-3.5 w-3.5"})," Completion Rate"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[(h==null?void 0:h.completionRate)??0,"%"]})]})}),e.jsx(_,{children:e.jsxs(b,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(ls,{className:"h-3.5 w-3.5"})," Avg Time"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[(h==null?void 0:h.avgMinutes)??0,e.jsx("span",{className:"text-sm font-normal text-muted-foreground ml-1",children:"min"})]})]})})]}),x&&e.jsxs("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsx(Ke,{title:"Role Distribution",data:x.roles}),e.jsx(Ke,{title:"Team Size",data:x.teamSizes}),e.jsx(Ke,{title:"Industry",data:x.industries}),e.jsx(Ke,{title:"Work Style",data:x.workStyles}),e.jsx(Ke,{title:"Referral Source",data:x.referrals}),e.jsx(at,{title:"Top Priorities",data:x.priorities})]}),e.jsxs(_,{children:[e.jsx(U,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(L,{className:"text-base",children:"Individual Responses"}),e.jsxs(le,{children:[j.length," users"]})]}),e.jsxs("div",{className:"relative w-64",children:[e.jsx($e,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Y,{placeholder:"Search email, role, industry...",value:a,onChange:d=>c(d.target.value),className:"pl-8 h-9"})]})]})}),e.jsx(b,{className:"p-0",children:e.jsx("div",{className:"overflow-auto max-h-[500px]",children:e.jsxs(ie,{children:[e.jsx(ce,{children:e.jsxs(z,{children:[e.jsx(v,{children:"Email"}),e.jsx(v,{children:"Role"}),e.jsx(v,{children:"Team Size"}),e.jsx(v,{children:"Industry"}),e.jsx(v,{children:"Work Style"}),e.jsx(v,{children:"Referral"}),e.jsx(v,{children:"Priorities"}),e.jsx(v,{children:"Status"}),e.jsx(v,{children:"Date"})]})}),e.jsx(de,{children:j.map(d=>e.jsxs(z,{children:[e.jsx(l,{className:"font-medium text-xs max-w-[180px] truncate",children:d.email??"—"}),e.jsx(l,{className:"text-xs",children:Re(d.role??"")}),e.jsx(l,{className:"text-xs",children:d.team_size??"—"}),e.jsx(l,{className:"text-xs",children:Re(d.industry??"")}),e.jsx(l,{className:"text-xs",children:Re(d.work_style??"")}),e.jsx(l,{className:"text-xs",children:Re(d.referral_source??"")}),e.jsx(l,{className:"text-xs max-w-[200px]",children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[(d.priorities||[]).slice(0,3).map(o=>e.jsx($,{variant:"secondary",className:"text-[10px] px-1 py-0",children:Re(o)},o)),(d.priorities||[]).length>3&&e.jsxs($,{variant:"outline",className:"text-[10px] px-1 py-0",children:["+",(d.priorities||[]).length-3]})]})}),e.jsx(l,{children:e.jsx($,{variant:d.onboarding_completed?"default":"destructive",className:"text-[10px]",children:d.onboarding_completed?"Done":`Step ${d.onboarding_step}`})}),e.jsx(l,{className:"text-xs text-muted-foreground",children:X(new Date(d.created_at),"MMM d, yyyy")})]}
42,d.user_id))})]})})})]}),e.jsx(et,{})]})};function Ke({title:a,data:c}){return e.jsxs(_,{children:[e.jsx(U,{className:"pb-2",children:e.jsx(L,{className:"text-sm",children:a})}),e.jsx(b,{className:"pb-3",children:e.jsx(Be,{width:"100%",height:180,children:e.jsxs(ps,{children:[e.jsx(gs,{data:c,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,dataKey:"value",paddingAngle:2,children:c.map((m,g)=>e.jsx(ss,{fill:Ms[g%Ms.length]},g))}),e.jsx(Ie,{}),e.jsx(Is,{wrapperStyle:{fontSize:"11px"}})]})})})]})}function at({title:a,data:c}){return e.jsxs(_,{children:[e.jsx(U,{className:"pb-2",children:e.jsx(L,{className:"text-sm",children:a})}),e.jsx(b,{className:"pb-3",children:e.jsx(Be,{width:"100%",height:180,children:e.jsxs(Os,{data:c.slice(0,6),layout:"vertical",margin:{left:80},children:[e.jsx(os,{type:"number",tick:{fontSize:11}}),e.jsx(ms,{type:"category",dataKey:"name",tick:{fontSize:11},width:75}),e.jsx(Ie,{}),e.jsx(Bs,{dataKey:"value",fill:"hsl(var(--primary))",radius:[0,4,4,0]})]})})})]})}const tt=[{value:"dashboard",label:"Dashboard",icon:ve},{value:"engagement",label:"Engagement",icon:Ls},{value:"behavior",label:"Behavior",icon:ne},{value:"users",label:"Users",icon:Ne},{value:"billing",label:"Billing",icon:Me},{value:"affiliates",label:"Affiliates",icon:$s},{value:"onboarding",label:"Onboarding",icon:Hs},{value:"logs",label:"Logs",icon:ne}],Rt=()=>{const{isInternalAdmin:a,checkingAdmin:c}=qe(),[m,g]=y.useState("dashboard"),[h,x]=y.useState(),[j,d]=y.useState(),[o,n]=y.useState(!1),[p,f]=y.useState(!1),{refreshEngagementScores:N}=fs(),t=oa(),s=(M,Q)=>{x(M),d(Q),t&&n(!0)},u=M=>{M==="refresh_scores"&&N()};return c?e.jsxs("div",{className:"container mx-auto p-4 md:p-6 space-y-4",children:[e.jsx(G,{className:"h-10 w-48"}),e.jsx(G,{className:"h-16 w-full"}),e.jsx(G,{className:"h-[400px] w-full"})]}):a?e.jsxs("div",{className:"container mx-auto p-3 md:p-6 space-y-3 md:space-y-4 max-w-[1800px] pb-20 md:pb-6",children:[e.jsx(Za,{onNavigateTab:g,onAction:u}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 md:gap-3 min-w-0",children:[e.jsx("div",{className:"p-1.5 md:p-2 rounded-lg bg-primary/10 shrink-0",children:e.jsx(Xe,{className:"h-5 w-5 md:h-6 md:w-6 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-lg md:text-2xl font-bold truncate",children:"Internal Admin"}),e.jsx("p",{className:"text-muted-foreground text-xs md:text-sm hidden sm:block",children:"TaskHuddle Business Metrics"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t&&e.jsxs(Ds,{open:p,onOpenChange:f,children:[e.jsx(ma,{asChild:!0,children:e.jsxs(O,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(za,{className:"h-3.5 w-3.5 text-green-500 animate-pulse"}),e.jsx("span",{className:"hidden xs:inline",children:"Live"})]})}),e.jsxs(Ts,{side:"bottom",className:"h-[70vh] p-0",children:[e.jsx(Rs,{className:"sr-only",children:e.jsx(zs,{children:"Live Activity Feed"})}),e.jsx(ks,{})]})]}),e.jsxs($,{variant:"outline",className:"text-xs gap-1 hidden sm:flex",children:[e.jsx(Da,{className:"h-3 w-3"}),e.jsx("span",{children:"⌘K"})]})]})]}),t?e.jsxs(ha,{open:o,onOpenChange:n,children:[e.jsx(ua,{asChild:!0,children:e.jsxs(O,{variant:"outline",className:"w-full justify-between h-auto py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium",children:"Quick Actions"}),j&&e.jsx($,{variant:"secondary",className:"text-xs truncate max-w-[120px]",children:j})]}),e.jsx(Ps,{className:`h-4 w-4 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(ja,{className:"mt-2",children:e.jsx(Ss,{selectedOrgId:h,selectedOrgName:j})})]}):e.jsx(Ss,{selectedOrgId:h,selectedOrgName:j}),e.jsxs("div",{className:"grid lg:grid-cols-4 gap-4",children:[e.jsx("div",{className:"lg:col-span-3",children:e.jsxs(hs,{value:m,onValueChange:g,className:"w-full",children:[e.jsxs(Fs,{className:"w-full whitespace-nowrap",children:[e.jsx(us,{className:"inline-flex w-max md:w-auto md:grid md:grid-cols-8 h-auto p-1",children:tt.map(({value:M,label:Q,icon:B})=>e.jsxs(Ue,{value:M,className:"flex items-center gap-1.5 px-2.5 py-1.5 md:px-3 md:py-2 text-xs md:text-sm",children:[e.jsx(B,{className:"h-3.5 w-3.5 md:h-4 md:w-4"}),e.jsx("span",{children:Q})]},M))}),e.jsx(xa,{orientation:"horizontal",className:"invisible"})]}),e.jsx(oe,{value:"dashboard",className:"mt-3 md:mt-4",children:e.jsx(Fa,{})}),e.jsx(oe,{value:"engagement",className:"mt-3 md:mt-4",children:e.jsx(Xa,{onSelectOrg:s})}),e.jsx(oe,{value:"behavior",className:"mt-3 md:mt-4",children:e.jsx(Va,{onSelectOrg:s})}),e.jsx(oe,{value:"users",className:"mt-3 md:mt-4",children:e.jsx(La,{})}),e.jsx(oe,{value:"billing",className:"mt-3 md:mt-4",children:e.jsx(Oa,{})}),e.jsx(oe,{value:"affiliates",className:"mt-3 md:mt-4",children:e.jsx(Ba,{})}),e.jsx(oe,{value:"onboarding",className:"mt-3 md:mt-4",children:e.jsx(st,{})}),e.jsx(oe,{value:"logs",className:"mt-3 md:mt-4",children:e.jsx(Ia,{})})]})}),!t&&e.jsx("div",{className:"lg:col-span-1 hidden lg:block",children:e.jsx("div",{className:"sticky top-4",children:e.jsx(ks,{})})})]})]}):e.jsx("div",{className:"container mx-auto p-4 md:p-6",children:e.jsx(_,{className:"border-destructive/50 bg-destructive/5",children:e.jsxs(U,{children:[e.jsxs(L,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Xe,{className:"h-5 w-5"}),"Access Denied"]}),e.jsx(le,{children:"You do not have permission to access the internal admin panel. This area is restricted to TaskHuddle team members only."})]})})})};export{Rt 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.