1import{u as G,s as S,r as Ce,j as e,B as ue}from"./index-DDM5dk0b.js";import{A as De}from"./AdminLayout-d2Xyuxm7.js";import{C as q,b as P,c as E,a as O}from"./card-DEgzWvw5.js";import{S as M}from"./skeleton-CKi5J8Hg.js";import{B as ie}from"./badge-BC_-ffdp.js";import{S as Ae,a as Re,b as Ie,c as qe,d as V}from"./select-B0YVmj_C.js";import{s as me,f as Oe,a as $e}from"./format-RyfQyywz.js";import{s as Te}from"./startOfMonth-BqpJtJQc.js";import{s as Le}from"./subDays-zfsdsliS.js";import{s as Fe}from"./startOfWeek-CGNiWUve.js";import{R as Ue}from"./refresh-cw-C6TP4FiG.js";import{S as Me}from"./shield-check-D1JMcDLV.js";import{U as oe}from"./users-DxMqsWAO.js";import{C as he}from"./crown-BeXfEaV_.js";import{T as ge}from"./timer-DUAxsEdG.js";import{D as z}from"./dollar-sign-BsPM1xqP.js";import{U as xe}from"./user-x-DsMN84aj.js";import{C as fe}from"./circle-alert-C-OLH9Mi.js";import{F as ne}from"./file-text-Btf8zv2A.js";import{B as X}from"./bot-BOFGcXc2.js";import{Z as Q}from"./zap-BXZh6OxN.js";import{C as pe}from"./clock-BmQdIgpA.js";import{R as B,X as ee,Y as H,T as K,L as le,B as je,C as be}from"./generateCategoricalChart-LBTMcQLH.js";import{L as ye}from"./LineChart-YezWGh77.js";import{C as ce}from"./CartesianGrid-BYmpcBts.js";import{L as J}from"./Line-D8JxjBt4.js";import{S as Pe}from"./sparkles-CpIfunfF.js";import{E as Ee}from"./external-link-Cn3bBx-h.js";import{B as Be}from"./briefcase-UMNYjHg9.js";import{A as ve}from"./activity-BHNC1Dce.js";import{P as Ke}from"./pause-D3K_A1Oj.js";import{I as _e}from"./image-DT5Eztxr.js";import{C as Je}from"./circle-arrow-down-U5BB-PRm.js";import{C as Ge}from"./circle-arrow-up-DoMVLRKB.js";import{B as We}from"./BarChart-DOPaZQne.js";import{P as ke,a as Ne}from"./PieChart-Cp80KwXv.js";import{A as ze}from"./AreaChart-DzLDuHW2.js";import{A as He}from"./Area-D7xqJ-MO.js";import{T as Ze}from"./trending-up-D7r9YC0v.js";import{T as Ye}from"./trending-down-C4CSPU14.js";import"./chevron-right-BBZt2Fbq.js";import"./chevron-left-HWpYslqI.js";import"./layout-dashboard-Bs40Jm_Q.js";import"./heart-pulse-CwtAYTDP.js";import"./wand-sparkles-CHCihP20.js";import"./key-DIpFm1x3.js";import"./percent-BMY1QmKU.js";import"./message-square-BJXqZWHi.js";import"./chart-column-B9VCejQo.js";import"./megaphone-DO-qAaXU.js";import"./users-round-N_50dZXr.js";import"./globe-B8QcTDpd.js";import"./database-DtgnIYRV.js";import"./upload-DyMQB0o1.js";import"./settings-r2YjUbHs.js";import"./code-BBEmPq6h.js";import"./mail-BGkfEyYp.js";import"./book-open-CEGtrXoL.js";import"./gauge-Dq-7NRRn.js";import"./download-B_uflK1r.js";import"./loader-circle-D4BXDxKA.js";import"./sheet-BgKQopPJ.js";import"./index-BjPFedwd.js";import"./Combination-Dkfmdx58.js";import"./menu-DxXqjd0J.js";import"./arrow-left-Cau1hHAu.js";import"./index-BdQq_4o_.js";import"./index-QaJzJ_Zg.js";import"./check-D9A8J6nx.js";import"./en-US-DgaeWpfW.js";import"./constructFrom-rJN6zrQ_.js";async function I(r,l,t){let m=[],d=0;for(;;){let c=S.from(r).select(l).range(d,d+1e3-1);t&&(c=t(c));const{data:x}=await c;if(!x||x.length===0||(m=m.concat(x),x.length<1e3))break;d+=1e3}return m}function Ve(r){const l=new Date;switch(r){case"daily":return me(l);case"weekly":return Fe(l,{weekStartsOn:1});case"monthly":return Te(l);case"yearly":return $e(l)}}function Xe(){return G({queryKey:["admin-stats"],queryFn:async()=>{const r=new Date,l=new Date(r.getTime()-24*60*60*1e3),t=me(r),o=Te(r),[m,d,c,x,u,f,C,p,i,b,T,j]=await Promise.all([S.from("profiles").select("id",{count:"exact",head:!0}),S.from("jobs").select("id",{count:"exact",head:!0}),S.from("articles").select("id",{count:"exact",head:!0}),S.from("jobs").select("id",{count:"exact",head:!0}).eq("status","processing"),S.from("jobs").select("id",{count:"exact",head:!0}).eq("status","paused"),S.from("jobs").select("id",{count:"exact",head:!0}).eq("status","processing").lt("updated_at",new Date(r.getTime()-30*60*1e3).toISOString()),S.from("profiles").select("id",{count:"exact",head:!0}).in("subscription_tier",["pro","business","agency"]),I("jobs","status, completed_articles, total_articles, failed_articles, created_at, updated_at"),I("jobs","id, failed_articles, created_at",n=>n.gte("created_at",l.toISOString())),I("usage_tracking","user_id, words_used, words_limit"),I("ai_usage_logs","total_cost, total_tokens",n=>n.gte("created_at",t.toISOString())),I("ai_usage_logs","total_cost",n=>n.gte("created_at",o.toISOString()))]),$=T.reduce((n,s)=>n+(Number(s.total_cost)||0),0),v=j.reduce((n,s)=>n+(Number(s.total_cost)||0),0),a=T.length,_=T.reduce((n,s)=>n+(s.total_tokens||0),0),L=i.reduce((n,s)=>n+(s.failed_articles||0),0),F=new Set(b.filter(n=>n.words_used>0).map(n=>
1n.user_id)).size,N=b.filter(n=>{const s=n.words_limit||5e3;return n.words_used>=s}).length,k=p.filter(n=>n.status==="completed"),D=k.length>0?k.reduce((n,s)=>{const g=new Date(s.created_at).getTime(),W=new Date(s.updated_at).getTime();return n+(W-g)/1e3},0)/k.length:0,A=p.filter(n=>n.total_articles>0),h=A.length>0?A.reduce((n,s)=>n+s.completed_articles/s.total_articles,0)/A.length*100:0;return{totalUsers:m.count||0,totalJobs:d.count||0,totalArticles:c.count||0,activeJobs:x.count||0,jobsLast24h:i.length,errorsLast24h:L,pausedJobs:u.count||0,stuckProcessing:f.count||0,aiUsers:F,trialLimitReached:N,avgGenerationTime:Math.round(D),avgAttainmentRate:Math.round(h),aiCostToday:$,aiCostThisMonth:v,aiRequestsToday:a,totalTokensToday:_,proUsers:C.count||0}},refetchIntervalInBackground:!1,refetchInterval:3e4})}function Qe(r){return G({queryKey:["admin-stats-period",r],queryFn:async()=>{var N,k,D,A;const t=Ve(r).toISOString(),[o,m,d]=await Promise.all([I("ai_usage_logs","total_cost, total_tokens, input_tokens, output_tokens, model, request_type",h=>h.gte("created_at",t)),I("usage_tracking","images_used"),I("image_generation_jobs","number_of_images, status",h=>h.eq("status","completed").gte("created_at",t))]),c=o.reduce((h,n)=>h+(Number(n.total_cost)||0),0),x=o.reduce((h,n)=>h+(n.total_tokens||0),0),u=o.reduce((h,n)=>h+(n.input_tokens||0),0),f=o.reduce((h,n)=>h+(n.output_tokens||0),0),C=o.length,p=m.reduce((h,n)=>h+(n.images_used||0),0),i=d.reduce((h,n)=>h+(n.number_of_images||0),0),b=Math.max(p,i),T={};for(const h of o){const n=h.model||"unknown";T[n]||(T[n]={requests:0,cost:0}),T[n].requests+=1,T[n].cost+=Number(h.total_cost)||0}const j=Object.entries(T).map(([h,n])=>({model:h,...n})).sort((h,n)=>n.requests-h.requests),$=((N=j[0])==null?void 0:N.model)||"N/A",v={};for(const h of o){const n=h.request_type||"content_generation";v[n]||(v[n]={cost:0,requests:0}),v[n].cost+=Number(h.total_cost)||0,v[n].requests+=1}const a=((k=v.image_generation)==null?void 0:k.cost)||0,_=((D=v.image_generation)==null?void 0:D.requests)||0,L=((A=v.image_prompt_generation)==null?void 0:A.cost)||0,F=c-a-L;return{cost:c,tokens:x,inputTokens:u,outputTokens:f,requests:C,images:b,topModel:$,modelUsage:j,imageCost:a,textCost:F,promptCost:L,imageRequests:_}},refetchIntervalInBackground:!1,refetchInterval:3e4})}function et(r){return G({queryKey:["admin-cost-trend",r],queryFn:async()=>{const o=Le(new Date,r==="daily"?7:r==="weekly"?14:r==="monthly"?30:90),m=await I("ai_usage_logs","created_at, total_cost, model",p=>p.gte("created_at",o.toISOString()).order("created_at",{ascending:!0})),d={};m.forEach(p=>{const i=Oe(new Date(p.created_at),r==="yearly"?"MMM":"MMM dd");d[i]||(d[i]={date:i,cost:0,requests:0}),d[i].cost+=Number(p.total_cost)||0,d[i].requests+=1});const c={};m.forEach(p=>{const i=p.model||"unknown",b=i.split("/").pop()||i;c[b]=(c[b]||0)+(Number(p.total_cost)||0)});const x=Object.entries(c).map(([p,i])=>({model:p,cost:i})).sort((p,i)=>i.cost-p.cost),u=Object.values(d),f=u.reduce((p,i)=>p+i.cost,0),C=u.length>0?f/u.length:0;return{trend:u,modelCostBreakdown:x,totalCost:f,avgDailyCost:C,totalRequests:m.length}},refetchIntervalInBackground:!1,refetchInterval:6e4})}function tt(){return G({queryKey:["admin-chart-data"],queryFn:async()=>{const r=new Date,l=[];for(let t=6;t>=0;t--){const o=new Date(r);o.setDate(o.getDate()-t);const m=me(o),d=new Date(m);d.setHours(23,59,59,999);const[c,x]=await Promise.all([S.from("jobs").select("id",{count:"exact",head:!0}).gte("created_at",m.toISOString()).lte("created_at",d.toISOString()),S.from("usage_tracking").select("user_id").gte("updated_at",m.toISOString()).lte("updated_at",d.toISOString())]),u=new Set((x.data||[]).map(f=>f.user_id)).size;l.push({name:m.toLocaleDateString("en-US",{weekday:"short"}),totalRequests:c.count||0,activeUsers:u})}return l},refetchIntervalInBackground:!1,refetchInterval:6e4})}function st(){return G({queryKey:["admin-generation-time-trend"],queryFn:async()=>{const r=new Date,l=new Date(r.getTime()-30*24*60*60*1e3),t=await I("jobs","created_at, updated_at, status",d=>d.eq("status","completed").gte("created_at",l.toISOString()).order("created_at",{ascending:!0}));if(t.length===0)return[];const o={};for(const d of t){const c=new Date(d.created_at).toISOString().split("T")[0],x=(new Date(d.updated_at).getTime()-new Date(d.created_at).getTime())/1e3;o[c]||(o[c]={totalTime:0,count:0}),o[c].totalTime+=x,o[c].count+=1}const m=[];for(let d=29;d>=0;d--){const c=new Date(r);c.setDate(c.getDate()-d);const x=c.toISOString().split("T")[0],u=o[x];m.push({date:c.toLocaleDateString("en-US",{month:"short",day:"numeric"}),avgTime:u?Math.round(u.totalTime/u.count):0,jobCount:(u==null?void 0:u.count)||0})}return m}
1,refetchIntervalInBackground:!1,refetchInterval:6e4})}function at(r){const l=new Date,t=new Date(l);if(r==="daily"&&t.setHours(0,0,0,0),r==="weekly"){const o=(t.getDay()+6)%7;t.setDate(t.getDate()-o),t.setHours(0,0,0,0)}return r==="monthly"&&(t.setDate(1),t.setHours(0,0,0,0)),r==="yearly"&&(t.setMonth(0,1),t.setHours(0,0,0,0)),t.toISOString()}const de=1e3,rt=new Set(["pro","business","agency","unlimited"]);async function Z(r,l,t,o){const m=[];for(let d=0;;d+=de){let c=S.from(r).select(l).range(d,d+de-1);t&&(c=c.gte("created_at",t)),o&&(c=c.lt("created_at",o));const{data:x,error:u}=await c;if(u)throw u;const f=x||[];if(m.push(...f),f.length<de)break}return m}function we(r){const l=r.trial_end_date||r.subscription_end_date;if(l)return new Date(l).getTime();const t=r.subscription_started_at||r.created_at;return new Date(t).getTime()+3*24*60*60*1e3}function w(r,l=null,t=!0){return{value:r,previous:l,available:t}}function U(r,l,t){return r.reduce((o,m)=>{if(!m.created_at)return o;const d=new Date(m.created_at).getTime();return d>=l&&d<t?o+1:o},0)}function it(r,l,t,o,m){const d=new Map,c=new Date(r);c.setHours(0,0,0,0);const x=new Date(l);for(x.setHours(0,0,0,0);c<=x;){const f=c.toISOString().slice(0,10);d.set(f,{date:f,signups:0,articles:0,errors:0,revenue:0,aiCost:0}),c.setDate(c.getDate()+1)}const u=(f,C)=>{if(!f.created_at)return;const p=new Date(f.created_at).toISOString().slice(0,10),i=d.get(p);i&&(i[C]+=1)};return t.forEach(f=>u(f,"signups")),o.forEach(f=>u(f,"articles")),m.forEach(f=>u(f,"errors")),Array.from(d.values())}async function ot(r,l){var n;const t=new Date(l),o=new Date(r),m=Math.max(t.getTime()-o.getTime(),60*60*1e3),d=new Date(o.getTime()-m),c=d.toISOString(),[x,u,f,C,p,i,b,T]=await Promise.all([Z("profiles","user_id,id,created_at,subscription_tier,subscription_status,subscription_end_date,subscription_started_at,trial_end_date,is_lifetime"),Z("articles","created_at",c,l),Z("jobs","created_at",c,l),Z("user_errors","created_at",c,l),Z("ai_usage_logs","created_at,total_tokens",c,l),S.from("email_tracking").select("id",{count:"exact",head:!0}).eq("event_type","sent").gte("created_at",r).lt("created_at",l),S.from("email_tracking").select("id",{count:"exact",head:!0}).eq("event_type","opened").gte("created_at",r).lt("created_at",l),S.from("email_tracking").select("id",{count:"exact",head:!0}).eq("event_type","clicked").gte("created_at",r).lt("created_at",l)]),$=(n=[i,b,T].find(s=>s.error))==null?void 0:n.error;if($)throw $;const v=Array.from(new Map(x.map(s=>[s.user_id||s.id,s])).values()),a=t.getTime(),_=v.filter(s=>["trial","trialing"].includes(s.subscription_status||"")&&we(s)>a).length,L=v.filter(s=>s.subscription_status==="trial_expired"||["trial","trialing"].includes(s.subscription_status||"")&&we(s)<=a).length,F=v.filter(s=>s.is_lifetime?!0:s.subscription_status!=="active"||!rt.has(s.subscription_tier||"")?!1:!s.subscription_end_date||new Date(s.subscription_end_date).getTime()>a).length,N=o.getTime(),k=t.getTime(),D=d.getTime(),A=p.filter(s=>{const g=new Date(s.created_at||0).getTime();return g>=N&&g<k}),h=p.filter(s=>{const g=new Date(s.created_at||0).getTime();return g>=D&&g<N});return{period:{start:r,end:l},metrics:{totalUsers:w(v.length),paidSubscriptions:w(F),activeTrials:w(_),expiredTrials:w(L),signups:w(U(v,N,k),U(v,D,N)),netRevenue:w(0,null,!1),churn:w(0,null,!1),articles:w(U(u,N,k),U(u,D,N)),jobs:w(U(f,N,k),U(f,D,N)),errors:w(U(C,N,k),U(C,D,N)),aiRequests:w(A.length,h.length),aiTokens:w(A.reduce((s,g)=>s+Number(g.total_tokens||0),0),h.reduce((s,g)=>s+Number(g.total_tokens||0),0)),aiCost:w(0,null,!1),emailSent:w(i.count||0),emailOpened:w(b.count||0),emailClicked:w(T.count||0)},series:it(o,t,v,u,C),as_of:new Date().toISOString(),source:"exact-operational-fallback",completeness:"complete",warnings:[]}}function nt(r){if(!r||typeof r!="object")return!1;const l=r;return l.code==="42501"||/admin access required|admin role required|permission denied/i.test(l.message||"")}function lt(r){return G({queryKey:["admin-dashboard-overview",r],queryFn:async()=>{const l=at(r),t=new Date().toISOString(),{data:o,error:m}
1=await S.rpc("admin_dashboard_overview",{p_start:l,p_end:t});if(!m&&o)return o;if(nt(m))throw m;return ot(l,t)},refetchInterval:5*60*1e3,refetchOnWindowFocus:!0})}function Y(r){return!r||r.available===!1||r.previous==null?null:r.previous===0?r.value===0?0:100:(r.value-r.previous)/Math.abs(r.previous)*100}const ct={daily:"Today",weekly:"This Week",monthly:"This Month",yearly:"This Year"},te=["hsl(var(--primary))","hsl(var(--primary) / 0.8)","hsl(var(--primary) / 0.6)","hsl(var(--primary) / 0.4)","hsl(var(--primary) / 0.2)"],se=["#22c55e","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#06b6d4"];function y({title:r,value:l,icon:t,loading:o,subtitle:m}){return e.jsx(q,{className:"bg-card border-border",children:e.jsx(O,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase tracking-wide truncate",children:r}),o?e.jsx(M,{className:"h-8 w-16 mt-1"}):e.jsx("p",{className:"text-2xl font-bold mt-1 truncate",children:l}),m&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:m})]}),e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0 ml-2",children:e.jsx(t,{className:"h-5 w-5 text-primary"})})]})})})}function Se({title:r,value:l,unit:t,loading:o}){return e.jsx(q,{className:"bg-card border-border",children:e.jsxs(O,{className:"p-6 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:r}),o?e.jsx(M,{className:"h-10 w-20 mx-auto"}):e.jsxs("div",{className:"flex items-baseline justify-center gap-1",children:[e.jsx("span",{className:"text-4xl font-bold",children:l}),e.jsx("span",{className:"text-muted-foreground",children:t})]})]})})}function R({title:r,metric:l,icon:t,format:o=c=>c.toLocaleString(),href:m,loading:d}){const c=Y(l),x=c!=null&&c>=0,u=(l==null?void 0:l.available)===!1;return e.jsx("a",{href:m,className:"block rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(q,{className:"h-full border-border transition-colors hover:border-primary/50",children:e.jsx(O,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:r}),d?e.jsx(M,{className:"mt-2 h-8 w-24"}):e.jsx("p",{className:"mt-1 text-2xl font-bold",children:u?"â":o((l==null?void 0:l.value)??0)}),u&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Awaiting reconciliation"}),c!=null&&e.jsxs("p",{className:`mt-1 flex items-center gap-1 text-xs ${x?"text-emerald-500":"text-rose-500"}`,children:[x?e.jsx(Ze,{className:"h-3 w-3"}):e.jsx(Ye,{className:"h-3 w-3"}),Math.abs(c).toFixed(1),"% vs previous period"]})]}),e.jsx("div",{className:"rounded-lg bg-primary/10 p-2 text-primary",children:e.jsx(t,{className:"h-5 w-5"})})]})})})})}function Ts(){var A,h,n;const[r,l]=Ce.useState("daily"),{data:t,isLoading:o,refetch:m,isFetching:d}=Xe(),{data:c,isLoading:x,refetch:u}=tt(),{data:f,isLoading:C,refetch:p}=st(),{data:i,isLoading:b,refetch:T}=Qe(r),{data:j,isLoading:$,refetch:v}=et(r),{data:a,isLoading:_,isError:L,refetch:F}=lt(r),N=()=>{m(),u(),p(),T(),v(),F()},k=ct[r],D=(()=>{if(!a)return[];const s=[],g=Y(a.metrics.errors),W=Y(a.metrics.churn),ae=Y(a.metrics.aiCost),re=Y(a.metrics.signups);return g!=null&&g>=25&&s.push({title:"Operational errors increased",detail:`Errors are ${g.toFixed(1)}% above the previous matching period (${a.metrics.errors.value} vs ${a.metrics.errors.previous}). Review the error queue and recent releases.`,severity:g>=100?"critical":"warning"}),W!=null&&W>=20&&s.push({title:"Churn requires attention",detail:`Churn events increased ${W.toFixed(1)}% (${a.metrics.churn.value} vs ${a.metrics.churn.previous}). Check failed renewals and cancellation reasons.`,severity:"warning"}),ae!=null&&ae>=25&&s.push({title:"AI spend is rising faster than baseline",detail:`System-paid AI cost increased ${ae.toFixed(1)}% to $${a.metrics.aiCost.value.toFixed(2)}. Drill into model and feature mix before changing budgets.`,severity:"warning"}),re!=null&&re<=-25&&s.push({title:"Signup volume declined",detail
1:`Signups are ${Math.abs(re).toFixed(1)}% below the previous matching period (${a.metrics.signups.value} vs ${a.metrics.signups.previous}). Validate acquisition tracking before acting.`,severity:"info"}),s.length===0&&s.push({title:"No material anomaly detected",detail:"The monitored signup, churn, error and AI-cost changes are within the current 25% review threshold.",severity:"info"}),s})();return e.jsx(De,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Admin Dashboard"}),e.jsx("p",{className:"text-muted-foreground",children:"Overview of system metrics and performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ae,{value:r,onValueChange:s=>l(s),children:[e.jsx(Re,{className:"w-36",children:e.jsx(Ie,{})}),e.jsxs(qe,{children:[e.jsx(V,{value:"daily",children:"Today"}),e.jsx(V,{value:"weekly",children:"This Week"}),e.jsx(V,{value:"monthly",children:"This Month"}),e.jsx(V,{value:"yearly",children:"This Year"})]})]}),e.jsxs(ue,{variant:"outline",size:"sm",onClick:N,disabled:d,children:[e.jsx(Ue,{className:`h-4 w-4 mr-2 ${d?"animate-spin":""}`}),"Refresh"]})]})]}),L&&e.jsxs("div",{className:"rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm",children:["Dashboard data could not be loaded. No fallback values are being shown as financial facts.",e.jsx(ue,{variant:"link",className:"h-auto px-2",onClick:()=>F(),children:"Retry"})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{className:"h-5 w-5 text-emerald-500"}),e.jsx("h2",{className:"font-semibold",children:(a==null?void 0:a.source)==="exact-operational-fallback"?"Operational overview":"Reconciled overview"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Source: ",(a==null?void 0:a.source)??"loading"," · As of ",a!=null&&a.as_of?new Date(a.as_of).toLocaleString():"â"]})]}),e.jsx(ie,{variant:(a==null?void 0:a.completeness)==="complete"?"default":"secondary",children:(a==null?void 0:a.completeness)??"loading"})]}),(A=a==null?void 0:a.warnings)==null?void 0:A.map(s=>e.jsx("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-300",children:s},s)),e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-6",children:[e.jsx(R,{title:"Users",metric:a==null?void 0:a.metrics.totalUsers,icon:oe,href:"/mts/users",loading:_}),e.jsx(R,{title:"Paid subscriptions",metric:a==null?void 0:a.metrics.paidSubscriptions,icon:he,href:"/mts/pro-users",loading:_}),e.jsx(R,{title:"Active trials",metric:a==null?void 0:a.metrics.activeTrials,icon:ge,href:"/mts/pro-users",loading:_}),e.jsx(R,{title:"Net revenue",metric:a==null?void 0:a.metrics.netRevenue,icon:z,href:"/mts/revenue",loading:_,format:s=>`$${s.toFixed(2)}`}),e.jsx(R,{title:"Churn events",metric:a==null?void 0:a.metrics.churn,icon:xe,href:"/mts/revenue",loading:_}),e.jsx(R,{title:"System errors",metric:a==null?void 0:a.metrics.errors,icon:fe,href:"/mts/errors",loading:_}),e.jsx(R,{title:"Signups",metric:a==null?void 0:a.metrics.signups,icon:oe,href:"/mts/analytics",loading:_}),e.jsx(R,{title:"Articles",metric:a==null?void 0:a.metrics.articles,icon:ne,href:"/mts/content",loading:_}),e.jsx(R,{title:"AI requests",metric:a==null?void 0:a.metrics.aiRequests,icon:X,href:"/mts/ai-usage",loading:_}),e.jsx(R,{title:"System AI cost",metric:a==null?void 0:a.metrics.aiCost,icon:z,href:"/mts/ai-costs",loading:_,format:s=>`$${s.toFixed(4)}`}),e.jsx(R,{title:"Email sent",metric:a==null?void 0:a.metrics.emailSent,icon:Q,href:"/mts/marketing",loading:_}),e.jsx(R,{title:"Expired trials",metric:a==null?void 0:a.metrics.expiredTrials,icon:pe,href:"/mts/pro-users",loading:_})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs(q,{className:"lg:col-span-2",children:[e.jsx(P,{children:e.jsx(E,{className:"text-base",children:"Business and operations trend"})}),e.jsx(O,{children:_?e.jsx(M,{className:"h-[260px] w-full"}):e.jsx(B,{width:"100%",height:260,children:e.jsxs(ye,{data:(a==null?void 0:a.series)??[],children:[e.jsx(ce,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(ee,{dataKey:"date",tick:{fontSize:11}}),e.jsx(H,{yAxisId:"count",tick:{fontSize:11}}),e.jsx(H,{yAxisId:"money",orientation:"right",tickFormatter:s=>`$${s}`,tick:{fontSize:11}}),e.jsx(K,{contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))"}}),e.jsx(le,{}),e.jsx(J,{yAxisId:"count",dataKey:"signups",name:"Signups",stroke:"#3b82f6",strokeWidth:2,dot:!1}),e.jsx(J,{yAxisId:"count",dataKey:"articles",name:"Articles",stroke:"#8b5cf6",strokeWidth:2,dot:!1}),e.jsx(J,{yAxisId:"count",dataKey:"errors",name:"Errors",stroke:"#ef4444",strokeWidth:2,dot:!1}),((h=a==null?void 0:a.metrics.netRevenue)==null?void 0:h.available)!==!1&&e.jsx(J,{yAxisId:"money",dataKey:"revenue",name:"Revenue",stroke:"#22c55e",strokeWidth:2,dot:!1})]})})})]}),e.jsxs(q,{children:[e.jsxs(P,{children:[e.jsxs(E,{className:"flex items-center gap-2 text-base",children:[e.jsx(Pe,{className:"h-5 w-5 text-primary"}),"AI Operations Insights"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Read-only anal
1ysis of aggregate metrics. It cannot execute actions."})]}),e.jsxs(O,{className:"space-y-3",children:[D.map(s=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"text-sm font-medium",children:s.title}),e.jsx(ie,{variant:s.severity==="critical"?"destructive":"secondary",children:s.severity})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:s.detail})]},s.title)),e.jsxs("a",{className:"flex items-center gap-1 text-xs text-primary hover:underline",href:"/mts/health",children:["Open system health ",e.jsx(Ee,{className:"h-3 w-3"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-medium text-muted-foreground mb-3 uppercase tracking-wide",children:"Operational counters"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4",children:[e.jsx(y,{title:"Total Users",value:(t==null?void 0:t.totalUsers)??0,icon:oe,loading:o}),e.jsx(y,{title:"Pro Users",value:(t==null?void 0:t.proUsers)??0,icon:he,loading:o}),e.jsx(y,{title:"Total Jobs",value:(t==null?void 0:t.totalJobs)??0,icon:Be,loading:o}),e.jsx(y,{title:"Total Articles",value:(t==null?void 0:t.totalArticles)??0,icon:ne,loading:o}),e.jsx(y,{title:"Active Jobs",value:(t==null?void 0:t.activeJobs)??0,icon:ve,loading:o}),e.jsx(y,{title:"Paused Jobs",value:(t==null?void 0:t.pausedJobs)??0,icon:Ke,loading:o}),((t==null?void 0:t.stuckProcessing)??0)>0&&e.jsx(y,{title:"Stuck Processing",value:(t==null?void 0:t.stuckProcessing)??0,icon:ve,loading:o})]})]}),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-sm font-medium text-muted-foreground mb-3 uppercase tracking-wide",children:["Activity (",k,")"]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4",children:[e.jsx(y,{title:"Jobs (24h)",value:(t==null?void 0:t.jobsLast24h)??0,icon:pe,loading:o}),e.jsx(y,{title:"Errors (24h)",value:(t==null?void 0:t.errorsLast24h)??0,icon:fe,loading:o}),e.jsx(y,{title:"AI Users",value:(t==null?void 0:t.aiUsers)??0,icon:X,loading:o}),e.jsx(y,{title:"Trial Limit Reached",value:(t==null?void 0:t.trialLimitReached)??0,icon:xe,loading:o}),e.jsx(y,{title:`Images (${k})`,value:(i==null?void 0:i.images)??0,icon:_e,loading:b}),e.jsx(y,{title:"AI Requests",value:(i==null?void 0:i.requests)??0,icon:Q,loading:b})]})]}),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-sm font-medium text-muted-foreground mb-3 uppercase tracking-wide",children:["AI Usage (",k,")"]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(y,{title:"Total Cost",value:`$${((i==null?void 0:i.cost)??0).toFixed(4)}`,icon:z,loading:b}),e.jsx(y,{title:"Text Cost",value:`$${((i==null?void 0:i.textCost)??0).toFixed(4)}`,icon:ne,loading:b}),e.jsx(y,{title:"Image Cost",value:`$${((i==null?void 0:i.imageCost)??0).toFixed(4)}`,icon:_e,loading:b,subtitle:`${(i==null?void 0:i.imageRequests)??0} generations`}),e.jsx(y,{title:"Monthly Cost",value:`$${((t==null?void 0:t.aiCostThisMonth)??0).toFixed(2)}`,icon:z,loading:o})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mt-4",children:[e.jsx(y,{title:"Total Tokens",value:((i==null?void 0:i.tokens)??0).toLocaleString(),icon:X,loading:b}),e.jsx(y,{title:"Input Tokens",value:((i==null?void 0:i.inputTokens)??0).toLocaleString(),icon:Je,loading:b}),e.jsx(y,{title:"Output Tokens",value:((i==null?void 0:i.outputTokens)??0).toLocaleString(),icon:Ge,loading:b}),e.jsx(y,{title:"Top Model",value:((n=i==null?void 0:i.topModel)==null?void 0:n.split("/").pop())??"N/A",icon:Q,loading:b})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(Se,{title:"Average Generation Time",value:(t==null?void 0:t.avgGenerationTime)??0,unit:"sec",loading:o}),e.jsx(Se,{title:"Average Attainment Rate",value:(t==null?void 0:t.avgAttainmentRate)??0,unit:"%",loading:o})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(q,{className:"bg-card border-border",children:[e.jsx(P,{children:e.jsxs(E,{className:"flex items-center gap-2",children:[e.jsx(X,{className:"h-5 w-5"}),"AI Usage (Last 7 Days)"]})}),e.jsx(O,{children:x?e.jsx(M,{className:"h-[300px] w-full"}):e.jsx(B,{width:"100%",height:300,children:e.jsxs(We,{data:c||[],children:[e.jsx(ee,{dataKey:"name",stroke:"hsl(var(--muted-foreground))"}),e.jsx(H,{stroke:"hsl(var(--muted-foreground))"}),e.jsx(K,{contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(le,{}),e.jsx(je,{dataKey:"totalRequests",name:"Total Requests",fill:"hsl(var(--primary))",radius:[4,4,0,0]}),e.jsx(je,{dataKey:"activeUsers",name:"Active Users",fill:"hsl(var(--primary) / 0.5)",radius:[4,4,0,0]})]})})})]}),e.jsxs(q,{className:"bg-card border-border",children:[e.jsx(P,{children:e.jsxs(E,{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"h-5 w-5"}),"Model Usage (",k,")"]})}),e.jsx(O,{children:b?e.jsx(M,{className:"h-[300px] w-full"}):i!=null&&i.modelUsage&&i.modelUsage.length>0?e.jsxs("div",{className:"flex flex-col lg:flex-row gap-4",children:[e.jsx("div",{className:"flex-1",children:e.jsx(B,{width:"100%",height:200,children:e.jsxs(ke,{children:[e.jsx(Ne,{data:i.modelUsage.slice(0,5),dataKey:"requests",nameKey:"model",cx:"50%",cy:"50%",outerRadius:80,label:({name:s,percent:g})=>`${(g*100).toFixed(0)}%`,labelLine:!1,children:i.modelUsage.slice(0,5).map((s,g)=>e.jsx(be,{fill:te[g%te.length]},`cell-${g}`))}),e.jsx(K,{contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"},formatter:(s,g)=>[`${s} requests`,g]})]})})}),e.jsx("div",{className:"flex-1 space-y-2",children:i.modelUsage.slice(0,5).map((s,g)=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:te[g%te.length]}}),e.jsx("span",{className:"truncate",children:s.model})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(ie,{variant:"secondary",children:s.requests}),e.jsxs("span",{className:"text-muted-foreground",children:["$",s.cost.toFixed(4)]})]})]},s.model))})]}):e.jsx("div",{className:"h-[200px] flex items-center justify-center text-muted-foreground",children:"No model usage data for this period"})})]}),e.jsxs(q,{className:"bg-card border-border lg:col-span-2",children:[e.jsx(P,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-2",children:[e.jsxs(E,{className:"flex items-center gap-2",children:[e.jsx(z,{className:"h-5 w-5"}),"AI Cost Analytics (",k,")"]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Total:"}),e.jsxs("span",{className:"font-bold ml-1 text-primary",children:["$",((j==null?void 0:j.totalCost)??0).toFixed(4)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg/Day:"}),e.jsxs("span",{className:"font-bold ml-1",children:["$",((j==null?void 0:j.avgDailyCost)??0).toFixed(4)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Requests:"}),e.jsx("span",{className:"font-bold ml-1",children:(j==null?void 0:j.totalRequests)??0})]})]})]})}),e.jsx(O,{children:$?e.jsx(M,{className:"h-[280px] w-full"}):e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsx(B,{width:"100%",height:280,children:e.jsxs(ze,{data:(j==null?void 0:j.trend)||[],children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"costGradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",
1stopColor:"hsl(var(--primary))",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"hsl(var(--primary))",stopOpacity:0})]})}),e.jsx(ce,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(ee,{dataKey:"date",stroke:"hsl(var(--muted-foreground))",tick:{fontSize:11}}),e.jsx(H,{stroke:"hsl(var(--muted-foreground))",tickFormatter:s=>`$${s.toFixed(3)}`,tick:{fontSize:11}}),e.jsx(K,{formatter:s=>[`$${s.toFixed(6)}`,"Cost"],contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(He,{type:"monotone",dataKey:"cost",stroke:"hsl(var(--primary))",fill:"url(#costGradient)",strokeWidth:2})]})})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-3 text-center",children:"Cost by Model"}),j!=null&&j.modelCostBreakdown&&j.modelCostBreakdown.length>0?e.jsxs(e.Fragment,{children:[e.jsx(B,{width:"100%",height:160,children:e.jsxs(ke,{children:[e.jsx(Ne,{data:j.modelCostBreakdown.slice(0,6),dataKey:"cost",nameKey:"model",cx:"50%",cy:"50%",innerRadius:35,outerRadius:60,label:({percent:s})=>`${(s*100).toFixed(0)}%`,labelLine:!1,children:j.modelCostBreakdown.slice(0,6).map((s,g)=>e.jsx(be,{fill:se[g%se.length]},`cost-cell-${g}`))}),e.jsx(K,{formatter:s=>[`$${s.toFixed(4)}`,"Cost"],contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}})]})}),e.jsx("div",{className:"mt-2 space-y-1",children:j.modelCostBreakdown.slice(0,5).map((s,g)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 truncate",children:[e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:se[g%se.length]}}),e.jsx("span",{className:"truncate",children:s.model})]}),e.jsxs("span",{className:"font-medium shrink-0",children:["$",s.cost.toFixed(4)]})]},s.model))})]}):e.jsx("div",{className:"h-[160px] flex items-center justify-center text-muted-foreground text-sm",children:"No cost data for this period"})]})]})})]}),e.jsxs(q,{className:"bg-card border-border lg:col-span-2",children:[e.jsx(P,{children:e.jsxs(E,{className:"flex items-center gap-2",children:[e.jsx(ge,{className:"h-5 w-5"}),"Generation Time Trend (Last 30 Days)"]})}),e.jsx(O,{children:C?e.jsx(M,{className:"h-[300px] w-full"}):e.jsx(B,{width:"100%",height:300,children:e.jsxs(ye,{data:f||[],children:[e.jsx(ce,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(ee,{dataKey:"date",stroke:"hsl(var(--muted-foreground))",tick:{fontSize:11},interval:"preserveStartEnd"}),e.jsx(H,{stroke:"hsl(var(--muted-foreground))",tickFormatter:s=>`${s}s`}),e.jsx(K,{contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"},formatter:(s,g)=>[g==="avgTime"?`${s}s`:s,g==="avgTime"?"Avg Time":"Jobs"]}),e.jsx(le,{}),e.jsx(J,{type:"monotone",dataKey:"avgTime",name:"Avg Time (sec)",stroke:"hsl(var(--primary))",strokeWidth:2,dot:{fill:"hsl(var(--primary))",strokeWidth:0,r:3},activeDot:{r:5}}),e.jsx(J,{type:"monotone",dataKey:"jobCount",name:"Jobs Completed",stroke:"hsl(var(--muted-foreground))",strokeWidth:1,strokeDasharray:"4 4",dot:!1})]})})})]})]})]})})}export{Ts 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.