1/* © 2026 PulseCX Technologies Pvt. Ltd. All rights reserved. Unauthorized reproduction or distribution is prohibited. */ 2import{at as Rt,aN as Lt,ap as Ot,aP as u,aF as C,aR as st,aO as he,aJ as e,V as dt,m as kt,a0 as ge,a3 as fe,C as Ct,a4 as je,a1 as ve,a2 as A,j as R,a9 as mt,v as Ft,F as Kt,Q as Bt,aa as At,ac as Dt,ad as I,ab as L,a8 as ut,af as at,A as rt,i as qe,u as it,ag as Ue,W as w,c as nt,k as P,ah as T,ai as z,ae as _,L as pe,b as De,z as ht,h as q,g as O,l as K,J as ze,P as Me,T as Ut,S as qt,f as G,aB as pt,n as Gt,a5 as Wt,E as Vt,aS as h,aC as Ht,aD as Xt,aE as Yt,aV as Jt,b4 as Qt,b0 as Zt,o as ot,aU as p,s as es,q as ts}from"./index-YL4KJj_M.js";import{L as H}from"./label-aY6SUgq_.js";import{s as gt}from"./subMonths-BpPXy5k7.js";import{U as ss}from"./users-B7DPMqc9.js";import{T as as}from"./trending-down-ClHvPoLa.js";import{S as ft}from"./switch-DXREgjM-.js";import{S as lt}from"./shield-check-CVJWXHoW.js";import{U as jt}from"./user-plus-C9QGgx5j.js";import{S as Pe}from"./sparkles-Cm5D2P9g.js";import{B as Be}from"./bell-CXJD5PCg.js";import{P as vt}from"./plus-BpDqJZeG.js";import{Z as ct}from"./zap-mLESb6no.js";import{M as bt}from"./mail-Ca4m3Ri7.js";import{M as rs}from"./message-square-DI7G2PMO.js";import{X as is}from"./x-BAhEismd.js";import{f as ns}from"./formatDistanceToNow-B327wdsx.js";import{T as ls}from"./trash-2-DoVZu1dk.js";import{C as yt}from"./credit-card-DgeJ_USJ.js";const ds=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],os=Rt("copy",ds);const cs=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],zt=Rt("pause",cs);function xs(o,m){const[f,x]=Lt(o,m.start,m.end);return{start:f,end:x}}function ms(o,m){const{start:f,end:x}=xs(m?.in,o);let k=+f>+x;const g=k?+f:+x,N=k?x:f;N.setHours(0,0,0,0),N.setDate(1);let E=1;const X=[];for(;+N<=g;)X.push(Ot(f,N)),N.setMonth(N.getMonth()+E);return k?X.reverse():X}const n={blue:"#3b82f6",purple:"#8b5cf6",orange:"#f97316",green:"#22c55e",red:"#ef4444",yellow:"#eab308",cyan:"#06b6d4",teal:"#14b8a6"},us=["#ef4444","#f97316","#eab308","#22c55e","#3b82f6"],V={positive:"#22c55e",neutral:"#6b7280",negative:"#ef4444"},Nt={google:"#4285F4",facebook:"#1877F2",yelp:"#d32323",tripadvisor:"#00AF87",manual:"#8b5cf6",mouthshut:"#ff6600",justdial:"#ffd700",mouthshut_manual:"#ff8c00",justdial_manual:"#daa520"},S={background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px",fontSize:"12px"};function wt(o){return o>=90?{grade:"A+",color:"#22c55e",bg:"#dcfce7"}:o>=80?{grade:"A",color:"#4ade80",bg:"#f0fdf4"}:o>=70?{grade:"B+",color:"#3b82f6",bg:"#eff6ff"}:o>=60?{grade:"B",color:"#60a5fa",bg:"#eff6ff"}:o>=50?{grade:"C",color:"#eab308",bg:"#fefce8"}:o>=35?{grade:"D",color:"#f97316",bg:"#fff7ed"}:{grade:"F",color:"#ef4444",bg:"#fef2f2"}}function _t(o){return(o.avgRating-1)/4*100*.4+o.responseRate*100*.25+Math.max(0,100-o.avgResponseHours*2)*.15+o.positiveRate*100*.1+o.capaResolutionRate*100*.1}function B({value:o,prefix:m="",suffix:f="",decimals:x=0}){const[k,g]=u.useState(0);return u.useEffect(()=>{let N=0;const E=o;if(E===N){g(E);return}const X=800,Y=performance.now(),te=re=>{const J=re-Y,F=Math.min(J/X,1),ie=1-Math.pow(1-F,3),ne=N+(E-N)*ie;g(ne),F<1&&requestAnimationFrame(te)};requestAnimationFrame(te)},[o]),e.jsxs("span",{children:[m,k.toFixed(x),f]})}function U({label:o,value:m,icon:f,color:x,subtitle:k}){return e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5 shadow-[var(--shadow-soft)] transition-transform hover:scale-[1.02]",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.15em] text-muted-foreground",children:o}),e.jsx("div",{className:"text-muted-foreground/50",children:f})]}),e.jsx("div",{className:"font-display mt-2 text-3xl lg:text-4xl",style:{color:x},children:m}),k&&e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:k})]})}function v({title:o,children:m,className:f="",id:x,headerRight:k}){return e.jsxs("div",{id:x,className:`rounded-2xl border border-border bg-card p-5 shadow-[var(--shadow-soft)] ${f}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide",children:o}),k]}),m]})}function we({title:o,icon:m,children:f}){return e.jsxs("div",{className:"flex items-center justify-between mb-4 mt-8 first:mt-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"grid h-8 w-8 place-items-center rounded-lg bg-primary/10 text-primary",children:m}),e.jsx("h2",{className:"font-display text-xl",children:o})]}),f]})}function hs({value:o,max:m,label:f}){const x=m>0?o/m:0,k=Math.round(239-x*205),g=Math.round(68+x*129),N=Math.round(68);return e.jsx("div",{className:"flex items-center justify-center rounded-md text-[10px] font-semibold h-8 min-w-[2.5rem] transition-colors",style:{background:`rgba(${k},${g},${N},${Math.max(.1,x*.8)})`,color:x>.5?"#fff":"inherit"},title:f,children:o>0?o:"â"})}function ps({orgs:o,subscriptions:m,plans:f}){const[x,k]=u.useState([]),[g,N]=u.useState([]),[E,X]=u.useState([]),[Y,te]=u.useState([]),[re,J]=u.useState(!1),[F,ie]=u.useState("30"),[ne,le]=u.useState("executive"),de=u.useRef(null),M=async()=>{J(!0);const a=st(new Date,Number(F)).toISOString(),[d,l,b,Q]=await Promise.all([h.from("reviews").select("id, rating, status, source, review_created_at, sentiment_label, sentiment_score, sentiment_themes, author_name, body, organization_id, location_id, replies(id, created_at)").gte("review_created_at",a).order("review_created_at",{ascending:!1}).limit(1e4),h.from("capa_tickets").select("id, status, priority, created_at, resolved_at, due_at, sla_breached, organization_id, location_id").gte("created_at",a),h.from("subscription_invoices").select("*, subscription_plans(name)").order("invoice_date",{ascending:!1}),h.from("reputation_snapshots").select("*").gte("snapshot_date",gt(new Date,12).toISOString()).order("snapshot_date",{ascending:!0})]);k(d.data??[]),N(l.data??[]),X(b.data??[]),te(Q.data??[]),J(!1)};u.useEffect(()=>{M()},[F]);const i=u.useMemo(()=>{const a=x.length,d=o.filter(s=>s.onboarding_status==="active"),l=a>0?x.reduce((s,t)=>s+(t.rating??0),0)/a:0,b=x.filter(s=>s.replies?.length>0),Q=a>0?b.length/a:0,oe=b.flatMap(s=>{const t=s.replies?.[0];if(!t)return[];const r=(new Date(t.created_at).getTime()-new Date(s.review_created_at).getTime())/36e5;return r>0?[r]:[]}),_e=oe.length?oe.reduce((s,t)=>s+t,0)/oe.length:0,Se=x.filter(s=>s.sentiment_label==="positive").length,Te=x.filter(s=>s.sentiment_label==="negative").length,Re=x.filter(s=>s.sentiment_label==="neutral").length,Ee=a>0?Se/a:0,ke=g.filter(s=>["resolved","closed"].includes(s.status)).length,Ce=g.length>0?ke/g.length:1,$e=_t({avgRating:l,responseRate:Q,avgResponseHours:_e,positiveRate:Ee,capaResolutionRate:Ce}),Ie=wt($e),Ge=m.filter(s=>s.status==="active").reduce((s,t)=>{const r=f.find(y=>y.id===t.plan_id);if(!r||!r.actual_price)return s;const c=Number(r.actual_price);return r.billing_cycle==="annually"?s+c/12:r.billing_cycle==="quarterly"?s+c/3:s+c},0),We=[1,2,3,4,5].map(s=>({rating:`${s}â `,count:x.filter(t=>t.rating===s).length,fill:us[s-1]})),Z={};x.forEach(s=>{const t=s.source??"unknown";Z[t]||(Z[t]={source:t,count:0,sumRating:0,positive:0,neutral:0,negative:0}),Z[t].count++,Z[t].sumRating+=s.rating??0,s.sentiment_label==="positive"?Z[t].positive++:s.sentiment_label==="neutral"?Z[t].neutral++:s.sentiment_label==="negative"&&Z[t].negative++});const Ve=Object.values(Z).map(s=>({...s,avgRating:s.count>0?parseFloat((s.sumRating/s.count).toFixed(2)):0})).sort((s,t)=>t.count-s.count),j={};o.forEach(s=>
2{j[s.id]={id:s.id,name:s.name,total:0,sumRating:0,replied:0,positive:0,negative:0,neutral:0,capaTotal:0,capaResolved:0}}),x.forEach(s=>{const t=j[s.organization_id];t&&(t.total++,t.sumRating+=s.rating??0,s.replies?.length>0&&t.replied++,s.sentiment_label==="positive"?t.positive++:s.sentiment_label==="negative"?t.negative++:s.sentiment_label==="neutral"&&t.neutral++)}),g.forEach(s=>{const t=j[s.organization_id];t&&(t.capaTotal++,["resolved","closed"].includes(s.status)&&t.capaResolved++)});const ee=Object.values(j).filter(s=>s.total>0).map(s=>({...s,avgRating:s.total>0?parseFloat((s.sumRating/s.total).toFixed(2)):0,responseRate:s.total>0?parseFloat((s.replied/s.total*100).toFixed(1)):0,capaResRate:s.capaTotal>0?parseFloat((s.capaResolved/s.capaTotal*100).toFixed(1)):100,reputationScore:_t({avgRating:s.total>0?s.sumRating/s.total:3,responseRate:s.total>0?s.replied/s.total:0,avgResponseHours:12,positiveRate:s.total>0?s.positive/s.total:0,capaResolutionRate:s.capaTotal>0?s.capaResolved/s.capaTotal:1})})).sort((s,t)=>t.reputationScore-s.reputationScore),ae={},ce={};for(let s=Number(F)-1;s>=0;s--){const t=C(st(new Date,s),"MMM d");ae[t]={date:t,reviews:0,avgRating:0}}x.forEach(s=>{const t=C(he(s.review_created_at),"MMM d");ae[t]&&(ae[t].reviews++,ce[t]||(ce[t]=[]),s.rating&&ce[t].push(s.rating))}),Object.entries(ce).forEach(([s,t])=>{ae[s]&&(ae[s].avgRating=parseFloat((t.reduce((r,c)=>r+c,0)/t.length).toFixed(2)))});const D=Object.values(ae),be={};for(let s=Number(F)-1;s>=0;s--){const t=C(st(new Date,s),"MMM d");be[t]={date:t,positive:0,neutral:0,negative:0}}x.forEach(s=>{const t=C(he(s.review_created_at),"MMM d");be[t]&&s.sentiment_label&&be[t][s.sentiment_label]++});const He=[{status:"Open",count:g.filter(s=>s.status==="open"||s.status==="assigned").length,fill:n.red},{status:"In Progress",count:g.filter(s=>s.status==="in_progress").length,fill:n.orange},{status:"Resolved",count:g.filter(s=>["resolved","closed"].includes(s.status)).length,fill:n.green},{status:"Escalated",count:g.filter(s=>s.status==="escalated").length,fill:n.purple}].filter(s=>s.count>0),Xe=[{priority:"Critical",count:g.filter(s=>s.priority==="critical").length,fill:n.red},{priority:"High",count:g.filter(s=>s.priority==="high").length,fill:n.orange},{priority:"Medium",count:g.filter(s=>s.priority==="medium").length,fill:n.yellow},{priority:"Low",count:g.filter(s=>s.priority==="low").length,fill:n.green}].filter(s=>s.count>0),Le=g.filter(s=>s.sla_breached).length,Ye=g.length>0?Le/g.length*100:0,Oe=[{status:"Active",count:m.filter(s=>s.status==="active").length,fill:n.green},{status:"Grace Period",count:m.filter(s=>s.status==="grace_period").length,fill:n.yellow},{status:"Suspended",count:m.filter(s=>s.status==="suspended").length,fill:n.red},{status:"Cancelled",count:m.filter(s=>s.status==="cancelled").length,fill:n.purple}].filter(s=>s.count>0),Je=f.map(s=>({name:s.name,count:m.filter(t=>t.plan_id===s.id).length})).filter(s=>s.count>0),Qe=[{status:"New",count:x.filter(s=>s.status==="new").length,fill:n.blue},{status:"Replied",count:x.filter(s=>s.status==="replied").length,fill:n.green},{status:"Needs Action",count:x.filter(s=>s.status==="needs_action").length,fill:n.orange},{status:"Archived",count:x.filter(s=>s.status==="archived").length,fill:"#6b7280"},{status:"Escalated",count:x.filter(s=>s.status==="escalated").length,fill:n.red}].filter(s=>s.count>0),xe=[{label:"<1h",min:0,max:1,count:0},{label:"1-4h",min:1,max:4,count:0},{label:"4-12h",min:4,max:12,count:0},{label:"12-24h",min:12,max:24,count:0},{label:"1-3d",min:24,max:72,count:0},{label:">3d",min:72,max:1/0,count:0}];oe.forEach(s=>{const t=xe.find(r=>s>=r.min&&s<r.max);t&&t.count++});const Ae={};x.forEach(s=>{(s.sentiment_themes??[]).forEach(t=>{Ae[t]=(Ae[t]??0)+1})});const Ze=Object.entries(Ae).map(([s,t])=>({theme:s,count:t})).sort((s,t)=>t.count-s.count).slice(0,15),Fe=[{name:"Positive",value:Se,fill:V.positive},{name:"Neutral",value:Re,fill:V.neutral},{name:"Negative",value:Te,fill:V.negative}].filter(s=>s.value>0),me={};ms({start:gt(new Date,11),end:new Date}).forEach(s=>{const t=C(s,"MMM yy");me[t]={month:t,revenue:0}}
2),(E??[]).forEach(s=>{if(!s.invoice_date)return;const t=C(he(s.invoice_date),"MMM yy");me[t]&&(me[t].revenue+=Number(s.amount??0))});const ye={};(E??[]).forEach(s=>{const r=o.find(c=>c.id===s.organization_id)?.name??"Unknown";ye[r]||(ye[r]={name:r,revenue:0}),ye[r].revenue+=Number(s.amount??0)});const Ne=Object.values(ye).sort((s,t)=>t.revenue-s.revenue).slice(0,10);return{total:a,avgRating:l,responseRate:Q,avgResponseHours:_e,positive:Se,negative:Te,neutral:Re,positiveRate:Ee,capaResolutionRate:Ce,score:$e,gradeInfo:Ie,mrr:Ge,activeOrgsCount:d.length,capaTotal:g.length,capaResolved:ke,slaBreach:Le,slaBreachRate:Ye,ratingDist:We,channelData:Ve,orgStats:ee,trendData:D,sentimentTrend:Object.values(be),capaByStatus:He,capaByPriority:Xe,subStatusDist:Oe,planDist:Je,reviewStatusDist:Qe,rtBuckets:xe,themeData:Ze,sentimentDonut:Fe,monthlyRevenue:Object.values(me),revenueByClientData:Ne,replied:b.length}},[x,g,m,f,o,E,F]),$=async a=>{const d=C(new Date,"yyyy-MM-dd");if(a==="csv"){const l=x.map(b=>({date:b.review_created_at?C(he(b.review_created_at),"yyyy-MM-dd HH:mm"):"",author:b.author_name??"",rating:b.rating??"",status:b.status??"",source:b.source??"",sentiment:b.sentiment_label??"",organization_id:b.organization_id??""}));pt(l,`pulsecx-superadmin-report-${d}.csv`)}else a==="excel"?await Ht([{name:"Reviews",data:x.map(l=>({date:l.review_created_at?C(he(l.review_created_at),"yyyy-MM-dd HH:mm"):"",author:l.author_name??"",rating:l.rating??"",status:l.status??"",source:l.source??"",sentiment:l.sentiment_label??""}))},{name:"CAPA Tickets",data:g.map(l=>({status:l.status,priority:l.priority,created:C(he(l.created_at),"yyyy-MM-dd"),resolved:l.resolved_at?C(he(l.resolved_at),"yyyy-MM-dd"):"â",sla_breached:l.sla_breached?"Yes":"No"}))},{name:"Client Stats",data:i.orgStats.map(l=>({client:l.name,reviews:l.total,avgRating:l.avgRating,responseRate:l.responseRate+"%",reputationScore:l.reputationScore.toFixed(1)}))}],`pulsecx-superadmin-report-${d}.xlsx`,de.current):a==="pdf"?Xt():a==="pptx"&&await Yt([{title:"Executive Summary",content:`Total Reviews: ${i.total} | Avg Rating: ${i.avgRating.toFixed(2)} | Response Rate: ${(i.responseRate*100).toFixed(0)}% | MRR: â¹${i.mrr.toLocaleString("en-IN")}`},{title:"Channel Analytics",content:i.channelData.map(l=>`${l.source}: ${l.count} reviews (${l.avgRating}â
)`).join(" | ")},{title:"Client Performance",content:i.orgStats.slice(0,5).map(l=>`${l.name}: ${l.reputationScore.toFixed(0)}/100`).join(" | ")},{title:"CAPA Summary",content:`Total: ${i.capaTotal} | Resolved: ${i.capaResolved} | SLA Breach: ${i.slaBreach} (${i.slaBreachRate.toFixed(1)}%)`}],`pulsecx-superadmin-report-${d}.pptx`)};return re?e.jsx("div",{className:"grid h-96 place-items-center",children:e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(dt,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading reportsâ¦"})]})}):e.jsxs("div",{className:"space-y-6 print:space-y-4",ref:de,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-display text-2xl flex items-center gap-2",children:[e.jsx(kt,{className:"h-6 w-6 text-primary"})," Reports & Analytics"]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Cross-organization platform analytics · Last ",F," days"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 print:hidden",children:[e.jsxs(ge,{value:F,onValueChange:ie,children:[e.jsxs(fe,{className:"h-9 w-36 rounded-full text-xs",children:[e.jsx(Ct,{className:"mr-1.5 h-3.5 w-3.5"}),e.jsx(je,{})]}),e.jsxs(ve,{children:[e.jsx(A,{value:"7",children:"Last 7 days"}),e.jsx(A,{value:"30",children:"Last 30 days"}),e.jsx(A,{value:"90",children:"Last 90 days"}),e.jsx(A,{value:"180",children:"Last 6 months"}),e.jsx(A,{value:"365",children:"Last year"})]})]}),e.jsxs(R,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>$("csv"),children:[e.jsx(mt,{className:"mr-1.5 h-3.5 w-3.5"})," CSV"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>$("excel"),children:[e.jsx(Ft,{className:"mr-1.5 h-3.5 w-3.5"})," Excel"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>$("pdf"),children:[e.jsx(Kt,{className:"mr-1.5 h-3.5 w-3.5"})," PDF"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>
2$("pptx"),children:[e.jsx(Bt,{className:"mr-1.5 h-3.5 w-3.5"})," PPTX"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"rounded-full",onClick:M,children:[e.jsx(dt,{className:"mr-1.5 h-3.5 w-3.5"})," Refresh"]})]})]}),e.jsxs(At,{value:ne,onValueChange:le,className:"print:hidden",children:[e.jsxs(Dt,{className:"h-10 p-1 bg-muted rounded-full inline-flex gap-1 flex-wrap",children:[e.jsx(I,{value:"executive",className:"rounded-full text-xs px-4",children:"Executive"}),e.jsx(I,{value:"financial",className:"rounded-full text-xs px-4",children:"Financial"}),e.jsx(I,{value:"clients",className:"rounded-full text-xs px-4",children:"Clients"}),e.jsx(I,{value:"channels",className:"rounded-full text-xs px-4",children:"Channels"}),e.jsx(I,{value:"capa",className:"rounded-full text-xs px-4",children:"CAPA"}),e.jsx(I,{value:"sentiment",className:"rounded-full text-xs px-4",children:"Sentiment"}),e.jsx(I,{value:"operations",className:"rounded-full text-xs px-4",children:"Operations"})]}),e.jsxs(L,{value:"executive",className:"space-y-6 mt-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 lg:grid-cols-4 xl:grid-cols-7",children:[e.jsxs("div",{className:"col-span-2 lg:col-span-1 rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-soft)] text-center",style:{borderColor:i.gradeInfo.color+"33"},children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-muted-foreground mb-1",children:"Platform Grade"}),e.jsx("div",{className:"font-display text-6xl font-bold leading-none",style:{color:i.gradeInfo.color},children:i.gradeInfo.grade}),e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[i.score.toFixed(1)," / 100"]})]}),e.jsx(U,{label:"Total Reviews",value:e.jsx(B,{value:i.total}),icon:e.jsx(ut,{className:"h-4 w-4"})}),e.jsx(U,{label:"Avg Rating",value:e.jsx(B,{value:i.avgRating,decimals:2,suffix:"â
"}),icon:e.jsx(at,{className:"h-4 w-4"}),color:n.yellow}),e.jsx(U,{label:"Response Rate",value:e.jsx(B,{value:i.responseRate*100,decimals:0,suffix:"%"}),icon:e.jsx(rt,{className:"h-4 w-4"}),color:n.green}),e.jsx(U,{label:"Active Clients",value:e.jsx(B,{value:i.activeOrgsCount}),icon:e.jsx(qe,{className:"h-4 w-4"}),color:n.blue}),e.jsx(U,{label:"MRR",value:e.jsx(B,{value:i.mrr,prefix:"â¹",decimals:0}),icon:e.jsx(it,{className:"h-4 w-4"}),color:n.green,subtitle:"Monthly Recurring Revenue"}),e.jsx(U,{label:"CAPA Tickets",value:e.jsx(B,{value:i.capaTotal}),icon:e.jsx(Ue,{className:"h-4 w-4"}),color:n.red,subtitle:`${i.capaResolved} resolved`})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-3",children:[e.jsx(v,{title:"Review Volume & Rating Trend",className:"lg:col-span-2",children:e.jsx(w,{width:"100%",height:240,children:e.jsxs(nt,{data:i.trendData,margin:{top:5,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"rptGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:n.blue,stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:n.blue,stopOpacity:0})]})}),e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"date",tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))",interval:"preserveStartEnd"}),e.jsx(z,{yAxisId:"left",tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),e.jsx(z,{yAxisId:"right",orientation:"right",tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))",domain:[0,5]}),e.jsx(_,{contentStyle:S}),e.jsx(pe,{wrapperStyle:{fontSize:"11px"}}),e.jsx(De,{yAxisId:"left",type:"monotone",dataKey:"reviews",stroke:n.blue,fill:"url(#rptGrad)",name:"Reviews",strokeWidth:2}),e.jsx(ht,{yAxisId:"right",type:"monotone",dataKey:"avgRating",stroke:n.yellow,name:"Avg Rating",strokeWidth:2,dot:!1})]})})}),e.jsx(v,{title:"Rating Distribution",children:e.jsx(w,{width:"100%",height:240,children:e.jsxs(q,{data:i.ratingDist,margin:{top:5,right:5,left:-25,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"rating",tick:{fontSize:11}}),e.jsx(z,{tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(O,{dataKey:"count",name:"Reviews",radius:[4,4,0,0],children:i.ratingDist.map((a,d)=>e.jsx(K,{fill:a.fill},d))})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsx(v,{title:"Sentiment Overview",children:i.sentimentDonut.length>0?e.jsx(w,{width:"100%",height:200,children:e.jsxs(ze,{children:[e.jsx(Me,{data:i.sentimentDonut,cx:"50%",cy:"50%",innerRadius:55,outerRadius:80,paddingAngle:3,dataKey:"value",children:i.sentimentDonut.map((a,d)=>e.jsx(K,{fill:a.fill},d))}),e.jsx(_,{contentStyle:S}),e.jsx(pe,{wrapperStyle:{fontSize:"11px"}})]})}):e.jsx("div",{className:"flex h-48 items-center justify-center text-sm text-muted-foreground",children:"No sentiment data"})}),e.jsx(v,{title:"Channel Mix",children:e.jsx(w,{width:"100%",height:200,children:e.jsxs(ze,{children:[e.jsx(Me,{data:i.channelData,cx:"50%",cy:"50%",outerRadius:80,paddingAngle:2,dataKey:"count",label:({source:a,percent:d})=>`${a} ${(d*100).toFixed(0)}%`,labelLine:!1,children:i.channelData.map((a,d)=>e.jsx(K,{fill:Nt[a.source]??[n.blue,n.purple,n.orange,n.teal][d%4]},d))}),e.jsx(_,{contentStyle:S})]})})}),e.jsx(v,{title:"Response Rate",children:e.jsxs("div",{className:"flex flex-col items-center justify-center h-48 gap-3",children:[e.jsx(w,{width:"100%",height:140,children:e.jsx(Ut,{cx:"50%",cy:"80%",innerRadius:"60%",outerRadius:"100%",startAngle:180,endAngle:0,data:[{value:i.responseRate*100}],children:e.jsx(qt,{dataKey:"value",cornerRadius:8,fill:i.responseRate>=.7?n.green:i.responseRate>=.4?n.yellow:n.red})})}),e.jsxs("div",{className:"text-center -mt-6",children:[e.jsxs("div",{className:"font-display text-3xl",children:[(i.responseRate*100).toFixed(0),"%"]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[i.replied," of ",i.total," replied"]})]})]})})]})]}),e.jsxs(L,{value:"financial",className:"space-y-6 mt-6",children:[e.jsx(we,{title:"Financial Reports",icon:e.jsx(it,{className:"h-4 w-4"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 lg:grid-cols-4",children:[e.jsx(U,{label:"MRR",value:e.jsx(B,{value:i.mrr,prefix:"â¹",decimals:0}),icon:e.jsx(it,{className:"h-4 w-4"}),color:n.green}),e.jsx(U,{label:"ARR",value:e.jsx(B,{value:i.mrr*12,prefix:"â¹",decimals:0}),icon:e.jsx(at,{className:"h-4 w-4"}),color:n.blue}),e.jsx(U,{label:"Active Subscriptions",value:e.jsx(B,{value:m.filter(a=>a.status==="active").length}),icon:e.jsx(ss,{className:"h-4 w-4"})}),e.jsx(U,{label:"Grace Period",value:e.jsx(B,{value:m.filter(a=>
2a.status==="grace_period").length}),icon:e.jsx(Ue,{className:"h-4 w-4"}),color:n.yellow})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[e.jsx(v,{title:"Monthly Revenue Trend (Last 12 Months)",children:e.jsx(w,{width:"100%",height:260,children:e.jsxs(nt,{data:i.monthlyRevenue,margin:{top:5,right:10,left:-10,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"revGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:n.green,stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:n.green,stopOpacity:0})]})}),e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"month",tick:{fontSize:10}}),e.jsx(z,{tick:{fontSize:10},tickFormatter:a=>`â¹${(a/1e3).toFixed(0)}k`}),e.jsx(_,{contentStyle:S,formatter:a=>[`â¹${a.toLocaleString("en-IN")}`,"Revenue"]}),e.jsx(De,{type:"monotone",dataKey:"revenue",stroke:n.green,fill:"url(#revGrad)",strokeWidth:2})]})})}),e.jsx(v,{title:"Revenue by Client (Top 10)",children:i.revenueByClientData.length>0?e.jsx(w,{width:"100%",height:260,children:e.jsxs(q,{data:i.revenueByClientData,layout:"vertical",margin:{top:0,right:20,left:10,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",horizontal:!1}),e.jsx(T,{type:"number",tick:{fontSize:10},tickFormatter:a=>`â¹${(a/1e3).toFixed(0)}k`}),e.jsx(z,{dataKey:"name",type:"category",tick:{fontSize:10},width:120}),e.jsx(_,{contentStyle:S,formatter:a=>[`â¹${a.toLocaleString("en-IN")}`,"Revenue"]}),e.jsx(O,{dataKey:"revenue",name:"Revenue",radius:[0,4,4,0],fill:n.blue})]})}):e.jsx("div",{className:"flex h-64 items-center justify-center text-sm text-muted-foreground",children:"No invoice data"})})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[e.jsx(v,{title:"Subscription Status",children:e.jsx(w,{width:"100%",height:220,children:e.jsxs(ze,{children:[e.jsx(Me,{data:i.subStatusDist,cx:"50%",cy:"50%",innerRadius:55,outerRadius:80,paddingAngle:3,dataKey:"count",children:i.subStatusDist.map((a,d)=>e.jsx(K,{fill:a.fill},d))}),e.jsx(_,{contentStyle:S}),e.jsx(pe,{wrapperStyle:{fontSize:"11px"}})]})})}),e.jsx(v,{title:"Plan Distribution",children:e.jsx(w,{width:"100%",height:220,children:e.jsxs(q,{data:i.planDist,margin:{top:5,right:5,left:-25,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"name",tick:{fontSize:10}}),e.jsx(z,{tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(O,{dataKey:"count",name:"Clients",radius:[4,4,0,0],children:i.planDist.map((a,d)=>e.jsx(K,{fill:[n.blue,n.purple,n.orange,n.green,n.cyan][d%5]},d))})]})})})]}),E.length>0&&e.jsx(v,{title:"Recent Invoices",headerRight:e.jsxs(R,{size:"sm",variant:"ghost",className:"rounded-full text-xs h-7",onClick:()=>{pt(E.map(a=>({date:a.invoice_date,org_id:a.organization_id,plan:a.subscription_plans?.name??"",amount:a.amount,status:a.status,type:a.invoice_type})),`pulsecx-invoices-${C(new Date,"yyyy-MM-dd")}.csv`)},children:[e.jsx(mt,{className:"mr-1 h-3 w-3"})," Export"]}),children:e.jsx("div",{className:"overflow-x-auto max-h-72",children:e.jsxs("table",{className:"w-full text-left text-sm border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-muted-foreground text-[10px] uppercase tracking-wider font-semibold sticky top-0 bg-card",children:[e.jsx("th",{className:"py-2.5 px-3",children:"Date"}),e.jsx("th",{className:"py-2.5 px-3",children:"Client"}),e.jsx("th",{className:"py-2.5 px-3",children:"Plan"}),e.jsx("th",{className:"py-2.5 px-3 text-right",children:"Amount"}),e.jsx("th",{className:"py-2.5 px-3",children:"Status"})]})}),e.jsx("tbody",{children:E.slice(0,20).map(a=>{const d=o.find(l=>l.id===a.organization_id);return e.jsxs("tr",{className:"border-b border-border/40 hover:bg-muted/10 transition-colors",children:[e.jsx("td",{className:"py-2.5 px-3 text-xs font-mono text-muted-foreground",children:a.invoice_date}),e.jsx("td",{className:"py-2.5 px-3 text-xs font-medium",children:d?.name??"â"}),e.jsx("td",{className:"py-2.5 px-3 text-xs",children:a.subscription_plans?.name??a.invoice_type}),e.jsxs("td",{className:"py-2.5 px-3 text-xs text-right font-mono font-semibold",children:["â¹",Number(a.amount??0).toLocaleStr
2ing("en-IN")]}),e.jsx("td",{className:"py-2.5 px-3",children:e.jsx(G,{variant:"outline",className:`rounded-full text-[9px] ${a.status==="paid"?"text-[#22c55e] border-[#22c55e]/30 bg-[#22c55e]/10":"text-muted-foreground"}`,children:a.status})})]},a.id)})})]})})})]}),e.jsxs(L,{value:"clients",className:"space-y-6 mt-6",children:[e.jsx(we,{title:"Client Performance",icon:e.jsx(qe,{className:"h-4 w-4"})}),e.jsx(v,{title:"Client Reputation Leaderboard",children:i.orgStats.length>0?e.jsx("div",{className:"space-y-2 max-h-[400px] overflow-y-auto pr-1",children:i.orgStats.map((a,d)=>{const l=wt(a.reputationScore);return e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border/50 bg-muted/20 p-3 hover:bg-muted/40 transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-center h-8 w-8 rounded-lg bg-muted text-xs font-bold text-muted-foreground",children:["#",d+1]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-semibold truncate",children:a.name}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[a.total," reviews"]}),e.jsxs("span",{children:[a.avgRating,"â
"]}),e.jsxs("span",{children:[a.responseRate,"% replied"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-24 h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${a.reputationScore}%`,background:l.color}})}),e.jsx("div",{className:"text-sm font-bold min-w-[2rem] text-right",style:{color:l.color},children:l.grade}),e.jsx("div",{className:"text-[10px] text-muted-foreground w-8 text-right",children:a.reputationScore.toFixed(0)})]})]},a.id)})}):e.jsx("div",{className:"flex h-48 items-center justify-center text-sm text-muted-foreground",children:"No client data"})}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[e.jsx(v,{title:"Avg Rating by Client",children:e.jsx(w,{width:"100%",height:Math.max(200,i.orgStats.length*30),children:e.jsxs(q,{data:i.orgStats.slice(0,12),layout:"vertical",margin:{top:0,right:20,left:10,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",horizontal:!1}),e.jsx(T,{type:"number",domain:[0,5],tick:{fontSize:10}}),e.jsx(z,{dataKey:"name",type:"category",tick:{fontSize:10},width:120}),e.jsx(_,{contentStyle:S}),e.jsx(O,{dataKey:"avgRating",name:"Avg Rating",radius:[0,4,4,0],children:i.orgStats.slice(0,12).map((a,d)=>e.jsx(K,{fill:a.avgRating>=4?n.green:a.avgRating>=3?n.yellow:n.red},d))})]})})}),e.jsx(v,{title:"Response Rate by Client",children:e.jsx(w,{width:"100%",height:Math.max(200,i.orgStats.length*30),children:e.jsxs(q,{data:i.orgStats.slice(0,12),layout:"vertical",margin:{top:0,right:20,left:10,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",horizontal:!1}),e.jsx(T,{type:"number",domain:[0,100],tick:{fontSize:10},tickFormatter:a=>`${a}%`}),e.jsx(z,{dataKey:"name",type:"category",tick:{fontSize:10},width:120}),e.jsx(_,{contentStyle:S,formatter:a=>[`${a}%`,"Response Rate"]}),e.jsx(O,{dataKey:"responseRate",name:"Response Rate",radius:[0,4,4,0],children:i.orgStats.slice(0,12).map((a,d)=>e.jsx(K,{fill:a.responseRate>=70?n.green:a.responseRate>=40?n.yellow:n.red},d))})]})})})]}),e.jsx(v,{title:"Review Volume by Client",children:e.jsx(w,{width:"100%",height:260,children:e.jsxs(q,{data:i.orgStats.slice(0,10),margin:{top:5,right:5,left:-20,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"name",tick:{fontSize:9},angle:-20,textAnchor:"end",height:50}),e.jsx(z,{tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(O,{dataKey:"total",name:"Reviews",radius:[4,4,0,0],fill:n.blue})]})})})]}),e.jsxs(L,{value:"channels",className:"space-y-6 mt-6",children:[e.jsx(we,{title:"Channel Analytics",icon:e.jsx(Gt,{className:"h-4 w-4"})}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[e.jsx(v,{title:"Reviews by Channel",children:e.jsx(w,{width:"100%",height:260,children:e.jsxs(q,{data:i.channelData,margin:{top:5,right:5,left:-20,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"source",tick:{fontSize:10}}),e.jsx(z,{tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(O,{dataKey:"count",name:"Reviews",radius:[4,4,0,0],children:i.channelData.map((a,d)=>e.jsx(K,{fill:Nt[a.source]??n.blue},d))})]})})}),e.jsx(v,{title:"Avg Rating by Channel",children:e.jsx(w,{width:"100%",height:260,children:e.jsxs(q,{data:i.channelData,margin:{top:5,right:5,left:-20,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"source",tick:{fontSize:10}}),e.jsx(z,{domain:[0,5],tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(O,{dataKey:"avgRating",name:"Avg Rating",radius:[4,4,0,0],children:i.channelData.map((a,d)=>e.jsx(K,{fill:a.avgRating>=4?n.green:a.avgRating>=3?n.yellow:n.red},d))})]})})})]}),e.jsx(v,{title:"Sentiment by Channel",children:e.jsx(w,{width:"100%",height:260,children:e.jsxs(q,{data:i.channelData,margin:{top:5,right:10,left:-20,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"source",tick:{fontSize:10}}),e.jsx(z,{tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(pe,{wrapperStyle:{fontSize:"11px"}}),e.jsx(O,{dataKey:"positive",name:"Positive",stackId:"s",fill:V.positive}),e.jsx(O,{dataKey:"neutral",name:"Neutral",stackId:"s",fill:V.neutral}),e.jsx(O,{dataKey:"negative",name:"Negative",stackId:"s",fill:V.negative,radius:[4,4,0,0]})]})})})]}),e.jsxs(L,{value:"capa",className:"space-y-6 mt-6",children:[e.jsx(we,{title:"CAPA & Quality",icon:e.jsx(Wt,{className:"h-4 w-4"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 lg:grid-cols-4",children:[e.jsx(U,{label:"Total CAPA",value:e.jsx(B,{value:i.capaTotal}),icon:e.jsx(Ue,{className:"h-4 w-4"})}),e.jsx(U,{label:"Resolved",value:e.jsx(B,{value:i.capaResolved}),icon:e.jsx(at,{className:"h-4 w-4"}),color:n.green}),e.jsx(U,{label:"SLA Breached",value:e.jsx(B,{value:i.slaBreach}),icon:e.jsx(as,{className:"h-4 w-4"}),color:n.red,subtitle:`${i.slaBreachRate.toFixed(1)}% breach rate`}),e.jsx(U,{label:"Resolution Rate",value:e.jsx(B,{value:i.capaResolutionRate*100,decimals:0,suffix:"%"}),icon:e.jsx(rt,{className:"h-4 w-4"}),color:i.capaResolutionRate>=.8?n.green:n.yellow})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[e.jsx(v,{title:"CAPA by Status",children:i.capaByStatus.length>0?e.jsx(w,{width:"100%",height:220,children:e.jsxs(ze,{children:[e.jsx(Me,{data:i.capaByStatus,cx:"50%",cy:"50%",innerRadius:55,outerRadius:80,paddingAngle:3,dataKey:"count",children:i.capaByStatus.map((a,d)=>e.jsx(K,{fill:a.fill},d))}),e.jsx(_,{contentStyle:S}),e.jsx(pe,{wrapperStyle:{fontSize:"11px"}})]})}):e.jsx("div",{className:"flex h-56 items-center justify-center text-sm text-muted-foreground",children:"No CAPA data"})}),e.jsx(v,{title:"CAPA by Priority",children:i.capaByPriority.length>0?e.jsx(w,{width:"100%",height:220,children:e.jsxs(q,{data:i.capaByPriority,margin:{top:5,right:5,left:-25,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"priority",tick:{fontSize:11}}),e.jsx(z,{tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(O,{dataKey:"count",name:"Tickets",radius:[4,4,0,0],children:i.capaByPriority.map((a,d)=>e.jsx(K,{fill:a.fill},d))})]})}):e.jsx("div",{className:"flex h-56 items-center justify-center text-sm text-muted-foreground",children:"No CAPA data"})})]}),e.jsx(v,{title:"CAPA Resolution Rate by Client",children:i.orgStats.filter(a=>a.capaTotal>0).length>0?e.jsx(w,{width:"100%",height:260,children:e.jsxs(q,{data:i.orgStats.filter(a=>a.capaTotal>
20),layout:"vertical",margin:{top:0,right:20,left:10,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",horizontal:!1}),e.jsx(T,{type:"number",domain:[0,100],tick:{fontSize:10},tickFormatter:a=>`${a}%`}),e.jsx(z,{dataKey:"name",type:"category",tick:{fontSize:10},width:120}),e.jsx(_,{contentStyle:S,formatter:a=>[`${a}%`,"Resolution Rate"]}),e.jsx(O,{dataKey:"capaResRate",name:"Resolution Rate",radius:[0,4,4,0],children:i.orgStats.filter(a=>a.capaTotal>0).map((a,d)=>e.jsx(K,{fill:a.capaResRate>=80?n.green:a.capaResRate>=50?n.yellow:n.red},d))})]})}):e.jsx("div",{className:"flex h-48 items-center justify-center text-sm text-muted-foreground",children:"No CAPA data"})})]}),e.jsxs(L,{value:"sentiment",className:"space-y-6 mt-6",children:[e.jsx(we,{title:"Sentiment & Rating Analysis",icon:e.jsx(ut,{className:"h-4 w-4"})}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[e.jsx(v,{title:"Sentiment Trend",children:e.jsx(w,{width:"100%",height:260,children:e.jsxs(nt,{data:i.sentimentTrend,margin:{top:5,right:10,left:-20,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"date",tick:{fontSize:10},interval:"preserveStartEnd"}),e.jsx(z,{tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(pe,{wrapperStyle:{fontSize:"11px"}}),e.jsx(De,{type:"monotone",dataKey:"positive",stroke:V.positive,fill:V.positive,fillOpacity:.2,stackId:"1"}),e.jsx(De,{type:"monotone",dataKey:"neutral",stroke:V.neutral,fill:V.neutral,fillOpacity:.2,stackId:"1"}),e.jsx(De,{type:"monotone",dataKey:"negative",stroke:V.negative,fill:V.negative,fillOpacity:.2,stackId:"1"})]})})}),e.jsx(v,{title:"Top Themes / Keywords",children:i.themeData.length>0?e.jsx(w,{width:"100%",height:260,children:e.jsxs(q,{data:i.themeData,layout:"vertical",margin:{top:0,right:20,left:10,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",horizontal:!1}),e.jsx(T,{type:"number",tick:{fontSize:10}}),e.jsx(z,{dataKey:"theme",type:"category",tick:{fontSize:9},width:100}),e.jsx(_,{contentStyle:S}),e.jsx(O,{dataKey:"count",name:"Mentions",radius:[0,4,4,0],fill:n.purple})]})}):e.jsx("div",{className:"flex h-64 items-center justify-center text-sm text-muted-foreground",children:"No theme data â run AI analysis on reviews"})})]}),e.jsx(v,{title:"Rating Heatmap â Client à Star Rating",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("div",{className:"grid gap-2",style:{gridTemplateColumns:"160px repeat(5, minmax(2.5rem, 1fr))"},children:[e.jsx("div",{className:"text-[10px] text-muted-foreground font-semibold uppercase",children:"Client"}),[1,2,3,4,5].map(a=>e.jsxs("div",{className:"text-center text-[10px] font-semibold",children:[a,"â
"]},a)),i.orgStats.slice(0,15).map(a=>{const d=Math.max(x.filter(l=>l.organization_id===a.id&&l.rating===1).length,x.filter(l=>l.organization_id===a.id&&l.rating===2).length,x.filter(l=>l.organization_id===a.id&&l.rating===3).length,x.filter(l=>l.organization_id===a.id&&l.rating===4).length,x.filter(l=>l.organization_id===a.id&&l.rating===5).length,1);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs truncate flex items-center",children:a.name},`label-${a.id}`),[1,2,3,4,5].map(l=>{const b=x.filter(Q=>Q.organization_id===a.id&&Q.rating===l).length;return e.jsx(hs,{value:b,max:d},`${a.id}-${l}`)})]})})]})})}),e.jsx(v,{title:"Negative Review Hotspots",children:e.jsx("div",{className:"overflow-x-auto max-h-72",children:e.jsxs("table",{className:"w-full text-left text-sm border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-muted-foreground text-[10px] uppercase tracking-wider font-semibold sticky top-0 bg-card",children:[e.jsx("th",{className:"py-2.5 px-3",children:"Client"}),e.jsx("th",{className:"py-2.5 px-3 text-center",children:"Negative"}),e.jsx("th",{className:"py-2.5 px-3 text-center",children:"Total"}),e.jsx("th",{className:"py-2.5 px-3 text-center",children:"Negative %"}),e.jsx("th",{className:"py-2.5 px-3",children:"Severity"})]})}),e.jsx("tbody",{children:i.orgStats.filter(a=>a.negative>0).sort((a,d)=>(d.total>0?d.negative/d.total:0)-(a.total>0?a.negative/a.total:0)).slice(0,10).map(a=>{const d=a.total>0?(a.negative/a.total*100).toFixed(1):"0",l=Number(d)>=40?"Critical":Number(d)>=25?"High":Number(d)>=10?"Medium":"Low",b=l==="Critical"?n.red:l==="High"?n.orange:l==="Medium"?n.yellow:n.green;return e.jsxs("tr",{className:"border-b border-border/40 hover:bg-muted/10 transition-colors",children:[e.jsx("td",{className:"py-2.5 px-3 text-xs font-medium",children:a.name}),e.jsx("td",{className:"py-2.5 px-3 text-xs text-center font-mono",style:{color:n.red},children:a.negative}),e.jsx("td",{className:"py-2.5 px-3 text-xs text-center font-mono",children:a.total}),e.jsxs("td",{className:"py-2.5 px-3 text-xs text-center font-mono font-semibold",children:[d,"%"]}),e.jsx("td",{className:"py-2.5 px-3",children:e.jsx(G,{variant:"outline",className:"rounded-full text-[9px]",style:{color:b,borderColor:b+"30",background:b+"10"},children:l})})]},a.id)})})]})})})]}),e.jsxs(L,{value:"operations",className:"space-y-6 mt-6",children:[e.jsx(we,{title:"Operational Reports",icon:e.jsx(rt,{className:"h-4 w-4"})}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[e.jsx(v,{title:"Review Status Distribution",children:i.reviewStatusDist.length>0?e.jsx(w,{width:"100%",height:220,children:e.jsxs(ze,{children:[e.jsx(Me,{data:i.reviewStatusDist,cx:"50%",cy:"50%",innerRadius:55,outerRadius:80,paddingAngle:3,dataKey:"count",children:i.reviewStatusDist.map((a,d)=>e.jsx(K,{fill:a.fill},d))}),e.jsx(_,{contentStyle:S}),e.jsx(pe,{wrapperStyle:{fontSize:"11px"}})]})}):e.jsx("div",{className:"flex h-56 items-center justify-center text-sm text-muted-foreground",children:"No data"})}),e.jsx(v,{title:"Response Time Distribution",children:e.jsx(w,{width:"100%",height:220,children:e.jsxs(q,{data:i.rtBuckets,margin:{top:5,right:5,left:-25,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"label",tick:{fontSize:10}}),e.jsx(z,{tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(O,{dataKey:"count",name:"Replies",radius:[4,4,0,0],children:i.rtBuckets.map((a,d)=>e.jsx(K,{fill:[n.green,n.teal,n.blue,n.yellow,n.orange,n.red][d]},d))})]})})})]}),e.jsx(v,{title:"Daily Review Velocity",children:e.jsx(w,{width:"100%",height:240,children:e.jsxs(Vt,{data:i.trendData,margin:{top:5,right:10,left:-20,bottom:0},children:[e.jsx(P,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(T,{dataKey:"date",tick:{fontSize:10},interval:"preserveStartEnd"}),e.jsx(z,{tick:{fontSize:10}}),e.jsx(_,{contentStyle:S}),e.jsx(ht,{type:"monotone",dataKey:"reviews",stroke:n.blue,strokeWidth:2,dot:{r:2},name:"Reviews / Day"})]})})})]})]})]})}function Ts(){const{user:o}=Jt(),m=Qt({from:"/app/admin"}),f=Zt({from:"/app/admin"}),x=m.tab??"workspaces",[k,g]=u.useState(!1),[N,E]=u.useState([]),[X,Y]=u.useState([]),[te,re]=u.useState([]),[J,F]=u.useState([]),[ie,ne]=u.useState([]),[le,de]=u.useState([]),[M,i]=u.useState([]),[$,a]=u.useState([]),[d,l]=u.useState(""),[b,Q]=u.useState({email:!0,telegram:!1,in_app:!0,whatsapp:!1}),[oe,_e]=u.useState(!1),[Se,Te]=u.useState(!0),[Re,Ee]=u.useState("7"),[ke,Ce]=u.useState(!1),[$e,Ie]=u.useState(null),[Ge,We]=u.useState({}),[Z,Ve]=u.useState([]),[j,ee]=u.useState({code:"",organization_id:"",discount_type:"percentage",discount_value:"",max_uses:"1",valid_until:"",applies_to:"all",notes:""}),[ae,ce]=u.useState(!1);u.useEffect(()=>{(async()=>
2{if(!o)return;const{data:r}=await h.from("profiles").select("is_super_admin, phone, notification_prefs").eq("id",o.id).single();g(r?.is_super_admin??!1),r?.is_super_admin&&(D(),l(r.phone??""),Q(r.notification_prefs??{email:!0,telegram:!1,in_app:!0,whatsapp:!1})),Te(!1)})()},[o?.id]);const D=async()=>{const[t,r,c,y,W,se,Ke,Mt,Pt,Tt]=await Promise.all([h.from("organizations").select("*, organization_members(count)").order("created_at",{ascending:!1}),h.from("invite_codes").select("*, profiles(email)").order("created_at",{ascending:!1}).limit(50),h.from("profiles").select("*").order("created_at",{ascending:!1}).limit(100),h.from("organization_members").select("*, organizations(id, name)"),h.from("client_subscriptions").select("*, subscription_plans(*)"),h.from("subscription_plans").select("*").order("actual_price",{ascending:!0}),h.from("contact_requests").select("*").order("created_at",{ascending:!1}),h.from("org_settings").select("*"),h.from("notifications").select("*").eq("type","system").order("created_at",{ascending:!1}).limit(100),h.from("signup_events").select("*").order("created_at",{ascending:!1}).limit(200)]);console.log("[Superadmin loadData] Orgs:",t.error,"Invites:",r.error,"Profiles:",c.error,"Members:",y.error),c.error&&p.error("Profiles query failed: "+c.error.message);const Et=(c.data??[]).map(ue=>{const et=(y.data??[]).filter(tt=>tt.user_id===ue.id);return{...ue,organization_members:et}}),$t=(t.data??[]).map(ue=>{const et=(Mt.data??[]).find(tt=>tt.organization_id===ue.id);return{...ue,org_settings:et}});E($t),Y(r.data??[]),re(Et),F(W.data??[]),ne(se.data??[]),de(Ke.data??[]),i(Pt.data??[]),a(Tt?.data??[]);const{data:It}=await h.from("discount_coupons").select("*, organizations(name)").order("created_at",{ascending:!1});Ve(It??[]);try{const{data:ue}=await h.functions.invoke("send-test-notification",{body:{organization_id:"platform-check",_probe:!0}});We(ue?.platform_keys??{})}catch{}};u.useEffect(()=>{if(!o||!k)return;const t=h.channel("superadmin_alerts").on("postgres_changes",{event:"*",schema:"public",table:"notifications",filter:`user_id=eq.${o.id}`},()=>{D()}).subscribe();return()=>{h.removeChannel(t)}},[o,k]);const be=async t=>{const{error:r}=await h.from("notifications").update({read:!0}).eq("id",t);r?p.error(r.message):D()},He=async t=>{const{error:r}=await h.from("notifications").delete().eq("id",t);r?p.error(r.message):(p.success("Alert deleted"),D())},Xe=async()=>{if(!o)return;const{error:t}=await h.from("notifications").update({read:!0}).eq("user_id",o.id).eq("type","system").eq("read",!1);t?p.error(t.message):(p.success("All alerts marked as read"),D())},Le=async()=>{if(!o)return;const{error:t}=await h.from("notifications").delete().eq("user_id",o.id).eq("type","system");t?p.error(t.message):(p.success("All alerts cleared"),D())},Ye=async()=>{if(!o)return;_e(!0);const{error:t}=await h.from("profiles").update({phone:d.trim(),notification_prefs:b}).eq("id",o.id);t?p.error(t.message):p.success("Superadmin alert preferences saved!"),_e(!1)},Oe=async(t,r)=>{const{error:c}=await h.from("org_settings").upsert({organization_id:t,twilio_whatsapp_from:r.trim()},{onConflict:"organization_id"});c?p.error(c.message):(p.success("Organization WhatsApp alert number updated!"),D())},Je=async()=>{if(!o)return;Ce(!0);const t=new Date(Date.now()+Number(Re)*864e5).toISOString(),{data:r,error:c}=await h.from("invite_codes").insert({created_by:o.id,expires_at:t}).select("code").single();c?p.error(c.message):(p.success(`Invite code generated: ${r.code}`),D()),Ce(!1)},Qe=async(t,r)=>{const c=`${window.location.origin}/login?invite=${t}`;await navigator.clipboard.writeText(c),Ie(r),setTimeout(()=>Ie(null),2e3),p.success("Invite link copied!")},xe=async(t,r)=>{const{error:c}=await h.from("organizations").update({onboarding_status:r}).eq("id",t);if(c){p.error(c.message);return}p.success(`Org ${r}`),D()},Ae=async(t,r)=>{const{error:c}=await h.from("contact_requests").update({status:r}).eq("id",t);if(c){p.error(c.message);return}p.success(`Lead status updated to ${r}`),D()},Ze=async t=>{const{error:r}=await h.from("contact_requests").delete().eq("id",t);if(r){p.error(r.message);return}p.success("Lead deleted"),D()},Fe=async(t,r,c,y,W)=>{const se=new Date;se.setMonth(se.getMonth()+W);const{error:Ke}=await h.from("client_subscriptions").upsert({organization_id:t,plan_id:r,status:c,current_period_start:new Date().toISOString(),current_period_end:se.toISOString(),grace_peri
2od_days:y,grace_period_end:c==="grace_period"?new Date(Date.now()+y*864e5).toISOString():null},{onConflict:"organization_id"});Ke?p.error(Ke.message):(p.success("Subscription parameters updated successfully!"),D())},me=async(t,r,c)=>{try{const{data:y,error:W}=await h.functions.invoke("billing-reminder-cron",{body:{event:"payment_success",organization_id:t,plan_id:r,period_months:c}});if(W)throw W;y?.success&&(p.success("Simulated Stripe Payment Succeeded!",{description:`Organization reactivated. Next renewal: ${C(new Date(y.subscription.current_period_end),"MMM d, yyyy")}`}),D())}catch(y){p.error("Simulation failed",{description:y.message})}};if(Se)return e.jsx("div",{className:"grid h-screen place-items-center",children:e.jsx("div",{className:"animate-pulse text-muted-foreground",children:"Loadingâ¦"})});const xt=async()=>{if(!j.code||!j.organization_id||!j.discount_value){p.error("Code, organization, and discount value are required");return}ce(!0);const{error:t}=await h.from("discount_coupons").insert({code:j.code.toUpperCase().replace(/\s/g,""),organization_id:j.organization_id,discount_type:j.discount_type,discount_value:Number(j.discount_value),max_uses:Number(j.max_uses)||1,valid_until:j.valid_until||null,applies_to:j.applies_to,notes:j.notes||null,created_by:o?.id});t?p.error("Failed: "+t.message):(p.success(`Coupon ${j.code.toUpperCase()} created`),ee({code:"",organization_id:"",discount_type:"percentage",discount_value:"",max_uses:"1",valid_until:"",applies_to:"all",notes:""}),D()),ce(!1)},ye=async(t,r)=>{const{error:c}=await h.from("discount_coupons").update({is_active:!r}).eq("id",t);c?p.error(c.message):(p.success(r?"Coupon deactivated":"Coupon activated"),D())};if(!k)return e.jsx("div",{className:"grid h-[calc(100vh-4rem)] place-items-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(lt,{className:"mx-auto h-12 w-12 text-muted-foreground/30 mb-4"}),e.jsx("h2",{className:"font-display text-2xl",children:"Access Denied"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Super admin access required."})]})});const Ne=N.filter(t=>t.onboarding_status==="pending"),s=N.filter(t=>t.onboarding_status==="active");return e.jsxs("div",{className:"mx-auto w-full max-w-7xl p-6 md:p-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"font-display text-4xl flex items-center gap-3",children:[e.jsx(lt,{className:"h-8 w-8 text-primary"}),"Super Admin"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"PulseCX platform & billing management"})]}),e.jsxs(R,{variant:"outline",className:"rounded-full",onClick:D,children:[e.jsx(dt,{className:"mr-1.5 h-3.5 w-3.5"})," Refresh"]})]}),e.jsxs(At,{value:x,onValueChange:t=>f({search:r=>({...r,tab:t})}),className:"w-full",children:[e.jsxs(Dt,{className:"flex w-full h-11 p-1 bg-muted rounded-full mb-8 overflow-x-auto",children:[e.jsx(I,{value:"workspaces",className:"rounded-full text-xs",children:"Workspaces & Billing"}),e.jsxs(I,{value:"signups",className:"rounded-full text-xs",children:[e.jsx(jt,{className:"mr-1 h-3 w-3"}),"Trial Signups"]}),e.jsx(I,{value:"users",className:"rounded-full text-xs",children:"User Accounts"}),e.jsx(I,{value:"invites",className:"rounded-full text-xs",children:"Invite Codes"}),e.jsxs(I,{value:"coupons",className:"rounded-full text-xs",children:[e.jsx(Pe,{className:"mr-1 h-3 w-3"}),"Coupons"]}),e.jsx(I,{value:"services",className:"rounded-full text-xs",children:"Services"}),e.jsx(I,{value:"leads",className:"rounded-full text-xs",children:"Leads"}),e.jsxs(I,{value:"reports",className:"rounded-full text-xs",children:[e.jsx(kt,{className:"mr-1 h-3 w-3"}),"Reports"]}),e.jsxs(I,{value:"alerts",className:"rounded-full text-xs",children:[e.jsx(Be,{className:"mr-1 h-3 w-3"}),"Alerts"]})]}),e.jsxs(L,{value:"workspaces",className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl text-[#22c55e]",children:s.length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"Active workspaces"})]}),e.jsxs("div",{className:"rounded-2xl border border-[var(--warning)]/30 bg-[var(--warning)]/5 p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl text-[#eab308]",children:Ne.length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"Pending approval"})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl",children:J.filter(t=>
2t.status==="grace_period").length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"Clients in Grace Period"})]})]}),Ne.length>0&&e.jsxs("div",{children:[e.jsxs("h2",{className:"font-display text-2xl mb-4 text-[#eab308]",children:["â³ Pending Onboarding (",Ne.length,")"]}),e.jsx("div",{className:"rounded-2xl border border-[var(--warning)]/30 bg-card shadow-[var(--shadow-soft)] overflow-hidden",children:e.jsx("div",{className:"divide-y divide-border",children:Ne.map(t=>e.jsx(St,{org:t,sub:J.find(r=>r.organization_id===t.id),plans:ie,onApprove:()=>xe(t.id,"active"),onSuspend:()=>xe(t.id,"suspended"),onUpdateSubscription:(r,c,y,W)=>Fe(t.id,r,c,y,W),onUpdateWhatsAppNumber:r=>Oe(t.id,r),onSimulatePayment:(r,c)=>me(t.id,r,c)},t.id))})})]}),e.jsxs("div",{children:[e.jsxs("h2",{className:"font-display text-2xl mb-4",children:["All Workspaces (",N.length,")"]}),e.jsx("div",{className:"rounded-2xl border border-border bg-card shadow-[var(--shadow-soft)] overflow-hidden",children:e.jsx("div",{className:"divide-y divide-border",children:N.map(t=>e.jsx(St,{org:t,sub:J.find(r=>r.organization_id===t.id),plans:ie,onApprove:t.onboarding_status!=="active"?()=>xe(t.id,"active"):void 0,onSuspend:t.onboarding_status!=="suspended"?()=>xe(t.id,"suspended"):void 0,onUpdateSubscription:(r,c,y,W)=>Fe(t.id,r,c,y,W),onUpdateWhatsAppNumber:r=>Oe(t.id,r),onSimulatePayment:(r,c)=>me(t.id,r,c),showStatus:!0},t.id))})})]})]}),e.jsxs(L,{value:"signups",className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl text-primary",children:$.length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"Total Signups"})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl text-[#22c55e]",children:$.filter(t=>t.plan_selected==="trial").length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"Trial Signups"})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl text-[#eab308]",children:$.filter(t=>t.converted_to_paid_at).length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"Converted to Paid"})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl",children:$.filter(t=>{const r=new Date(t.created_at),c=new Date;return r.getTime()>c.getTime()-10080*60*1e3}).length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"This Week"})]})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card shadow-[var(--shadow-soft)] overflow-hidden",children:[e.jsx("div",{className:"border-b border-border px-6 py-3 bg-muted/30",children:e.jsxs("div",{className:"grid grid-cols-[1fr_120px_100px_140px_100px] gap-4 text-[10px] uppercase tracking-[0.15em] text-muted-foreground",children:[e.jsx("span",{children:"User"}),e.jsx("span",{children:"Plan"}),e.jsx("span",{children:"Source"}),e.jsx("span",{children:"Activity"}),e.jsx("span",{children:"Signed Up"})]})}),e.jsxs("div",{className:"divide-y divide-border",children:[$.length===0&&e.jsxs("div",{className:"p-8 text-center text-sm text-muted-foreground",children:[e.jsx(jt,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/30"}),"No signups tracked yet. Events will appear here once the migration is applied."]}),$.map(t=>e.jsxs("div",{className:"grid grid-cols-[1fr_120px_100px_140px_100px] gap-4 px-6 py-4 items-center hover:bg-muted/20 transition-colors",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:t.full_name||"â"}),e.jsx("div",{className:"truncate text-xs text-muted-foreground",children:t.email})]}),e.jsx("div",{children:e.jsxs(G,{variant:"outline",className:`rounded-full text-[10px] ${t.plan_selected==="trial"?"text-blue-500 border-blue-500/30 bg-blue-500/10":t.plan_selected==="premium"?"text-purple-500 border-purple-500/30 bg-purple-500/10":"text-[#22c55e] border-[#22c55e]/30 bg-[#22c55e]/10"}`,children:[t.plan_selected,t.billing_cycle?` / ${t.billing_cycle}`:""]})}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t.referral_source||"direct"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{title:"Review fetched",className:`h-2 w-2 rounded-full ${t.first_review_fetched_at?"bg-[#22c55e]":"bg-muted"}`}),e.jsx("span",{title:"AI draft",className:`h-2 w-2 rounded-full ${t.first_ai_draft_at?"bg-blue-500":"bg-muted"}`}),e.jsx("span",{title:"Reply sent",className:`h-2 w-2 rounded-full ${t.first_reply_sent_at?"bg-purple-500":"bg-muted"}`}),e.jsx("span",{title:"Converted",className:`h-2 w-2 rounded-full ${t.converted_to_paid_at?"bg-[#eab308]":"bg-muted"}`}),e.jsxs("span",{className:"text-[9px] text-muted-foreground ml-1",children:[[t.first_review_fetched_at,t.first_ai_draft_at,t.f
2irst_reply_sent_at,t.converted_to_paid_at].filter(Boolean).length,"/4"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:C(new Date(t.created_at),"MMM d, yyyy")})]},t.id))]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-[10px] text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[#22c55e]"})," Review Fetched"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-blue-500"})," AI Draft Generated"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-purple-500"})," Reply Sent"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[#eab308]"})," Converted to Paid"]})]})]}),e.jsxs(L,{value:"users",className:"space-y-6",children:[e.jsxs("h2",{className:"font-display text-2xl",children:["Registered Users (",te.length,")"]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card shadow-[var(--shadow-soft)] overflow-hidden",children:[e.jsx("div",{className:"border-b border-border px-6 py-3 bg-muted/30",children:e.jsxs("div",{className:"grid grid-cols-[1fr_260px_120px] gap-4 text-[10px] uppercase tracking-[0.15em] text-muted-foreground",children:[e.jsx("span",{children:"User"}),e.jsx("span",{children:"Workspaces / Role"}),e.jsx("span",{children:"Joined"})]})}),e.jsxs("div",{className:"divide-y divide-border",children:[te.length===0&&e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No users found"}),te.map(t=>e.jsxs("div",{className:"grid grid-cols-[1fr_260px_120px] gap-4 px-6 py-4 items-center hover:bg-muted/20 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-full bg-gradient-to-br from-primary/80 to-[var(--warning)]/80 text-sm font-semibold text-white",children:(t.full_name??t.email??"?").slice(0,1).toUpperCase()}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"truncate text-sm font-medium flex items-center gap-2",children:[t.full_name??"No Name",t.is_super_admin&&e.jsx(G,{className:"bg-primary/20 text-primary border-primary/30 text-[9px] rounded-full px-1.5 py-0",children:"Super Admin"})]}),e.jsx("div",{className:"truncate text-xs text-muted-foreground",children:t.email})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground min-w-0 space-y-1",children:t.organization_members&&t.organization_members.length>0?t.organization_members.map((r,c)=>e.jsxs("div",{className:"truncate",children:[e.jsx("strong",{className:"text-foreground",children:r.organizations?.name??"Unknown Workspace"})," ","· ",e.jsx("span",{className:"capitalize",children:r.role})]},c)):e.jsx("span",{className:"italic text-muted-foreground/60",children:"No workspaces linked"})}),e.jsx("div",{className:"text-xs text-muted-foreground",children:C(new Date(t.created_at),"MMM d, yyyy")})]},t.id))]})]})]}),e.jsx(L,{value:"invites",className:"space-y-6",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"font-display text-2xl",children:"Invite Codes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ge,{value:Re,onValueChange:Ee,children:[e.jsx(fe,{className:"h-9 w-32 text-xs rounded-full",children:e.jsx(je,{})}),e.jsxs(ve,{children:[e.jsx(A,{value:"1",children:"Expires in 1 day"}),e.jsx(A,{value:"3",children:"Expires in 3 days"}),e.jsx(A,{value:"7",children:"Expires in 7 days"}),e.jsx(A,{value:"30",children:"Expires in 30 days"})]})]}),e.jsxs(R,{className:"rounded-full",onClick:Je,disabled:ke,children:[e.jsx(vt,{className:"mr-1.5 h-4 w-4"}),ke?"Generatingâ¦":"New invite code"]})]})]}),e.jsx("div",{className:"rounded-2xl border border-border bg-card shadow-[var(--shadow-soft)] overflow-hidden",children:e.jsxs("div",{className:"divide-y divide-border",children:[X.length===0&&e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No invite codes yet â generate one above"}),X.map(t=>{const r=t.expires_at&&new Date(t.expires_at)<new Date,c=!!t.used_by;return e.jsxs("div",{className:"flex items-center justify-between gap-4 px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("code",{className:"rounded-lg bg-muted px-3 py-1.5 font-mono text-sm font-semibold tracking-widest",children:t.code}),c?e.jsx(G,{variant:"outline",className:"rounded-full text-[10px] text-[#22c55e] border-[#22c55e]/30 bg-[#22c55e]/10",children:"Used"}):r?e.jsx(G,{variant:"outline",className:"rounded-full text-[10px] text-destructive border-destructive/30 bg-destructive/10",children:"Expired"}):e.jsx(G,{variant:"outline",className:"rounded-full text-[10px] text-primary border-primary/30 bg-primary/10",children:"Active"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.expires_at?`Expires ${C(new Date(t.expires_at),"MMM d, yyyy")}`:"No expiry",t.used_by&&t.profiles?.email&&` · Used by ${t.profiles.email}`]}),!c&&!r&&e.jsx(R,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>Qe(t.code,t.id),children:$e===t.id?e.jsx(ot,{className:"h-3.5 w-3.5 text-[#22c55e]"}):e.jsx(os,{className:"h-3.5 w-3.5"})})]},t.id)})]})})]})}),e.jsxs(L,{value:"coupons",className:"space-y-6",children:[e.jsxs("div",{className:"rounded-2xl border border-border bg-card shadow-[var(--shadow-soft)] p-6",children:[e.jsxs("h2",{className:"font-display text-xl mb-4 flex items-center gap-2",children:[e.jsx(Pe,{className:"h-5 w-5 text-primary"})," Create Discount Coupon"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"Coupon Code *"}),e.jsx("input",{className:"w-full h-9 rounded-lg border border-border bg-background px-3 text-sm",placeholder:"e.g. LAUNCH50",value:j.code,onChange:t=>ee(r=>({...r,code:t.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"Assign to Organization *"}),e.jsxs(ge,{value:j.organization_id,onValueChange:t=>ee(r=>({...r,organization_id:t})),children:[e.jsx(fe,{className:"h-9 rounded-lg text-sm",children:e.jsx(je,{placeholder:"Select org..."})}),e.jsx(ve,{children:N.map(t=>e.jsx(A,{value:t.id,children:t.name},t.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"Discount Type"}),e.jsxs(ge,{value:j.discount_type,onValueChange:t=>ee(r=>({...r,discount_type:t})),children:[e.jsx(fe,{className:"h-9 rounded-lg text-sm",children:e.jsx(je,{})}),e.jsxs(ve,{children:[e.jsx(A,{value:"percentage",children:"Percentage (%)"}),e.jsx(A,{value:"flat",children:"Flat Amount (â¹)"})]})]})]}
2),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(H,{className:"text-xs text-muted-foreground",children:["Discount Value * ",j.discount_type==="percentage"?"(%)":"(â¹)"]}),e.jsx("input",{type:"number",className:"w-full h-9 rounded-lg border border-border bg-background px-3 text-sm",placeholder:j.discount_type==="percentage"?"e.g. 20":"e.g. 5000",value:j.discount_value,onChange:t=>ee(r=>({...r,discount_value:t.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"Applies To"}),e.jsxs(ge,{value:j.applies_to,onValueChange:t=>ee(r=>({...r,applies_to:t})),children:[e.jsx(fe,{className:"h-9 rounded-lg text-sm",children:e.jsx(je,{})}),e.jsxs(ve,{children:[e.jsx(A,{value:"all",children:"All Payments"}),e.jsx(A,{value:"license_fee",children:"License Fee Only"}),e.jsx(A,{value:"subscription",children:"Subscription Only"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"Max Uses"}),e.jsx("input",{type:"number",className:"w-full h-9 rounded-lg border border-border bg-background px-3 text-sm",value:j.max_uses,onChange:t=>ee(r=>({...r,max_uses:t.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"Valid Until (optional)"}),e.jsx("input",{type:"date",className:"w-full h-9 rounded-lg border border-border bg-background px-3 text-sm",value:j.valid_until,onChange:t=>ee(r=>({...r,valid_until:t.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"Admin Note"}),e.jsx("input",{className:"w-full h-9 rounded-lg border border-border bg-background px-3 text-sm",placeholder:"Internal note...",value:j.notes,onChange:t=>ee(r=>({...r,notes:t.target.value}))})]}),e.jsx("div",{className:"flex items-end",children:e.jsxs(R,{className:"rounded-full w-full",onClick:xt,disabled:ae,children:[e.jsx(vt,{className:"mr-1.5 h-4 w-4"}),ae?"Creatingâ¦":"Create Coupon"]})})]})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card shadow-[var(--shadow-soft)] overflow-hidden",children:[e.jsx("div",{className:"border-b border-border px-6 py-3 bg-muted/30",children:e.jsxs("div",{className:"grid grid-cols-[1fr_120px_100px_80px_80px_120px_80px] gap-4 text-[10px] uppercase tracking-[0.15em] text-muted-foreground",children:[e.jsx("span",{children:"Code / Org"}),e.jsx("span",{children:"Discount"}),e.jsx("span",{children:"Applies To"}),e.jsx("span",{children:"Uses"}),e.jsx("span",{children:"Status"}),e.jsx("span",{children:"Valid Until"}),e.jsx("span",{children:"Action"})]})}),e.jsxs("div",{className:"divide-y divide-border",children:[Z.length===0&&e.jsxs("div",{className:"p-8 text-center text-sm text-muted-foreground",children:[e.jsx(Pe,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/30"}),"No coupons created yet. Use the form above to create your first coupon."]}),Z.map(t=>{const r=t.valid_until&&new Date(t.valid_until)<new Date,c=t.used_count>=t.max_uses;return e.jsxs("div",{className:"grid grid-cols-[1fr_120px_100px_80px_80px_120px_80px] gap-4 px-6 py-4 items-center hover:bg-muted/20 transition-colors",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("code",{className:"text-sm font-semibold tracking-wider text-primary",children:t.code}),e.jsx("div",{className:"text-[11px] text-muted-foreground truncate",children:t.organizations?.name||"â"})]}),e.jsx("div",{className:"text-sm font-medium",children:t.discount_type==="percentage"?`${t.discount_value}%`:`â¹${Number(t.discount_value).toLocaleString()}`}),e.jsx(G,{variant:"outline",className:"rounded-full text-[10px] justify-center",children:t.applies_to==="all"?"All":t.applies_to==="license_fee"?"License":"Subscription"}),e.jsxs("div",{className:"text-xs",children:[t.used_count,"/",t.max_uses]}),e.jsx("div",{children:t.is_active?r?e.jsx(G,{variant:"outline",className:"rounded-full text-[10px] text-destructive border-destructive/30 bg-destructive/10",children:"Expired"}):c?e.jsx(G,{variant:"outline",className:"rounded-full text-[10px] text-[#eab308] border-[#eab308]/30 bg-[#eab308]/10",children:"Used Up"}):e.jsx(G,{variant:"outline",className:"rounded-full text-[10px] text-[#22c55e] border-[#22c55e]/30 bg-[#22c55e]/10",children:"Active"}):e.jsx(G,{variant:"outline",className:"rounded-full text-[10px] text-muted-foreground border-muted",children:"Disabled"})}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t.valid_until?C(new Date(t.valid_until),"MMM d, yyyy"):"No expiry"}),e.jsx(R,{variant:"outline",size:"sm",className:"rounded-full h-7 text-[10px]",onClick:()=>ye(t.id,t.is_active),children:t.is_active?e.jsxs(e.Fragment,{children:[e.jsx(zt,{className:"h-3 w-3 mr-1"})," Disable"]}):e.jsxs(e.Fragment,{children:[e.jsx(ot,{className:"h-3 w-3 mr-1"})," Enable"]})})]},t.id)})]})]})]}),e.jsx(L,{value:"services",className:"space-y-6",children:e.jsxs("div",{className:"rounded-2xl border border-border bg-card shadow-[var(--shadow-soft)] p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"grid h-7 w-7 place-items-center rounded-md bg-primary/10 text-primary",children:e.jsx(ct,{className:"h-4 w-4"})}),e.jsx("h2",{className:"font-display text-xl",children:"Platform Services"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:"Managed by you â inv
2isible to clients"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:[{key:"gemini",icon:e.jsx(Pe,{className:"h-4 w-4"}),label:"Gemini AI",desc:"Primary LLM",envKey:"GEMINI_API_KEY"},{key:"groq",icon:e.jsx(ct,{className:"h-4 w-4"}),label:"Groq Llama",desc:"Fallback LLM",envKey:"GROQ_API_KEY"},{key:"resend",icon:e.jsx(bt,{className:"h-4 w-4"}),label:"Resend Email",desc:"Weekly digest",envKey:"RESEND_API_KEY"},{key:"telegram",icon:e.jsx(rs,{className:"h-4 w-4"}),label:"Telegram Bot",desc:"Instant alerts",envKey:"TELEGRAM_BOT_TOKEN"}].map(({key:t,icon:r,label:c,desc:y,envKey:W})=>{const se=Ge[t]??!1;return e.jsxs("div",{className:`rounded-xl border p-3 ${se?"border-[#22c55e]/20 bg-[#22c55e]/5":"border-[#ef4444]/20 bg-[#ef4444]/5"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`grid h-7 w-7 place-items-center rounded-lg ${se?"bg-[#22c55e]/10 text-[#22c55e]":"bg-[#ef4444]/10 text-[#ef4444]"}`,children:r}),e.jsx("div",{className:`text-[10px] font-medium ${se?"text-[#22c55e]":"text-[#ef4444]"}`,children:se?"â Set":"â Missing"})]}),e.jsx("div",{className:"text-sm font-semibold",children:c}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:y}),e.jsx("code",{className:"text-[9px] text-muted-foreground/60 mt-1 block",children:W})]},t)})}),e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:["Set these in"," ",e.jsx("strong",{children:"Supabase Dashboard â Project Settings â Edge Function Secrets"}),". Once set, all clients benefit automatically."]})]})}),e.jsx(L,{value:"leads",className:"space-y-6",children:e.jsxs("div",{className:"rounded-3xl border border-border bg-card p-6 shadow-[var(--shadow-elegant)]",children:[e.jsx("div",{className:"flex items-center justify-between mb-6",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-bold",children:["Contact Requests & Leads (",le.length,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Leads captured from the landing page form"})]})}),le.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground text-sm",children:"No contact requests submitted yet."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left text-sm border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-muted-foreground text-xs uppercase tracking-wider font-semibold",children:[e.jsx("th",{className:"py-3.5 px-3",children:"Date"}),e.jsx("th",{className:"py-3.5 px-3",children:"Contact / Business"}),e.jsx("th",{className:"py-3.5 px-3",children:"Email"}),e.jsx("th",{className:"py-3.5 px-3",children:"Phone"}),e.jsx("th",{className:"py-3.5 px-3 text-center",children:"Locations"}),e.jsx("th",{className:"py-3.5 px-3",children:"Message"}),e.jsx("th",{className:"py-3.5 px-3",children:"Status"}),e.jsx("th",{className:"py-3.5 px-3 text-right",children:"Actions"})]})}),e.jsx("tbody",{children:le.map(t=>e.jsxs("tr",{className:"border-b border-border/60 hover:bg-muted/10 transition-colors",children:[e.jsx("td",{className:"py-4 px-3 text-xs font-mono text-muted-foreground",children:new Date(t.created_at).toLocaleDateString()}),e.jsxs("td",{className:"py-4 px-3",children:[e.jsx("div",{className:"font-semibold text-foreground",children:t.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t.business_name||"â"})]}),e.jsx("td",{className:"py-4 px-3 font-mono text-xs",children:t.email}),e.jsx("td",{className:"py-4 px-3 font-mono text-xs",children:t.phone}),e.jsx("td",{className:"py-4 px-3 text-xs font-semibold text-center",children:e.jsx("span",{className:"bg-primary/5 text-primary border border-primary/10 rounded px-2 py-0.5",children:t.locations})}),e.jsx("td",{className:"py-4 px-3 max-w-xs truncate text-xs",title:t.message,children:t.message||e.jsx("span",{className:"text-muted-foreground/50 italic",children:"None"})}),e.jsx("td",{className:"py-4 px-3",children:e.jsxs("select",{className:"bg-background border border-border/80 rounded-md px-2 py-1 text-xs focus:ring-1 focus:ring-primary focus:outline-none",value:t.status||"new",onChange:r=>Ae(t.id,r.target.value),children:[e.jsx("option",{value:"new",children:"New"}),e.jsx("option",{value:"contacted",children:"Contacted"}
2),e.jsx("option",{value:"qualified",children:"Qualified"}),e.jsx("option",{value:"closed",children:"Closed / Churned"})]})}),e.jsx("td",{className:"py-4 px-3 text-right",children:e.jsx(R,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-red-500 hover:text-red-700 hover:bg-red-500/10 rounded-full",onClick:()=>{confirm("Delete this lead?")&&Ze(t.id)},children:e.jsx(is,{className:"h-4 w-4"})})})]},t.id))})]})})]})}),e.jsx(L,{value:"reports",className:"space-y-6",children:e.jsx(ps,{orgs:N,subscriptions:J,plans:ie})}),e.jsxs(L,{value:"alerts",className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl text-primary",children:M.length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 font-medium",children:"Total Alerts logged"})]}),e.jsxs("div",{className:"rounded-2xl border border-[#22c55e]/20 bg-[#22c55e]/5 p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl text-[#22c55e]",children:M.filter(t=>t.title?.includes("Registered")||t.title?.includes("Created")).length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 font-medium",children:"New Joinees"})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-500/20 bg-blue-500/5 p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl text-blue-500",children:M.filter(t=>t.title?.includes("Payment")||t.title?.includes("Renewal")||t.title?.includes("Success")).length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 font-medium font-semibold",children:"Renewals & Payments"})]}),e.jsxs("div",{className:"rounded-2xl border border-[#ef4444]/20 bg-[#ef4444]/5 p-5 text-center shadow-[var(--shadow-soft)]",children:[e.jsx("div",{className:"font-display text-4xl text-[#ef4444]",children:M.filter(t=>t.read===!1).length}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 font-medium",children:"Unread Alerts"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 rounded-3xl border border-border bg-card p-6 shadow-[var(--shadow-elegant)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2",children:[e.jsx(Be,{className:"h-5 w-5 text-primary"}),"Platform Activity Timeline"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Real-time log of client actions, renewals, and registrations"})]}),e.jsxs("div",{className:"flex gap-2",children:[M.some(t=>!t.read)&&e.jsx(R,{variant:"outline",size:"sm",className:"rounded-full h-8 text-xs font-semibold px-4",onClick:Xe,children:"Mark all read"}),M.length>0&&e.jsx(R,{variant:"outline",size:"sm",className:"rounded-full h-8 text-xs text-red-500 border-red-500/20 hover:bg-red-500/5 font-semibold px-4",onClick:Le,children:"Clear all log"})]})]}),M.length===0?e.jsxs("div",{className:"py-16 text-center text-muted-foreground text-sm flex flex-col items-center justify-center",children:[e.jsx(Be,{className:"h-12 w-12 text-muted-foreground/20 mb-3"}),e.jsx("p",{className:"font-medium text-foreground/75",children:"No activity alerts logged yet."}),e.jsx("p",{className:"text-xs mt-1 text-muted-foreground max-w-xs",children:"New registrations, payments, status updates, and leads will appear here in real time."})]}):e.jsx("div",{className:"relative border-l border-border pl-6 ml-4 space-y-6 max-h-[600px] overflow-y-auto pr-2",children:M.map(t=>{const r=!t.read;let c=Be,y="bg-primary/10 text-primary border-primary/20";return t.title?.includes("Registered")||t.title?.includes("Created")?(c=qe,y="bg-emerald-500/10 text-emerald-500 border-emerald-500/20"):t.title?.includes("Payment")||t.title?.includes("Renewal")||t.title?.includes("Success")?(c=ts,y="bg-blue-500/10 text-blue-500 border-blue-500/20"):t.title?.includes("Status")||t.title?.includes("Change")||t.title?.includes("Suspended")||t.title?.includes("Breach")?(c=Ue,y="bg-amber-500/10 text-amber-500 border-amber-500/20"):(t.t
2itle?.includes("Lead")||t.title?.includes("Request"))&&(c=bt,y="bg-purple-500/10 text-purple-500 border-purple-500/20"),e.jsxs("div",{className:"relative group",children:[e.jsx("span",{className:`absolute -left-[37px] top-1 grid h-6 w-6 place-items-center rounded-full border bg-background shadow-sm ${y} transition-transform group-hover:scale-110`,children:e.jsx(c,{className:"h-3 w-3"})}),e.jsx("div",{className:`p-4 rounded-2xl border transition-all ${r?"bg-primary/[0.02] border-primary/20 hover:bg-primary/[0.04]":"bg-muted/10 border-border/80 hover:bg-muted/20"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:`text-sm font-semibold tracking-tight ${r?"text-foreground":"text-muted-foreground"}`,children:t.title}),r&&e.jsx(G,{className:"bg-primary/20 text-primary border-primary/30 text-[9px] rounded-full px-1.5 py-0",children:"New"})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed whitespace-pre-wrap",children:t.body}),e.jsx("span",{className:"text-[10px] text-muted-foreground/60 block font-medium",children:ns(new Date(t.created_at),{addSuffix:!0})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[r&&e.jsx(R,{size:"sm",variant:"ghost",className:"h-7 rounded-full text-[10px] font-semibold px-2.5 bg-primary/5 text-primary hover:bg-primary/10",onClick:()=>be(t.id),children:"Mark Read"}),e.jsx(R,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 rounded-full text-muted-foreground hover:text-red-500 hover:bg-red-500/10",onClick:()=>He(t.id),children:e.jsx(ls,{className:"h-3.5 w-3.5"})})]})]})})]},t.id)})})]}),e.jsxs("div",{className:"lg:col-span-1 space-y-6",children:[e.jsxs("div",{className:"rounded-3xl border border-border bg-card p-6 shadow-[var(--shadow-elegant)] space-y-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[e.jsx(lt,{className:"h-5 w-5 text-primary"}),"Alert Preferences"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Configure where you receive real-time notifications"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(H,{className:"text-xs font-semibold text-muted-foreground",children:"WhatsApp Alert Number"}),e.jsx("input",{type:"text",className:"flex h-9 w-full rounded-full border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring font-mono",value:d,onChange:t=>l(t.target.value),placeholder:"e.g. +919980434101"}),e.jsx("p",{className:"text-[10px] text-muted-foreground leading-normal pl-2",children:"Enter with country code (e.g. +91...) to receive WhatsApp notifications."})]}),e.jsxs("div",{className:"divide-y divide-border rounded-2xl border border-border overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-muted/5 hover:bg-muted/10 transition-colors",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"text-xs font-semibold",children:"WhatsApp Alerts"}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Get instant notifications on your phone"})]}),e.jsx(ft,{checked:b?.whatsapp??!1,onCheckedChange:t=>Q(r=>({...r,whatsapp:t}))})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-muted/5 hover:bg-muted/10 transition-colors",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"text-xs font-semibold",children:"Email Alerts"}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Receive updates via registered email"})]}),e.jsx(ft,{checked:b?.email??!1,onCheckedChange:t=>Q(r=>({...r,email:t}))})]})]}),e.jsx(R,{className:"w-full rounded-full text-xs font-semibold h-9",disabled:oe,onClick:Ye,children:oe?"Saving...":"Save Preferences"})]})]}),e.jsxs("div",{className:"rounded-2xl border border-primary/20 bg-primary/5 p-4 text-xs text-muted-foreground space-y-2",children:[e.jsxs("div",{className:"font-semibold text-primary flex items-center gap-1.5",children:[e.jsx(Pe,{className:"h-3.5 w-3.5 text-primary"})," Verified Outbox Active"]}),e.jsxs("p",{className:"leading-relaxed text-[11px]",children:["All alerts are processed and dispatched by ",e.jsx("strong",{children:"PulseCX"})," utilizing native Meta WhatsApp and Resend Email cloud gateways."]})]})]})]})]})]})]})}function St({org:o,sub:m,plans:f,onApprove:x,onSuspend:k,onUpdateSubscription:g,onUpdateWhatsAppNumber:N,onSimulatePayment:E,showStatus:X=!1}){const[Y,te]=u.useState(m?.plan_id??""),[re,J]=u.useState(m?.status??"active"),[F,ie]=u.useState(m?.grace_peri
2od_days??7),[ne,le]=u.useState(o.org_settings?.twilio_whatsapp_from??"");u.useEffect(()=>{le(o.org_settings?.twilio_whatsapp_from??"")},[o.org_settings?.twilio_whatsapp_from]);const de={active:{label:"Active",color:"#22c55e"},grace_period:{label:"Grace Period",color:"#f59e0b"},suspended:{label:"Suspended",color:"#ef4444"},pending:{label:"Onboarding Draft",color:"#eab308"}},M=f.find(i=>i.id===(m?.plan_id??Y));return e.jsxs("div",{className:"p-6 hover:bg-muted/10 transition-all border-b border-border space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-gradient-to-br from-primary/10 to-[var(--warning)]/10 text-primary border border-primary/20",children:e.jsx(qe,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"truncate text-base font-semibold flex items-center gap-2",children:[o.name,m&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{color:de[m.status]?.color??"#777",background:(de[m.status]?.color??"#777")+"15"},children:de[m.status]?.label??m.status}),M?.name?.toLowerCase().includes("trial")&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium bg-purple-500/15 text-purple-600",children:"â± Trial"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Slug: ",e.jsx("strong",{className:"text-foreground",children:o.slug})," · Created"," ",C(new Date(o.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[x&&e.jsxs(R,{size:"sm",className:"rounded-full h-8 text-xs bg-[#22c55e] hover:bg-[#16a34a] text-white",onClick:x,children:[e.jsx(ot,{className:"mr-1 h-3.5 w-3.5"})," Activate Tenant"]}),k&&o.onboarding_status!=="suspended"&&e.jsxs(R,{size:"sm",variant:"outline",className:"rounded-full h-8 text-xs text-destructive border-destructive/20 hover:bg-destructive/5",onClick:k,children:[e.jsx(zt,{className:"mr-1 h-3.5 w-3.5"})," Suspend"]})]})]}),m?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 p-4 rounded-xl bg-muted/30 border border-border/60",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("span",{className:"text-[10px] text-muted-foreground uppercase font-semibold tracking-wider flex items-center gap-1",children:[e.jsx(yt,{className:"h-3 w-3 text-primary"})," Active Pricing"]}),e.jsxs("div",{className:"text-sm font-medium leading-relaxed",children:["License Fee (â¹50,000) +"," ",M?.name==="Growth Trial"?"Growth Trial (7 Days - Free)":M?.name??"7-Day Free Trial"]}),e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:M?.billing_cycle?`${M.billing_cycle} Billing`:"Trial Mode"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("span",{className:"text-[10px] text-muted-foreground uppercase font-semibold tracking-wider flex items-center gap-1",children:[e.jsx(es,{className:"h-3 w-3 text-primary"})," Grace Margin"]}),e.jsxs("div",{className:"text-sm font-medium",children:[m.grace_period_days," Days"]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:m.grace_period_end?`Expires ${C(new Date(m.grace_period_end),"MMM d, yyyy")}`:"No grace active"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("span",{className:"text-[10px] text-muted-foreground uppercase font-semibold tracking-wider flex items-center gap-1",children:[e.jsx(Ct,{className:"h-3 w-3 text-primary"})," Billing Term"]}),e.jsx("div",{className:"text-sm font-medium truncate",children:C(new Date(m.current_period_end),"MMM d, yyyy")}),e.jsx("div",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:"Renewal Date"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("span",{className:"text-[10px] text-muted-foreground uppercase font-semibold tracking-wider flex items-center gap-1",children:[e.jsx(ct,{className:"h-3 w-3 text-primary"})," License Form"]}),e.jsx("div",{className:"text-sm font-medium capitalize",children:"Mandatory License + Sub"}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:m.auto_renew?"Auto Reminders: On":"Auto Reminders: Off"})]})]}):e.jsx("div",{className:"text-xs text-muted-foreground italic bg-muted/10 p-3 rounded-lg border border-dashed border-border/80",children:"No active subscription seeded for this organization yet."}),m&&e.jsxs("div",{className:"flex flex-wrap items-center gap-4 pt-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"Plan Option:"}),e.jsxs(ge,{value:Y,onValueChange:te,children:[e.jsx(fe,{className:"h-8 w-44 text-xs rounded-full",children:e.jsx(je,{placeholder:"Select plan"})}),e.jsx(ve,{children:f.filter(i=>i.billing_cycle!=="one_time").map(i=>e.jsx(A,{value:i.id,children:i.name==="Growth Trial"?"Growth Trial (7 Days - Free)":`${i.name}
2 (â¹${Number(i.actual_price).toLocaleString("en-IN")})`},i.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"Status:"}),e.jsxs(ge,{value:re,onValueChange:J,children:[e.jsx(fe,{className:"h-8 w-28 text-xs rounded-full",children:e.jsx(je,{placeholder:"Status"})}),e.jsxs(ve,{children:[e.jsx(A,{value:"active",children:"Active"}),e.jsx(A,{value:"grace_period",children:"Grace Period"}),e.jsx(A,{value:"suspended",children:"Suspended"}),e.jsx(A,{value:"cancelled",children:"Cancelled"})]})]})]}),e.jsx(R,{size:"sm",variant:"outline",className:"rounded-full h-8 text-xs font-semibold px-4",onClick:()=>{const i=f.find(a=>a.id===Y),$=i?.name==="Growth Trial"?0:i?.billing_cycle==="annually"?12:i?.billing_cycle==="quarterly"?3:1;g?.(Y,re,F,$,"recurring")},children:"Apply Overrides"}),e.jsxs("div",{className:"flex items-center gap-2 border-l border-border/80 pl-4",children:[e.jsx(H,{className:"text-xs text-muted-foreground",children:"WhatsApp Alerts:"}),e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{type:"text",className:"h-8 w-36 rounded-full border border-input bg-background px-3 py-1 text-xs shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring font-mono",value:ne,onChange:i=>le(i.target.value),placeholder:"e.g. +919980434101"}),e.jsx(R,{size:"sm",variant:"outline",className:"rounded-full h-8 text-xs font-semibold px-3",onClick:()=>N?.(ne),children:"Save Phone"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(R,{size:"sm",variant:"outline",className:"rounded-full h-8 text-xs border-[#22c55e]/30 bg-[#22c55e]/5 text-[#22c55e] hover:bg-[#22c55e]/10",onClick:()=>{const i=f.find(d=>d.id===Y),$=i?.billing_cycle,a=i?.name==="Growth Trial"?0:$==="annually"?12:$==="quarterly"?3:1;E?.(Y,a)},children:[e.jsx(yt,{className:"mr-1 h-3.5 w-3.5"})," Simulate Stripe Success"]})})]})]})}export{Ts as component};
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.