PageSourceSearch

https://www.underpriced.app/assets/AdminPanel-D-NKNPuH.js

js underpriced.app collected 2026-09-24 13:02:40 UTC 334,670 bytes, 20 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-DtY4eCf0.js","assets/vendor-react-_Neh0V1j.js"])))=>i.map(i=>d[i]);
2import{u as xn,C as Ue,_ as mn,j as e}from"./index-DwVNqoeI.js";import{r as i,b as Oa,R as Qs}from"./vendor-react-_Neh0V1j.js";import{s as pn}from"./fileExport-CJZL483N.js";import{z as Ba,a as hn,g as _a}from"./alignedDealOverview-Dx5Pc0ei.js";import{s as bn}from"./stripeMoney-DhaW1d56.js";import{bT as qa,X as ht,U as Ge,M as Ut,l as Va,a2 as Ys,bN as Cs,k as st,b as es,a3 as mt,aa as bs,a6 as Fs,i as za,bU as Rt,O as Pe,Z as pt,w as At,v as Ha,ac as gs,bV as Fe,L as H,q as Ga,d as gn,aI as wa,p as fn,_ as yn,C as jn,bO as Wa,ae as Nn,f as at,af as Ca,a5 as Os,a7 as vn,u as Bs,Y as Ka,aN as fs,aJ as Ja,a8 as wn,bW as Cn,b6 as Xs,ah as Sn,n as Re,E as Xt,$ as An,D as kn,a4 as Ss,al as $n,o as Za,bD as Qa,c as xt,g as _s,S as En,ak as In,bX as Rn,V as Zt,aD as Pn,ab as Un,bY as _t,H as Tn}from"./vendor-lucide-B_zWGxDE.js";import"./api-jWBHdGmS.js";import{g as Dn,F as Mn}from"./FlipperItemCard-Dzjir7Pz.js";import{D as ys,q as js}from"./listingDraftsConfig-DX7v3J5a.js";import"./platformUtils-U0I6pZtn.js";import{B as Ln}from"./BarcodeResultCard-Cz7yOL6t.js";import"./economicsContract-B_Xdd9Nj.js";import"./pricingMath-Butp0AXX.js";const Fn=()=>{const{user:t}=xn(),s=i.useCallback(async(n=!1)=>{try{return t?await t.getIdToken(n):null}catch{if(!n)return null;try{return await t.getIdToken(!1)}catch{return null}}},[t]);return{user:t,getAuthToken:s}},On=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",Bn=t=>{const[s,n]=i.useState(null),[a,d]=i.useState(!0),[p,r]=i.useState(""),u=i.useCallback(async(f=!1)=>{try{const c=await t(!1);if(!c)return r("Authentication required"),!1;const N=`${On}/admin?action=stats${f?"&force=true":""}`;let b=await fetch(N,{headers:{Authorization:`Bearer ${c}`}});if(b.status===401||b.status===403){const x=await t(!0);x&&x!==c&&(b=await fetch(N,{headers:{Authorization:`Bearer ${x}`}}))}if(!b.ok){const x=await b.json().catch(()=>({}));return r((x==null?void 0:x.error)||"Failed to load admin stats"),!1}const m=await b.json();return n(m),r(""),!0}catch(c){return r(c.message||"Failed to load admin stats"),!1}finally{d(!1)}},[t]);return i.useMemo(()=>
2({stats:s,loading:a,setLoading:d,error:p,fetchStats:u}),[s,a,p,u])},qs="underpriced:admin-notify",Vs="underpriced:admin-confirm";let Qt=0;function _n(){return Qt+=1,()=>{Qt=Math.max(0,Qt-1)}}function K(t,s={}){const n=typeof t=="object"?t:{message:t,...s};if(typeof window=="undefined"||Qt===0){const a=n.tone==="error"?"error":"log";console[a](`[Admin] ${n.title||""} ${n.message||""}`.trim());return}window.dispatchEvent(new CustomEvent(qs,{detail:n}))}function Qe(t){const s=typeof t=="string"?{message:t}:t;return typeof window=="undefined"||Qt===0?(console.error("[Admin] Confirmation requested without AdminFeedbackProvider"),Promise.resolve(!1)):new Promise(n=>{window.dispatchEvent(new CustomEvent(Vs,{detail:{...s,resolve:n}}))})}async function Ve(t,s,n=""){const a=await pn(t,s);return K(`${a.message}${a.status!=="cancelled"&&n?` ${n}`:""}`,{title:"Export",tone:a.status==="saved"?"success":"info"}),a}const Ya=["Prompt Origin","Prompt Version","Starter ID","Starter Edited","Follow-Up Message ID","Follow-Up Index","Response Prompt Version"],Xa=t=>{var s;return[t.promptOrigin||"unknown",t.promptVersion||"",t.starterId||"",t.starterEdited===!0?"true":t.starterEdited===!1?"false":"",t.followUpMessageId||"",(s=t.followUpIndex)!=null?s:"",t.responsePromptVersion||""]};function ne(t){if(t==null)return"";let s=String(t);return/^[=+\-@\t\r]/.test(s)&&(s=`'${s}`),/[",\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function Ns(t){if(!t)return"";const s=new Date(t);return Number.isNaN(s.getTime())?"":s.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function Tt(t,s){return[t.map(ne).join(","),...s.map(n=>n.map(ne).join(","))].join(`
3`)}function en(t){return Array.isArray(t)?t.filter(Boolean).join(`
4`):""}function qn(t){var s,n,a,d,p,r;return[t.id||"",t.userId||"",t.userEmail||"",t.userName||"",t.title||"",t.messageCount||0,t.lastMode||"",Ns(t.createdAt),Ns(t.lastMessageAt),t.totalCreditsUsed||0,t.lastIntent||"",t.lastSource||"",(s=t.avgLatencyMs)!=null?s:"",(n=t.safetyRedirects)!=null?n:"",(a=t.responseTruncations)!=null?a:"",(d=t.actionFollowUpRate)!=null?d:"",(p=t.totalRatings)!=null?p:"",(r=t.helpfulRate)!=null?r:"",t.preview||""]}function Vn(t=[]){const s=["Conversation ID","User ID","User Email","User Name","Conversation Title","Conversation Messages","Conversation Last Mode","Conversation Created At","Conversation Last Message At","Conversation Total Credits Used","Conversation Last Intent","Conversation Last Source","Conversation Avg Latency Ms","Conversation Safety Redirects","Conversation Response Truncations","Conversation Action Follow-Up Rate","Conversation Total Ratings","Conversation Helpful Rate","Conversation Preview","Message #","Message ID","Message Role","Message Text","Message Mode","Message Credits Used","Message Category","Message Intent","Message Source","Message Latency Ms","Message Safety Redirected","Message Response Truncated","Message Action Follow-Up Count","Message Finish Reason","Message Rating","Message Rating Feedback","Message Saved","Message Timestamp","AI Follow-Up Suggestions",...Ya],n=t.flatMap(a=>{const d=Array.isArray(a.messages)?a.messages:[],p=qn(a),r=s.length-p.length;return d.length===0?[[...p,...Array(r).fill("")]]:d.map((u,f)=>{var c,N,b;return[...p,f+1,u.id||"",u.role||"",u.text||"",u.mode||"",(c=u.creditsUsed)!=null?c:"",u.category||"",u.intent||"",u.source||"",(N=u.latencyMs)!=null?N:"",u.safetyRedirected===!0?"true":u.safetyRedirected===!1?"false":"",u.responseTruncated===!0?"true":u.responseTruncated===!1?"false":"",(b=u.actionFollowUpCount)!=null?b:"",u.finishReason||"",u.rating||"",u.ratingFeedback||"",u.saved===!0?"true":u.saved===!1?"false":"",Ns(u.timestamp),en(u.followUpSuggestions),...Xa(u)]})});return Tt(s,n)}function zn(t){const s=["Message #","Message ID","Role","Text","Mode","Credits Used","Category","Intent","Source","Latency Ms","Safety Redirected","Response Truncated","Action Follow-Up Count","Finish Reason","Rating","Rating Feedback","Saved","Timestamp","AI Follow-Up Suggestions",...Ya],a=(Array.isArray(t==null?void 0:t.messages)?t.messages:[]).map((d,p)=>{var r,u,f;return[p+1,d.id||"",d.role||"",d.text||"",d.mode||"",(r=d.creditsUsed)!=null?r:"",d.category||"",d.intent||"",d.source||"",(u=d.latencyMs)!=null?u:"",d.safetyRedirected===!0?"true":d.safetyRedirected===!1?"false":"",d.responseTruncated===!0?"true":d.responseTruncated===!1?"false":"",(f=d.actionFollowUpCount)!=null?f:"",d.finishReason||"",d.rating||"",d.ratingFeedback||"",d.saved===!0?"true":d.saved===!1?"false":"",Ns(d.timestamp),en(d.followUpSuggestions),...Xa(d)]});return Tt(s,a)}function Hn(t={}){var d,p,r,u,f,c,N,b,m,x,j,R,o,y,$,P,E,l;const s=t.analytics||{},n=["Section","Name","Value","Detail"],a=[["Summary","Analytics Version",(d=t.analyticsVersion)!=null?d:1,t.metricBasis||""],["Summary","Complete",t.complete===!0?"true":"false",(t.incompleteReasons||[]).join(" | ")],["Summary","As Of",t.asOf||"",t.coverageStart?`Coverage starts ${t.coverageStart}`:""],["Summary","Days",(p=t.days)!=null?p:"",t.since?`Since ${t.since}`:""],["Summary","User Filter",t.userId||"All users",""],["Summary",t.sampled?"Sampled Conversations":"Scanned Turns",t.sampled?(r=t.sampledConversations)!=null?r:"":(u=t.scannedTurns)!=null?u:"",t.sampled?`Query limit ${(f=t.queryLimit)!=null?f:""}`:"Immutable turn events"],["Summary","Total Conversations",(c=s.totalConversations)!=null?c:"",""],["Summary","Active Users",(N=s.activeUsers)!=null?N:"",""],["Summary","AI Turns",(b=s.totalTurns)!=null?b:"",""],["Summary","Messages",(m=s.totalMessages)!=null?m:"",""],["Summary","Credits Used",(x=s.totalCreditsUsed)!=null?x:"",""],["Summary","Average Latency Ms",(j=s.avgLatencyMs)!=null?j:"",""],["Summary","Support Rate",(R=s.supportRate)!=null?R:"","Share of tracked AI turns routed to product support"],["Summary","Safety Redirect Rate",(o=s.safetyRedirectRate)!=null?o:"","Share of tracked AI turns rewritten by safety validator"],["Summary","Response Truncation Rate",(y=s.responseTruncationRate)!=null?y:"","Share of tracked AI turns shortened by validator"],["Summary","Action Follow-Up Rate",($=s.actionFollowUpRate)!=null?$:"","Action-shaped follow-ups divided by all follow-ups"],["Summary","Pro Share",(P=s.proShare)!=null?P:"","Share of tracked AI turns in Pro mode"],["Summary","Total Ratings",(E=s.totalRatings)!=null?E:"","Thumb ratings captured in FlipExpert answers"],["Summary","Helpful Rate",(l=s.helpfulRate)!=null?l:"","Thumbs-up ratings divi
4ded by all ratings"]];for(const S of s.topIntents||[])a.push(["Intent",S.key,S.value,"Tracked AI turns"]);for(const S of s.topCategories||[])a.push(["Category",S.key,S.value,"Model response categories"]);for(const S of s.modeBreakdown||[])a.push(["Mode",S.key,S.value,"Fast vs Pro mix"]);for(const S of s.sourceBreakdown||[])a.push(["Source",S.key,S.value,"Client surface"]);for(const S of s.ratingBreakdown||[])a.push(["Rating",S.key,S.value,"Thumb feedback"]);for(const S of s.qualityFlags||[])a.push(["Quality Flag",S,"1","Needs review"]);for(const S of s.recentConversations||[])a.push(["Recent Conversation",S.title||S.id||"",S.lastIntent||"",[S.userEmail||S.userId||"",S.lastMode?`mode=${S.lastMode}`:"",S.lastSource?`source=${S.lastSource}`:"",S.lastLatencyMs?`latencyMs=${S.lastLatencyMs}`:"",typeof S.helpfulRate=="number"?`helpfulRate=${S.helpfulRate}`:"",S.lastMessageAt||""].filter(Boolean).join(" | ")]);return Tt(n,a)}function It(t="admin"){var n,a;const s=((a=(n=globalThis.crypto)==null?void 0:n.randomUUID)==null?void 0:a.call(n))||`${Date.now()}_${Math.random().toString(36).slice(2,12)}`;return`${t}_${s}`.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,128)}function tt(t,s="Admin operation failed"){const n=(t==null?void 0:t.error)||(t==null?void 0:t.message)||s,a=t!=null&&t.operationId?` (operation ${t.operationId})`:"",d=new Error(`${n}${a}`);return d.code=(t==null?void 0:t.code)||null,d.operationId=(t==null?void 0:t.operationId)||null,d.state=(t==null?void 0:t.state)||null,d.partial=(t==null?void 0:t.partial)===!0,d}function zs(t){if(typeof t!="string"||!t.trim())return!1;try{const s=new URL(t.trim());return s.protocol==="https:"||s.protocol==="http:"}catch{return!1}}const Le=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",Hs=3,$s=t=>t===!0?"true":t===!1?"false":"",dt=(t,s)=>{var n,a;return(a=(n=t==null?void 0:t.analysisContentMetrics)==null?void 0:n[s])!=null?a:""};function Gn(t){const s=String(t||"").trim();return s.length>0&&s.length<Hs&&!s.includes("@")}const Wn=t=>{const[s,n]=i.useState([]),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState(null),[c,N]=i.useState(null),[b,m]=i.useState(""),[x,j]=i.useState(!1),[R,o]=i.useState(!1),[y,$]=i.useState(!1),[P,E]=i.useState(null),[,l]=i.useState(null),S=i.useRef(null),A=i.useRef(0),g=i.useRef(0),h=i.useRef(null),C=i.useRef(null),U=i.useRef(null),[k,I]=i.useState(""),[O,Z]=i.useState(""),[D,ee]=i.useState(""),[V,X]=i.useState(!1),[ae,q]=i.useState(""),[te,w]=i.useState(""),[v,M]=i.useState(""),[_,B]=i.useState(!1),[J,re]=i.useState(""),[F,se]=i.useState(""),[ye,oe]=i.useState(!1),[be,ge]=i.useState(""),[ce,Se]=i.useState(""),[Ie,Oe]=i.useState(!1),[bt,We]=i.useState(!1),[le,gt]=i.useState(""),[Te,Ae]=i.useState(""),[De,nt]=i.useState(""),[rt,it]=i.useState(!1),[Ye,lt]=i.useState(!1),ve=i.useCallback(async(W="",Y=!1,z=!1)=>{var de;const Q=++A.current,T=String(W||"").trim();h.current&&h.current.abort();const ie=typeof AbortController!="undefined"?new AbortController:null;h.current=ie,d(!0),r("");try{if(Y||(l(null),S.current=null),!Y&&Gn(T)){n([]),$(!1),E({query:T,searchTooShort:!0,minBroadSearchChars:Hs});return}const he=await t(!1);if(!he)throw new Error("Authentication required");const Me=new URLSearchParams;Me.set("action","users"),Me.set("limit","50"),T&&Me.set("search",T),z&&Me.set("force","true"),Y&&S.current&&Me.set("startAfter",S.current),Me.set("_t",Date.now());const $t=await fetch(`${Le}/admin?${Me.toString()}`,{headers:{Authorization:`Bearer ${he}`},...ie?{signal:ie.signal}:{}});if(!$t.ok){const G=await $t.json().catch(()=>({}));throw new Error((G==null?void 0:G.error)||"Failed to fetch users")}const we=await $t.json();if(Q!==A.current)return;n(Y?(G=>{const je=new Set(G.map(ct=>ct.uid));return[...G,...(we.users||[]).filter(ct=>(ct==null?void 0:ct.uid)&&!je.has(ct.uid))]}):we.users||[]),$(!!we.hasMore),l(we.lastDoc||null),S.current=we.lastDoc||null,E({query:we.query||T,total:(de=we.total)!=null?de:null,source:we.source||null,searchTooShort:!!we.searchTooShort,minBroadSearchChars:we.minBroadSearchChars||Hs})}catch(he){if(Q!==A.current||(he==null?void 0:he.name)==="AbortError")return;console.error("Fetch users error:",he),r(he.message||"Failed to fetch users")}finally{Q===A.current&&(d(!1),h.current===ie&&(h.current=null))}},[t]),Ce=i.useCallback(async W=>{const Y=++g.current;C.current&&C.current.abort(),U.current&&(U.current.abort(),U.current=null);const z=typeof AbortController!="undefined"?new AbortController:null;C.current=z,j(!0),o(!1),m("");try{const Q=await t(!1);if(!Q)throw new Error("Authentication required");const T=new URLSearchParams;T.set("action","user"),T.set("uid",W),T.set("light","true"),T.set("_t",Date.now());const ie=await fetch(`${Le}/admin?${T.toString()}`,{headers:{Authorization:`Bearer ${Q}`,"Cache-Control":"no-cache"}
4,...z?{signal:z.signal}:{}});if(!ie.ok){const we=await ie.json().catch(()=>({}));throw tt(we,`Failed to fetch details for ${W}`)}const de=await ie.json();if(Y!==g.current)return;N(de),m(""),j(!1),C.current===z&&(C.current=null);const he=typeof AbortController!="undefined"?new AbortController:null;U.current=he,o(!0);const Me=new URLSearchParams;Me.set("action","user-metrics"),Me.set("uid",W),Me.set("_t",Date.now()),(async()=>{try{const we=await fetch(`${Le}/admin?${Me.toString()}`,{headers:{Authorization:`Bearer ${Q}`,"Cache-Control":"no-cache"},...he?{signal:he.signal}:{}});if(!we.ok)throw new Error("Failed to fetch user detail metrics");const G=await we.json();if(Y!==g.current)return;N(je=>(je==null?void 0:je.uid)===W?{...je,...G,metricsPending:!1,metricsError:""}:je)}catch(we){if(Y!==g.current||(we==null?void 0:we.name)==="AbortError")return;console.error("User detail metrics error:",we),N(G=>(G==null?void 0:G.uid)===W?{...G,metricsPending:!1,metricsError:we.message||"Failed to load user detail metrics"}:G)}finally{Y===g.current&&(o(!1),U.current===he&&(U.current=null))}})()}catch(Q){if(Y!==g.current||(Q==null?void 0:Q.name)==="AbortError")return;console.error("User details error:",Q),m(Q.message||`Failed to fetch details for ${W}`)}finally{Y===g.current&&(j(!1),C.current===z&&(C.current=null))}},[t]),ft=i.useCallback(()=>{g.current+=1,C.current&&(C.current.abort(),C.current=null),U.current&&(U.current.abort(),U.current=null),j(!1),o(!1),m(""),N(null)},[]),Dt=i.useCallback(async()=>{var Q,T;if(!u||!O||!D)return;const W=Number(O);if(!Number.isSafeInteger(W)||W===0){K("Credit adjustment must be a non-zero whole number.",{tone:"error"});return}const Y=Number((T=(Q=c==null?void 0:c.bonusCredits)!=null?Q:c==null?void 0:c.extraAnalyses)!=null?T:0);if(await Qe({title:"Confirm credit adjustment",message:`${W>0?"Add":"Remove"} ${Math.abs(W)} credits for this account?`,detail:`Current balance: ${Y}. Expected balance: ${Y+W}. Reason: ${D}
4`,confirmLabel:"Apply adjustment",destructive:W<0,...W<0||Math.abs(W)>=1e3?{requiredText:`ADJUST ${W}`}:{}})){X(!0);try{const ie=await t(!1);if(!ie)throw new Error("Authentication required");const de=await fetch(`${Le}/admin?action=adjust-credits`,{method:"POST",headers:{Authorization:`Bearer ${ie}`,"Content-Type":"application/json"},body:JSON.stringify({targetUid:u,amount:W,reason:D})}),he=await de.json();if(!de.ok){K(he.error||"Paid top-up failed",{tone:"error"});return}K(`New balance: ${he.newBalance} credits`,{title:"Credits updated",tone:"success"}),Z(""),ee(""),Ce(u),ve(k)}catch(ie){K(ie.message,{title:"Paid top-up failed",tone:"error"})}finally{X(!1)}}},[u,O,D,c,t,Ce,ve,k]),yt=i.useCallback(async()=>{if(!u||!ae||!te)return;const W=Number(ae);if(!Number.isSafeInteger(W)||W<=0){K("Enter a positive whole-number credit amount.",{tone:"error"});return}if(await Qe({title:"Confirm paid credit top-up",message:`Add ${W} paid extra analyses to this user?`,detail:`Stripe invoice: ${te.trim()}. The paid invoice total will be verified with Stripe.`,confirmLabel:"Verify and add credits"})){B(!0);try{const z=await t(!1);if(!z)throw new Error("Authentication required");const Q=await fetch(`${Le}/admin?action=paid-top-up`,{method:"POST",headers:{Authorization:`Bearer ${z}`,"Content-Type":"application/json"},body:JSON.stringify({targetUid:u,credits:W,stripeInvoiceId:te.trim(),note:v.trim()})}),T=await Q.json();if(!Q.ok){K(T.error||"Credit adjustment failed",{tone:"error"});return}K(`Added ${T.credits} paid extra analyses. New balance: ${T.newBalance}.`,{title:"Paid credits added",tone:"success"}),q(""),w(""),M(""),await Ce(u),ve(k)}catch(z){K(z.message,{title:"Credit adjustment failed",tone:"error"})}finally{B(!1)}}},[u,ae,te,v,t,Ce,ve,k]),ts=i.useCallback(async()=>{if(!u||!J||!F)return;let W=!1;const Y=!!(c!=null&&c.stripeSubscriptionId)&&(c==null?void 0:c.subscriptionStatus)!=="admin_granted";if(Y&&J!=="free"){K("This is a Stripe-managed subscriber. Change paid plans through the billing flow or Stripe Dashboard.",{tone:"error"});return}if(Y&&J==="free"&&(W=await Qe({title:"Cancel paid subscription?",message:"This will cancel the active Stripe subscription immediately and move the user to Free.",detail:`Account: ${(c==null?void 0:c.email)||u}. Reason: ${F}`,confirmLabel:"Cancel subscription",destructive:!0}),!W))return;oe(!0);const z=It("subscription");try{const Q=await t(!1);if(!Q)throw new Error("Authentication required");const T=await fetch(`${Le}/admin?action=change-subscription`,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({targetUid:u,tier:J,reason:F,cancelStripeSubscription:W,operationId:z,expectedPreviousTier:(c==null?void 0:c.subscriptionTier)||"free"})}),ie=await T.json();if(!T.ok)throw tt(ie,"Failed to change subscription");K(`${ie.message||`Changed to ${ie.newTier} tier (was ${ie.previousTier}).`}${ie.warning?` Warning: ${ie.warning}`:""}`,{title:"Subscription updated",tone:ie.warning?"info":"success",operationId:z}),re(""),se(""),await Ce(u),ve(k)}catch(Q){K(Q.message,{title:"Subscription update failed",tone:"error",operationId:Q.operationId||z})}finally{oe(!1)}},[u,J,F,c,t,Ce,ve,k]),ss=i.useCallback(async()=>{if(!u||!be||!ce)return;Oe(!0);const W=It("subscription_status");try{const Y=await t(!1);if(!Y)throw new Error("Authentication required");const z=await fetch(`${Le}/admin?action=set-subscription-status`,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({targetUid:u,status:be,reason:ce,operationId:W,expectedPreviousStatus:(c==null?void 0:c.subscriptionStatus)||"none"})}),Q=await z.json();if(!z.ok)throw tt(Q,"Failed to change subscription status");K(`Status changed to ${Q.newStatus} (was ${Q.previousStatus}).`,{title:"Subscription status updated",tone:"success",operationId:W}),ge(""),Se(""),await Ce(u),ve(k)}catch(Y){K(Y.message,{title:"Status update failed",tone:"error",operationId:Y.operationId||W})}finally{Oe(!1)}},[u,be,ce,c,t,Ce,ve,k]),jt=i.useCallback(async(W,Y="")=>{if(!u||!W||!await Qe({title:"Confirm live status change",message:`Set this live account's subscription status to ${W}
4?`,detail:`Current status: ${(c==null?void 0:c.subscriptionStatus)||"none"}. Account: ${(c==null?void 0:c.email)||u}.`,confirmLabel:`Set ${W}`,destructive:["canceled","past_due","unpaid"].includes(W)}))return;Oe(!0);const Q=Y||`Admin QA quick toggle: ${W}`,T=It("subscription_status");try{const ie=await t(!1);if(!ie)throw new Error("Authentication required");const de=await fetch(`${Le}/admin?action=set-subscription-status`,{method:"POST",headers:{Authorization:`Bearer ${ie}`,"Content-Type":"application/json"},body:JSON.stringify({targetUid:u,status:W,reason:Q,operationId:T,expectedPreviousStatus:(c==null?void 0:c.subscriptionStatus)||"none"})}),he=await de.json();if(!de.ok)throw tt(he,"Failed to change subscription status");K(`Status changed to ${he.newStatus} (was ${he.previousStatus}).`,{title:"Subscription status updated",tone:"success",operationId:T}),ge(""),Se(""),await Ce(u),ve(k)}catch(ie){K(ie.message,{title:"Status update failed",tone:"error",operationId:ie.operationId||T})}finally{Oe(!1)}},[u,c,t,Ce,ve,k]),ot=i.useCallback(async W=>{if(!u||!c)return;const Y=`Are you sure you want to DELETE user "${c.displayName||c.email||"Anonymous"}"?
5
6This will permanently remove:
7- User profile and authentication
8- All nested user data, transactions, and analysis history
9- Marketing contact
10- Any attached active Stripe subscription (it will be canceled first)
11
12This action cannot be undone!`;if(!await Qe({title:"Permanently delete user?",message:Y,detail:`Target UID: ${u}. A durable operation record will track cleanup and reconciliation.`,confirmLabel:"Permanently delete",destructive:!0,requiredText:`DELETE ${u}`}))return;We(!0);const Q=It("delete_user");try{const T=await t(!1);if(!T)throw new Error("Authentication required");const ie=await fetch(`${Le}/admin?action=delete-user`,{method:"POST",headers:{Authorization:`Bearer ${T}`,"Content-Type":"application/json"},body:JSON.stringify({targetUid:u,operationId:Q})}),de=await ie.json();if(!ie.ok)throw tt(de,"Failed to delete user");K("User data, authentication, billing, and marketing cleanup completed.",{title:"User deleted",tone:"success",operationId:Q}),f(null),N(null),ve(k),W&&W()}catch(T){K(T.message,{title:"User deletion needs attention",tone:"error",operationId:T.operationId||Q,duration:12e3})}finally{We(!1)}},[u,c,t,ve,k]),as=i.useCallback(async()=>{var Y;if(!u)return;if(le&&Te&&Te<le){K("End date must be on or after start date.",{tone:"error"});return}if(De){const z=Number.parseInt(De,10);if(!Number.isFinite(z)||z<1||z>5e3){K("Export limit must be between 1 and 5,000.",{tone:"error"});return}}lt(!0);const W=await t();if(!W){lt(!1);return}try{const z=new URLSearchParams({userId:u,exportVersion:"2",timeZone:"UTC"});le&&z.append("startDate",le),Te&&z.append("endDate",Te),De&&parseInt(De)>0&&z.append("limit",De);const Q=await fetch(`${Le}/admin?action=export-user-history&${z.toString()}`,{headers:{Authorization:`Bearer ${W}`}});if(!Q.ok){const G=await Q.json().catch(()=>({}));throw new Error(G.error||"Export failed")}const T=await Q.json();if(((Y=T.manifest)==null?void 0:Y.complete)===!1){const G=(T.manifest.failedSources||[]).map(je=>je.source).join(", ");throw new Error(`Export was incomplete because required history readers failed${G?`: ${G}`:""}. No file was downloaded.`)}if(!T.analyses||T.analyses.length===0){K("No analysis history found for this user.",{tone:"info"});return}const ie=["Date","Title","Identified As","Category","Analytics Category ID","Analytics Category","Condition","Source Price","Market Value","Profit","Saved Deal Score","Saved Deal Tier","Current Score","Current Tier","Profitability Known","Profitability Basis","Analysis Mode","Price Known","Value Only","Score Meaning","Source Price Analytics","Profit Analytics","ROI Analytics","Current Margin Label","Current Recommendation","Confidence","Source Type","Platform","Images","Items","Item Analysis Count","Avg Analysis Words","Avg Analysis Chars","Max Analysis Words","Max Analysis Chars","Long Analyses","Analysis Outliers","Notes"],de=T.analyses.map(G=>{var aa,na,ra,ia,la,oa,ca,da,ua,xa,ma,pa,ha,ba,ga,fa,ya,ja,Na,va;const je=Ba(G),ct=typeof G.category=="object"?((aa=G.category)==null?void 0:aa.label)||"":G.category||"",un=je.profitabilityKnown?(ra=(na=G.estimatedProfitForAnalytics)!=null?na:je.calc.netProfit)!=null?ra:0:"";return[G.timestamp?new Date(G.timestamp).toISOString().replace("T"," ").replace(/\.\d+Z$/,""):"",G.title,G.identifiedAs||"",ct,G.categoryAnalyticsId||"",G.categoryAnalyticsLabel||"",G.condition||"",(ia=G.priceVal)!=null?ia:0,(la=G.marketVal)!=null?la:0,un,G.dealScore,G.dealTier,(oa=je.currentScore)!=null?oa:"",(ca=je.currentTierKey)!=null?ca:"",$s(je.profitabilityKnown),je.profitabilityBasis||G.profitabilityBasis||"",((da=je.semantics)==null?void 0:da.analysisMode)||G.anal
12ysisMode||"",$s((xa=(ua=je.semantics)==null?void 0:ua.priceKnown)!=null?xa:G.priceKnown),$s((ma=je.isValueOnly)!=null?ma:G.valueOnly),((pa=je.semantics)==null?void 0:pa.dealScoreMeaning)||G.dealScoreMeaning||"",(ga=(ba=(ha=je.semantics)==null?void 0:ha.sourcePriceForAnalytics)!=null?ba:G.sourcePriceForAnalytics)!=null?ga:"",(fa=G.estimatedProfitForAnalytics)!=null?fa:"",(Na=(ja=(ya=je.semantics)==null?void 0:ya.roiForAnalytics)!=null?ja:G.roiForAnalytics)!=null?Na:"",je.marginMeta.label,je.recommendation.headline,(va=G.confidence)!=null?va:"",G.sourceType||"thrift",G.platform||"web",G.imageCount||0,G.itemCount||dt(G,"itemCount")||0,dt(G,"itemAnalysisCount"),dt(G,"avgItemAnalysisWords"),dt(G,"avgItemAnalysisChars"),dt(G,"maxItemAnalysisWords"),dt(G,"maxItemAnalysisChars"),dt(G,"longItemAnalysisCount"),dt(G,"itemAnalysisOutlierCount"),G.reason||""]}),he=Tt(ie,de),Me=new Blob([he],{type:"text/csv;charset=utf-8;"}),$t=T.userEmail&&T.userEmail!=="No email"?T.userEmail.replace(/[^a-zA-Z0-9@._-]/g,"_"):u,we=new Date().toISOString().split("T")[0];await Ve(Me,`analysis_history_${$t}_${we}.csv`,`${T.analyses.length} analyses for ${T.userName||"user"}${T.truncated?" (maximum 5,000 rows reached)":""}.`)}catch(z){K(z.message,{title:"Export failed",tone:"error"})}finally{lt(!1)}},[u,le,Te,De,t]),[kt,Nt]=i.useState(!1),[ke,Xe]=i.useState(null),[ns,Mt]=i.useState(!1),[Lt,vt]=i.useState(null),Ft=i.useCallback(async()=>{const W=await t();if(W){Nt(!0),Xe(null);try{const Y=await fetch(`${Le}/admin?action=repair-profiles`,{method:"POST",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"},body:JSON.stringify({mode:"dry-run",repairTypes:["identity","root","credits"]})}),z=await Y.json();if(!Y.ok)throw new Error(z.error||"Repair failed");Xe(z)}catch(Y){Xe({error:Y.message})}finally{Nt(!1)}}},[t]),Ot=i.useCallback(async W=>{if(!(ke!=null&&ke.planId)||!(ke!=null&&ke.planHash))return;const Y=await t();if(!Y)return;const z=It("profile_repair");Nt(!0);try{let Q="running",T=0;for(;Q!=="complete"&&T<1e4;){const ie=await fetch(`${Le}/admin?action=repair-profiles`,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({mode:"apply",planId:ke.planId,planHash:ke.planHash,operationId:z,confirmation:W})}),de=await ie.json().catch(()=>({}));if(!ie.ok)throw tt(de,"Repair apply failed");Q=de.state,Xe({...ke,...de,operationId:z}),T+=1}if(Q!=="complete")throw new Error("Repair stopped before completion; use the operation ID to reconcile it");await ve("",!1,!0)}catch(Q){Xe(T=>({...T||ke,error:Q.message,operationId:z}))}finally{Nt(!1)}},[ve,t,ke]),Bt=i.useCallback(async()=>{const W=await t();if(W){Mt(!0),vt(null);try{const Y=await fetch(`${Le}/admin?action=repair-annual-credit-cycles`,{method:"POST",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"},body:JSON.stringify({mode:"dry-run"})}),z=await Y.json().catch(()=>({}));if(!Y.ok)throw tt(z,"Annual credit audit failed");if(vt(z),!z.complete)throw new Error("The annual credit audit was incomplete. Resolve the listed Stripe lookup or ownership issue before applying repairs.");if(z.candidateCount===0){K(`Checked ${z.annualSubscribers} annual subscriber${z.annualSubscribers===1?"":"s"}; every monthly credit cycle is current.`,{title:"Annual credit audit complete",tone:"success"});return}const Q=(z.candidates||[]).slice(0,5).map(he=>`${he.email||he.uid}: ${he.needsReset?`${he.previousUsage} usage will reset`:"cycle metadata backfill"}`).join("; ");if(!await Qe({title:"Repair annual credit cycles",message:`Repair ${z.candidateCount} annual subscriber account${z.candidateCount===1?"":"s"}
12?`,detail:`${z.resetCount} usage reset${z.resetCount===1?"":"s"} and ${z.backfillOnlyCount} metadata-only backfill${z.backfillOnlyCount===1?"":"s"}. ${Q}`,confirmLabel:"Apply annual repairs",requiredText:`REPAIR ${z.candidateCount}`}))return;const ie=await fetch(`${Le}/admin?action=repair-annual-credit-cycles`,{method:"POST",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"},body:JSON.stringify({mode:"apply",planHash:z.planHash,confirmation:`REPAIR ${z.candidateCount}`})}),de=await ie.json().catch(()=>({}));if(!ie.ok)throw tt(de,"Annual credit repair failed");vt(de),de.failedCount>0?K(`${de.repairedCount} repaired and ${de.failedCount} failed. Review the audit result before retrying.`,{title:"Annual repair partially completed",tone:"error"}):K(`${de.repairedCount} annual account${de.repairedCount===1?"":"s"} repaired; ${de.resetAppliedCount} monthly usage reset${de.resetAppliedCount===1?"":"s"} applied.`,{title:"Annual credit repair complete",tone:"success"}),await ve(k,!1,!0),u&&await Ce(u)}catch(Y){vt(z=>({...z||{},error:Y.message})),K(Y.message,{title:"Annual credit repair failed",tone:"error"})}finally{Mt(!1)}}},[Ce,ve,t,k,u]);return i.useMemo(()=>({users:s,loadingUsers:a,usersError:p,selectedUser:u,userDetails:c,userDetailsError:b,loadingDetails:x,loadingDetailsMetrics:R,hasMore:y,usersLookupMeta:P,searchQuery:k,adjustAmount:O,adjustReason:D,adjusting:V,topUpCredits:ae,topUpInvoiceId:te,topUpNote:v,topUpSubmitting:_,selectedTier:J,tierChangeReason:F,changingTier:ye,selectedSubscriptionStatus:be,statusChangeReason:ce,changingSubscriptionStatus:Ie,deleting:bt,exportStartDate:le,exportEndDate:Te,exportLimit:De,showExportOptions:rt,exportingHistory:Ye,setSelectedUser:f,setUserDetails:N,clearUserDetails:ft,setSearchQuery:I,setAdjustAmount:Z,setAdjustReason:ee,setTopUpCredits:q,setTopUpInvoiceId:w,setTopUpNote:M,setSelectedTier:re,setTierChangeReason:se,setSelectedSubscriptionStatus:ge,setStatusChangeReason:Se,setExportStartDate:gt,setExportEndDate:Ae,setExportLimit:nt,setShowExportOptions:it,fetchUsers:ve,fetchUserDetails:Ce,handleAdjustCredits:Dt,handlePaidTopUp:yt,handleChangeTier:ts,handleChangeSubscriptionStatus:ss,handleQuickSetSubscriptionStatus:jt,handleDeleteUser:ot,handleExportUserHistory:as,repairProfiles:Ft,applyRepairPlan:Ot,repairing:kt,repairResult:ke,repairAnnualCreditCycles:Bt,repairingAnnualCycles:ns,annualCycleRepairResult:Lt}),[s,a,p,u,c,b,x,R,y,P,k,O,D,V,ae,te,v,_,J,F,ye,be,ce,Ie,bt,le,Te,De,rt,Ye,f,N,I,Z,ee,re,q,w,M,se,ge,Se,gt,Ae,nt,it,ft,ve,Ce,Dt,yt,ts,ss,jt,ot,as,Ft,Ot,kt,ke,Bt,ns,Lt])},qt=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",Kn=t=>{const[s,n]=i.useState([]),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState(null),[c,N]=i.useState(!1),[b,m]=i.useState("all"),[x,j]=i.useState(null),[R,o]=i.useState(null),[y,$]=i.useState(null),[P,E]=i.useState(!1),[l,S]=i.useState(!1),[A,g]=i.useState(!1),[h,C]=i.useState(""),[U,k]=i.useState(!1),I=i.useRef(0),O=i.useCallback(async(v={})=>{var J,re;const M=v.append===!0,_=(J=v.filter)!=null?J:b,B=M?(re=v.cursor)!=null?re:y:null;if(!(M&&!B)){M?S(!0):d(!0),r("");try{const F=await t(!1);if(!F)throw new Error("Authentication required");const se=new URLSearchParams({action:"tickets",limit:"50",includeCounts:M?"0":"1"});_!=="all"&&se.set("status",_),B&&se.set("startAfter",B);const ye=await fetch(`${qt}/admin?${se.toString()}`,{headers:{Authorization:`Bearer ${F}`}});if(!ye.ok){const ce=await ye.json().catch(()=>({}));throw new Error((ce==null?void 0:ce.error)||"Failed to fetch tickets")}const oe=await ye.json(),be=oe.tickets||[],ge=!M||oe.cursorReset===!0;n(ce=>{if(ge)return be;const Se=new Set(ce.map(Ie=>Ie.id));return[...ce,...be.filter(Ie=>!Se.has(Ie.id))]}),$(oe.nextCursor||null),E(!!(oe.hasMore&&oe.nextCursor)),oe.statusCounts&&j(oe.statusCounts),oe.cursorReset&&r("Ticket results changed while paging, so the list was refreshed from the beginning."),f(ce=>{if(!ce)return null;const Se=be.find(Ie=>Ie.id===ce.id);return Se?{...ce,...Se,attachment:ce.attachment||null}:ce})}catch(F){console.error("Fetch tickets error:",F),r(F.message||"Failed to fetch tickets")}finally{M?S(!1):d(!1)}}},[t,y,b]),Z=i.useCallback(v=>{m(v),$(null),E(!1),O({filter:v,append:!1})},[O]),D=i.useCallback(()=>O({append:!0}),[O]),ee=i.useCallback(async()=>{try{const v=await t(!1);if(!v)return;const M=await fetch(`${qt}/admin?action=ticket-count`,{headers:{Authorization:`Bearer ${v}`}});if(!M.ok)return;const _=await M.json();j(B=>({...B||{},new:Number(_.newTicketCount||0),in_progress:Math.max(0,Number(_.openTicketCount||0)-Number(_.newTicketCount||0))})),o(_.ticketCountAsOf||null)}catch(v){console.warn("Ticket count refresh failed:",v)}},[t]),V=i.useCallback(async v=>{if(!(v!=null&&v.id))return;const M=++I.current;f(v),N(!0);try{const _=await t(!1);if(!_)throw new Error("Authentication required");const B=new URLSearchParams({action:"ticket",ticketId:v.id}),J=await fetch(`${qt}/admin?${B.toString()}`,{headers:{Authorization:`Bearer ${_}`}}),re=await J.json().catch(()=>({}));if(!J.ok)throw new Error((re==null?void 0:re.error)||"Failed to fetch ticket details");if(M!==I.current)return;
12f(re.ticket||v)}catch(_){if(M!==I.current)return;r(_.message||"Failed to fetch ticket details")}finally{M===I.current&&N(!1)}},[t]),X=i.useCallback(async(v,M)=>{g(!0);const _=await t();if(!_){g(!1);return}try{const B=await fetch(`${qt}/admin?action=update-ticket`,{method:"POST",headers:{Authorization:`Bearer ${_}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:v,status:M})}),J=await B.json().catch(()=>({}));if(!B.ok)throw new Error((J==null?void 0:J.error)||"Failed to update ticket");await Promise.all([O({filter:b}),ee()])}catch(B){r(B.message||"Failed to update ticket")}finally{g(!1)}},[t,O,ee,b]),ae=i.useCallback(async()=>{if(!u||!h.trim())return;k(!0);const v=await t();if(!v){k(!1);return}try{const M=await fetch(`${qt}/admin?action=respond-ticket`,{method:"POST",headers:{Authorization:`Bearer ${v}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:u.id,response:h.trim(),strictLength:!0})}),_=await M.json().catch(()=>({}));if(!M.ok)throw new Error((_==null?void 0:_.error)||"Failed to send response");C(""),await Promise.all([O({filter:b}),ee()])}catch(M){r(M.message||"Failed to send response")}finally{k(!1)}},[u,h,t,O,ee,b]),q=i.useCallback(()=>s.filter(v=>b==="all"||v.status===b),[s,b]),te=i.useCallback(()=>Number.isFinite(x==null?void 0:x.new)?x.new:s.filter(v=>v.status==="new").length,[x,s]),w=i.useCallback(()=>Number.isFinite(x==null?void 0:x.new)&&Number.isFinite(x==null?void 0:x.in_progress)?x.new+x.in_progress:s.filter(v=>v.status==="new"||v.status==="in_progress").length,[x,s]);return i.useMemo(()=>({tickets:s,loadingTickets:a,ticketsError:p,selectedTicket:u,loadingTicketDetails:c,ticketFilter:b,ticketCounts:x,ticketCountAsOf:R,nextTicketCursor:y,hasMoreTickets:P,loadingMoreTickets:l,updatingTicket:A,ticketResponse:h,sendingResponse:U,setSelectedTicket:f,setTicketFilter:Z,setTicketResponse:C,fetchTickets:O,fetchTicketCount:ee,loadMoreTickets:D,handleSelectTicket:V,handleUpdateTicket:X,handleSendTicketResponse:ae,getFilteredTickets:q,getNewTicketCount:te,getOpenTicketCount:w}),[s,a,p,u,c,b,x,R,y,P,l,A,h,U,f,Z,C,O,ee,D,V,X,ae,q,te,w])},rs=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",Jn=t=>{const[s,n]=i.useState([]),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState(!1),[c,N]=i.useState(!1),[b,m]=i.useState(null),[x,j]=i.useState({id:null,code:"",type:"percent_off",value:"",description:"",maxUses:"",maxUsesPerUser:"1",validFrom:"",validUntil:"",firstPurchaseOnly:!1,active:!0,applicablePackages:[],minPackage:"",expectedUpdatedAt:""}),R=i.useCallback(()=>{j({id:null,code:"",type:"percent_off",value:"",description:"",maxUses:"",maxUsesPerUser:"1",validFrom:"",validUntil:"",firstPurchaseOnly:!1,active:!0,applicablePackages:[],minPackage:"",expectedUpdatedAt:""})},[]),o=i.useCallback(async()=>{d(!0),r("");try{const l=await t(!1);if(!l)throw new Error("Authentication required");const S=await fetch(`${rs}/promo?action=list`,{headers:{Authorization:`Bearer ${l}`}}),A=await S.json().catch(()=>({}));if(!S.ok)throw new Error((A==null?void 0:A.error)||"Failed to fetch promos");n(A.promos||[])}catch(l){console.error("Fetch promos error:",l),r(l.message||"Failed to fetch promos")}finally{d(!1)}},[t]),y=i.useCallback(async l=>{l.preventDefault(),N(!0),r("");try{const S=await t(!1);if(!S)throw new Error("Authentication required");const A={promoId:x.id||void 0,code:x.code,type:x.type,value:x.type==="free"?100:x.value!==""?Number(x.value):void 0,description:x.description||"",maxUses:x.maxUses!==""?parseInt(x.maxUses,10):null,maxUsesPerUser:x.maxUsesPerUser!==""?parseInt(x.maxUsesPerUser,10):1,validFrom:x.validFrom||null,validUntil:x.validUntil||null,firstPurchaseOnly:!!x.firstPurchaseOnly,active:x.active!==!1,applicablePackages:x.applicablePackages.length>0?x.applicablePackages:null,minPackage:x.minPackage||null,expectedUpdatedAt:x.expectedUpdatedAt||void 0};if(!A.code||A.code.trim().length<3)throw new Error("Promo code must be at least 3 characters");if(!x.id&&x.type!=="free"&&(A.value===void 0||Number.isNaN(A.value)))throw new Error("Promo value is required");const g=x.id?"update":"create",h=await fetch(`${rs}/promo?action=${g}`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify(A)});if(!h.ok){const C=await h.json();throw new Error(C.error||"Failed to save promo")}R(),f(!1),await o()}catch(S){r(S.message||"Failed to save promo")}finally{N(!1)}},[x,t,o,R]),$=i.useCallback(async(l,S)=>{m(l),r("");try{const A=await t(!1);if(!A)throw new Error("Authentication required");const g=S?"archive":"restore",h=await fetch(`${rs}/promo?action=${g}`,{method:"POST",headers:{Authorization:`Bearer ${A}`,"Content-Type":"application/json"},body:JSON.stringify({promoId:l})}),C=await h.json().catch(()=>({}));if(!h.ok)throw new Error((C==null?void 0:C.error)||`Failed to ${g} promo`);await o()}catch(A){r(A.message||"Failed to change promo status")}finally{m(null)}},[o,t]),P=i.useCallback(async l=>{if(await Qe({title:"Permanently delete promo draft?",message:"Only an unused, unreferenced promo can be permanently deleted. Referenced promos must be archived.",detail:`Promo ID: ${l}`,confirmLabel:"Delete draft",destructive:!0,requiredText:"DELETE"})){m(l);try{const A=await t(!1);if(!A)throw new Error("Authentication required");const g=await fetch(`${rs}/promo?action=delete`,{method:"POST",headers:{Authorization:`Bearer ${A}`,"Content-Type":"application/json"},body:JSON.stringify({promoId:l})}),h=await g.json().catch(()=>({}));if(!g.ok)throw new Error((h==null?void 0:h.error)||"Failed to delete promo");await o()}catch(A){r(A.message||"Failed to delete promo")}finally{m(null)}}},[t,o]),E=i.useCallback(l=>{var S,A;j({id:l.id,code:l.code,type:l.type||"percent_off",value:l.value.toString(),description:l.description||"",maxUses:((S=l.maxUses)==null?void 0:S.toString())||"",maxUsesPerUser:((A=l.maxUsesPerUser)==null?void 0:A.toString())||"1",validFrom:l.validFrom?new Date(l.validFrom).toISOString().split("T")[0]:"",validUntil:l.validUntil?new Date(l.validUntil).toISOString().split("T")[0]:"",firstPurchaseOnly:l.firstPurchaseOnly||!1,active:l.active!==!1,applicablePackages:Array.isArray(l.applicablePackages)?l.applicablePackages:[],minPackage:l.minPackage||"",expectedUpdatedAt:l.updatedAt||""}),f(!0)},[]);return i.useMemo(()=>({promos:s,loadingPromos:a,promosError:p,showPromoForm:u,savingPromo:c,deletingPromoId:b,promoForm:x,setShowPromoForm:f,setPromoForm:j,fetchPromos:o,savePromo:y,deletePromo:P,setPromoArchived:$,editPromo:E,resetPromoForm:R}),[s,a,p,u,c,b,x,f,j,o,y,P,$,E,R])},is=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",Es=t=>t===!0?"true":t===!1?"false":"",ut=(t,s)=>{var n,a;return(a=(n=t==null?void 0:t.analysisContentMetrics)==null?void 0:n[s])!=null?a:""},Zn=t=>{const[s,n]=i.useState([]),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState(""),[c,N]=i.useState(!1),[b,m]=i.useState(1),x=i.useRef([null]),j=i.useRef(0),[R,o]=i.useState(null),[y,$]=i.useState(null),[P,E]=i.useState(null),[l,S]=i.useState(""),[A,g]=i.useState(""),[h,C]=i.useState(""),[U,k]=i.useState(!1),[I,O]=i.useState("number"),Z=i.useCallback(async(X="reset",ae)=>
12{var te;if(a&&X!=="reset")return;const q=++j.current;d(!0),r(""),X==="reset"&&(n([]),m(1),N(!1));try{const w=await t(!1);if(!w)throw new Error("Authentication required");if(q!==j.current)return;const v=b-1,M=X==="next"?v+1:X==="previous"?Math.max(0,v-1):0;if(X==="next"&&!x.current[M])return;X==="reset"&&(x.current=[null]);const _=new URLSearchParams({exportVersion:"2",timeZone:"UTC"});_.set("action","analyses"),_.set("limit","10");const B=((te=ae!=null?ae:u)!=null?te:"").trim();B&&_.set("userId",B);const J=x.current[M];J&&_.set("startAfter",J);let re=await fetch(`${is}/admin?${_.toString()}`,{headers:{Authorization:`Bearer ${w}`}});if(re.status===401||re.status===403){const se=await t(!0);se&&(re=await fetch(`${is}/admin?${_.toString()}`,{headers:{Authorization:`Bearer ${se}`}}))}const F=await re.json().catch(()=>({}));if(!re.ok)throw new Error((F==null?void 0:F.error)||"Failed to fetch analyses");if(q!==j.current)return;n(F.analyses||[]),N(!!F.hasMore),m(M+1),x.current[M+1]=F.lastDoc||null,x.current=x.current.slice(0,M+2)}catch(w){if(q!==j.current)return;console.error("Fetch analyses error:",w),r(w.message||"Failed to fetch analyses")}finally{q===j.current&&d(!1)}},[t,u,b,a]),D=i.useCallback(async X=>{if(!(X!=null&&X.docPath)){o(X||null);return}$(X.id),r("");try{const ae=await t(!1);if(!ae)throw new Error("Authentication required");const q=new URLSearchParams({action:"analysis",path:X.docPath}),te=await fetch(`${is}/admin?${q.toString()}`,{headers:{Authorization:`Bearer ${ae}`}}),w=await te.json().catch(()=>({}));if(!te.ok)throw new Error((w==null?void 0:w.error)||"Failed to fetch analysis details");o(w.analysis||X)}catch(ae){r(ae.message||"Failed to fetch analysis details")}finally{$(null)}},[t]),ee=i.useCallback(async()=>{var ae;k(!0);const X=await t();if(!X){k(!1),K("Authentication failed. Please refresh and try again.",{tone:"error"});return}try{const q=new URLSearchParams({exportVersion:"2",timeZone:"UTC",dateMode:"calendar-day"});if(I==="number"&&h&&parseInt(h)>0?q.append("limit",h):I==="date"&&l?(q.append("startDate",l),q.append("endDate",l)):I==="dateRange"&&(l&&q.append("startDate",l),A&&q.append("endDate",A)),I==="number"&&(!h||parseInt(h)<=0)){K("Please enter a valid number of analyses to export.",{tone:"error"}),k(!1);return}if(I==="number"&&parseInt(h,10)>5e3){K("A single export is limited to 5,000 analyses.",{tone:"error"}),k(!1);return}if(I==="date"&&!l){K("Please select a date.",{tone:"error"}),k(!1);return}if(I==="dateRange"&&!l&&!A){K("Please select at least one date for the range.",{tone:"error"}),k(!1);return}if(l&&A&&A<l){K("End date must be on or after start date.",{tone:"error"}),k(!1);return}const te=await fetch(`${is}/admin-analyses-export?${q.toString()}`,{headers:{Authorization:`Bearer ${X}`}});if(!te.ok){const F=await te.json().catch(()=>({}));throw new Error(F.error||"Export failed")}const w=await te.json();if(((ae=w.manifest)==null?void 0:ae.complete)===!1){const F=(w.manifest.failedSources||[]).map(se=>se.source).join(", ");throw new Error(`Export was incomplete because required history indexes/readers failed${F?`: ${F}`:""}. No file was downloaded.`)}if(!w.analyses||w.analyses.length===0){k(!1),K("No analyses found matching your filters.",{tone:"info"});return}const v=["Date","User ID","User Email","Title","Identified As","Category","Analytics Category ID","Analytics Category","Condition","Source Price","Market Value","Profit","Saved Deal Score","Profitability Known","Profitability Basis","Analysis Mode","Price Known","Value Only","Score Meaning","Source Price Analytics","Profit Analytics","ROI Analytics","Saved Deal Tier","Current Score","Current Tier","Current Margin Label","Current Recommendation","Confidence","Source Type","Platform","Images","Items","Item Analysis Count","Avg Analysis Words","Avg Analysis Chars","Max Analysis Words","Max Analysis Chars","Long Analyses","Analysis Outliers","Notes"],M=w.analyses.map(F=>{var be,ge,ce,Se,Ie,Oe,bt,We,le,gt,Te,Ae,De,nt,rt,it,Ye,lt,ve,Ce;const se=Ba(F),ye=typeof F.category=="object"?((be=F.category)==null?void 0:be.label)||"":F.category||"",oe=se.profitabilityKnown?(ce=(ge=F.estimatedProfitForAnalytics)!=null?ge:se.calc.netProfit)!=null?ce:0:"";return[F.timestamp?new Date(F.timestamp).toISOString().replace("T"," ").replace(/\.\d+Z$/,""):"",F.userId||"",F.userEmail||"",F.title,F.identifiedAs||"",ye,F.categoryAnalyticsId||"",F.categoryAnalyticsLabel||"",F.condition||"",(Se=F.priceVal)!=null?Se:0,(Ie=F.marketVal)!=null?Ie:0,oe,F.dealScore,Es(se.profitabilityKnown),se.profitabilityBasis||F.profitabilityBasis||"",((Oe=se.semantics)==null?void 0:Oe.analysisMode)||F.analysisMode||"",Es((We=(bt=se.semantics)==null?void 0:bt.priceKnown)!=null?We:F.priceKnown),Es((le=se.isValueOnly)!=null?le:F.valueOnly),((gt=se.semantics)==null?void 0:gt.dealScoreMeaning)||F.dealScoreMeaning||"",(De=(Ae=(Te=se.semantics)==null?void 0:Te.sourcePriceForAnalytics)!=null?Ae:F.sourcePriceForAnalytics)!=null?De:"",(nt=F.estimatedProfitForAnalytics)!=null?nt:"",(Ye=(it=(rt=se.semantics)==null?void 0:rt.roiForAnalytics)!=null?it:F.roiForAnalytics)!=null?Ye:"",F.dealTier,(lt=se.currentScore)!=null?lt:"",(ve=se.currentTierKey)!=null?ve:"",se.marginMeta.label,se.recommendation.headline,(Ce=F.confidence)!=null?Ce:"",F.sourceType,F.platform,F.imageCount||0,F.itemCount||ut(F,"itemCount")||0,ut(F,"itemAnalysisCount"),ut(F,"avgItemAnalysisWords"),ut(F,"avgItemAnalysisChars"),ut(F,"maxItemAnalysisWords"),ut(F,"maxItemAnalysisChars"),ut(F,"longItemAnalysisCount"),ut(F,"itemAnalysisOutlierCount"),F.reason||""]}),_=Tt(v,M),B=new Blob([_],{type:"text/csv;charset=utf-8;"}),J=new Date().toISOString().split("T")[0];let re=`all_analyses_${J}.csv`;I==="number"?re=`all_analyses_recent_${h}_${J}.csv`:I==="date"?re=`all_analyses_${l}.csv`:I==="dateRange"&&(re=`all_analyses_${l||"start"}_to_${A||"end"}.csv`),await Ve(B,re,`${w.analyses.length} analyses from ${w.userCount||"multiple"} users${w.truncated?" (maximum 5,000 rows reached)":""}.`)}catch(q){K(q.message,{title:"Export failed",tone:"error"})}finally{k(!1)}},[t,I,h,l,A]),V=i.useCallback(()=>{f("")},[]);return i.useMemo(()=>({analyses:s,loadingAnalyses:a,analysesError:p,analysesFilter:u,analysesHasMore:c,analysesPage:b,selectedAnalysis:R,loadingAnalysisId:y,lightboxImage:P,allExportStartDate:l,allExportEndDate:A,allExportLimit:h,exportingAllAnalyses:U,allExportFilterType:I,setAnalysesFilter:f,setSelectedAnalysis:o,set
12LightboxImage:E,setAllExportStartDate:S,setAllExportEndDate:g,setAllExportLimit:C,setAllExportFilterType:O,fetchAnalyses:Z,fetchAnalysisDetail:D,handleExportAllAnalyses:ee,clearAnalysesFilter:V}),[s,a,p,u,c,b,R,y,P,l,A,h,U,I,f,o,E,S,g,C,O,Z,D,ee,V])},Sa=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api";function Is(t){if(!t)return"";const s=new Date(t);return Number.isNaN(s.getTime())?"":s.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function Qn(t){return Array.isArray(t==null?void 0:t.platforms)&&t.platforms.length>0?t.platforms:Array.isArray(t==null?void 0:t.platformDrafts)?t.platformDrafts.map(s=>s.platform).filter(Boolean):[]}function Yn(t){return Array.isArray(t==null?void 0:t.platformDrafts)&&t.platformDrafts.find(s=>(s==null?void 0:s.title)||(s==null?void 0:s.description))||null}const Xn=t=>{const[s,n]=i.useState([]),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState(""),[c,N]=i.useState("all"),[b,m]=i.useState(!1),[x,j]=i.useState(null),[R,o]=i.useState(null),[y,$]=i.useState(!1),[P,E]=i.useState(null),l=i.useRef(null),S=i.useCallback(async(h=!1,C,U)=>{var k;if(!(h&&!l.current)){d(!0),r("");try{const I=await t(!1);if(!I)throw new Error("Authentication required");const O=new URLSearchParams;O.set("action","listing-drafts"),O.set("limit","25");const Z=((k=C!=null?C:u)!=null?k:"").trim(),D=U!=null?U:c;Z&&O.set("userId",Z),D&&D!=="all"&&O.set("status",D),h&&l.current&&O.set("startAfter",l.current);const ee=await fetch(`${Sa}/admin?${O.toString()}`,{headers:{Authorization:`Bearer ${I}`}}),V=await ee.json().catch(()=>({}));if(!ee.ok)throw new Error((V==null?void 0:V.error)||"Failed to fetch listing drafts");n(h?X=>{const ae=new Set(X.map(q=>`${q.userId}:${q.id}`));return[...X,...(V.drafts||[]).filter(q=>!ae.has(`${q.userId}:${q.id}`))]}:V.drafts||[]),m(!!V.hasMore),j(V.stats||null),l.current=V.lastDoc||null}catch(I){console.error("Fetch listing drafts error:",I),r(I.message||"Failed to fetch listing drafts")}finally{d(!1)}}},[t,u,c]),A=i.useCallback(async()=>{$(!0),E({rows:0,pages:0});try{const h=await t(!1);if(!h)throw new Error("Authentication required");const C=(u||"").trim(),U=[],k=new Set;let I=null,O=!0,Z=0;for(;O;){if(Z>=500)throw new Error("Export safety limit reached after 50,000 rows");const q=new URLSearchParams({action:"listing-drafts",limit:"100",export:"true"});C&&q.set("userId",C),c!=="all"&&q.set("status",c),I&&q.set("startAfter",I);const te=await fetch(`${Sa}/admin?${q.toString()}`,{headers:{Authorization:`Bearer ${h}`}}),w=await te.json().catch(()=>({}));if(!te.ok)throw new Error((w==null?void 0:w.error)||"Export failed");for(const M of w.drafts||[]){const _=`${M.userId}:${M.id}`;k.has(_)||(k.add(_),U.push(M))}Z++;const v=w.lastDoc||null;if(O=!!w.hasMore,O&&(!v||v===I))throw new Error("Export cursor did not advance; no incomplete file was downloaded");I=v,E({rows:U.length,pages:Z})}if(U.length===0){K("No listing drafts found.",{tone:"info"});return}const D=["Draft ID","User ID","User Email","User Name","Status","Source Type","Source Title","Generated Platforms","Selected Platforms","Generation Count","Credits Spent","Last Copied Platform","Last Copied At","Created At","Updated At","First Platform Title","Description Preview"].join(","),ee=U.map(q=>{var v,M,_,B,J,re;const te=Yn(q),w=((v=q.sourceSummary)==null?void 0:v.identifiedAs)||((M=q.sourceSummary)==null?void 0:M.title)||"";return[ne(q.id),ne(q.userId),ne(q.userEmail),ne(q.userName),ne(q.status),ne(q.sourceType),ne(w),ne(Qn(q).join(" | ")),ne((q.selectedPlatforms||[]).join(" | ")),((_=q.generationSummary)==null?void 0:_.generationCount)||0,((B=q.generationSummary)==null?void 0:B.creditsSpentTotal)||0,ne(((J=q.uiState)==null?void 0:J.last
12CopiedPlatform)||""),ne(Is((re=q.uiState)==null?void 0:re.lastCopiedAt)),ne(Is(q.createdAt)),ne(Is(q.updatedAt)),ne((te==null?void 0:te.title)||q.previewTitle||""),ne(((te==null?void 0:te.description)||q.previewDescription||"").slice(0,500))].join(",")}),V=[D,...ee].join(`
13`),X=new Blob([V],{type:"text/csv;charset=utf-8;"}),ae=new Date().toISOString().split("T")[0];await Ve(X,`listing_drafts_${ae}.csv`,`${U.length} listing drafts.`)}catch(h){K(h.message,{title:"Export failed",tone:"error"})}finally{$(!1),E(null)}},[t,u,c]),g=i.useCallback(()=>{f("")},[]);return i.useMemo(()=>({listingDrafts:s,loadingListingDrafts:a,listingDraftsError:p,listingDraftsFilter:u,listingDraftsStatus:c,listingDraftsHasMore:b,listingDraftsStats:x,selectedListingDraft:R,exportingListingDrafts:y,listingDraftsExportProgress:P,setListingDraftsFilter:f,setListingDraftsStatus:N,setSelectedListingDraft:o,fetchListingDrafts:S,handleExportListingDrafts:A,clearListingDraftsFilter:g}),[s,a,p,u,c,b,x,R,y,P,S,A,g])},er=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",tr=t=>{const[s,n]=i.useState([]),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState(!1),[,c]=i.useState(null),N=i.useRef(null),[b,m]=i.useState(null),x=i.useCallback(async(j=!1)=>{d(!0),r("");try{const R=await t(!1);if(!R)throw new Error("Authentication required");const o=new URLSearchParams;o.set("action","referrals"),o.set("limit","50"),j&&N.current&&o.set("startAfter",N.current);const y=await fetch(`${er}/admin?${o.toString()}`,{headers:{Authorization:`Bearer ${R}`}}),$=await y.json().catch(()=>({}));if(!y.ok)throw $!=null&&$.cursorReset&&(f(!1),c(null),N.current=null),new Error(($==null?void 0:$.error)||"Failed to fetch referrals");n(j?(l=>{const S=new Set(l.map(A=>A.id));return[...l,...($.referrals||[]).filter(A=>!S.has(A.id))]}):$.referrals||[]);const P=N.current,E=!j||$.lastId&&$.lastId!==P;f(!!$.hasMore&&E),c($.lastId||null),N.current=$.lastId||null,$.stats&&m($.stats)}catch(R){console.error("Fetch referrals error:",R),r(R.message||"Failed to fetch referrals")}finally{d(!1)}},[t]);return i.useMemo(()=>({referrals:s,loadingReferrals:a,referralsError:p,referralsHasMore:u,referralsStats:b,fetchReferrals:x}),[s,a,p,u,b,x])},Aa=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",sr=t=>{const[s,n]=i.useState([]),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState(!1),[,c]=i.useState(null),N=i.useRef(null),[b,m]=i.useState(""),[x,j]=i.useState(0),[R,o]=i.useState(null),y=i.useCallback(async(P="",E=!1)=>{var l;if(d(!0),r(""),E&&!N.current){f(!1),d(!1);return}try{const S=await t(!1);if(!S)throw new Error("Authentication required");const A=N.current,g=new URLSearchParams;g.set("action","paying-users"),g.set("limit","50"),g.set("searchVersion","2"),P&&g.set("search",P),E&&N.current&&g.set("startAfter",N.current),g.set("_t",Date.now());const h=await fetch(`${Aa}/admin?${g.toString()}`,{headers:{Authorization:`Bearer ${S}`}}),C=await h.json().catch(()=>({}));if(!h.ok)throw new Error((C==null?void 0:C.error)||"Failed to fetch paying users");const U=C.users||[];n(E?(I=>{const O=new Set(I.map(D=>D.uid)),Z=U.filter(D=>(D==null?void 0:D.uid)&&!O.has(D.uid));return[...I,...Z]}):U);const k=!E||C.lastUid&&C.lastUid!==A;f(!!C.hasMore&&k),c(C.lastUid||null),N.current=C.lastUid||null,j(C.total||0),o({sampled:C.sampled===!0,truncated:C.truncated===!0,scannedCount:(l=C.scannedCount)!=null?l:null,queryCoverage:C.queryCoverage||null,searchMode:C.searchMode||null,searchField:C.searchField||null,indexedFallback:C.indexedFallback===!0,scope:C.scope||(P?"filtered":"all")})}catch(S){console.error("Fetch paying users error:",S),r(S.message||"Failed to fetch paying users")}finally{d(!1)}},[t]),$=i.useCallback(async(P="all")=>{const E=await t();if(E)try{const l=new URLSearchParams;l.set("action","paying-users"),l.set("limit","500"),l.set("export","true"),l.set("scope",P),l.set("searchVersion","2"),P==="filtered"&&b.trim()&&l.set("search",b.trim()),l.set("_t",Date.now());const S=[],A=new Set;let g=null,h=!0,C=0;for(;h&&C<1e3;){g?l.set("startAfter",g):l.delete("startAfter");const I=await fetch(`${Aa}/admin?${l.toString()}`,{headers:{Authorization:`Bearer ${E}`}}),O=await I.json().catch(()=>({}));if(!I.ok)throw new Error((O==null?void 0:O.error)||"Failed to fetch paying users");if(O.sampled||O.truncated)throw new Error(`Export was stopped because the server reported incomplete coverage (${O.queryCoverage||"unknown coverage"}). Deploy the paying-user index or narrow the filter.`);for(const Z of O.users||[])Z!=null&&Z.uid&&!A.has(Z.uid)&&(A.add(Z.uid),S.push(Z));if(h=O.hasMore===!0,h&&(!O.lastUid||O.lastUid===g))throw new Error("Export pagination cursor did n
13ot advance");g=O.lastUid||null,C+=1}if(h)throw new Error("Export exceeded the 500,000-row safety limit");const U=[["UID","Email","Name","Plan","Status","Period Usage","Monthly Limit","Bonus Credits","Total Spent","Stripe Customer ID","Stripe Subscription ID","Signed Up"].join(",")];S.forEach(I=>{const O=I.email||"",Z=I.displayName||"Anonymous",D=(I.subscriptionTier||"free").toUpperCase(),ee=I.subscriptionStatus||"active",V=I.periodUsage||0,X=I.usageLimit||0,ae=I.bonusCredits||0,q=I.createdAt?new Date(I.createdAt).toLocaleDateString():"N/A";U.push([I.uid,O,Z,D,ee,V,X,ae,I.totalSpent||0,I.stripeCustomerId||"",I.stripeSubscriptionId||"",q].map(ne).join(","))});const k=new Blob([U.join(`
14`)],{type:"text/csv"});await Ve(k,`paying-users-${P}-${new Date().toISOString().slice(0,10)}.csv`)}catch(l){console.error("Export paying users error:",l),K(l.message,{title:"Export failed",tone:"error"})}},[t,b]);return i.useMemo(()=>({payingUsers:s,loadingPayingUsers:a,payingUsersError:p,payingUsersHasMore:u,payingUsersSearch:b,payingUsersTotal:x,payingUsersMeta:R,setPayingUsersSearch:m,fetchPayingUsers:y,exportPayingUsers:$}),[s,a,p,u,b,x,R,m,y,$])},Rs=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",ar=t=>{const[s,n]=i.useState(null),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState(!1),[c,N]=i.useState(!1),[b,m]=i.useState("contact_and_list"),[x,j]=i.useState(null),R=i.useCallback(async()=>{d(!0),r("");try{const E=await t(!1);if(!E)throw new Error("Authentication required");const l=await fetch(`${Rs}/admin?action=marketing-stats`,{headers:{Authorization:`Bearer ${E}`}}),S=await l.json().catch(()=>({}));if(!l.ok)throw new Error((S==null?void 0:S.error)||"Failed to fetch marketing stats");n(S)}catch(E){console.error("Fetch marketing stats error:",E),r(E.message||"Failed to fetch marketing stats")}finally{d(!1)}},[t]),o=i.useCallback(async()=>{f(!0);try{const E=await t(!1);if(!E)throw new Error("Authentication required");const l=[],S=new Set;let A="",g=!0,h=0;for(;g&&h<1e3;){const C=new URLSearchParams({action:"export-marketing-users",exportVersion:"2",limit:"500"});A&&C.set("startAfter",A);const U=await fetch(`${Rs}/admin?${C.toString()}`,{headers:{Authorization:`Bearer ${E}`}}),k=await U.json().catch(()=>({}));if(!U.ok)throw new Error((k==null?void 0:k.error)||"Export failed");for(const O of k.users||[])O.uid&&!S.has(O.uid)&&(S.add(O.uid),l.push(O));const I=k.nextCursor||"";if(g=k.hasMore===!0,g&&(!I||I===A))throw new Error("Marketing export cursor did not advance; no incomplete file was downloaded");A=I,h+=1}if(g)throw new Error("Marketing export exceeded the 500,000-row safety limit");if(l.length>0){const C=`Email,Name,UID,OptInDate
15`,U=l.map(I=>[I.email,I.displayName,I.uid,I.optInDate].map(ne).join(",")).join(`
16`),k=new Blob([C+U],{type:"text/csv"});await Ve(k,`marketing_users_${new Date().toISOString().split("T")[0]}.csv`,`${l.length} opted-in users.`)}else K("No users opted into marketing found.",{tone:"info"})}catch(E){K(E.message,{title:"Export failed",tone:"error"})}finally{f(!1)}},[t]),y=i.useCallback(async({mode:E="job",sourceOperationId:l=null}={})=>{var S;N(!0),E==="job"&&j(null);try{const A=await t(!1);if(!A)throw new Error("Authentication required");const g=It(E==="retry_failures"?"brevo_retry":"brevo_sync");let h=!0,C=0,U=null;for(;h&&C<1e4;){const k=await fetch(`${Rs}/admin?action=bulk-brevo-sync`,{method:"POST",headers:{Authorization:`Bearer ${A}`,"Content-Type":"application/json"},body:JSON.stringify({mode:E,syncMode:b,operationId:g,sourceOperationId:l,pageSize:25})}),I=await k.json().catch(()=>({}));if(!k.ok)throw tt(I,"Sync failed");U=I,j(I),h=I.state!=="complete"&&((S=I.progress)==null?void 0:S.hasMore)===!0,C+=1}if(!U||U.state!=="complete")throw new Error("Sync stopped before completion; retry with the displayed operation ID");return await R(),U}catch(A){return j(g=>({...g||{},error:A.message})),null}finally{N(!1)}},[b,R,t]),$=i.useCallback(async()=>{await Qe({title:"Start Brevo bulk sync?",message:`This will sync every opted-in user in ${b.replaceAll("_"," ")} mode.`,detail:"The job is resumable and every failed row will be retained with its operation ID.",confirmLabel:"Start sync"})&&await y({mode:"job"})},[b,y]),P=i.useCallback(async()=>{var A,g,h,C,U,k;const E=(x==null?void 0:x.sourceOperationId)||(x==null?void 0:x.operationId);if(!E){K("The source operation ID is unavailable. Open Recent operations to inspect the job.",{tone:"error"});return}const l=(k=(U=(h=(A=x==null?void 0:x.progress)==null?void 0:A.remainingFailures)!=null?h:(g=x==null?void 0:x.progress)==null?void 0:g.unresolvedFailureCount)!=null?U:(C=x==null?void 0:x.progress)==null?void 0:C.failCount)!=null?k:0;await Qe({title:"Retry failed Brevo contacts?",message:`Retry ${l} unresolved contact${l===1?"":"s"} from operation ${E}
16.`,detail:"Consent is checked again before each retry. Revoked or missing contacts are safely skipped.",confirmLabel:"Retry failures"})&&await y({mode:"retry_failures",sourceOperationId:E})},[x,y]);return i.useMemo(()=>({marketingStats:s,loadingMarketing:a,marketingError:p,exportingMarketing:u,syncingBrevo:c,brevoSyncMode:b,brevoSyncResult:x,fetchMarketingStats:R,setBrevoSyncMode:m,handleExportMarketing:o,handleBulkBrevoSync:$,handleRetryBrevoFailures:P}),[s,a,p,u,c,b,x,R,o,$,P])},Vt=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",nr=t=>{const[s,n]=i.useState([]),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState(""),[c,N]=i.useState(!1),b=i.useRef(null),[m,x]=i.useState(null),[j,R]=i.useState(!1),[o,y]=i.useState(!1),[$,P]=i.useState(null),[E,l]=i.useState(null),[S,A]=i.useState(!1),[g,h]=i.useState(""),[C,U]=i.useState(14),[k,I]=i.useState(!1),O=i.useCallback(w=>{f(w),l(null),h("")},[]),Z=i.useCallback(async(w=!1,v)=>{var M;d(!0),r("");try{const _=await t(!1);if(!_)throw new Error("Authentication required");const B=new URLSearchParams;B.set("action","flipexpert-conversations"),B.set("limit","50");const J=((M=v!=null?v:u)!=null?M:"").trim();J&&B.set("userId",J),w&&b.current&&B.set("startAfter",b.current);const re=await fetch(`${Vt}/admin?${B.toString()}`,{headers:{Authorization:`Bearer ${_}`}}),F=await re.json().catch(()=>({}));if(!re.ok)throw new Error((F==null?void 0:F.error)||"Failed to fetch chats");n(w?(se=>{const ye=new Set(se.map(oe=>`${oe.userId}:${oe.id}`));return[...se,...(F.conversations||[]).filter(oe=>!ye.has(`${oe.userId}:${oe.id}`))]}):F.conversations||[]),N(!!F.hasMore),b.current=F.lastDoc||null}catch(_){console.error("Fetch chats error:",_),r(_.message||"Failed to fetch chats")}finally{d(!1)}},[t,u]),D=i.useCallback(async(w,v)=>{R(!0);try{const M=await t(!1);if(!M)throw new Error("Authentication required");const _=new URLSearchParams;_.set("action","flipexpert-conversation-detail"),_.set("userId",w),_.set("conversationId",v);const B=await fetch(`${Vt}/admin?${_.toString()}`,{headers:{Authorization:`Bearer ${M}`}}),J=await B.json().catch(()=>({}));if(!B.ok)throw new Error((J==null?void 0:J.error)||"Failed to fetch chat detail");x(J.conversation||null)}catch(M){console.error("Fetch chat detail error:",M),K(M.message,{title:"Conversation failed to load",tone:"error"})}finally{R(!1)}},[t]),ee=i.useCallback(async()=>{y(!0),P({conversations:0,pages:0});const w=await t();if(!w){y(!1),K("Authentication failed.",{tone:"error"});return}try{const v=(u||"").trim(),M=[],_=new Set;let B=null,J=!0,re=0;for(;J;){if(re>=500)throw new Error("Export safety limit reached after 50,000 conversations");const be=new URLSearchParams({action:"flipexpert-conversations",limit:"100",export:"true",exportVersion:"2"});v&&be.set("userId",v),B&&be.set("startAfter",B);const ge=await fetch(`${Vt}/admin?${be.toString()}`,{headers:{Authorization:`Bearer ${w}`}}),ce=await ge.json().catch(()=>({}));if(!ge.ok)throw new Error((ce==null?void 0:ce.error)||"Export failed");for(const Ie of ce.conversations||[]){const Oe=`${Ie.userId}:${Ie.id}`;_.has(Oe)||(_.add(Oe),M.push(Ie))}re++;const Se=ce.lastDoc||null;if(J=!!ce.hasMore,J&&(!Se||Se===B))throw new Error("Export cursor did not advance; no incomplete file was downloaded");B=Se,P({conversations:M.length,pages:re})}if(M.length===0){K("No conversations found.",{tone:"info"}),y(!1);return}const F=M.reduce((be,ge)=>be+(Array.isArray(ge.messages)?ge.messages.length:0),0),se=Vn(M),ye=new Blob([se],{type:"text/csv;charset=utf-8;"}),oe=new Date().toISOString().split("T")[0];await Ve(ye,`flipexpert_chats_${oe}.csv`,`${M.length} conversations with ${F} messages.`)}catch(v){K(v.message,{title:"Export failed",tone:"error"})}finally{y(!1),P(null)}},[t,u]),V=i.useCallback(async w=>{var B;if(!w||!w.messages)return;const v=zn(w),M=new Blob([v],{type:"text/csv;charset=utf-8;"}),_=(w.title||"conversation").replace(/[^a-zA-Z0-9]/g,"_").slice(0,30);try{await Ve(M,`chat_${_}_${((B=w.id)==null?void 0:B.slice(0,8))||"export"}.csv`)}catch(J){K(J.message,{title:"Export failed",tone:"error"})}},[]),X=i.useCallback(async w=>{if(!(!(w!=null&&w.userId)||!(w!=null&&w.id))){R(!0);try{const v=await t(!1);if(!v)throw new Error("Authentication required");const M=new URLSearchParams({action:"flipexpert-conversation-detail",userId:w.userId,conversationId:w.id}),_=await fetch(`${Vt}/admin?${M.toString()}`,{headers:{Authorization:`Bearer ${v}`}}),B=await _.json().catch(()=>({}));if(!_.ok)throw new Error((B==null?void 0:B.error)||"Failed to fetch chat detail");await V(B.conversation)}catch(v){K(v.message,{title:"Export failed",tone:"error"})}finally{R(!1)}}},[t,V]),ae=i.useCallback(async(w,v)=>{var M;A(!0),h("");try{const _=await t(!1);if(!_)throw new Error("Authentication required");const B=Number(w!=null?w:C)||14,J=new URLSearchParams;J.set("action","flipexpert-analytics"),J.set("analyticsVersion","2"),J.set("days",String(B)),J.set("limit","1000");const re=((M=v!=null?v:u)!=null?M:"").trim();re&&J.set("userId",re);const F=await fetch(`${Vt}/admin?${J.toString()}`,{headers:{Authorization:`Bearer ${_}`}}),se=await F.json().catch(()=>({}));
16if(!F.ok)throw new Error((se==null?void 0:se.error)||"Failed to fetch chat analytics");return l(se),U(B),se}catch(_){return console.error("Fetch chat analytics error:",_),h(_.message||"Failed to fetch chat analytics"),null}finally{A(!1)}},[C,u,t]),q=i.useCallback(async()=>{I(!0);try{const w=await ae(C);if(!w)throw new Error("Analytics unavailable");const v=Hn(w),M=new Blob([v],{type:"text/csv;charset=utf-8;"}),_=new Date().toISOString().split("T")[0];await Ve(M,`flipexpert_analytics_${_}.csv`)}catch(w){K(w.message,{title:"Analytics export failed",tone:"error"})}finally{I(!1)}},[C,ae]),te=i.useCallback(()=>{f(""),l(null),h("")},[]);return i.useMemo(()=>({chats:s,loadingChats:a,chatsError:p,chatsFilter:u,chatsHasMore:c,selectedChat:m,loadingChatDetail:j,exportingChats:o,chatsExportProgress:$,chatAnalytics:E,loadingChatAnalytics:S,chatAnalyticsError:g,chatAnalyticsDays:C,exportingChatAnalytics:k,setChatsFilter:O,setSelectedChat:x,setChatAnalyticsDays:U,fetchChats:Z,fetchChatDetail:D,fetchChatAnalytics:ae,handleExportChats:ee,handleExportChatDetail:V,handleExportSingleChat:X,handleExportChatAnalytics:q,clearChatsFilter:te}),[s,a,p,u,c,m,j,o,$,E,S,g,C,k,Z,D,ee,ae,V,X,q,te,O])},ka=90;function hs(t){if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(t))return!1;const s=new Date(`${t}T00:00:00.000Z`);return Number.isFinite(s.getTime())&&s.toISOString().slice(0,10)===t}function ls(t){const s=new Error(t);throw s.statusCode=400,s.code="INVALID_TELEMETRY_RANGE",s}function rr({startDate:t,endDate:s,days:n}={}){for(const[a,d]of[["Start",t],["End",s]])d!=null&&d!==""&&!hs(d)&&ls(`${a} must be a valid calendar date (YYYY-MM-DD).`);n!=null&&n!==""&&(!/^\d+$/.test(String(n))||Number(n)<1||Number(n)>ka)&&ls("Choose between 1 and 90 telemetry days."),t&&s&&(t>s&&ls("Start date must be on or before end date."),(Date.parse(s)-Date.parse(t))/864e5+1>ka&&ls("Telemetry ranges cannot exceed 90 days."))}const St=t=>!!(t&&typeof t=="object"&&!Array.isArray(t)),os=t=>St(t)&&Object.entries(t).every(([s,n])=>/^by[A-Z]/.test(s)||s==="longestItemAnalyses"?Array.isArray(n)&&n.every(St):/(Count|Rate|Bytes|Ms|Usd|Chars|Words)$/.test(s)?n===null&&s.endsWith("Rate")||typeof n=="number"&&Number.isFinite(n):!0);function ir(t){if(!St(t)||!hs(t.startDate)||!hs(t.endDate)||t.startDate>t.endDate||!St(t.totals)||!Array.isArray(t.daily)||!Number.isFinite(Date.parse(t.generatedAt)))return!1;const s=n=>St(n)&&hs(n.date)&&n.date>=t.startDate&&n.date<=t.endDate;return!t.daily.every(n=>s(n)&&St(n.providers)&&Object.values(n.providers).every(os))||!Object.values(t.totals).every(os)?!1:["analysisContent","imageEncoding","searchGrounding"].every(n=>{const a=t[n];return St(a)&&os(a.totals)&&Array.isArray(a.daily)&&a.startDate===t.startDate&&a.endDate===t.endDate&&a.daily.every(d=>s(d)&&os(d.stats))})}function Ps(t,s,n){return{days:!s&&!n?String(t||""):null,startDate:s||null,endDate:n||null}}const $a=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api";function Ea(t,s,n){const a=new Blob([t],{type:n});return Ve(a,s)}function Us(){return new Date().toISOString().slice(0,10)}function He(t){const s=[...new Set(t.flatMap(n=>Object.keys(n||{})))];return s.length===0?"":[s.map(ne).join(","),...t.map(n=>s.map(a=>{const d=n==null?void 0:n[a];return ne(d&&typeof d=="object"?JSON.stringify(d):d!=null?d:"")}).join(","))].join(`
17`)}function tn(t){return((t==null?void 0:t.daily)||[]).flatMap(s=>Object.entries(s.providers||{}).map(([n,a])=>({date:s.date,provider:n,...a})))}function sn(t){var s;return(((s=t==null?void 0:t.imageEncoding)==null?void 0:s.daily)||[]).map(n=>({date:n.date,...n.stats||{}}))}function an(t){var s;return(((s=t==null?void 0:t.analysisContent)==null?void 0:s.daily)||[]).map(n=>({date:n.date,...n.stats||{}}))}function nn(t){var s;return(((s=t==null?void 0:t.searchGrounding)==null?void 0:s.daily)||[]).map(n=>({date:n.date,...n.stats||{}}))}function Gs(t){var a;const s=[["Provider","byProvider"],["Policy Version","byPolicyVersion"],["Pipeline Revision","byPipelineRevision"],["Decision Stage","byDecisionStage"],["Decision Threshold","byDecisionThreshold"],["Decision Skip Reason","byDecisionSkipReason"],["Skip Reason","bySkipReason"],["Forced Reason","byForcedReason"],["Fallback Reason","byFallbackReason"],["Evidence Stage","byMarketEvidenceDecisionStage"],["Evidence Rejection","byMarketEvidenceRejectionReason"],["Identity Validation","byGroundedIdentityValidationReason"],["Identity Match Reason","byIdentityMatchReason"],["Pre-main Identity Authority","byPreMainIdentityAuthorityReason"],["Output Status","byOutputStatus"],["Cache Status","byCacheStatus"],["Cache Eligibility","byCacheEligibilityReason"],["Comps Provider","byCompsProvider"],["Comps Status","byCompsProviderStatus"],["Request Source","bySource"],["Client Surface","bySurface"]],n=((a=t==null?void 0:t.searchGrounding)==null?void 0:a.totals)||{};return s.flatMap(([d,p])=>(n[p]||[]).map(r=>({dimension:d,...r})))}function Ws(t){const s=[["Model","byModel"],["Source","bySource"],["Transport","byTransport"],["Service Tier","byServiceTier"],["Web Search Context","byWebSearchContextSize"],["HTTP Status","byStatus"],["Provider Status","byProviderStatus"]];return Object.entries((t==null?void 0:t.totals)||{}).flatMap(([n,a])=>s.flatMap(([d,p])=>((a==null?void 0:a[p])||[]).map(r=>({provider:n,dimension:d,...r}))))}function Ks(t){var s,n;return(((n=(s=t==null?void 0:t.analysisContent)==null?void 0:s.totals)==null?void 0:n.longestItemAnalyses)||[]).map(a=>({...a,outlierReasons:Array.isArray(a.outlierReasons)?a.outlierReasons.join("|"):""}))}function lr(t){var x,j,R,o,y,$,P,E;const s=["Date","Provider","Requests","Successes","Errors","Estimated Cost USD","Reconciled Cost USD","Cost Variance USD","Cost Source","Input Tokens","Cached Input Tokens","Cache Write Tokens","Output Tokens","Reasoning Tokens","Total Tokens","Grounding Search Queries","Web Search Calls","Web Search Cost USD","Reported Grounding Search Queries","Grounding Search Requests","Fallback Grounding Search Requests","Fallback Grounding Search Queries","Generated Images","Image Output Requests","Usage Metadata Missing","Cache Hits","Live Provider Calls","Rate Limited","Found","Items","Evidence Items","Attempt Count","Total Duration Ms","Unknown Cost Count"],n=tn(t).map(l=>{var S,A;return[ne(l.date),ne(l.provider),l.requestCount||0,l.successCount||0,l.errorCount||0,l.estimatedCostUsd||0,(S=l.reconciledCostUsd)!=null?S:"",(A=l.costVarianceUsd)!=null?A:"",ne(l.costSource||""),l.inputTokenCount||l.promptTokenCount||0,l.cachedInputTokenCount||l.cachedContentTokenCount||0,l.cacheWriteTokenCount||0,l.outputTokenCount||l.candidatesTokenCount||0,l.reasoningTokenCount||l.thoughtsTokenCount||0,l.totalTokenCount||0,l.groundingSearchQueryCount||0,l.webSearchCallCount||0,l.webSearchCostUsd||0,l.reportedGroundingSearchQueryCount||0,l.groundingSearchRequestCount||0,l.groundingSearchFallbackRequestCount||0,l.groundingSearchFallbackQueryCount||0,l.generatedImageCount||0,l.imageOutputRequestCount||0,l.usageMetadataMissingCount||0,l.cacheHitCount||0,l.liveCallCount||0,l.rateLimitedCount||0,l.foundCount||0,l.itemCount||0,l.evidenceItemCount||0,l.attemptCount||0,l.durationMs||0,l.estimatedCostUnknownCount||0].join(",")}),a=["Provider","Dimension","Key","Requests","Successes","Errors","Estimated Cost USD"],d=Ws(t).map(l=>[ne(l.provider),ne(l.dimension),ne(l.key),l.requestCount||0,l.successCount||0,l.errorCount||0,l.estimatedCostUsd||0].join(",")),p=["Date","Analyses","Items","Item Analyses","Empty Item Analyses","Avg Items Per Analysis","Avg Analysis Words","Avg Analysis Chars","Min Analysis Words","Max Analysis Words","Max Analysis Chars","Long Analyses","Analysis Outliers","Outlier Rate"],r=an(t).map(l=>[ne(l.date),l.requestCount||0,l.itemCount||0,l.itemAnalysisCount||0,l.emptyItemAnalysisCount||0,l.avgItemsPerAnalysis||0,l.avgItemAnalysisWords||0,l.avgItemAnalysisChars||0,l.minItemAnalysisWords||0,l.maxItemAnalysisWords||0,l.maxItemAnalysisChars||0,l.longItemAnalysisCount||0,l.itemAnalysisOutlierCount||0,l.itemAnalysisOutlierRate||0].join(",")),u=["Analysis ID","Analysis Request ID","Source","Source Type","Analysis Mode","Goal Type","Platform","Item Index","Title","Words","Chars","Source Field","Outlier Reasons"],f=Ks(t).map(l=>{var S;
17return[ne(l.analysisId||""),ne(l.analysisRequestId||""),ne(l.source||""),ne(l.sourceType||""),ne(l.analysisMode||""),ne(l.goalType||""),ne(l.platform||""),(S=l.index)!=null?S:"",ne(l.title||""),l.wordCount||0,l.charCount||0,ne(l.sourceField||""),ne(l.outlierReasons||"")].join(",")}),c=["Date","Requests","Images","Input Bytes","Output Bytes","Bytes Saved","Bytes Increased","Preserved Images","Re-encoded Images","Fallback Images","Decode Failures","Target Miss Images","Server Limit Miss Images","Encode Duration Ms","Source Pixels","Output Pixels"],N=sn(t).map(l=>[ne(l.date),l.requestCount||0,l.imageCount||0,l.inputBytes||0,l.outputBytes||0,l.bytesSaved||0,l.bytesIncreased||0,l.preservedImageCount||0,l.reencodedImageCount||0,l.fallbackImageCount||0,l.decodeFailedImageCount||0,l.targetMissImageCount||0,l.serverLimitMissImageCount||0,l.encodeDurationMs||0,l.sourcePixelCount||0,l.outputPixelCount||0].join(",")),b=nn(t),m=Gs(t);return["Provider Telemetry",s.join(","),...n,"","Provider Breakdown Telemetry",a.join(","),...d,"","Search Grounding Telemetry",He(b),"","Search Grounding Breakdown Telemetry",He(m),"","Analysis Content Telemetry",p.join(","),...r,"","Analysis Content Longest Items",u.join(","),...f,"","OpenAI Billing (separate scope)",He([{startDate:(x=t==null?void 0:t.openAiCosts)==null?void 0:x.startDate,endDate:(j=t==null?void 0:t.openAiCosts)==null?void 0:j.endDate,timeZone:(R=t==null?void 0:t.openAiCosts)==null?void 0:R.bucketTimeZone,scope:(o=t==null?void 0:t.openAiCosts)==null?void 0:o.scope,projectIds:(y=t==null?void 0:t.openAiCosts)==null?void 0:y.projectIds,status:($=t==null?void 0:t.openAiCosts)==null?void 0:$.status,totalCostUsd:(P=t==null?void 0:t.openAiCosts)==null?void 0:P.totalCostUsd}]),He(((E=t==null?void 0:t.openAiCosts)==null?void 0:E.daily)||[]),"","Image Encoding Telemetry",c.join(","),...N].join(`
18`)}const or=t=>{const[s,n]=i.useState(null),[a,d]=i.useState(!1),[p,r]=i.useState(""),[u,f]=i.useState("14"),[c,N]=i.useState(""),[b,m]=i.useState(""),[x,j]=i.useState(null),R=i.useRef(0),o=i.useRef(null);i.useEffect(()=>()=>{var A;R.current+=1,(A=o.current)==null||A.abort()},[]);const y=i.useMemo(()=>Ps(u,c,b),[u,c,b]),$=!!(s&&x&&JSON.stringify(y)!==JSON.stringify(x)),P=i.useCallback(async()=>{var h;const A=++R.current;(h=o.current)==null||h.abort();const g=new AbortController;o.current=g,d(!0),r("");try{rr(Ps(u,c,b));const C=await t(!1);if(!C)throw new Error("Authentication required");const U=new URLSearchParams;U.set("action","telemetry"),c&&U.set("startDate",c),b&&U.set("endDate",b),!c&&!b&&u&&U.set("days",u);let k=await fetch(`${$a}/admin?${U.toString()}`,{headers:{Authorization:`Bearer ${C}`},signal:g.signal});if(k.status===401||k.status===403){const Z=await t(!0);Z&&(k=await fetch(`${$a}/admin?${U.toString()}`,{headers:{Authorization:`Bearer ${Z}`},signal:g.signal}))}const I=await k.json().catch(()=>({}));if(!k.ok)throw new Error((I==null?void 0:I.error)||"Failed to fetch telemetry");if(!ir(I))throw new Error("The telemetry response was incomplete or invalid. Please retry.");if(I.disabled)throw new Error("Telemetry storage is unavailable. Please retry.");const O=(Date.parse(I.endDate)-Date.parse(I.startDate))/864e5+1;if(c&&I.startDate!==c||b&&I.endDate!==b||!c&&O!==Number(b?14:u))throw new Error("The telemetry response did not match the requested date range.");return A!==R.current?!1:(n(I),j(Ps(u,c,b)),!0)}catch(C){return(C==null?void 0:C.name)!=="AbortError"&&A===R.current&&r(C.message||"Failed to fetch telemetry"),!1}finally{A===R.current&&(d(!1),o.current=null)}},[t,u,c,b]),E=i.useCallback(async()=>{if(!(!s||$||a))try{const A=lr(s);await Ea(A,`admin_telemetry_${s.startDate||"start"}_to_${s.endDate||Us()}.csv`,"text/csv;charset=utf-8;")}catch(A){K(A.message||"Could not export telemetry.",{title:"Export failed",tone:"error"})}},[s,$,a]),l=i.useCallback(async(A=3)=>{var g,h,C,U,k,I,O,Z;if(!(!s||$||a))try{const D=[...(s.daily||[]).map(V=>({type:"providerDaily",...V})),...(((g=s.analysisContent)==null?void 0:g.daily)||[]).map(V=>({type:"analysisContentDaily",...V})),...(((h=s.imageEncoding)==null?void 0:h.daily)||[]).map(V=>({type:"imageEncodingDaily",...V})),...(((C=s.searchGrounding)==null?void 0:C.daily)||[]).map(V=>({type:"searchGroundingDaily",...V}))],ee=A===1?D:[{type:"manifest",schemaVersion:3,request:s.request||x,resolvedFilters:s.resolvedFilters||null,asOf:s.asOf||s.generatedAt||null},{type:"openAiBilling",...s.openAiCosts||{}},...Object.entries(s.totals||{}).map(([V,X])=>({type:"providerTotal",provider:V,...X})),{type:"analysisContentTotal",...((U=s.analysisContent)==null?void 0:U.totals)||{}},{type:"imageEncodingTotal",...((k=s.imageEncoding)==null?void 0:k.totals)||{}},{type:"searchGroundingTotal",...((I=s.searchGrounding)==null?void 0:I.totals)||{}},{type:"searchGroundingActiveRevisionTotal",pipelineRevision:((O=s.searchGrounding)==null?void 0:O.activePipelineRevision)||null,...((Z=s.searchGrounding)==null?void 0:Z.activeRevisionTotals)||{}},...Ws(s).map(V=>({type:"providerBreakdown",...V})),...Gs(s).map(V=>({type:"searchGroundingBreakdown",...V}
18)),...Ks(s).map(V=>({type:"analysisContentOutlier",...V})),...D];await Ea(ee.map(V=>JSON.stringify(V)).join(`
19`),`admin_telemetry_v${A}_${s.startDate||"start"}_to_${s.endDate||Us()}.jsonl`,"application/x-ndjson;charset=utf-8;")}catch(D){K(D.message||"Could not export telemetry.",{title:"Export failed",tone:"error"})}},[x,s,$,a]),S=i.useCallback(async()=>{var A;if(!(!s||$||a))try{const{default:g}=await mn(async()=>{const{default:k}=await import("./jszip.min-DtY4eCf0.js").then(I=>I.j);return{default:k}},__vite__mapDeps([0,1])),h=new g,C={schemaVersion:3,request:s.request||x,resolvedFilters:s.resolvedFilters||null,asOf:s.asOf||s.generatedAt||null,activeSearchGroundingPipelineRevision:((A=s.searchGrounding)==null?void 0:A.activePipelineRevision)||null,files:["openai_billing.json","provider_daily.csv","provider_breakdowns.csv","search_grounding_daily.csv","search_grounding_breakdowns.csv","analysis_content_daily.csv","analysis_content_outliers.csv","image_encoding_daily.csv"]};h.file("openai_billing.json",JSON.stringify(s.openAiCosts||{},null,2)),h.file("manifest.json",JSON.stringify(C,null,2)),h.file("provider_daily.csv",He(tn(s))),h.file("provider_breakdowns.csv",He(Ws(s))),h.file("search_grounding_daily.csv",He(nn(s))),h.file("search_grounding_breakdowns.csv",He(Gs(s))),h.file("analysis_content_daily.csv",He(an(s))),h.file("analysis_content_outliers.csv",He(Ks(s))),h.file("image_encoding_daily.csv",He(sn(s)));const U=await h.generateAsync({type:"blob",compression:"DEFLATE"});await Ve(U,`admin_telemetry_v3_${s.startDate||"start"}_to_${s.endDate||Us()}.zip`)}catch(g){K(g.message||"Could not export telemetry.",{title:"Export failed",tone:"error"})}},[x,s,$,a]);return i.useMemo(()=>({telemetry:s,loadingTelemetry:a,telemetryError:p,telemetryDays:u,telemetryStartDate:c,telemetryEndDate:b,telemetryDirty:$,loadedTelemetryFilters:x,setTelemetryDays:f,setTelemetryStartDate:N,setTelemetryEndDate:m,fetchTelemetry:P,exportTelemetryCsv:E,exportTelemetryJsonl:l,exportTelemetryZip:S}),[s,a,p,u,c,b,$,x,P,E,l,S])},et=t=>String(t!=null?t:"—").replace(/\|/g,"\\|").replace(/[\r\n]+/g," "),Ke=t=>Number.isFinite(t)?`${t.toFixed(2)}%`:"not yet eligible",cs=t=>{const s=Object.entries(t||{}).sort(([n],[a])=>n.localeCompare(a));return s.length>0?s.map(([n,a])=>`${n.toUpperCase()} ${Math.trunc(Number(a==null?void 0:a.netMinor)||0)}`).join("; "):"—"};function cr(t){var d,p,r,u,f,c,N,b;const s=(t==null?void 0:t.overall)||{},n=s.rates||{};return["# Acquisition and Product-Outcome Signup-Cohort Report","",`**Generated:** ${et(t==null?void 0:t.generatedAt)}`,`**Signup cohort:** ${et((d=t==null?void 0:t.window)==null?void 0:d.startAt)} through ${et((p=t==null?void 0:t.window)==null?void 0:p.endAt)} (${et((r=t==null?void 0:t.window)==null?void 0:r.days)} days)`,"","This is an aggregate, consent-aware signup-cohort report. It contains no user IDs or email addresses. Source dimensions contain consented attribution only; overall operational outcomes may include unattributed accounts. Store clicks and signed-in client first-use reports are separate facts; neither is represented as a store-confirmed install.","","Retention measures successful server-saved analyses on UTC calendar days, not visits or logins. D1, D7, and D30 use exact days; week 1 uses days 7–13 and week 4 uses days 28–34. Only fully elapsed windows enter retention denominators.","","## Overall","","| Metric | Value |","|---|---:|",`| Signups | ${s.signups||0} |`,`| Attributed signups | ${s.attributedSignups||0} (${Ke(n.attributionCoveragePct)}) |`,`| Organic-search signups | ${s.organicSignups||0} (${Ke(n.organicSharePct)}) |`,`| First-analysis users | ${s.firstAnalysisUsers||0} (${Ke(n.signupToFirstAnalysisPct)}) |`,`| D1 retained / eligible | ${s.d1Retained||0} / ${s.d1Eligible||0} (${Ke(n.d1RetentionPct)}) |`,`| D7 retained / eligible | ${s.d7Retained||0} / ${s.d7Eligible||0} (${Ke(n.d7RetentionPct)}) |`,`| D30 retained / eligible | ${s.d30Retained||0} / ${s.d30Eligible||0} (${Ke(n.d30RetentionPct)}) |`,`| Week-1 retained / eligible | ${s.week1Retained||0} / ${s.week1Eligible||0} (${Ke(n.week1RetentionPct)}) |`,`| Week-4 retained / eligible | ${s.week4Retained||0} / ${s.week4Eligible||0} (${Ke(n.week4RetentionPct)}) |`,`| Payers | ${s.payers||0} (${Ke(n.signupToPayerPct)}) |`,"","## Official-store click and signed-in client first-use observations","","These are same-profile observations, not store-confirmed installs or causal attribution.","","| Platform | Click users | First-use users | Click then first use | Observed rate |","|---|---:|---:|---:|---:|",...Object.keys(s.firstUse||{}).map(m=>{var x,j,R,o;return`| ${et(m)} | ${((x=s.installClickUsers)==null?void 0:x[m])||0} | ${((j=s.firstUse)==null?void 0:j[m])||0} | ${((R=s.clickThenFirstUseUsers)==null?void 0:R[m])||0} | ${Ke((o=s.installClickToFirstUsePct)==null?void 0:o[m])} |`}),"","## By acquisition channel","","| Channel | Signups | First analysis | D7 retained / eligible | Payers | Net revenue (minor units) |","|---|---:|---:|---:|---:|---|",...((t==null?void 0:t.byChannel)||[]).map(m=>`| ${et(m.channel)} | ${m.signups} | ${m.firstAnalysisUsers} | ${m.d7Retained} / ${m.d7Eligible} | ${m.payers} | ${cs(m.revenueByCurrency)} |`),"","## Organic search engines","","| Engine | Signups | First analysis | Payers | Net revenue (minor units) |","|---|---:|---:|---:|---|",...((t==null?void 0:t.byOrganicSearchEngine)||[]).map(m=>`| ${et(m.searchEngine)} | ${m.signups} | ${m.firstAnalysisUsers} | ${m.payers} | ${cs(m.revenueByCurrency)} |`),"","## Signup methods","","| Method | Signups | First analysis | Payers | Net revenue (minor units) |","|---|---:|---:|---:|---|",...((t==null?void 0:t.bySignupMethod)||[]).map(m=>`| ${et(m.signupMethod)} | ${m.signups} | ${m.firstAnalysisUsers} | ${m.payers} | ${cs(m.revenueByCurrency)}
19 |`),"","## First consented content-touch cohorts","",`Rows with fewer than ${((u=t==null?void 0:t.privacy)==null?void 0:u.minimumPublishedEntryCohortSize)||3} signups are suppressed.`,"","| Entry | Signups | First analysis | D7 retained / eligible | Payers | Net revenue (minor units) |","|---|---:|---:|---:|---:|---|",...((t==null?void 0:t.byEntryPage)||[]).map(m=>`| ${et(m.entry)} | ${m.signups} | ${m.firstAnalysisUsers} | ${m.d7Retained} / ${m.d7Eligible} | ${m.payers} | ${cs(m.revenueByCurrency)} |`),"","## Revenue by original currency","","Amounts remain in Stripe minor units so currencies with different exponents are not converted or mislabeled.","","| Currency | Gross minor units | Refunded minor units | Net minor units |","|---|---:|---:|---:|",...Object.entries(s.revenueByCurrency||{}).map(([m,x])=>`| ${m.toUpperCase()} | ${x.grossMinor} | ${x.refundedMinor} | ${x.netMinor} |`),"","## Instrumentation coverage and cautions","",`- Profiles in window: ${((f=t==null?void 0:t.instrumentation)==null?void 0:f.profileCountInWindow)||0}`,`- Profiles with acquisition attribution: ${((c=t==null?void 0:t.instrumentation)==null?void 0:c.attributedProfileCount)||0}`,`- Profiles with first-analysis milestones: ${((N=t==null?void 0:t.instrumentation)==null?void 0:N.firstAnalysisMilestoneCount)||0}`,`- Small entry cohorts suppressed: ${((b=t==null?void 0:t.privacy)==null?void 0:b.suppressedSmallEntryCohorts)||0}`,...((t==null?void 0:t.warnings)||[]).map(m=>`- ${m}`),""].join(`
20`)}const dr=Object.freeze([7,30,60,90,180,365]),ur=Object.freeze({bing:"Bing",brave:"Brave Search",duckduckgo:"DuckDuckGo",ecosia:"Ecosia",google:"Google",other_search:"Other search",unknown:"Unknown",yahoo:"Yahoo"}),xr=Object.freeze({apple:"Apple",email_link:"Email link",google:"Google",unknown:"Unknown / not consented"});function vs(t,s=60){const n=Math.trunc(Number(t));return Number.isFinite(n)&&n>=1&&n<=366?n:s}function mr(t){var u,f,c,N,b;const s=Number((u=t==null?void 0:t.window)==null?void 0:u.days),n=Number((f=t==null?void 0:t.privacy)==null?void 0:f.minimumPublishedEntryCohortSize),a=m=>!!(m&&typeof m=="object"&&!Array.isArray(m)),d=m=>Number.isSafeInteger(m)&&m>=0,p=m=>m===null||typeof m=="number"&&Number.isFinite(m)&&m>=0&&m<=100,r=m=>a(m)&&d(m.signups)&&["attributedSignups","organicSignups","firstAnalysisUsers","payers","paymentCount","refundChargeCount"].every(x=>d(m[x]))&&["attributedSignups","organicSignups","firstAnalysisUsers","payers"].every(x=>m[x]<=m.signups)&&["d1","d7","d30","week1","week4"].every(x=>d(m[`${x}Eligible`])&&d(m[`${x}Retained`])&&m[`${x}Retained`]<=m[`${x}Eligible`]&&m[`${x}Eligible`]<=m.signups)&&a(m.rates)&&Object.values(m.rates).every(p)&&["firstUse","installClickUsers","clickThenFirstUseUsers"].every(x=>a(m[x])&&Object.values(m[x]).every(j=>d(j)&&j<=m.signups))&&a(m.installClickToFirstUsePct)&&Object.values(m.installClickToFirstUsePct).every(p)&&a(m.revenueByCurrency)&&Object.entries(m.revenueByCurrency).every(([x,j])=>/^[a-z]{3}$/.test(x)&&a(j)&&d(j.grossMinor)&&d(j.refundedMinor)&&j.netMinor===j.grossMinor-j.refundedMinor);return!!(t&&typeof t=="object"&&Number(t.schemaVersion)>=1&&((c=t.window)==null?void 0:c.basis)==="signup_cohort"&&Number.isInteger(s)&&s>=1&&s<=366&&Number.isFinite(Date.parse(t.generatedAt))&&Number.isFinite(Date.parse(t.window.startAt))&&Date.parse(t.window.endAt)===Date.parse(t.generatedAt)&&Date.parse(t.window.endAt)-Date.parse(t.window.startAt)===s*864e5&&r(t.overall)&&[["byChannel","channel"],["byOrganicSearchEngine","searchEngine"],["byEntryPage","entry"],["bySignupMethod","signupMethod"]].every(([m,x])=>Array.isArray(t[m])&&t[m].every(j=>r(j)&&typeof j[x]=="string"))&&t.byEntryPage.every(m=>m.signups>=n)&&((N=t.privacy)==null?void 0:N.containsUserIds)===!1&&((b=t.privacy)==null?void 0:b.containsEmailAddresses)===!1&&Number.isInteger(n)&&n>=3)}function Be(t){if(t==null||t==="")return"Not yet eligible";const s=Number(t);return Number.isFinite(s)?`${s.toFixed(1)}%`:"Not yet eligible"}function pr(t,s){const n=String(t||"").trim();if(!n)return"Unknown";if(s==="entry"){const[a,...d]=n.split(":"),p=d.join(":");if(a==="blog"&&p)return`/blog/${p}`;if(a==="tool"&&p)return`/tools/${p}`}if(s==="searchEngine")return ur[n.toLowerCase()]||n;if(s==="signupMethod")return xr[n.toLowerCase()]||n;if(s==="channel"){const a=n.replace(/_/g," ");return a.charAt(0).toUpperCase()+a.slice(1)}return n}function Yt(t,s,n){const a=/^[a-z]{3}$/i.test(String(s||""))?String(s).toUpperCase():null,d=a?bn(t,a):null;if(!a||!Number.isFinite(d))return"—";try{return new Intl.NumberFormat(n,{style:"currency",currency:a,maximumFractionDigits:2}).format(d)}catch{return`${a} ${d.toFixed(2)}`}}function hr(t,s=60){var d,p;const n=vs((d=t==null?void 0:t.window)==null?void 0:d.days,vs(s)),a=((p=/^\d{4}-\d{2}-\d{2}/.exec(String((t==null?void 0:t.generatedAt)||"")))==null?void 0:p[0])||new Date().toISOString().slice(0,10);return`underpriced_acquisition_${n}d_${a}.md`}const br=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api";async function gr(t,s){const n=await t.text().catch(()=>"");
20if(!n)return s;try{const a=JSON.parse(n);return(a==null?void 0:a.error)||(a==null?void 0:a.message)||s}catch{return s}}function fr(t,s){const n=new Blob([t],{type:"text/markdown;charset=utf-8"});return Ve(n,s)}const yr=t=>{const[s,n]=i.useState(null),[a,d]=i.useState("60"),[p,r]=i.useState(null),[u,f]=i.useState(!1),[c,N]=i.useState(!1),[b,m]=i.useState(""),[x,j]=i.useState(""),R=i.useRef(0),o=i.useRef(null);i.useEffect(()=>()=>{var l;R.current+=1,(l=o.current)==null||l.abort()},[]);const y=i.useCallback(async(l,S={})=>{const A=await t(!1);if(!A)throw new Error("Authentication required");let g=await fetch(l,{...S,headers:{...S.headers,Authorization:`Bearer ${A}`}});if(g.status===401||g.status===403){const h=await t(!0);h&&(g=await fetch(l,{...S,headers:{...S.headers,Authorization:`Bearer ${h}`}}))}return g},[t]),$=i.useCallback(async l=>{var h;const S=vs(l!=null?l:a),A=R.current+1;R.current=A,(h=o.current)==null||h.abort();const g=new AbortController;o.current=g,f(!0),m(""),j("");try{const C=new URLSearchParams({action:"report",days:String(S),refresh:"1"}),U=await y(`${br}/acquisition?${C.toString()}`,{signal:g.signal});if(!U.ok)throw new Error(await gr(U,"Failed to generate acquisition report"));const k=await U.json();if(!mr(k))throw new Error("The acquisition report response did not match the privacy-safe aggregate contract");if(Number(k.window.days)!==S)throw new Error("The acquisition report response did not match the requested cohort window");return A!==R.current?!1:(n(k),r(String(vs(k.window.days,S))),!0)}catch(C){return(C==null?void 0:C.name)==="AbortError"||A===R.current&&m((C==null?void 0:C.message)||"Failed to generate acquisition report"),!1}finally{A===R.current&&(f(!1),o.current===g&&(o.current=null))}},[y,a]),P=i.useCallback(async()=>{if(!s||!p||String(a)!==p||c||u)return!1;N(!0),j("");try{const l=cr(s);return(await fr(l,hr(s,p))).status!=="cancelled"}catch(l){return j((l==null?void 0:l.message)||"Failed to export acquisition report"),!1}finally{N(!1)}},[c,p,u,s,a]),E=!!(s&&p&&String(a)!==p);return i.useMemo(()=>({report:s,reportDays:a,loadedReportDays:p,loadingReport:u,exportingMarkdown:c,reportError:b,exportError:x,reportDirty:E,setReportDays:d,fetchAcquisitionReport:$,exportAcquisitionMarkdown:P}),[s,a,p,u,c,b,x,E,$,P])},jr=({onClose:t})=>{const s=Oa(),n=()=>{t?t():s("/dashboard")};return e.jsx("header",{className:"border-b border-slate-800 bg-slate-950/80 backdrop-blur-xl sticky top-0 z-40",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 py-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(qa,{className:"w-6 h-6 text-red-500"}),e.jsx("h1",{className:"text-xl font-bold",children:"Admin Panel"})]}),e.jsxs("button",{type:"button",onClick:n,className:"text-sm text-slate-400 hover:text-white flex items-center gap-2",children:[e.jsx(ht,{className:"w-4 h-4"}),"Close"]})]})})},Nr=({id:t,icon:s,label:n,active:a,focusable:d,onClick:p,onKeyDown:r,badge:u,buttonRef:f})=>{const c=s;return e.jsxs("button",{ref:f,type:"button",id:`admin-tab-${t}`,role:"tab","aria-selected":a,"aria-controls":"admin-tab-panel",tabIndex:a||d?0:-1,onClick:p,onKeyDown:r,className:`px-3 py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 text-sm relative ${a?"bg-indigo-600 text-white":"bg-slate-800 text-slate-400 hover:text-white hover:bg-slate-700"}`,children:[e.jsx(c,{className:"w-4 h-4"})," ",n,u>0&&e.jsx("span",{className:"absolute -top-1 -right-1 bg-red-500 text-white text-[10px] w-5 h-5 flex items-center justify-center rounded-full",children:u})]})},vr=({activeTab:t,onTabChange:s,newTicketCount:n=0,capabilities:a=["*"]})=>{const d=i.useRef([]),p=u=>a.includes("*")||a.includes(u),r=[{id:"users",icon:Ge,label:"Users",capability:"users:read"},{id:"tickets",icon:Ut,label:"Tickets",badge:n,capability:"support:read"},{id:"promos",icon:Va,label:"Promos",capability:"promos:read"},{id:"analyses",icon:Ys,label:"Analyses",capability:"analytics:read"},{id:"ratings",icon:Cs,label:"Ratings",capability:"analytics:read"},{id:"listing-drafts",icon:st,label:"Listing Drafts",capability:"analytics:read"},{id:"referrals",icon:es,label:"Referrals",capability:"analytics:read"},{id:"paying",icon:mt,label:"Paying",capability:"users:read"},{id:"chats",icon:bs,label:"AI Chats",capability:"analytics:read"},{id:"acquisition",icon:Fs,label:"Acquisition",capability:"analytics:read"},{id:"paid-acquisition",icon:za,label:"Paid Acquisition",capability:"analytics:read"},{id:"telemetry",icon:Rt,label:"Telemetry",capability:"analytics:read"},{id:"marketing",icon:Ut,label:"Marketing",capability:"marketing:read"},{id:"analysis-export",icon:Pe,label:"Export",capability:"analytics:export"}].filter(u=>p(u.capability));return e.jsx("div",{role:"tablist","aria-label":"Admin sections",className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 lg:grid-cols-12 gap-2 mb-6",children:r.map((u,f)=>e.jsx(Nr,{id:u.id,icon:u.icon,label:u.label,active:t===u.id,focusable:!t&&f===0,onClick:()=>s(u.id),badge:u.badge,buttonRef:c=>{d.current[f]=c},onKeyDown:c=>{var b;if(!["ArrowLeft","ArrowRight","Home","End"].includes(c.key))return;c.preventDefault();const N=c.key==="Home"?0:c.key==="End"?r.length-1:(f+(c.key==="ArrowRight"?1:-1)+r.length)%r.length;
20s(r[N].id),(b=d.current[N])==null||b.focus()}},u.id))})},wr=({icon:t,color:s,label:n,value:a,definition:d,detail:p})=>{const r=t;return e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl p-4 sm:p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 sm:w-10 sm:h-10 rounded-lg bg-slate-900/70 border border-slate-700 flex items-center justify-center shrink-0",children:e.jsx(r,{className:`w-5 h-5 sm:w-5 sm:h-5 ${s}`})}),e.jsx("span",{className:"text-slate-400 text-sm sm:text-sm leading-tight",title:d,children:n})]}),e.jsx("p",{className:"text-2xl sm:text-3xl font-bold",children:(a==null?void 0:a.toLocaleString())||0}),p&&e.jsx("p",{className:"mt-1 text-xs text-slate-500",children:p})]})},Cr=({stats:t})=>{var n,a,d,p,r,u,f,c,N;if(!t)return null;const s=[{icon:Ge,color:"text-blue-400",label:"Root User Records",value:t.totalUsers,definition:(a=(n=t.metricDefinitions)==null?void 0:n.totalUsers)==null?void 0:a.definition,detail:Number.isFinite(t.canonicalProfileCount)?`${t.canonicalProfileCount.toLocaleString()} canonical profiles (${t.profileGapCount||0} record gap)`:"Canonical profile census unavailable"},{icon:es,color:"text-emerald-400",label:"New Root Records Today (UTC)",value:(d=t.newRootRecordsTodayUtc)!=null?d:t.newUsersToday,definition:((r=(p=t.metricDefinitions)==null?void 0:p.newRootRecordsTodayUtc)==null?void 0:r.definition)||((f=(u=t.metricDefinitions)==null?void 0:u.newUsersToday)==null?void 0:f.definition)},{icon:pt,color:"text-yellow-400",label:"History Documents",value:t.totalAnalyses,definition:(N=(c=t.metricDefinitions)==null?void 0:c.totalAnalyses)==null?void 0:N.definition}];return e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4 mb-8",children:s.map((b,m)=>e.jsx(wr,{icon:b.icon,color:b.color,label:b.label,value:b.value,definition:b.definition,detail:b.detail},m))})},Ia=["button:not([disabled])","a[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function As(t,s){const n=i.useRef(null);return i.useEffect(()=>{if(!t)return;const a=document.activeElement,d=n.current,p=document.body.style.overflow;document.body.style.overflow="hidden";const r=()=>{var N,b;(b=(N=(d==null?void 0:d.querySelector(Ia))||d)==null?void 0:N.focus)==null||b.call(N)},u=window.requestAnimationFrame(r),f=c=>{if(c.key==="Escape"){c.preventDefault(),s==null||s();return}if(c.key!=="Tab"||!d)return;const N=[...d.querySelectorAll(Ia)].filter(x=>x.getClientRects().length>0);if(N.length===0){c.preventDefault(),d.focus();return}const b=N[0],m=N[N.length-1];c.shiftKey&&document.activeElement===b?(c.preventDefault(),m.focus()):!c.shiftKey&&document.activeElement===m&&(c.preventDefault(),b.focus())};return document.addEventListener("keydown",f),()=>{var c;window.cancelAnimationFrame(u),document.removeEventListener("keydown",f),document.body.style.overflow=p,(c=a==null?void 0:a.focus)==null||c.call(a)}},[s,t]),n}function Sr({tone:t}){return t==="error"?e.jsx(At,{className:"h-4 w-4 text-red-300"}):t==="success"?e.jsx(Ha,{className:"h-4 w-4 text-emerald-300"}):e.jsx(gs,{className:"h-4 w-4 text-blue-300"})}function Ar({children:t}){const[s,n]=i.useState([]),[a,d]=i.useState(null),[p,r]=i.useState(""),u=i.useCallback((c=!1)=>{d(N=>{var b;return(b=N==null?void 0:N.resolve)==null||b.call(N,c),null}),r("")},[]),f=As(!!a,()=>u(!1));return i.useEffect(()=>{const c=_n(),N=m=>{var R,o;const x=((o=(R=globalThis.crypto)==null?void 0:R.randomUUID)==null?void 0:o.call(R))||`${Date.now()}_${Math.random()}`,j={id:x,tone:"info",...m.detail};n(y=>[...y.slice(-3),j]),window.setTimeout(()=>n(y=>y.filter($=>$.id!==x)),j.duration||6500)},b=m=>{r(""),d(m.detail)};return window.addEventListener(qs,N),window.addEventListener(Vs,b),()=>{c(),window.removeEventListener(qs,N),window.removeEventListener(Vs,b),d(m=>{var x;return(x=m==null?void 0:m.resolve)==null||x.call(m,!1),null})}},[]),e.jsxs(e.Fragment,{children:[t,e.jsx("div",{className:"fixed right-4 top-4 z-[80] w-[min(24rem,calc(100vw-2rem))] space-y-2","aria-live":"polite","aria-atomic":"false",children:s.map(c=>e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-slate-600 bg-slate-900 p-3 text-sm text-slate-200 shadow-xl",children:[e.jsx(Sr,{tone:c.tone}),e.jsxs("div",{className:"min-w-0 flex-1",children:[c.title&&e.jsx("p",{className:"font-semibold text-white",children:c.title}),e.jsx("p",{className:"break-words",children:c.message}),c.operationId&&e.jsxs("p",{className:"mt-1 break-all font-mono text-[11px] text-slate-500",children:["Operation ",c.operationId]})]}),e.jsx("button",{type:"button",onClick:()=>n(N=>N.filter(b=>b.id!==c.id)),"aria-label":"Dismiss notification",className:"rounded p-1 hover:bg-slate-800",children:e.jsx(ht,{className:"h-3.5 w-3.5"})})]},c.id))}),a&&e.jsx("div",{className:"fixed inset-0 z-[90] flex items-center justify-center bg-black/75 p-4",onMouseDown:c=>c.target===c.currentTarget&&u(!1),children:e.jsxs("div",{ref:f,role:"alertdialog","aria-modal":"true","aria-labelledby":"admin-confirm-title","aria-describedby":"admin-confirm-description",tabIndex:-1,
20className:"w-full max-w-md rounded-xl border border-slate-600 bg-slate-900 p-5 shadow-2xl",children:[e.jsx("h2",{id:"admin-confirm-title",className:"text-lg font-bold text-white",children:a.title||"Confirm admin action"}),e.jsx("p",{id:"admin-confirm-description",className:"mt-2 whitespace-pre-wrap text-sm text-slate-300",children:a.message}),a.detail&&e.jsx("p",{className:"mt-2 rounded bg-slate-950 p-2 text-xs text-slate-400",children:a.detail}),a.requiredText&&e.jsxs("label",{className:"mt-4 block text-xs font-medium text-slate-300",children:["Type ",e.jsx("span",{className:"font-mono text-amber-300",children:a.requiredText})," to continue",e.jsx("input",{autoComplete:"off",value:p,onChange:c=>r(c.target.value),"aria-label":"Typed confirmation",className:"mt-2 w-full rounded-lg border border-slate-600 bg-slate-950 px-3 py-2 font-mono text-sm text-white outline-none focus:border-indigo-500"})]}),e.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>u(!1),className:"rounded-lg bg-slate-700 px-4 py-2 text-sm font-medium hover:bg-slate-600",children:"Cancel"}),e.jsx("button",{type:"button",disabled:!!a.requiredText&&p!==a.requiredText,onClick:()=>u(!0),className:`rounded-lg px-4 py-2 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:opacity-40 ${a.destructive?"bg-red-600 hover:bg-red-500":"bg-indigo-600 hover:bg-indigo-500"}`,children:a.confirmLabel||"Continue"})]})]})})]})}const Ts=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",Kt={complete:{label:"Complete",className:"text-emerald-300 bg-emerald-500/10",Icon:fn},failed:{label:"Failed",className:"text-red-300 bg-red-500/10",Icon:wa},canceled:{label:"Canceled",className:"text-slate-300 bg-slate-500/10",Icon:wa},needs_reconciliation:{label:"Needs reconciliation",className:"text-amber-300 bg-amber-500/10",Icon:At},external_cleanup_pending:{label:"External cleanup pending",className:"text-amber-300 bg-amber-500/10",Icon:At},running:{label:"Running",className:"text-blue-300 bg-blue-500/10",Icon:H},requested:{label:"Requested",className:"text-slate-300 bg-slate-500/10",Icon:gn}};function kr(t){return String(t||"operation").replaceAll("_"," ")}function Ds(t){return!t||typeof t!="object"||Array.isArray(t)?"":Object.entries(t).filter(([,s])=>["string","number","boolean"].includes(typeof s)||s===null).slice(0,6).map(([s,n])=>`${s}: ${n!=null?n:"none"}`).join(" / ")}function $r(t){return Kt[t]?Kt[t]:["complete","failed","canceled"].includes(t)?Kt.requested:Kt.running}function Er({operation:t,onDownloadFailures:s,downloadingFailures:n,onRetry:a,retrying:d,canRetryDeletion:p}){const r=$r(t.state),u=r.Icon,f=Ds(t.progress),c=t.steps&&typeof t.steps=="object"?Object.entries(t.steps).filter(([,m])=>m===!0).map(([m])=>m.replaceAll("_"," ")):[],N=Ds(t.before),b=Ds(t.after);return e.jsxs("li",{className:"rounded-lg border border-slate-700 bg-slate-950/60 p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold capitalize text-white",children:kr(t.type)}),e.jsx("p",{className:"mt-0.5 break-all font-mono text-[11px] text-slate-500",children:t.id})]}),e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full px-2 py-1 text-[11px] font-semibold ${r.className}`,children:[e.jsx(u,{className:`h-3.5 w-3.5 ${r===Kt.running?"animate-spin":""}`}),r.label]})]}),e.jsxs("div",{className:"mt-2 space-y-1 text-xs text-slate-400",children:[t.targetUid&&e.jsxs("p",{children:["Target: ",e.jsx("span",{className:"break-all font-mono",children:t.targetUid})]}),t.adminUid&&e.jsxs("p",{children:["Actor: ",e.jsx("span",{className:"break-all font-mono",children:t.adminUid})]}),t.updatedAt&&e.jsxs("p",{children:["Updated ",new Date(t.updatedAt).toLocaleString()]}),f&&e.jsx("p",{className:"break-words",children:f}),c.length>0&&e.jsxs("p",{className:"break-words",children:["Completed steps: ",c.join(", ")]}),(N||b)&&e.jsxs("p",{className:"break-words",children:["Before: ",N||"not recorded"," / After: ",b||"not recorded"]}),t.sourceOperationId&&e.jsxs("p",{children:["Source: ",e.jsx("span",{className:"break-all font-mono",children:t.sourceOperationId})]}),t.failureCount>0&&e.jsxs("p",{className:"text-amber-300",children:[t.failureCount," recorded failure",t.failureCount===1?"":"s",t.retryState?` / retry ${t.retryState.replaceAll("_"," ")}`:""]}),t.retryable&&p&&e.jsxs("button",{type:"button",onClick:()=>a(t),disabled:d,className:"inline-flex min-h-8 items-center gap-1 rounded px-2 py-1 text-xs text-amber-300 hover:bg-amber-500/10 disabled:opacity-50",children:[d?e.jsx(H,{className:"h-3 w-3 animate-spin"}):e.jsx(Fe,{className:"h-3 w-3"}),"Resume cleanup"]}),t.error&&e.jsxs("p",{className:"rounded bg-red-500/10 p-2 text-red-300",role:"alert",children:[t.errorCode?`${t.errorCode}: `:"",t.error]})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(t.id),K("Operation ID copied.",{tone:"success"})}catch{K("Copy failed. Select the operation ID above and copy it manually.",{tone:"error"})}},className:"inline-flex min-h-8 items-center gap-1 rounded px-2 py-1 text-xs text-indigo-300 hover:bg-indigo-500/10",children:[e.jsx(Ga,{className:"h-3 w-3"})," Copy ID"]}),t.failureCount>0&&e.jsxs("button",{type:"button",onClick:()=>s(t),disabled:n,className:"inline-flex min-h-8 items-center gap-1 rounded px-2 py-1 text-xs text-amber-300 hover:bg-amber-500/10 disabled:opacity-50",children:[n?e.jsx(H,{className:"h-3 w-3 animate-spin"}):e.jsx(Pe,{className:"h-3 w-3"}),"Download failures"]})]})]})}function Ir({open:t,onClose:s,getAuthToken:n,loadOperations:a=null,loadOperationFailures:d=null,capabilities:p=["*"]}){const[r,u]=i.useState([]),[f,c]=i.useState(!1),[N,b]=i.useState(""),[m,x]=i.useState(""),[j,R]=i.useState(null),[o,y]=i.useState(null),$=As(t,s),P=p.includes("*")||p.includes("users:write"),E=i.useCallback(async({quiet:g=!1}={})=>
20{if(t){g||c(!0),b("");try{if(typeof a=="function"){const I=await a({state:m});u(Array.isArray(I)?I:(I==null?void 0:I.operations)||[]);return}const h=await n(!1);if(!h)throw new Error("Authentication required");const C=new URLSearchParams({action:"operations",limit:"100",_t:String(Date.now())});m&&C.set("state",m);const U=await fetch(`${Ts}/admin?${C.toString()}`,{headers:{Authorization:`Bearer ${h}`}}),k=await U.json().catch(()=>({}));if(!U.ok)throw new Error(k.error||"Failed to load admin operations");u(k.operations||[])}catch(h){b(h.message||"Failed to load admin operations")}finally{c(!1)}}},[n,a,t,m]),l=i.useCallback(async g=>{R(g.id);try{let h=[];if(typeof d=="function"){const k=await d(g.id);h=Array.isArray(k)?k:(k==null?void 0:k.failures)||[]}else{const k=await n(!1);if(!k)throw new Error("Authentication required");let I="",O=!0,Z=0;for(;O&&Z<1e4;){const D=new URLSearchParams({action:"operation-failures",operationId:g.id,limit:"500"});I&&D.set("cursor",I);const ee=await fetch(`${Ts}/admin?${D.toString()}`,{headers:{Authorization:`Bearer ${k}`}}),V=await ee.json().catch(()=>({}));if(!ee.ok)throw new Error(V.error||"Failed to load operation failures");h.push(...V.failures||[]),O=V.hasMore===!0,I=V.nextCursor||"",Z+=1}if(O)throw new Error("Failure export exceeded its page safety limit")}if(h.length===0){K("This operation has no retained failure rows.",{tone:"info"});return}const C=Tt(["Failure ID","UID","Email","Code","Error","HTTP Status","Retry After","Retryable","Resolved","Resolution","Attempts","Updated At"],h.map(k=>[k.id,k.uid,k.email,k.code,k.error,k.status,k.retryAfter,k.retryable,k.resolved,k.resolutionCode,k.attemptCount,k.updatedAt])),U=new Blob([`\uFEFF${C}`],{type:"text/csv;charset=utf-8"});await Ve(U,`admin_operation_failures_${g.id.replace(/[^a-zA-Z0-9_-]/g,"_")}.csv`,`${h.length} failure rows.`)}catch(h){K(h.message||"Failure export failed.",{title:"Download failed",tone:"error"})}finally{R(null)}},[n,d]),S=i.useCallback(async g=>{if(await Qe({title:"Resume account-deletion cleanup?",message:"This resumes only the unfinished checkpoints recorded for this deletion. Completed Stripe, database, authentication, and marketing steps will not be repeated.",detail:`Operation ${g.id} / target ${g.targetUid||"unknown"}`,requiredText:"RESUME",confirmLabel:"Resume cleanup",destructive:!0})){y(g.id);try{const C=await n(!1);if(!C)throw new Error("Authentication required");const U=await fetch(`${Ts}
20/admin?action=retry-delete-user`,{method:"POST",headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"},body:JSON.stringify({operationId:g.id})}),k=await U.json().catch(()=>({}));if(!U.ok){const I=new Error(k.error||"Account-deletion cleanup is still incomplete");throw I.operationId=k.operationId||g.id,I}K(k.message||"Account-deletion cleanup completed.",{tone:"success",operationId:k.operationId||g.id})}catch(C){K(C.message||"Account-deletion cleanup could not be resumed.",{title:"Cleanup still needs attention",tone:"error",operationId:C.operationId||g.id})}finally{y(null),await E({quiet:!0})}}},[E,n]);i.useEffect(()=>{if(!t)return;E();const g=window.setInterval(()=>E({quiet:!0}),15e3);return()=>window.clearInterval(g)},[E,t]);const A=i.useMemo(()=>r.filter(g=>!["complete","failed","canceled"].includes(g.state)).length,[r]);return t?e.jsx("div",{className:"fixed inset-0 z-[70] flex justify-end bg-black/65",onMouseDown:g=>g.target===g.currentTarget&&s(),children:e.jsxs("aside",{ref:$,role:"dialog","aria-modal":"true","aria-labelledby":"admin-operations-title",tabIndex:-1,className:"flex h-full w-full max-w-lg flex-col border-l border-slate-700 bg-slate-900 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-slate-700 p-4",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"admin-operations-title",className:"text-lg font-bold text-white",children:"Recent operations"}),e.jsxs("p",{className:"text-xs text-slate-400",children:[A," active or requiring attention / refreshes every 15 seconds"]})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close recent operations",className:"rounded p-2 text-slate-400 hover:bg-slate-800 hover:text-white",children:e.jsx(ht,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"flex items-center gap-2 border-b border-slate-800 p-3",children:[e.jsx("label",{htmlFor:"operation-state-filter",className:"text-xs text-slate-400",children:"State"}),e.jsxs("select",{id:"operation-state-filter",value:m,onChange:g=>x(g.target.value),className:"min-w-0 flex-1 rounded border border-slate-700 bg-slate-950 px-2 py-1.5 text-sm text-white",children:[e.jsx("option",{value:"",children:"All recent"}),e.jsx("option",{value:"running",children:"Running"}),e.jsx("option",{value:"requested",children:"Requested"}),e.jsx("option",{value:"needs_reconciliation",children:"Needs reconciliation"}),e.jsx("option",{value:"external_cleanup_pending",children:"External cleanup pending"}),e.jsx("option",{value:"failed",children:"Failed"}),e.jsx("option",{value:"complete",children:"Complete"})]}),e.jsx("button",{type:"button",onClick:()=>E(),disabled:f,"aria-label":"Refresh operations",className:"rounded p-2 text-slate-300 hover:bg-slate-800 disabled:opacity-50",children:e.jsx(Fe,{className:`h-4 w-4 ${f?"animate-spin":""}`})})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:[N&&e.jsx("div",{className:"mb-3 rounded border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-300",role:"alert",children:N}),f&&r.length===0?e.jsxs("div",{className:"flex justify-center p-10",role:"status",children:[e.jsx(H,{className:"h-6 w-6 animate-spin text-indigo-400"}),e.jsx("span",{className:"sr-only",children:"Loading operations"})]}):r.length===0?e.jsx("p",{className:"p-10 text-center text-sm text-slate-500",children:"No operations match this filter."}):e.jsx("ul",{className:"space-y-3",children:r.map(g=>e.jsx(Er,{operation:g,onDownloadFailures:l,downloadingFailures:j===g.id,onRetry:S,retrying:o===g.id,canRetryDeletion:P},g.id))})]})]})}):null}const Rr=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",Pr={web:"Web",ios:"iOS",android:"Android",chrome_extension:"Chromium extension",firefox_extension:"Firefox extension"};function Ur({getAuthToken:t,onOpenAnalysis:s}){var y,$;const[n,a]=i.useState("all"),[d,p]=i.useState([]),[r,u]=i.useState(null),[f,c]=i.useState(null),[N,b]=i.useState(!1),[m,x]=i.useState(""),j=i.useRef(null),R=i.useCallback(async(P=null)=>{var l;(l=j.current)==null||l.abort();const E=new AbortController;j.current=E,b(!0),x(""),P||(p([]),c(null));try{const S=await t(),A=new URLSearchParams({action:"analysis-ratings",rating:n});P&&A.set("cursor",P);const g=await fetch(`${Rr}/admin?${A}`,{headers:{Authorization:`Bearer ${S}`},signal:E.signal}),h=await g.json();if(!g.ok)throw new Error(h.error||"Could not load ratings.");if(E.signal.aborted)return;p(C=>P?[...new Map([...C,...h.ratings].map(U=>[U.id,U])).values()]:h.ratings),u(h.totals),c(h.nextCursor)}catch(S){E.signal.aborted||x(S.message||"Could not load ratings.")}finally{E.signal.aborted||b(!1)}},[t,n]);i.useEffect(()=>(R(),()=>{var P;return(P=j.current)==null?void 0:P.abort()}),[R]);const o=r?r.up+r.down:0;return e.jsxs("section",{className:"rounded-2xl border border-slate-700 bg-slate-800/50 p-4 sm:p-6","aria-label":"Analysis ratings",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:"Analysis ratings"}),e.jsx("p",{className:"mt-1 text-xs text-slate-400",children:"One current vote per item. Notes are optional."})]}),e.jsxs("button",{type:"button",onClick:()=>R(),disabled:N,className:"flex min-h-11 items-center gap-2 rounded-lg bg-slate-700 px-3 text-sm text-white disabled:opacity-50",children:[e.jsx(yn,{className:`h-4 w-4 ${N?"animate-spin":""}`}),"Refresh"]})]}),e.jsx("div",{className:"mb-5 grid grid-cols-3 gap-2 text-center",children:[["Total ratings",r?o:"—"],["Helpful",(y=r==null?void 0:r.up)!=null?y:"—"],["Not helpful",($=r==null?void 0:r.down)!=null?$:"—"]].map(([P,E])=>e.jsxs("div",{className:"rounded-xl border border-slate-700 bg-slate-900/60 p-3",children:[e.jsx("p",{className:"text-xl font-bold text-white",children:E}),e.jsx("p",{className:"mt-1 text-xs text-slate-400",children:P})]},P))}),o>0&&e.jsxs("p",{className:"mb-4 text-sm text-slate-400",children:[Math.round(r.up/o*100),"% found their analysis helpful."]}),e.jsxs("label",{className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-slate-300",children:["Show",e.jsxs("span",{className:"relative",children:[e.jsxs("select",{"aria-label":"Filter analysis ratings",value:n,onChange:P=>a(P.target.value),className:"min-h-11 appearance-none rounded-lg border border-slate-600 bg-slate-900 py-2 pl-3 pr-9 text-white [color-scheme:dark]",children:[e.jsx("option",{value:"all",children:"All ratings"}),e.jsx("option",{value:"down",children:"Not helpful"}),e.jsx("option",{value:"up",children:"Helpful"})]}),e.jsx(jn,{"aria-hidden":"true",className:"pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2"})]})]}),m&&e.jsx("p",{role:"alert",className:"mb-4 text-sm text-amber-300",children:m}),e.jsxs("div",{className:"space-y-3","aria-busy":N,children:[d.map(P=>{const E=P.rating==="up"?Cs:Wa;return e.jsx("article",{className:"rounded-xl border border-slate-700 bg-slate-900/60 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(E,{"aria-label":P.rating==="up"?"Helpful":"Not helpful",className:`mt-1 h-5 w-5 shrink-0 ${P.rating==="up"?"text-emerald-400":"text-rose-400"}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"break-words text-sm font-semibold text-white",children:P.title}),e.jsxs("p",{className:"mt-1 break-words text-xs text-slate-500",children:[Pr[P.source]||P.source," · Item ",P.itemIndex+1," · ",P.updatedAt?new Date(P.updatedAt).toLocaleStr
20ing():"Date unavailable"]}),e.jsxs("p",{className:"mt-1 break-all text-xs text-slate-500",children:["User: ",P.userId]}),P.note?e.jsx("p",{className:"mt-3 whitespace-pre-wrap break-words text-sm text-slate-200",children:P.note}):e.jsx("p",{className:"mt-3 text-xs text-slate-500",children:"No note added."}),e.jsx("button",{type:"button",onClick:()=>s(P),className:"mt-2 min-h-11 text-xs font-medium text-indigo-300 underline underline-offset-4 hover:text-white",children:"Open analysis"})]})]})},P.id)}),!N&&!m&&!d.length&&e.jsx("p",{className:"py-8 text-center text-sm text-slate-400",children:"No ratings yet."}),N&&e.jsx("p",{role:"status",className:"py-3 text-sm text-slate-400",children:"Loading ratings…"})]}),f&&e.jsx("button",{type:"button",onClick:()=>R(f),disabled:N,className:"mt-4 min-h-11 rounded-lg bg-indigo-600 px-4 text-sm font-semibold text-white disabled:opacity-40",children:"Load more"})]})}const Tr=({users:t,loadingUsers:s,usersError:n,usersLookupMeta:a,usersSearchPending:d=!1,selectedUser:p,userDetails:r,userDetailsError:u,loadingDetails:f,loadingDetailsMetrics:c,hasMore:N,searchQuery:b,adjustAmount:m,adjustReason:x,adjusting:j,topUpCredits:R,topUpInvoiceId:o,topUpNote:y,topUpSubmitting:$,selectedTier:P,tierChangeReason:E,changingTier:l,selectedSubscriptionStatus:S,statusChangeReason:A,changingSubscriptionStatus:g,deleting:h,exportStartDate:C,exportEndDate:U,exportLimit:k,showExportOptions:I,exportingHistory:O,setSelectedUser:Z,setSearchQuery:D,setAdjustAmount:ee,setAdjustReason:V,setTopUpCredits:X,setTopUpInvoiceId:ae,setTopUpNote:q,setSelectedTier:te,setTierChangeReason:w,setSelectedSubscriptionStatus:v,setStatusChangeReason:M,setExportStartDate:_,setExportEndDate:B,setExportLimit:J,setShowExportOptions:re,fetchUsers:F,fetchUserDetails:se,handleAdjustCredits:ye,handlePaidTopUp:oe,handleChangeTier:be,handleChangeSubscriptionStatus:ge,handleQuickSetSubscriptionStatus:ce,handleDeleteUser:Se,handleExportUserHistory:Ie,repairProfiles:Oe,applyRepairPlan:bt,repairing:We,repairResult:le,repairAnnualCreditCycles:gt,repairingAnnualCycles:Te,annualCycleRepairResult:Ae,onAfterRepair:De,capabilities:nt=["*"]})=>{var Mt,Lt,vt,Ft,Ot,Bt,W,Y,z,Q;const[rt,it]=i.useState(!1),[Ye,lt]=i.useState(""),ve=[100,250,500],Ce=!1,ft=T=>nt.includes("*")||nt.includes(T),Dt=ft("users:write"),yt=ft("billing:write"),ts=ft("maintenance:write"),ss=ft("analytics:export"),jt=b.trim(),ot=d||s&&!!jt,as=s&&t.length>0,kt=(a==null?void 0:a.searchTooShort)&&!!jt,Nt=Number.isFinite(a==null?void 0:a.total)?a.total:t.length,ke=c||!!(r!=null&&r.metricsPending),Xe=()=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm font-medium text-slate-400",children:[e.jsx(H,{className:"w-3.5 h-3.5 animate-spin text-indigo-400"}),"Loading..."]}),ns=async()=>{it(!0);try{await F(b,!1,!0)}finally{setTimeout(()=>it(!1),500)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"font-bold text-lg",children:"Users"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("button",{type:"button",onClick:gt,disabled:Te||!yt,className:"flex min-h-8 items-center gap-1 rounded-lg px-2 py-1.5 text-xs text-cyan-400 transition-colors hover:bg-slate-700 hover:text-cyan-300 disabled:opacity-50",title:"Audit Stripe-backed annual subscriptions and repair stale monthly credit cycles",children:[Te?e.jsx(H,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Fe,{className:"w-3.5 h-3.5"}),Te?"Auditing...":"Audit Annual Cycles"]}),e.jsxs("button",{type:"button",onClick:Oe,disabled:We||!ts,className:"flex min-h-8 items-center gap-1 rounded-lg px-2 py-1.5 text-xs text-amber-400 transition-colors hover:bg-slate-700 hover:text-amber-300 disabled:opacity-50",title:"Create a write-free preview for identity, root-document, and intro-credit repairs",children:[We?e.jsx(H,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Nn,{className:"w-3.5 h-3.5"}),We?"Working…":"Preview Repairs"]}),e.jsx("button",{type:"button",onClick:ns,disabled:rt||s,className:"min-h-8 min-w-8 rounded-lg p-1.5 text-slate-400 transition-colors hover:bg-slate-700 hover:text-white",title:"Refresh users list",children:e.jsx(Fe,{className:`w-4 h-4 ${rt?"animate-spin":""}`})})]})]}),le&&e.jsx("div",{className:`mb-2 text-xs rounded-lg px-3 py-2 ${le.error?"bg-red-900/40 text-red-300 border border-red-700":"bg-green-900/40 text-green-300 border border-green-700"}`,children:le.error?`Repair error: ${le.error}
20${le.operationId?` (operation ${le.operationId})`:""}`:le.mode==="dry-run"&&!le.state?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{children:["Preview scanned ",le.scannedAuthUsers," Auth users and found ",le.candidateCount," candidate(s). No user data was changed. Plan expires in one hour."]}),le.candidateCount>0&&e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx("label",{htmlFor:"repair-confirmation",className:"sr-only",children:"Repair confirmation phrase"}),e.jsx("input",{id:"repair-confirmation",value:Ye,onChange:T=>lt(T.target.value),placeholder:`Type APPLY ${le.candidateCount}`,className:"min-w-0 flex-1 rounded border border-slate-600 bg-slate-950 px-2 py-1 text-xs text-white"}),e.jsx("button",{type:"button",onClick:async()=>{await bt(Ye),De&&De()},disabled:We||Ye!==`APPLY ${le.candidateCount}`,className:"rounded bg-amber-600 px-3 py-1 font-semibold text-white disabled:opacity-40",children:"Apply previewed plan"})]})]}):e.jsxs("span",{children:["Repair ",le.state||"running",": ",((Mt=le.progress)==null?void 0:Mt.applied)||0," applied,"," ",((Lt=le.progress)==null?void 0:Lt.failed)||0," failed of ",(Ot=(Ft=(vt=le.progress)==null?void 0:vt.total)!=null?Ft:le.candidateCount)!=null?Ot:0,".",le.operationId?` Operation ${le.operationId}.`:""]})}),Ae&&e.jsx("div",{className:`mb-2 rounded-lg border px-3 py-2 text-xs ${Ae.error?"border-red-700 bg-red-900/40 text-red-300":Ae.mode==="apply"?"border-emerald-700 bg-emerald-900/40 text-emerald-300":"border-cyan-700 bg-cyan-900/40 text-cyan-200"}`,children:Ae.error?`Annual audit error: ${Ae.error}`:Ae.mode==="apply"?`Annual repair complete: ${Ae.repairedCount||0} repaired, ${Ae.resetAppliedCount||0} usage resets, ${Ae.failedCount||0} failed.`:`Annual audit: ${Ae.paidProfiles||0} paid profiles checked, ${Ae.annualSubscribers||0} annual subscribers, ${Ae.candidateCount||0} needing repair.`}),e.jsxs("div",{className:"relative",children:[ot?e.jsx(H,{className:"w-4 h-4 text-indigo-400 absolute left-3 top-1/2 -translate-y-1/2 animate-spin"}):e.jsx(at,{className:"w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx("input",{type:"text","aria-label":"Search users",value:b,onChange:T=>D(T.target.value),placeholder:"Search by email, UID, or name...","aria-busy":ot,className:`w-full bg-slate-900 border rounded-lg pl-10 pr-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none transition-colors ${ot?"border-indigo-500/70":"border-slate-600"}`})]}),(ot||kt||jt&&!s&&!n)&&e.jsx("div",{className:"mt-2 flex items-center gap-2 text-xs text-slate-400 min-h-4",children:ot?e.jsxs(e.Fragment,{children:[e.jsx(H,{className:"w-3.5 h-3.5 animate-spin text-indigo-400"}),e.jsx("span",{children:"Searching users..."})]}):kt?e.jsxs("span",{children:["Type at least ",a.minBroadSearchChars||3," characters, or paste an email."]}):e.jsxs("span",{children:[Nt===1?"1 match":`${Nt} matches`,(a==null?void 0:a.source)==="fast"?" from fast lookup":""]})}),n&&e.jsx("p",{className:"mt-2 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-xs text-red-300",children:n})]}),e.jsxs("div",{className:"max-h-[500px] overflow-y-auto",children:[as&&e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-center gap-2 border-b border-indigo-500/20 bg-slate-900/95 px-4 py-2 text-xs text-indigo-200 backdrop-blur",children:[e.jsx(H,{className:"w-3.5 h-3.5 animate-spin"}),"Updating results..."]}),s&&t.length===0&&e.jsxs("div",{className:"p-8 flex flex-col items-center justify-center gap-2 text-sm text-slate-400",children:[e.jsx(H,{className:"w-5 h-5 animate-spin text-indigo-400"}),e.jsx("span",{children:jt?"Searching users...":"Loading users..."})]}),t.map(T=>e.jsx("button",{type:"button",onClick:()=>Z(T.uid),"aria-pressed":p===T.uid,"aria-label":`View ${T.displayName||T.email||T.uid}`,className:`block w-full p-4 text-left border-b border-slate-700/50 cursor-pointer hover:bg-slate-700/30 transition-colors ${p===T.uid?"bg-indigo-900/30 border-l-2 border-l-indigo-500":""}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[T.photoURL?e.jsx("img",{src:T.photoURL,alt:T.displayName||"User avatar",className:"w-8 h-8 rounded-full"}):e.jsx("div",{className:"w-8 h-8 rounded-full bg-slate-600 flex items-center justify-center",children:e.jsx(Ge,{className:"w-4 h-4 text-slate-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:T.displayName||"Anonymous"}),e.jsx("p",{className:"text-sm text-slate-400 truncate",children:T.email||"No email"})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium text-emerald-400",children:[T.totalCredits," cr"]}),e.jsxs("p",{className:"text-xs text-slate-500",children:[T.planName||T.subscriptionTier||"Free"," plan"]})]})]})},T.uid)),N&&e.jsx("button",{type:"button",onClick:()=>F(b,!0),disabled:s,className:"w-full p-3 text-sm text-indigo-400 hover:bg-slate-700/30",children:"Load more..."}),!s&&t.length===0&&e.jsx("p",{className:"p-8 text-center text-slate-500",children:kt?`Type at least ${a.minBroadSearchChars||3} characters, or paste an email.`:"No users found"})]})]}),e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"p-4 border-b border-slate-700",children:e.jsx("h2",{className:"font-bold text-lg",children:"User Details"})}),u&&e.jsxs("div",{className:"m-4 flex items-center justify-between gap-3 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",role:"alert",children:[e.jsxs("span",{children:[u,r?" The previously loaded profile remains visible below.":""]}),e.jsx("button",{type:"button",onClick:()=>se(p),className:"rounded bg-red-500/20 px-2 py-1 font-medium hover:bg-red-500/30",children:"Retry"})]}),f&&!r?e.jsx("div",{className:"p-8 flex justify-center",children:e.jsx(H,{className:"w-6 h-6 animate-spin text-indigo-500"})}):r?e.jsxs("div",{className:"p-4 space-y-6 max-h-[70vh] overflow-y-auto",children:[f&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-indigo-500/30 bg-indigo-500/10 px-3 py-2 text-xs text-indigo-200",role:"status",children:[e.jsx(H,{className:"h-3.5 w-3.5 animate-spin"})," Loading the selected user; this profile is stale until that finishes."]}),e.jsxs("div",{className:"flex items-center gap-4",children:[r.photoURL?e.jsx("img",{src:r.photoURL,alt:r.displayName||"User profile photo",className:"w-16 h-16 rounded-full"}):e.jsx("div",{className:"w-16 h-16 rounded-full bg-slate-600 flex items-center justify-center",children:e.jsx(Ge,{className:"w-8 h-8 text-slate-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg",children:r.displayName}),e.jsx("p",{className:"text-slate-400",children:r.email||"Anonymous"}),e.jsx("p",{className:"text-xs text-slate-500 font-mono mt-1",children:r.uid})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Usage"}),e.jsx("p",{className:"text-xl font-bold text-emerald-400",children:r.subscriptionTier&&r.subscriptionTier!=="free"?`${r.periodUsage||0}/${r.monthlyLimit||500}
20`:`${r.introCreditsUsed||0}/5`}),e.jsxs("p",{className:"text-xs text-slate-500",children:[r.subscriptionTier||"free"," tier"]}),(r.bonusCredits>0||r.adminCreditBonus>0)&&e.jsxs("p",{className:"text-xs text-slate-500",children:[r.bonusCredits>0?`+${r.bonusCredits} paid/bonus`:"",r.bonusCredits>0&&r.adminCreditBonus>0?" · ":"",r.adminCreditBonus>0?`+${r.adminCreditBonus} admin`:""]})]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Total Spent"}),ke?Xe():e.jsxs("p",{className:"text-xl font-bold",children:["$",(Number(r.totalSpent)||0).toFixed(2)]})]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Analyses"}),ke?Xe():e.jsx("p",{className:"text-xl font-bold",children:r.analysisCount})]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Flip Tracker"}),ke?Xe():e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xl font-bold text-purple-400",children:((Bt=r.flipStats)==null?void 0:Bt.totalFlips)||0}),e.jsxs("p",{className:"text-xs text-slate-500",children:[((W=r.flipStats)==null?void 0:W.activeFlips)||0," active · $",((z=(Y=r.flipStats)==null?void 0:Y.totalProfit)==null?void 0:z.toFixed(0))||0," profit"]})]})]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Joined"}),e.jsx("p",{className:"text-sm font-medium",children:r.createdAt?new Date(r.createdAt).toLocaleDateString():"N/A"})]})]}),r.metricsError&&e.jsxs("p",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-200",children:["Lifetime metrics could not load: ",r.metricsError]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-400 mb-2",children:"Subscription Details"}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-400",children:"Status:"}),e.jsx("span",{className:`font-medium ${r.subscriptionStatus==="active"||r.subscriptionStatus==="admin_granted"?"text-emerald-400":r.subscriptionStatus==="canceled"?"text-red-400":"text-slate-300"}`,children:r.subscriptionStatus||"No subscription"})]}),r.currentPeriodEnd&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-400",children:"Period Ends:"}),e.jsx("span",{className:"text-slate-300",children:new Date(r.currentPeriodEnd).toLocaleDateString()})]}),r.cancelAtPeriodEnd&&e.jsx("div",{className:"text-amber-400 text-xs mt-1",children:"⚠️ Canceling at period end"})]})]}),e.jsx("div",{className:"bg-slate-900/50 rounded-xl p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center ${r.agreedToMarketing?"bg-emerald-600/20":"bg-slate-700/50"}`,children:e.jsx(Ut,{className:`w-4 h-4 ${r.agreedToMarketing?"text-emerald-400":"text-slate-500"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400 font-medium",children:"Marketing Consent"}),e.jsx("p",{className:"text-sm font-semibold mt-0.5",children:r.agreedToMarketing?e.jsxs("span",{className:"text-emerald-400 flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400"}),"Opted In"]}):e.jsxs("span",{className:"text-slate-500 flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-slate-500"}),"Not Opted In"]})})]})]}),r.marketingOptInDate&&e.jsx("p",{className:"text-xs text-slate-500",children:new Date(r.marketingOptInDate).toLocaleDateString()})]})}),e.jsxs("div",{className:"border-t border-slate-700 pt-4",children:[e.jsxs("h4",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(mt,{className:"w-4 h-4 text-amber-400"}),"Change Subscription Tier"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("select",{"aria-label":"New subscription tier",value:P,onChange:T=>te(T.target.value),className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm focus:border-indigo-500 outline-none",children:[e.jsx("option",{value:"",children:"Select new tier..."}),e.jsx("option",{value:"free",children:"Free (5 intro analyses)"}),e.jsx("option",{value:"starter",children:"Starter (75/mo)"}
20),e.jsx("option",{value:"reseller",children:"Reseller (200/mo)"}),e.jsx("option",{value:"pro",children:"Pro (500/mo)"}),e.jsx("option",{value:"ultra",children:"Ultra (1000/mo)"})]}),e.jsx("input",{type:"text","aria-label":"Tier change reason",value:E,onChange:T=>w(T.target.value),placeholder:"Reason for tier change...",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm focus:border-indigo-500 outline-none"}),e.jsxs("button",{type:"button",onClick:be,disabled:l||!P||!E||!yt,className:"w-full bg-amber-600 hover:bg-amber-700 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium py-2 rounded-lg flex items-center justify-center gap-2",children:[l?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(mt,{className:"w-4 h-4"}),"Change Tier"]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Use for manual/admin grants. Stripe-managed paid-plan changes are blocked; moving to Free requires confirmed cancellation."})]})]}),e.jsxs("div",{className:"border-t border-slate-700 pt-4",children:[e.jsxs("h4",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(mt,{className:"w-4 h-4 text-amber-400"}),"QA: Subscription Status Toggle"]}),e.jsxs("div",{className:"space-y-3",children:[Ce,e.jsxs("select",{"aria-label":"QA subscription status",value:S,onChange:T=>v(T.target.value),className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm focus:border-indigo-500 outline-none",children:[e.jsx("option",{value:"",children:"Select status..."}),e.jsx("option",{value:"past_due",children:"past_due"}),e.jsx("option",{value:"active",children:"active"})]}),e.jsx("input",{type:"text","aria-label":"Subscription status change reason",value:A,onChange:T=>M(T.target.value),placeholder:"Reason for status change...",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm focus:border-indigo-500 outline-none"}),e.jsxs("button",{type:"button",onClick:ge,disabled:g||!S||!A||!yt,className:"w-full bg-slate-700 hover:bg-slate-600 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium py-2 rounded-lg flex items-center justify-center gap-2",children:[g?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(mt,{className:"w-4 h-4"}),"Set Subscription Status"]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Testing only. This updates Firebase status directly and does not charge or retry Stripe."})]})]}),e.jsxs("div",{className:"border-t border-slate-700 pt-4",children:[e.jsxs("h4",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Ca,{className:"w-4 h-4 text-emerald-400"}),"Paid Top-Up"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{type:"number","aria-label":"Paid top-up credits",min:"1",step:"1",value:R,onChange:T=>X(T.target.value),placeholder:"Extra analyses",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm focus:border-emerald-500 outline-none"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:ve.map(T=>e.jsx("button",{type:"button",onClick:()=>X(String(T)),className:"bg-slate-900 border border-slate-700 hover:border-emerald-500/70 hover:text-emerald-300 rounded-lg px-3 py-2 text-xs font-semibold text-slate-300 transition-colors",children:T},T))}),e.jsx("input",{type:"text","aria-label":"Stripe invoice ID",value:o,onChange:T=>ae(T.target.value),placeholder:"Stripe invoice ID (in_...)",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm focus:border-emerald-500 outline-none font-mono"}),e.jsx("input",{type:"text","aria-label":"Paid top-up note",value:y,onChange:T=>q(T.target.value),placeholder:"Optional note",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm focus:border-emerald-500 outline-none"}),e.jsxs("button",{type:"button",onClick:oe,disabled:$||!R||!o||!yt,className:"w-full bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium py-2 rounded-lg flex items-center justify-center gap-2",children:[$?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(Ca,{className:"w-4 h-4"}),"Add Paid Top-Up"]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Requires a paid Stripe invoice. The invoice amount is logged from Stripe and can vary by pack."})]})]}),e.jsxs("div",{className:"border-t border-slate-700 pt-4",children:[e.jsxs("h4",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Os,{className:"w-4 h-4"}),"Adjust Credits"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex gap-2",children:e.jsx("input",{type:"number","aria-label":"Credit adjustment amount",value:m,onChange:T=>ee(T.target.value),placeholder:"Amount (+ or -)",className:"flex-1 bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm focus:border-indigo-500 outline-none"})}),e.jsx("input",{type:"text","aria-label":"Credit adjustment reason",value:x,onChange:T=>
20V(T.target.value),placeholder:"Reason for adjustment...",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm focus:border-indigo-500 outline-none"}),e.jsxs("button",{type:"button",onClick:ye,disabled:j||!m||!x||!Dt,className:"w-full bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium py-2 rounded-lg flex items-center justify-center gap-2",children:[j?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(vn,{className:"w-4 h-4"}),"Apply Adjustment"]})]})]}),e.jsxs("div",{className:"border-t border-slate-700 pt-4",children:[e.jsxs("h4",{className:"font-semibold mb-3 flex items-center gap-2 text-red-400",children:[e.jsx(Bs,{className:"w-4 h-4"}),"Danger Zone"]}),e.jsxs("button",{type:"button",onClick:Se,disabled:h||!Dt,className:"w-full bg-red-600/20 hover:bg-red-600/40 border border-red-600/50 text-red-400 hover:text-red-300 font-medium py-2 rounded-lg flex items-center justify-center gap-2 transition-colors disabled:opacity-50",children:[h?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(Bs,{className:"w-4 h-4"}),"Delete User"]}),e.jsx("p",{className:"text-xs text-slate-500 mt-2",children:"Starts a checkpointed permanent-deletion workflow. Any unfinished external cleanup remains visible and resumable in Recent operations."})]}),e.jsxs("div",{className:"border-t border-slate-700 pt-4",children:[e.jsxs("h4",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4 text-emerald-400"}),"Export Data"]}),e.jsxs("button",{type:"button",onClick:()=>re(!I),className:"mb-2 flex min-h-8 w-full items-center gap-2 text-left text-sm text-slate-400 hover:text-slate-300",children:[e.jsx(Os,{className:"w-3 h-3"}),I?"Hide":"Show"," Export Options"]}),I&&e.jsxs("div",{className:"space-y-3 mb-3 p-3 bg-slate-800/50 rounded-lg border border-slate-700/50",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Start Date (optional)"}),e.jsx("input",{type:"date","aria-label":"User export start date",value:C,onChange:T=>_(T.target.value),className:"w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-sm text-slate-300 focus:outline-none focus:border-emerald-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"End Date (optional)"}),e.jsx("input",{type:"date","aria-label":"User export end date",value:U,onChange:T=>B(T.target.value),className:"w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-sm text-slate-300 focus:outline-none focus:border-emerald-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Limit (optional)"}),e.jsx("input",{type:"number","aria-label":"User export row limit",min:"1",max:"5000",value:k,onChange:T=>J(T.target.value),placeholder:"Leave empty for all (max 5,000)",className:"w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-sm text-slate-300 focus:outline-none focus:border-emerald-500"})]}),e.jsx("button",{type:"button",onClick:()=>{_(""),B(""),J("")},className:"text-xs text-slate-500 hover:text-slate-400",children:"Clear all filters"})]}),e.jsxs("button",{type:"button",onClick:Ie,disabled:O||!ss,className:"w-full bg-emerald-600/20 hover:bg-emerald-600/40 border border-emerald-600/50 text-emerald-400 hover:text-emerald-300 font-medium py-2 rounded-lg flex items-center justify-center gap-2 transition-colors disabled:opacity-50",children:[O?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(Pe,{className:"w-4 h-4"}),"Export Analysis History (CSV)"]}),e.jsxs("p",{className:"text-xs text-slate-500 mt-2",children:[C||U||k?`Filtered export${k?` (latest ${k})`:""}`:"Download all analysis history"," as CSV"]})]}),ke?e.jsx("div",{className:"border-t border-slate-700 pt-4",children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-slate-900/50 px-3 py-2 text-sm text-slate-400",children:[e.jsx(H,{className:"w-4 h-4 animate-spin text-indigo-400"}),"Loading recent transactions..."]})}):((Q=r.transactions)==null?void 0:Q.length)>0&&e.jsxs("div",{className:"border-t border-slate-700 pt-4",children:[e.jsxs("h4",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Ka,{className:"w-4 h-4"}),"Recent Transactions"]}),e.jsx("div",{className:"space-y-2 max-h-48 overflow-y-auto",children:r.transactions.slice(0,10).map(T=>e.jsxs("div",{className:"flex items-center justify-between text-sm bg-slate-900/50 rounded-lg px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.description}),e.jsx("p",{className:"text-xs text-slate-500",children:T.timestamp?new Date(T.timestamp).toLocaleStr
20ing():"N/A"})]}),e.jsxs("span",{className:`font-mono font-bold ${T.amount>=0?"text-emerald-400":"text-red-400"}`,children:[T.amount>=0?"+":"",T.amount]})]},T.id))})]})]}):e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(Ge,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:"Select a user to view details"})]})]})]})},rn=({image:t,onClose:s})=>{const n=As(!!t,s);return t?e.jsxs("div",{className:"fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4",onClick:s,role:"dialog","aria-modal":"true","aria-label":"Analysis image preview",ref:n,tabIndex:-1,children:[e.jsx("button",{type:"button",onClick:s,"aria-label":"Close image preview",className:"absolute top-4 right-4 text-white hover:text-slate-300 p-2",children:e.jsx(ht,{className:"w-8 h-8"})}),e.jsx("img",{src:t,alt:"Full size",className:"max-w-full max-h-full object-contain rounded-lg",onClick:a=>a.stopPropagation()})]}):null},Ra=t=>{const s=String(t||"").trim().toLowerCase();return!s||["web","app","extension"].includes(s)?"ebay":["facebook","fb_marketplace","fb-marketplace"].includes(s)?"facebook":["offerup","craigslist","ebay","mercari","poshmark","depop","whatnot"].includes(s)?s:s==="nextdoor"?"facebook":"ebay"},Dr=t=>(t==null?void 0:t.historyKind)==="barcode-scan"||(t==null?void 0:t.sourceType)==="barcode",Mr=({fallback:t})=>e.jsxs("div",{className:"bg-amber-900/20 border border-amber-500/30 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(At,{className:"w-4 h-4 text-amber-400"}),e.jsx("p",{className:"text-sm font-medium text-amber-400",children:"Recovered from Usage Transaction"})]}),e.jsx("p",{className:"text-xs text-amber-200/70 mb-4",children:"Full analysis history wasn't saved, but we recovered this data from the usage audit trail."}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[t.identifiedAs&&e.jsxs("div",{className:"bg-slate-800/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase mb-1",children:"Identified As"}),e.jsx("p",{className:"text-sm text-white font-medium",children:t.identifiedAs})]}),t.priceVal!=null&&e.jsxs("div",{className:"bg-slate-800/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase mb-1",children:"Source Price"}),e.jsxs("p",{className:"text-lg text-white font-bold",children:["$",t.priceVal]})]}),t.marketVal!=null&&e.jsxs("div",{className:"bg-slate-800/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase mb-1",children:"Market Value"}),e.jsxs("p",{className:"text-lg text-emerald-400 font-bold",children:["$",t.marketVal]})]}),t.confidence!=null&&e.jsxs("div",{className:"bg-slate-800/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase mb-1",children:"Confidence"}),e.jsxs("p",{className:"text-lg text-blue-400 font-bold",children:[t.confidence,"%"]})]})]}),t.priceVal!=null&&t.marketVal!=null&&e.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-emerald-900/30 border border-emerald-500/30 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase mb-1",children:"Potential Profit"}),e.jsxs("p",{className:"text-xl font-bold text-emerald-400",children:["$",(t.marketVal-t.priceVal).toLocaleString()]})]}),e.jsxs("div",{className:"bg-purple-900/30 border border-purple-500/30 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase mb-1",children:"ROI"}),e.jsxs("p",{className:"text-xl font-bold text-purple-400",children:[t.priceVal>0?Math.round((t.marketVal-t.priceVal)/t.priceVal*100):0,"%"]})]})]}),t.pageUrl&&e.jsxs("div",{className:"mt-3 bg-slate-800/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-500 uppercase mb-1",children:"Source URL"}),zs(t.pageUrl)?e.jsxs("a",{href:t.pageUrl.trim(),target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-400 hover:underline break-all",children:[new URL(t.pageUrl.trim()).hostname," — ",t.pageUrl.trim()]}):e.jsxs("p",{className:"break-all text-sm text-slate-400",title:"Legacy URL is not an absolute HTTP(S) destination",children:["Unsupported URL: ",String(t.pageUrl)]})]})]}),Lr=({analysis:t,onClose:s,onImageClick:n,usageSummary:a})=>{var y,$,P,E,l,S,A;const d=As(!!t,s),[p,r]=i.useState(()=>Ra(t==null?void 0:t.platform));if(i.useEffect(()=>
20{r(Ra(t==null?void 0:t.platform))},[t]),!t)return null;const u=hn(t),f=u.length>0?u:t.fullAnalysis||t.items||[],c=Array.isArray(t.images)&&t.images.length>0?t.images:Array.isArray(t.imageData)?t.imageData:t.imageData?[t.imageData]:[],N=_a(t),b=N.isValueOnly||t.analysisMode==="estimate",m=Dr(t),x=m?Dn(t):null,j=m?{code:(t==null?void 0:t.barcode)||"",format:(t==null?void 0:t.barcodeFormat)||"Unknown"}:null,R=(($=(y=t==null?void 0:t.analysisMetadata)==null?void 0:y.barcodeLookupSnapshot)==null?void 0:$.lookedUpAt)||((P=t==null?void 0:t.analysisMetadata)==null?void 0:P.analyzedAt)||(t==null?void 0:t.timestamp)||(t==null?void 0:t.analyzedAt),o=t.id||t.firestoreId||t.analysisId||null;return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-1.5 min-[360px]:p-2 sm:p-4",onClick:s,children:e.jsxs("div",{ref:d,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"analysis-details-title",className:"bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col relative",onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-slate-700 bg-slate-900 p-3 sm:p-4",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"analysis-details-title",className:"text-lg font-bold text-white",children:m?"Barcode Scan Details":b?"Value Estimate Details":"Analysis Details"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx("p",{className:"text-sm text-slate-400",children:t.timestamp?new Date(t.timestamp).toLocaleString():"N/A"}),b&&e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-violet-500/15 border border-violet-500/30 text-violet-300 text-[10px] font-bold uppercase",children:"Estimate"})]})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close analysis details",className:"p-2 hover:bg-slate-800 rounded-full transition-colors text-slate-400 hover:text-white",children:e.jsx(ht,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"flex-1 space-y-6 overflow-y-auto p-2 min-[360px]:p-3 sm:p-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-500",children:"User"}),e.jsx("p",{className:"text-white font-medium",children:t.userName}),e.jsx("p",{className:"text-xs text-slate-500 font-mono",children:t.userId})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-500",children:"Date"}),e.jsx("p",{className:"text-white",children:t.timestamp?new Date(t.timestamp).toLocaleString():"N/A"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-500",children:"Source"}),e.jsx("p",{className:"text-white capitalize",children:t.sourceType||"thrift"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-500",children:b?"Confidence":"Deal Score"}),e.jsx("p",{className:`text-lg font-bold ${N.marginMeta.scoreClass}`,children:N.currentScore||"N/A"}),e.jsx("p",{className:"text-[11px] text-slate-500",children:N.marginMeta.label})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-500",children:b?"Valuation":"Current Read"}),e.jsx("p",{className:`font-medium ${N.recommendation.className}`,children:N.recommendation.headline}),N.tierChanged&&N.legacyTierKey&&ys[N.legacyTierKey]&&e.jsxs("p",{className:"text-[11px] text-indigo-300",children:["Saved as ",ys[N.legacyTierKey].label]})]})]}),!m&&c.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-slate-500 mb-2",children:["Images (",c.length,")"]}),e.jsx("div",{className:"flex gap-3 flex-wrap",children:c.map((g,h)=>e.jsxs("button",{type:"button",onClick:()=>n(g),className:"relative group",children:[e.jsx("img",{src:g,alt:`Image ${h+1}`,className:"w-24 h-24 object-cover rounded-lg border border-slate-600 hover:border-indigo-500 transition-colors"}),e.jsx("div",{className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center",children:e.jsx(at,{className:"w-5 h-5 text-white"})})]},h))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-500 mb-2",children:m?"Scan Results":"Analysis Results"}),m?e.jsx(Ln,{readOnly:!0,analysisId:o,userTier:"pro",usageSummary:a,barcodeScan:j,lookupResult:x,lookupLoading:!1,lookupError:"",currency:(t==null?void 0:t.currency)||"USD",currencySymbol:(t==null?void 0:t.currencySymbol)||"$",inferredCategory:((l=(E=t==null?void 0:t.topDeal)==null?void 0:E.
20category)==null?void 0:l.label)||(typeof(t==null?void 0:t.category)=="string"?t.category:((S=t==null?void 0:t.category)==null?void 0:S.label)||""),inferredCondition:(t==null?void 0:t.condition)||((A=t==null?void 0:t.topDeal)==null?void 0:A.condition)||"Unknown",onDismiss:s,lookupCompletedAt:R,onAddToTracker:void 0,onScanAgain:void 0,onListOnEbay:void 0,onRetryLookup:void 0,showDismissButton:!1,showScanAgainButton:!1}):f.length>0?e.jsx("div",{className:"space-y-6",children:f.map((g,h)=>{var C,U,k,I;return e.jsx(Mn,{item:g,readOnly:!0,platform:p,onPlatformChange:r,userTier:"pro",usageSummary:a,analysisId:o,itemIndex:h,soldCompsRerunMeta:((C=t.analysisMetadata)==null?void 0:C.soldCompsRerun)||null,sourceType:g.sourceType||t.sourceType||"thrift",hideNewDeal:!0,scoreDisplayMode:"stored",platformSelectorEnabled:!1,shippingPref:t.shippingPref||"auto",manualShipping:(U=t.manualShipping)!=null?U:0,taxReserve:t.taxReserve||g.taxReserve||((k=g.scoringInputsV3)==null?void 0:k.taxReserve)||null,promotion:t.promotion||g.promotion||((I=g.scoringInputsV3)==null?void 0:I.promotion)||null,currencySymbol:g.currencySymbol||t.currencySymbol||"$",currency:g.currency||t.currency||"USD",images:c,analysisMode:g.analysisMode||t.analysisMode||"deal"},`${o}-${g.title||g.identifiedAs||"analysis-item"}-${h}`)})}):t._fallback?e.jsx(Mr,{fallback:t._fallback}):e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl p-4 text-center",children:[e.jsx("p",{className:"text-slate-400",children:"No analysis results available"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"This may be a failed or incomplete analysis"})]})]}),e.jsxs("details",{className:"bg-slate-800/30 rounded-xl",children:[e.jsx("summary",{className:"p-3 text-slate-400 text-sm cursor-pointer hover:text-white",children:"View Raw Data (Debug)"}),e.jsx("pre",{className:"p-4 text-xs text-slate-400 overflow-x-auto",children:JSON.stringify(t,null,2)})]})]})]})})},Fr=({tickets:t,loadingTickets:s,ticketsError:n,selectedTicket:a,loadingTicketDetails:d,ticketFilter:p,updatingTicket:r,ticketResponse:u,sendingResponse:f,ticketCounts:c,hasMoreTickets:N,loadingMoreTickets:b,lightboxImage:m,setTicketFilter:x,setTicketResponse:j,setLightboxImage:R,handleUpdateTicket:o,handleSendTicketResponse:y,handleSelectTicket:$,loadMoreTickets:P,onViewUser:E,onViewUserAnalyses:l,getFilteredTickets:S,capabilities:A=["*"]})=>{const g=A.includes("*")||A.includes("support:write"),h=A.includes("*")||A.includes("users:read"),C=A.includes("*")||A.includes("analytics:read"),U=typeof(a==null?void 0:a.userId)=="string"?a.userId.trim():"",k=!!(U&&U!=="anonymous"),I={new:"bg-red-500/20 text-red-400 border-red-500/30",in_progress:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",resolved:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",closed:"bg-slate-500/20 text-slate-400 border-slate-500/30"},O={feedback:"text-blue-400",bug:"text-red-400",support:"text-amber-400"},Z=S();return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-700",children:[e.jsx("h2",{className:"font-bold text-lg mb-3",children:"Support Tickets"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:[{value:"all",label:"All"},{value:"new",label:"New"},{value:"in_progress",label:"In Progress"},{value:"resolved",label:"Resolved"},{value:"closed",label:"Closed"}].map(D=>e.jsxs("button",{type:"button",onClick:()=>x(D.value),"aria-pressed":p===D.value,className:`min-h-8 px-3 py-1.5 text-xs font-medium rounded-full transition-colors ${p===D.value?"bg-indigo-600 text-white":"bg-slate-700 text-slate-300 hover:bg-slate-600"}`,children:[D.label,Number.isFinite(c==null?void 0:c[D.value])&&e.jsxs("span",{className:"ml-1",children:["(",c[D.value],")"]})]},D.value))})]}),e.jsxs("div",{className:"max-h-[600px] overflow-y-auto",children:[n&&e.jsx("p",{className:"m-4 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:n}),s&&t.length===0&&e.jsx("div",{className:"p-8 flex justify-center",children:e.jsx(H,{className:"w-5 h-5 animate-spin text-indigo-400"})}),Z.map(D=>e.jsxs("div",{role:"button",tabIndex:0,"aria-label":`Open support ticket ${D.ticketNumber?`number ${D.ticketNumber}`:D.id} from ${D.name}`,onClick:()=>$(D),onKeyDown:ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),$(D))},className:`p-4 border-b border-slate-700/50 cursor-pointer hover:bg-slate-700/30 transition-colors ${(a==null?void 0:a.id)===D.id?"bg-indigo-900/30 border-l-2 border-l-indigo-500":""}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[D.ticketNumber&&e.jsxs("span",{className:"text-xs font-bold text-emerald-400",children:["#",D.ticketNumber]}),e.jsx("span",{className:`text-xs font-medium uppercase ${O[D.type]||"text-slate-400"}`,children:D.type}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full border ${I[D.status]}`,children:D.status.replaceAll("_"," ")}),D.responses&&D.responses.length>0&&e.jsxs("span",{className:"text-xs bg-indigo-500/20 text-indigo-400 px-1.5 py-0.5 rounded",children:[D.responses.length," reply"]}),D.hasUnreadCustomerReply&&e.jsx("span",{className:"text-xs bg-amber-500/20 text-amber-400 px-1.5 py-0.5 rounded font-medium",children:"New reply"})]}),e.jsx("span",{className:"text-xs text-slate-500",children:D.timestamp?new Date(D.timestamp).toLocaleDateString():"N/A"})]}),e.jsx("p",{className:"text-sm font-medium text-white truncate",children:D.name}),e.jsx("p",{className:"text-xs text-slate-400 truncate",children:D.email||"No email"}),e.jsx("p",{className:"text-sm text-slate-300 mt-2 line-clamp-2",children:D.message}),D.hasAttachment&&e.jsxs("span",{className:"inline-flex items-center gap-1 mt-2 text-xs text-purple-400",children:[e.jsx(fs,{className:"w-3 h-3"})," Attachment"]})]},D.id)),!s&&Z.length===0&&e.jsx("p",{className:"p-8 text-center text-slate-500",children:"No tickets found"}),N&&e.jsx("div",{className:"p-4 flex justify-center",children:e.jsxs("button",{type:"button",onClick:P,disabled:b,className:"inline-flex items-center gap-2 rounded-lg border border-slate-600 bg-slate-800 px-4 py-2 text-sm text-slate-200 hover:bg-slate-700 disabled:opacity-50",children:[b&&e.jsx(H,{className:"h-4 w-4 animate-spin"}),b?"Loading…":"Load more tickets"]})})]})]}),e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"p-4 border-b border-slate-700",children:e.jsx("h2",{className:"font-bold text-lg",children:"Ticket Details"})}),a?e.jsxs("div",{className:"p-4 space-y-4 max-h-[700px] overflow-y-auto",children:[d&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(H,{className:"w-3.5 h-3.5 animate-spin"})," Loading full ticket details…"]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[a.ticketNumber&&e.jsxs("span",{className:"text-lg font-bold text-emerald-400",children:["#",a.ticketNumber]}),e.jsx("span",{className:`text-sm font-medium uppercase ${O[a.type]||"text-slate-400"}`,children:a.type})]}),e.jsx("span",{className:`text-xs px-2 py-1 rounded-full border ${I[a.status]}`,children:a.status.replaceAll("_"," ")})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-400 mb-1",children:"From"}),e.jsx("p",{className:"font-medium text-white",children:a.name}),e.jsx("p",{className:"text-sm text-slate-400",children:a.email||"No email provided"}),k&&e.jsxs("p",{className:"text-xs text-slate-500 font-mono mt-1 break-all",children:["UID: ",U]}),k?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[h&&E&&e.jsxs("button",{type:"button",onClick:()=>E(U),className:"inline-flex min-h-10 items-center gap-2 rounded-lg border border-indigo-400/30 bg-indigo-500/10 px-3 text-xs font-semibold text-indigo-200 hover:bg-indigo-500/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:[e.jsx(Ge,{className:"h-4 w-4","aria-hidden":"true"})," View user"]}),C&&l&&e.jsxs("button",{type:"button",onClick:()=>l(U),className:"inline-flex min-h-10 items-center gap-2 rounded-lg border border-cyan-400/30 bg-cyan-500/10 px-3 text-xs font-semibold text-cyan-200 hover:bg-cyan-500/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-400",children:[e.jsx(Ys,{className:"h-4 w-4","aria-hidden":"true"})," View analyses"]})]}):e.jsx("p",{className:"mt-2 text-xs text-slate-500",children:"No user account is linked to this ticket."})]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-slate-400 mb-1",children:"Submitted"}),e.jsx("p",{className:"text-sm text-white",children:a.timestamp?new Date(a.timestamp).toLocaleStr
20ing():"N/A"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400 mb-2",children:"Message"}),e.jsx("div",{className:"bg-slate-900 rounded-lg p-4 border border-slate-700",children:e.jsx("p",{className:"text-sm text-slate-200 whitespace-pre-wrap",children:a.message})})]}),a.attachment&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400 mb-2",children:"Attachment"}),e.jsxs("button",{type:"button",onClick:()=>R(a.attachment.data),className:"relative group",children:[e.jsx("img",{src:a.attachment.data,alt:"Attachment",className:"w-full max-w-xs h-40 object-cover rounded-lg border border-slate-700 hover:border-indigo-500 transition-colors"}),e.jsx("div",{className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center",children:e.jsx(at,{className:"w-6 h-6 text-white"})})]})]}),a.responses&&a.responses.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-slate-400 mb-2",children:["Previous Responses (",a.responses.length,")"]}),e.jsx("div",{className:"space-y-2",children:a.responses.map((D,ee)=>{const V=D.author==="admin"||!!D.adminUid;return e.jsxs("div",{className:V?"bg-indigo-900/30 border border-indigo-500/30 rounded-lg p-3":"bg-amber-900/20 border border-amber-500/30 rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:`text-xs font-medium ${V?"text-indigo-400":"text-amber-400"}`,children:V?"Support Team":a.name||"Customer"}),e.jsx("span",{className:"text-xs text-slate-500",children:D.timestamp?new Date(D.timestamp).toLocaleString():""})]}),e.jsx("p",{className:"text-sm text-slate-200 whitespace-pre-wrap",children:D.message})]},ee)})})]}),a.status!=="closed"&&e.jsxs("div",{className:"border-t border-slate-700 pt-4",children:[e.jsx("p",{className:"text-xs text-slate-400 mb-2",children:"Send Response to User"}),e.jsx("textarea",{"aria-label":"Support response",value:u,onChange:D=>j(Array.from(D.target.value).slice(0,2e3).join("")),"aria-describedby":"ticket-response-limit",placeholder:"Type your response to the user...",className:"w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-sm text-white placeholder-slate-500 resize-none focus:outline-none focus:border-indigo-500",rows:3}),e.jsxs("p",{id:"ticket-response-limit",className:"mt-1 text-right text-xs text-slate-500",children:[Array.from(u).length.toLocaleString()," / 2,000 characters"]}),e.jsx("button",{type:"button",onClick:y,disabled:f||!u.trim()||Array.from(u).length>2e3||!g,className:"mt-2 w-full bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium py-2 rounded-lg text-sm transition-colors flex items-center justify-center gap-2",children:f?e.jsxs(e.Fragment,{children:[e.jsx(H,{className:"w-4 h-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"w-4 h-4"}),"Send Response"]})})]}),e.jsxs("div",{className:"border-t border-slate-700 pt-4",children:[e.jsx("p",{className:"text-xs text-slate-400 mb-3",children:"Update Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.status==="new"&&e.jsx("button",{type:"button",onClick:()=>o(a.id,"in_progress"),disabled:r||!g,className:"bg-yellow-600/20 hover:bg-yellow-600/40 border border-yellow-600/50 text-yellow-400 font-medium py-2 rounded-lg text-sm transition-colors disabled:opacity-50",children:"Mark In Progress"}),(a.status==="new"||a.status==="in_progress")&&e.jsx("button",{type:"button",onClick:()=>o(a.id,"resolved"),disabled:r||!g,className:"bg-emerald-600/20 hover:bg-emerald-600/40 border border-emerald-600/50 text-emerald-400 font-medium py-2 rounded-lg text-sm transition-colors disabled:opacity-50",children:"Mark Resolved"}),a.status!=="closed"&&e.jsx("button",{type:"button",onClick:()=>o(a.id,"closed"),disabled:r||!g,className:"bg-slate-600/20 hover:bg-slate-600/40 border border-slate-600/50 text-slate-400 font-medium py-2 rounded-lg text-sm transition-colors disabled:opacity-50",children:"Close Ticket"}),a.status==="closed"&&e.jsx("button",{type:"button",onClick:()=>o(a.id,"new"),disabled:r||!g,className:"bg-blue-600/20 hover:bg-blue-600/40 border border-blue-600/50 text-blue-400 font-medium py-2 rounded-lg text-sm transition-colors disabled:opacity-50",children:"Reo
20pen Ticket"})]}),a.email&&e.jsxs("a",{href:`mailto:${a.email}?subject=Re: Your ${a.type} submission to Underpriced`,className:"mt-3 w-full bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2 rounded-lg text-sm transition-colors flex items-center justify-center gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"}),"Reply via Email"]})]})]}):e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(Ut,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:"Select a ticket to view details"})]})]}),e.jsx(rn,{image:m,onClose:()=>R(null)})]})},Pa=["tryit","starter","popular","plus","power"],Or=({promos:t,loadingPromos:s,promosError:n,showPromoForm:a,savingPromo:d,deletingPromoId:p,promoForm:r,setShowPromoForm:u,setPromoForm:f,savePromo:c,deletePromo:N,setPromoArchived:b,editPromo:m,resetPromoForm:x,capabilities:j=["*"]})=>{const R=j.includes("*")||j.includes("promos:write");return e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-700 flex items-center justify-between",children:[e.jsx("h2",{className:"font-bold text-lg",children:a?r.id?"Edit Promo Code":"Create Promo Code":"Promo Codes"}),!a&&e.jsxs("button",{type:"button",onClick:()=>{x(),u(!0)},disabled:!R,className:"bg-indigo-600 hover:bg-indigo-700 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-colors",children:[e.jsx(wn,{className:"w-4 h-4"})," New Promo"]})]}),n&&e.jsx("p",{className:"m-4 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:n}),a?e.jsxs("form",{onSubmit:c,className:"p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Promo Code *"}),e.jsx("input",{type:"text","aria-label":"Promo code",value:r.code,onChange:o=>f({...r,code:o.target.value.toUpperCase()}),placeholder:"e.g., SUMMER20",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Type *"}
20),e.jsxs("select",{"aria-label":"Promo type",value:r.type,onChange:o=>f({...r,type:o.target.value}),className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none",children:[e.jsx("option",{value:"percent_off",children:"Percentage Off"}),e.jsx("option",{value:"fixed_credits",children:"Fixed Amount Off (cents)"}),e.jsx("option",{value:"bonus_credits",children:"Bonus Credits"}),e.jsx("option",{value:"multiplier",children:"Credit Multiplier"}),e.jsx("option",{value:"free",children:"Free Package"})]})]}),e.jsxs("div",{className:r.type==="free"?"opacity-50":"",children:[e.jsxs("label",{className:"block text-xs text-slate-400 mb-1",children:["Value ",r.type==="free"?"(not applicable)":r.type==="percent_off"?"(%)":r.type==="fixed_credits"?"(cents)":r.type==="multiplier"?"(e.g. 1.5×)":"(credits)"]}),e.jsx("input",{type:"number","aria-label":"Promo value",value:r.value,onChange:o=>f({...r,value:o.target.value}),placeholder:r.type==="percent_off"?"20":r.type==="fixed_credits"?"500":"3",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none",required:!0,min:"1",step:r.type==="multiplier"?"0.1":"1",disabled:r.type==="free"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Description"}),e.jsx("input",{type:"text","aria-label":"Promo description",value:r.description,onChange:o=>f({...r,description:o.target.value}),placeholder:"Summer sale 20% off",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Max Total Uses"}),e.jsx("input",{type:"number","aria-label":"Maximum total promo uses",value:r.maxUses,onChange:o=>f({...r,maxUses:o.target.value}),placeholder:"Leave empty for unlimited",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none",min:"1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Max Uses Per User"}),e.jsx("input",{type:"number","aria-label":"Maximum promo uses per user",value:r.maxUsesPerUser,onChange:o=>f({...r,maxUsesPerUser:o.target.value}),placeholder:"1",className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none",min:"1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Valid From"}),e.jsx("input",{type:"date","aria-label":"Promo valid from date",value:r.validFrom,onChange:o=>f({...r,validFrom:o.target.value}),className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Valid Until"}),e.jsx("input",{type:"date","aria-label":"Promo valid until date",value:r.validUntil,onChange:o=>f({...r,validUntil:o.target.value}),className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-400 mb-1",children:"Minimum Package"}),e.jsxs("select",{"aria-label":"Minimum credit package",value:r.minPackage,onChange:o=>f({...r,minPackage:o.target.value}),className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-4 py-2 text-sm",children:[e.jsx("option",{value:"",children:"No minimum"}),Pa.map(o=>e.jsx("option",{value:o,children:o},o))]})]}),e.jsxs("fieldset",{className:"md:col-span-2 rounded-lg border border-slate-700 p-3",children:[e.jsx("legend",{className:"px-1 text-xs text-slate-400",children:"Applicable legacy credit packages (none means all)"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Pa.map(o=>e.jsxs("label",{className:"flex items-center gap-1.5 text-sm text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:r.applicablePackages.includes(o),onChange:y=>f({...r,applicablePackages:y.target.checked?[...r.applicablePackages,o]:r.applicablePackages.filter($=>$!==o)})}),o]},o))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-5 pt-2 md:col-span-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r.firstPurchaseOnly,onChange:o=>
20f({...r,firstPurchaseOnly:o.target.checked}),className:"rounded border-slate-600 bg-slate-900 text-indigo-600 focus:ring-indigo-500"}),e.jsx("span",{className:"text-sm text-slate-300",children:"First purchase only"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r.active,onChange:o=>f({...r,active:o.target.checked})}),e.jsx("span",{className:"text-sm text-slate-300",children:"Active immediately"})]})]})]}),e.jsxs("p",{className:"rounded-lg border border-blue-500/20 bg-blue-500/10 px-3 py-2 text-xs text-blue-200",children:["Scope: legacy one-time credit packages only. Subscription checkout behavior is unchanged. Stored ",e.jsx("code",{children:"fixed_off"})," promos are normalized as ",e.jsx("code",{children:"fixed_credits"})," without rewriting history."]}),e.jsxs("div",{className:"flex gap-3 pt-2",children:[e.jsx("button",{type:"button",onClick:()=>u(!1),className:"px-4 py-2 bg-slate-700 hover:bg-slate-600 rounded-lg text-sm font-medium transition-colors",children:"Cancel"}),e.jsxs("button",{type:"submit",disabled:d||!R,className:"px-4 py-2 bg-indigo-600 hover:bg-indigo-700 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 flex items-center gap-2",children:[d&&e.jsx(H,{className:"w-4 h-4 animate-spin"}),r.id?"Update":"Create"," Promo"]})]})]}):e.jsx("div",{className:"overflow-x-auto",children:s?e.jsx("div",{className:"p-8 text-center",children:e.jsx(H,{className:"w-6 h-6 animate-spin mx-auto text-slate-400"})}):t.length===0?e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(Va,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:"No promo codes yet"}),e.jsx("p",{className:"text-xs mt-1",children:"Create your first promo code to get started"})]}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-900/50",children:e.jsxs("tr",{className:"text-left",children:[e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Code"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Type"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Value"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Uses"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Expires"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Status"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-700/50",children:t.map(o=>{var y;return e.jsxs("tr",{className:"hover:bg-slate-700/20",children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("span",{className:"font-mono font-medium text-white",children:o.code}),o.description&&e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:o.description}),e.jsxs("p",{className:"mt-1 text-[11px] text-slate-500",children:["schema v",o.promoSchemaVersion||1," · stored ",o.storedType||o.type,(y=o.applicablePackages)!=null&&y.length?` · packages ${o.applicablePackages.join(", ")}`:" · all packages"]})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${o.type==="percent_off"?"bg-blue-500/20 text-blue-400":o.type==="fixed_credits"?"bg-emerald-500/20 text-emerald-400":"bg-purple-500/20 text-purple-400"}`,children:o.type==="percent_off"?"% Off":o.type==="fixed_credits"?"Fixed Off":o.type==="multiplier"?"Multiplier":o.type==="free"?"Free":"Bonus"})}),e.jsx("td",{className:"px-4 py-3 font-medium",children:o.type==="percent_off"?`${o.value}%`:o.type==="fixed_credits"?`$${(o.value/100).toFixed(2)}`:o.type==="multiplier"?`${o.value}×`:o.type==="free"?"Free":`+${o.value} credits`}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("span",{className:"text-slate-300",children:o.usedCount||0}),e.jsxs("span",{className:"text-slate-500",children:["/",o.maxUses||"∞"]})]}),e.jsx("td",{className:"px-4 py-3 text-slate-400",children:o.validUntil?new Date(o.validUntil).toLocaleDateString():"Never"}),e.jsx("td",{className:"px-4 py-3",children:o.active!==!1?o.validUntil&&new Date(o.validUntil)<new Date?e.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-red-500/20 text-red-400",children:"Expired"}):o.maxUses&&(o.usedCount||0)>=o.maxUses?e.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-yellow-500/20 text-yellow-400",children:"Max Uses"}):e.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-emerald-500/20 text-emerald-400",children:"Active"}):e.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-slate-500/20 text-slate-400",children:"Disabled"})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","aria-label":`Edit promo ${o.code}`,onClick:()=>m(o),disabled:p===o.id||!R,className:"min-h-8 min-w-8 rounded bg-slate-700 p-1.5 text-slate-300 transition-colors hover:bg-slate-600 hover:text-white",title:"Edit",children:e.jsx(Cn,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button","aria-label":`${o.active!==!1?"Archive":"Restore"} promo ${o.code}`,onClick:()=>b(o.id,o.active!==!1),disabled:p===o.id||!R,className:"min-h-8 min-w-8 rounded bg-amber-500/20 p-1.5 text-amber-300 transition-colors hover:bg-amber-500/30",title:o.active!==!1?"Archive":"Restore",children:p===o.id?e.jsx(H,{className:"w-3.5 h-3.5 animate-spin"}):o.active!==!1?e.jsx(Xs,{className:"w-3.5 h-3.5"}):e.jsx(Sn,{className:"w-3.5 h-3.5"})}),(o.usedCount||0)===0&&o.active===!1&&e.jsx("button",{type:"button","aria-label":`Permanently delete promo ${o.code}`,onClick:()=>N(o.id),disabled:p===o.id||!R,className:"min-h-8 min-w-8 rounded bg-red-500/20 p-1.5 text-red-400 transition-colors hover:bg-red-500/40",title:"Permanently delete unused draft",children:e.jsx(Bs,{className:"w-3.5 h-3.5"})})]})})]},o.id)})})]})})]})})},Br=({analyses:t,loadingAnalyses:s,analysesError:n,analysesFilter:a,analysesHasMore:d,analysesPage:p,selectedAnalysis:r,loadingAnalysisId:u,lightboxImage:f,usageSummary:c,setAnalysesFilter:N,setSelectedAnalysis:b,setLightboxImage:m,fetchAnalyses:x,fetchAnalysisDetail:j,clearAnalysesFilter:R})=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-700 flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-bold text-lg",children:"User Analyses"}),t.length>0&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:["Page ",p," · ",t.length," analyses"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text","aria-label":"Filter analyses by user ID",value:a,onChange:o=>N(o.target.value),placeholder:"Filter by user ID...",className:"bg-slate-900 border border-slate-600 rounded-lg px-3 py-1.5 text-sm flex-1 sm:w-48 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none"}),a&&e.jsx("button",{type:"button",onClick:()=>{R(),x("reset","")},className:"px-2 py-1.5 bg-slate-700 hover:bg-slate-600 rounded-lg text-sm transition-colors",title:"Clear filter",children:e.jsx(ht,{className:"w-4 h-4"})}),e.jsxs("button",{type:"button",onClick:()=>x(),disabled:s,className:"px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex items-center gap-1",children:[s?e.jsx(H,{className:"w-4 h-4 animate-spin"}):null,"Search"]})]})]}),n&&e.jsxs("div",{className:"m-4 flex items-start gap-2 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:[e.jsx(Re,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:n})]}),s&&t.length===0?e.jsx("div",{className:"p-8 text-center",children:e.jsx(H,{className:"w-6 h-6 animate-spin mx-auto text-slate-400"})}):t.length===0?e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(Ys,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}
20),e.jsx("p",{children:"No analyses found"})]}):e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-900/50",children:e.jsxs("tr",{className:"text-left",children:[e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"User"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Image"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Item"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Current Read"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Context"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Date"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-700/50",children:t.map(o=>{var Z,D;const y=_a(o),{currentScore:$,marginMeta:P,recommendation:E,tierChanged:l,legacyTierKey:S,riskBadge:A,platformConfig:g,calc:h,deal:C,currencySymbol:U}=y,k=y.isValueOnly||o.analysisMode==="estimate"||(C==null?void 0:C.analysisMode)==="estimate",I=o.sourceType==="barcode"?"Barcode Scan":o.sourceType==="thrift"?"Thrift":"Marketplace",O=o.sourceType==="barcode"?"bg-cyan-500/20 text-cyan-300":o.sourceType==="thrift"?"bg-purple-500/20 text-purple-400":"bg-blue-500/20 text-blue-400";return e.jsxs("tr",{className:"hover:bg-slate-700/20",children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("p",{className:"font-medium text-white",children:o.userName}),e.jsxs("p",{className:"text-xs text-slate-500 font-mono",children:[(Z=o.userId)==null?void 0:Z.slice(0,8),"..."]})]}),e.jsx("td",{className:"px-4 py-3",children:Array.isArray(o.imageData)&&o.imageData.length>0?e.jsxs("button",{type:"button",onClick:()=>m(o.imageData[0]),className:"relative group",children:[e.jsx("img",{src:o.imageData[0],alt:"Analysis item thumbnail",className:"w-12 h-12 object-cover rounded-lg border border-slate-600 group-hover:border-indigo-500 transition-colors cursor-pointer",onError:ee=>{ee.target.style.display="none"}}),o.imageData.length>1&&e.jsx("span",{className:"absolute -top-1 -right-1 bg-indigo-600 text-white text-[10px] w-4 h-4 rounded-full flex items-center justify-center",children:o.imageData.length}),e.jsx("div",{className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center",children:e.jsx(at,{className:"w-4 h-4 text-white"})})]}):e.jsx("div",{className:"w-12 h-12 bg-slate-700 rounded-lg flex items-center justify-center",title:o.imageCount>0?"Open the analysis to load images":"No image available",children:e.jsx(fs,{className:"w-5 h-5 text-slate-500"})})}),e.jsxs("td",{className:"px-4 py-3 max-w-[300px]",children:[e.jsx("p",{className:"text-white",title:o.title||C.title,children:o.title||C.title||C.identifiedAs||"Untitled analysis"}),e.jsxs("p",{className:"text-xs text-slate-500",children:[(D=o.imageCount)!=null?D:0," image(s)"]})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("div",{className:"min-w-[220px] space-y-1",children:k?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx("span",{className:"text-xs px-2 py-1 rounded-full border border-violet-500/25 bg-violet-500/10 text-violet-300",children:"Value Estimate"})}),e.jsxs("p",{className:"text-sm font-medium text-violet-300",children:["Market Value: ",U,Number(C.marketVal||0).toFixed(0)]}),e.jsxs("p",{className:"text-xs text-slate-500",children:["Seller Payout ",U,h.netProfit.toFixed(0)]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:`text-xs px-2 py-1 rounded-full border ${P.badgeClass}`,children:P.label}),A&&e.jsx("span",{className:`text-xs px-2 py-1 rounded-full border ${A.className}`,children:A.label}),e.jsxs("span",{className:`font-bold text-sm ${P.scoreClass}`,children:[$,"/100"]})]}),e.jsx("p",{className:`text-sm font-medium ${E.className}`,children:E.headline}),e.jsxs("p",{className:"text-xs text-slate-500",children:["Net ",U,h.netProfit.toFixed(0)," • ROI ",Math.round(h.roi),"%"]}),l&&S&&ys[S]&&e.jsxs("p",{className:"text-[11px] text-indigo-300",children:["Saved as ",ys[S].label]})]})})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${O}`,children:I}),e.jsx("p",{className:"text-xs text-slate-400",children:g.name})]})}),e.jsx("td",{className:"px-4 py-3 text-slate-400 text-xs",children:o.timestamp?new Date(o.timestamp).toLocaleStr
20ing():"N/A"}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>j(o),disabled:u===o.id,className:"min-h-8 px-2 py-1.5 bg-indigo-600/20 hover:bg-indigo-600/30 text-indigo-400 text-xs rounded-lg transition-colors flex items-center gap-1",children:[u===o.id?e.jsx(H,{className:"w-3 h-3 animate-spin"}):e.jsx(Xt,{className:"w-3 h-3"}),o.sourceType==="barcode"?"View Scan":"View"]}),o.dealLink&&zs(o.dealLink)&&e.jsxs("a",{href:o.dealLink,target:"_blank",rel:"noopener noreferrer",className:"min-h-8 px-2 py-1.5 bg-slate-700/60 hover:bg-slate-700 text-slate-200 text-xs rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(Xt,{className:"w-3 h-3"}),"Listing"]}),o.dealLink&&!zs(o.dealLink)&&e.jsxs("span",{className:"max-w-48 break-all text-xs text-slate-500",title:"Legacy URL is not an absolute HTTP(S) destination",children:["Unsupported URL: ",o.dealLink]})]})})]},`${o.userId||"unknown"}:${o.id}`)})})]}),e.jsxs("div",{className:"p-4 border-t border-slate-700 flex items-center justify-between gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>x("previous"),disabled:s||p<=1,className:"px-4 py-2 text-sm text-slate-300 bg-slate-700/60 hover:bg-slate-700 rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-1.5",children:[e.jsx(An,{className:"w-4 h-4"})," Previous"]}),e.jsxs("span",{className:"text-xs text-slate-500",children:["Page ",p]}),e.jsxs("button",{type:"button",onClick:()=>x("next"),disabled:s||!d,className:"px-4 py-2 text-sm text-indigo-300 bg-indigo-600/20 hover:bg-indigo-600/30 rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-1.5",children:[s?e.jsx(H,{className:"w-4 h-4 animate-spin"}):null,"Next ",e.jsx(kn,{className:"w-4 h-4"})]})]})]})]}),e.jsx(rn,{image:f,onClose:()=>m(null)}),e.jsx(Lr,{analysis:r,usageSummary:c,onClose:()=>b(null),onImageClick:m})]});function Et(t){if(!t)return"N/A";const s=new Date(t);return Number.isNaN(s.getTime())?"N/A":s.toLocaleString()}function Ua(t){if(!t)return"N/A";const s=new Date(t);return Number.isNaN(s.getTime())?"N/A":s.toLocaleDateString()}function zt(t){return Number.isFinite(Number(t))?Number(t).toLocaleString():"--"}function ks(t){if(t==null)return"";if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.map(ks).filter(Boolean).join(", ");if(typeof t=="object")try{return JSON.stringify(t)}catch{return"[Unsupported object]"}return String(t)}function _r(t){return Array.isArray(t==null?void 0:t.platforms)&&t.platforms.length>0?t.platforms:Array.isArray(t==null?void 0:t.platformDrafts)?t.platformDrafts.map(s=>s.platform).filter(Boolean):[]}function Js(t){var s,n;return((s=t==null?void 0:t.sourceSummary)==null?void 0:s.identifiedAs)||((n=t==null?void 0:t.sourceSummary)==null?void 0:n.title)||(t==null?void 0:t.title)||"Untitled draft"}function ln(t){return{tracker:"Tracker",history:"History",analysis:"Analysis",extension:"Extension",manual:"Manual"}[t]||t||"Source"}function ds({icon:t,label:s,value:n,detail:a,color:d="text-indigo-300"}){const p=t;return e.jsx("div",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase text-slate-500",children:s}),e.jsx("p",{className:"mt-1 text-2xl font-bold text-white",children:n}),a&&e.jsx("p",{className:"mt-1 text-xs text-slate-500",children:a})]}),e.jsx(p,{className:`h-5 w-5 ${d}`})]})})}function on({status:t}){const s=t==="archived",n=t==="active";return e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full px-2 py-1 text-xs font-medium ${s?"bg-slate-700/70 text-slate-300":n?"bg-emerald-500/15 text-emerald-300":"bg-amber-500/15 text-amber-200"}`,children:[s?e.jsx(Xs,{className:"h-3 w-3"}):n?e.jsx(Ha,{className:"h-3 w-3"}):e.jsx(Re,{className:"h-3 w-3"}),s?"Archived":n?"Active":`Unknown (${ks(t)||"missing"})`]})}function qr({platforms:t}){return t!=null&&t.length?e.jsx("div",{className:"flex max-w-[260px] flex-wrap gap-1.5",children:t.map((s,n)=>e.jsx("span",{className:"rounded-full bg-indigo-500/15 px-2 py-1 text-xs font-medium text-indigo-300",children:s==="facebook"?"FB":js(s)},`${ks(s)}-${n}`))}):e.jsx("span",{className:"text-xs text-slate-500",children:"No platforms"})}function us({title:t,items:s}){return!Array.isArray(s)||s.length===0?null:e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-xs font-bold uppercase text-slate-500",children:t}),e.jsx("div",{className:"space-y-1.5",children:s.map((n,a)=>{var r,u;
20const d=(n==null?void 0:n.name)||(n==null?void 0:n.label)||null,p=n&&typeof n=="object"&&(u=(r=n.value)!=null?r:n.text)!=null?u:n;return e.jsxs("div",{className:"rounded-lg border border-slate-700/70 bg-slate-950/40 px-3 py-2 text-sm",children:[d?e.jsxs("span",{className:"font-medium text-slate-200",children:[d,": "]}):null,e.jsx("span",{className:"text-slate-300 break-words",children:ks(p)})]},`${d||"item"}-${a}`)})})]})}function Vr({draft:t,onBack:s}){var d,p,r,u,f,c,N,b,m;if(!t)return null;const n=Array.isArray(t.platformDrafts)?t.platformDrafts:[],a=(d=t.uiState)==null?void 0:d.lastCopiedAt;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-slate-700 bg-slate-800/50",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-slate-700 p-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{type:"button",onClick:s,className:"rounded-lg p-1.5 transition-colors hover:bg-slate-700","aria-label":"Back to listing drafts",children:e.jsx(Za,{className:"h-5 w-5 text-slate-400"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-bold text-white",children:t.title||"Untitled draft"}),e.jsx(on,{status:t.status})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-slate-500",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ge,{className:"h-3 w-3"}),t.userName||"Unknown"]}),e.jsx("span",{children:t.userEmail||"No email"}),e.jsxs("span",{className:"font-mono",children:[(p=t.userId)==null?void 0:p.slice(0,12),"..."]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ss,{className:"h-3 w-3"}),"Created ",Et(t.createdAt)]}),t.lastActivityAt&&t.lastActivityAt!==t.createdAt&&e.jsxs("span",{children:["Updated ",Et(t.lastActivityAt)]})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 sm:justify-end",children:[e.jsx("span",{className:"rounded-full bg-slate-900 px-3 py-1.5 text-xs text-slate-300",children:ln(t.sourceType)}),e.jsxs("span",{className:"rounded-full bg-amber-500/15 px-3 py-1.5 text-xs font-medium text-amber-300",children:[((r=t.generationSummary)==null?void 0:r.creditsSpentTotal)||0," credits"]})]})]}),e.jsxs("div",{className:"grid gap-4 p-4 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg border border-slate-700 bg-slate-900/50 p-3",children:[e.jsx("p",{className:"text-xs font-medium uppercase text-slate-500",children:"Source"}),e.jsx("p",{className:"mt-1 font-medium text-white",children:Js(t)}),e.jsx("p",{className:"mt-1 text-xs text-slate-500",children:[(u=t.sourceSummary)==null?void 0:u.brand,(f=t.sourceSummary)==null?void 0:f.model,(c=t.sourceSummary)==null?void 0:c.condition].filter(Boolean).join(" - ")||"No extra source fields"})]}),e.jsxs("div",{className:"rounded-lg border border-slate-700 bg-slate-900/50 p-3",children:[e.jsx("p",{className:"text-xs font-medium uppercase text-slate-500",children:"Generated"}),e.jsxs("p",{className:"mt-1 font-medium text-white",children:[((N=t.generationSummary)==null?void 0:N.generationCount)||n.length||0," platform runs"]}),e.jsxs("p",{className:"mt-1 text-xs text-slate-500",children:["Last generated ",Et((b=t.generationSummary)==null?void 0:b.lastGeneratedAt)]})]}),e.jsxs("div",{className:"rounded-lg border border-slate-700 bg-slate-900/50 p-3",children:[e.jsx("p",{className:"text-xs font-medium uppercase text-slate-500",children:"Copy Activity"}),e.jsx("p",{className:"mt-1 font-medium text-white",children:(m=t.uiState)!=null&&m.lastCopiedPlatform?js(t.uiState.lastCopiedPlatform):"Not copied yet"}),e.jsx("p",{className:"mt-1 text-xs text-slate-500",children:a?Et(a):"No recorded copy action"})]})]})]}),n.length===0?e.jsxs("div",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-8 text-center text-slate-500",children:[e.jsx(st,{className:"mx-auto mb-3 h-10 w-10 opacity-30"}),e.jsx("p",{children:"No generated platform drafts saved on this record."})]}):e.jsx("div",{className:"space-y-4",children:n.map((x,j)=>e.jsxs("article",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-bold text-white",children:js(x.platform)}),e.jsxs("p",{className:"text-xs text-slate-500",children:["Generated ",Et(x.generatedAt),x.editedAt?` - Edited ${Et(x.editedAt)}`:""]})]}),e.jsxs("span",{className:"self-start rounded-full bg-slate-900 px-2 py-1 text-xs text-slate-400",children:[x.generationCount||0," generations"]})]}),e.jsxs("div",{className:"space-y-4",children:[x.title&&e.jsxs("div",{children:[e.jsx("h4",{className:"mb-1 text-xs font-bold uppercase text-slate-500",children:"Title"}),e.jsx("p",{className:"rounded-lg border border-slate-700/70 bg-slate-950/40 px-3 py-2 text-sm font-medium text-slate-100",children:x.title})]}),x.description&&e.jsxs("div",{children:[e.jsx("h4",{className:"mb-1 text-xs font-bold uppercase text-slate-500",children:"Description"}),e.jsx("p",{className:"max-h-80 overflow-y-auto whitespace-pre-wrap rounded-lg border border-slate-700/70 bg-slate-950/40 px-3 py-2 text-sm leading-6 text-slate-200",children:x.description})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(us,{title:"Item Specifics",items:x.itemSpecifics}),e.jsx(us,{title:"Platform Fields",items:x.platformFields}),e.jsx(us,{title:"Photo Checklist",items:x.photoChecklist}),e.jsx(us,{title:"Warnings",items:x.warnings})]}),(x.pricingNote||x.categorySuggestion||x.conditionSummary)&&e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[x.pricingNote&&e.jsx("p",{className:"rounded-lg border border-amber-500/20 bg-amber-500/10 p-3 text-xs text-amber-200",children:x.pricingNote}),x.categorySuggestion&&e.jsx("p",{className:"rounded-lg border border-indigo-500/20 bg-indigo-500/10 p-3 text-xs text-indigo-200",children:x.categorySuggestion}),x.conditionSummary&&e.jsx("p",{className:"rounded-lg border border-emerald-500/20 bg-emerald-500/10 p-3 text-xs text-emerald-200",children:x.conditionSummary})]})]})]},`${x.id||x.platform||"unknown"}-${x.generatedAt||j}-${j}`))})]})}const zr=({listingDrafts:t,loadingListingDrafts:s,listingDraftsError:n,listingDraftsFilter:a,listingDraftsStatus:d,listingDraftsHasMore:p,listingDraftsStats:r,selectedListingDraft:u,exportingListingDrafts:f,listingDraftsExportProgress:c,setListingDraftsFilter:N,setListingDraftsStatus:b,setSelectedListingDraft:m,fetchListingDrafts:x,handleExportListingDrafts:j,clearListingDraftsFilter:R})=>u?e.jsx(Vr,{draft:u,onBack:()=>m(null)}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(ds,{icon:st,label:"Total Drafts",value:zt(r==null?void 0:r.totalDrafts),detail:`${zt(r==null?void 0:r.activeDrafts)} active`,color:"text-indigo-300"}),e.jsx(ds,{icon:Ss,label:"Updated 7 Days",value:zt(r==null?void 0:r.updatedLast7Days),detail:"Drafts touched re
20cently",color:"text-cyan-300"}),e.jsx(ds,{icon:Ga,label:"Copied 7 Days",value:zt(r==null?void 0:r.copiedLast7Days),detail:"Recorded clipboard actions",color:"text-emerald-300"}),e.jsx(ds,{icon:Xs,label:"Archived",value:zt(r==null?void 0:r.archivedDrafts),detail:"Saved but hidden by users",color:"text-slate-300"})]}),e.jsxs("div",{className:"overflow-hidden rounded-xl border border-slate-700 bg-slate-800/50",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-slate-700 p-4 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-bold",children:[e.jsx(st,{className:"h-5 w-5 text-indigo-400"}),"Listing Drafts"]}),t.length>0&&e.jsxs("p",{className:"mt-1 text-xs text-slate-500",children:["Showing ",t.length," recent drafts"]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx("input",{type:"text","aria-label":"Filter listing drafts by user ID",value:a,onChange:o=>N(o.target.value),onKeyDown:o=>o.key==="Enter"&&x(!1),placeholder:"Filter by user ID...",className:"min-w-0 rounded-lg border border-slate-600 bg-slate-900 px-3 py-1.5 text-sm outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 sm:w-48"}),a&&e.jsx("button",{type:"button",onClick:()=>{R(),x(!1,"")},className:"rounded-lg bg-slate-700 px-2 py-1.5 text-sm transition-colors hover:bg-slate-600",title:"Clear filter",children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsxs("select",{"aria-label":"Listing draft status",value:d,onChange:o=>{b(o.target.value),x(!1,void 0,o.target.value)},className:"rounded-lg border border-slate-600 bg-slate-900 px-3 py-1.5 text-sm outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500",children:[e.jsx("option",{value:"all",children:"All statuses"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"archived",children:"Archived"})]}),e.jsxs("button",{type:"button",onClick:()=>x(!1),disabled:s,className:"flex items-center justify-center gap-1 rounded-lg bg-indigo-600 px-3 py-1.5 text-sm font-medium transition-colors hover:bg-indigo-700 disabled:opacity-50",children:[s?e.jsx(H,{className:"h-4 w-4 animate-spin"}):null,"Search"]}),e.jsxs("button",{type:"button",onClick:j,disabled:f||t.length===0,className:"flex items-center justify-center gap-1 rounded-lg bg-emerald-600/20 px-3 py-1.5 text-sm font-medium text-emerald-400 transition-colors hover:bg-emerald-600/30 disabled:opacity-50",children:[f?e.jsx(H,{className:"h-4 w-4 animate-spin"}):e.jsx(Pe,{className:"h-4 w-4"}),f?`Exporting ${(c==null?void 0:c.rows)||0}…`:"Export all CSV"]})]})]}),n&&e.jsxs("div",{className:"m-4 flex items-start gap-2 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:[e.jsx(Re,{className:"mt-0.5 h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:n})]}),s&&t.length===0?e.jsx("div",{className:"p-8 text-center",children:e.jsx(H,{className:"mx-auto h-6 w-6 animate-spin text-slate-400"})}):t.length===0?e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(st,{className:"mx-auto mb-3 h-12 w-12 opacity-30"}),e.jsx("p",{children:"No listing drafts found"}),e.jsx("p",{className:"mt-1 text-xs",children:"Click Search to load generated listing drafts."})]}):e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-900/50",children:e.jsxs("tr",{className:"text-left",children:[e.jsx("th",{className:"px-4 py-3 font-medium text-slate-400",children:"User"}),e.jsx("th",{className:"px-4 py-3 font-medium text-slate-400",children:"Draft"}),e.jsx("th",{className:"px-4 py-3 font-medium text-slate-400",children:"Platforms"}),e.jsx("th",{className:"px-4 py-3 font-medium text-slate-400",children:"Usage"}),e.jsx("th",{className:"px-4 py-3 font-medium text-slate-400",children:"Status"}),e.jsx("th",{className:"px-4 py-3 font-medium text-slate-400",children:"Created At"}),e.jsx("th",{className:"px-4 py-3 font-medium text-slate-400",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-700/50",children:t.map(o=>{var P,E,l,S;const y=_r(o),$=(P=o.uiState)==null?void 0:P.lastCopiedPlatform;return e.jsxs("tr",{className:"hover:bg-slate-700/20",children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("p",{className:"font-medium text-white",children:o.userName||"Unknown"}),e.jsx("p",{className:"text-xs text-slate-500",children:o.userEmail||""}),e.jsxs("p",{className:"font-mono text-xs text-slate-600",children:[(E=o.userId)==null?void 0:E.slice(0,10),"..."]})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex min-w-[280px] items-center gap-3",children:[o.thumbnailUrl?e.jsx("img",{src:o.thumbnailUrl,alt:"Draft source thumbnail",className:"h-12 w-12 rounded-lg border border-slate-600 object-cover",onError:A=>{A.currentTarget.style.display="none"}}):e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-lg bg-slate-700",children:e.jsx($n,{className:"h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium text-white",title:o.title,children:o.title||"Untitled draft"}),e.jsxs("p",{className:"truncate text-xs text-slate-500",title:Js(o),children:[ln(o.sourceType)," - ",Js(o)]}),o.previewDescription&&e.jsx("p",{className:"mt-0.5 max-w-[360px] truncate text-xs text-slate-600",title:o.previewDescription,children:o.previewDescription})]})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(qr,{platforms:y})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("p",{className:"flex items-center gap-1 text-amber-300",children:[e.jsx(pt,{className:"h-3 w-3"}
20),((l=o.generationSummary)==null?void 0:l.creditsSpentTotal)||0," credits"]}),e.jsxs("p",{className:"text-slate-400",children:[((S=o.generationSummary)==null?void 0:S.generationCount)||y.length||0," generations"]}),e.jsx("p",{className:$?"text-emerald-300":"text-slate-500",children:$?`Copied ${js($)}`:"No copy recorded"})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(on,{status:o.status})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-400",children:[e.jsx("p",{children:Ua(o.createdAt)}),o.lastActivityAt&&o.lastActivityAt!==o.createdAt&&e.jsxs("p",{className:"text-slate-600",children:["Updated ",Ua(o.lastActivityAt)]})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>m(o),className:"flex min-h-8 items-center gap-1 rounded-lg bg-indigo-600/20 px-2 py-1.5 text-xs text-indigo-400 transition-colors hover:bg-indigo-600/30",children:[e.jsx(Xt,{className:"h-3 w-3"}),"View"]})})]},`${o.userId||"unknown"}:${o.id}`)})})]}),p&&e.jsx("div",{className:"border-t border-slate-700 p-4",children:e.jsx("button",{type:"button",onClick:()=>x(!0),disabled:s,className:"flex w-full items-center justify-center gap-2 rounded-lg py-2 text-sm text-indigo-400 transition-colors hover:bg-slate-700/30 disabled:opacity-50",children:s?e.jsxs(e.Fragment,{children:[e.jsx(H,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):"Load more drafts..."})})]})]})]}),Hr=({referrals:t,loadingReferrals:s,referralsError:n,referralsHasMore:a,referralsStats:d,fetchReferrals:p})=>e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-700 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-bold text-lg",children:"Referrals"}),d&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Total rewarded: ",e.jsx("span",{className:"text-emerald-400 font-semibold",children:d.totalRewarded})]})]}),e.jsx("button",{type:"button",onClick:()=>p(),disabled:s,className:"px-3 py-1.5 bg-slate-700 hover:bg-slate-600 rounded-lg text-sm font-medium transition-colors disabled:opacity-50",children:s?e.jsx(H,{className:"w-4 h-4 animate-spin"}):"Refresh"})]}),n&&e.jsx("p",{className:"m-4 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:n}),s&&t.length===0?e.jsx("div",{className:"p-8 flex items-center justify-center",children:e.jsx(H,{className:"w-6 h-6 animate-spin text-indigo-400"})}):t.length===0?e.jsxs("div",{className:"p-8 text-center text-slate-400",children:[e.jsx(es,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No referrals yet"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-900/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase",children:"Referrer"}),e.jsx("th",{className:"px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase",children:"Friend (Referee)"}),e.jsx("th",{className:"px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase",children:"Code"}),e.jsx("th",{className:"px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase",children:"Status"}),e.jsx("th",{className:"px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase",children:"Date"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-700/50",children:t.map(r=>{var u,f;return e.jsxs("tr",{className:"hover:bg-slate-700/30",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-white",children:r.referrerName}),e.jsx("p",{className:"text-xs text-slate-500",children:r.referrerEmail||((u=r.referrerUid)==null?void 0:u.slice(0,8))+"..."})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-white",children:r.refereeName}),e.jsx("p",{className:"text-xs text-slate-500",children:r.refereeEmail||((f=r.refereeUid)==null?void 0:f.slice(0,8))+"..."})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("code",{className:"bg-slate-900 px-2 py-1 rounded text-xs font-mono text-indigo-400",children:r.code})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${r.status==="rewarded"?"bg-emerald-900/50 text-emerald-400":"bg-amber-900/50 text-amber-400"}`,children:r.status==="rewarded"?"✓ Rewarded":r.status})}),e.jsx("td",{className:"px-4 py-3 text-slate-400",children:r.appliedAt?new Date(r.appliedAt).toLocaleDateString():"-"})]},r.id)})})]})}),a&&e.jsx("div",{className:"p-4 border-t border-slate-700",children:e.jsx("button",{type:"button",onClick:()=>p(!0),disabled:s,className:"w-full py-2 text-sm text-indigo-400 hover:bg-slate-700/30 rounded-lg transition-colors disabled:opacity-50",children:s?"Loading...":"Load more"})})]})]}),Gr=({marketingStats:t,loadingMarketing:s,marketingError:n,exportingMarketing:a,syncingBrevo:d,brevoSyncMode:p,brevoSyncResult:r,fetchMarketingStats:u,setBrevoSyncMode:f,handleExportMarketing:c,handleBulkBrevoSync:N,handleRetryBrevoFailures:b,capabilities:m=["*"]})=>{var $,P,E,l,S,A,g,h,C,U;const x=m.includes("*")||m.includes("marketing:write"),j=t==null?void 0:t.brevoHealth,R=k=>k==="active"?"text-emerald-400":k==="degraded"?"text-amber-300":"text-red-300",o=k=>String(k||"unknown").replaceAll("_"," "),y=(A=(S=(E=($=r==null?void 0:r.progress)==null?void 0:$.remainingFailures)!=null?E:(P=r==null?void 0:r.progress)==null?void 0:P.unresolvedFailureCount)!=null?S:(l=r==null?void 0:r.progress)==null?void 0:l.failCount)!=null?A:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl p-6",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsxs("h2",{className:"font-bold text-lg flex items-center gap-2",children:[e.jsx(Ut,{className:"w-5 h-5 text-pink-400"}),"Marketing User Management"]}),e.jsx("button",{type:"button","aria-label":"Refresh marketing totals",onClick:u,disabled:s,className:"p-2 text-slate-400 hover:text-white hover:bg-slate-700 rounded-lg transition-colors disabled:opacity-50",title:"Refresh marketing totals",children:e.jsx(Fe,{className:`w-4 h-4 ${s?"animate-spin":""}`})})]}),n&&e.jsxs("div",{className:"mb-4 flex items-start gap-2 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:[e.jsx(Re,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:n})]}),s?e.jsx("div",{className:"flex justify-center p-4",children:e.jsx(H,{className:"w-6 h-6 animate-spin text-indigo-400"})}):t?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-6",children:[e.jsxs("div",{className:"bg-slate-900/50 rounded-xl p-4 border border-slate-700",children:[e.jsx("p",{className:"text-slate-400 text-sm mb-1",children:"Opted-In Users"}),e.jsx("p",{className:"text-3xl font-bold text-emerald-400",children:t.totalOptedIn}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:'Users who checked "Send me deal tips & updates"'})]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-xl p-4 border border-slate-700",children:[e.jsx("p",{className:"text-slate-400 text-sm mb-1",children:"Canonical Profiles"}),e.jsx("p",{className:"text-3xl font-bold text-white",children:(g=t.canonicalProfileCount)!=null?g:t.totalChecked}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[typeof t.optInRate=="number"?`${Math.round(t.optInRate*100)}
20% opted in | `:"","Root users: ",(h=t.rootUserCount)!=null?h:t.totalChecked]})]})]}):null,e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("button",{type:"button",onClick:c,disabled:a,className:"flex items-center justify-center gap-2 bg-indigo-600 hover:bg-indigo-500 text-white font-semibold py-3 px-4 rounded-xl transition-all disabled:opacity-50",children:[a?e.jsx(H,{className:"w-5 h-5 animate-spin"}):e.jsx(Xt,{className:"w-5 h-5"}),"Download CSV List"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"brevo-sync-mode",className:"sr-only",children:"Brevo sync mode"}),e.jsxs("select",{id:"brevo-sync-mode",value:p,onChange:k=>f(k.target.value),disabled:d||!x,className:"w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm",children:[e.jsx("option",{value:"contact_and_list",children:"Contacts + configured list"}),e.jsx("option",{value:"contact_only",children:"Contacts only"})]}),e.jsxs("button",{type:"button",onClick:N,disabled:d||!x||!(j!=null&&j.apiKeyConfigured)||p==="contact_and_list"&&(j==null?void 0:j.listStatus)!=="active",className:"w-full flex items-center justify-center gap-2 bg-slate-700 hover:bg-slate-600 text-white font-semibold py-3 px-4 rounded-xl transition-all disabled:opacity-50",children:[d?e.jsx(H,{className:"w-5 h-5 animate-spin"}):e.jsx(Ja,{className:"w-5 h-5 text-indigo-400"}),d?`Syncing ${((C=r==null?void 0:r.progress)==null?void 0:C.processed)||0}…`:"Sync Opted-In Users"]})]})]}),r&&e.jsxs("div",{className:`mt-4 rounded-lg border px-3 py-3 text-sm ${r.error?"border-red-500/40 bg-red-500/10 text-red-300":y>0?"border-amber-500/40 bg-amber-500/10 text-amber-200":"border-emerald-500/30 bg-emerald-500/10 text-emerald-200"}`,role:"status",children:[e.jsx("p",{children:r.error?`Sync paused: ${r.error}`:`${r.state==="complete"?"Sync complete":"Sync in progress"} — ${((U=r.progress)==null?void 0:U.successCount)||0} succeeded, ${y} unresolved (operation ${r.operationId})`}),y>0&&r.state==="complete"&&typeof b=="function"&&e.jsxs("button",{type:"button",onClick:b,disabled:d||!x,className:"mt-2 inline-flex min-h-9 items-center gap-1.5 rounded-lg bg-amber-500/15 px-3 py-2 font-semibold text-amber-100 hover:bg-amber-500/25 disabled:opacity-50",children:[e.jsx(Fe,{className:"h-4 w-4"})," Retry failed contacts"]}),e.jsx("p",{className:"mt-1 text-xs opacity-75",children:"Failure rows can be downloaded from Recent operations."})]}),e.jsx("div",{className:"mt-8 bg-amber-900/20 border border-amber-900/50 rounded-xl p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Re,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"text-amber-200 font-bold mb-1",children:"Compliance Warning"}),e.jsx("p",{className:"text-amber-200/70 leading-relaxed",children:"Ensure you are complying with regional laws (GDPR, CASL, CAN-SPAM) before sending marketing emails. Users in Canada and Europe require explicit opt-in."})]})]})})]}),e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl p-6",children:[e.jsx("h3",{className:"font-bold text-white mb-4",children:"Brevo Integration Status"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-900/50 rounded-lg border border-slate-700",children:[e.jsx("span",{className:"text-slate-400 text-sm",children:"Brevo API connectivity"}),e.jsx("span",{className:`${R(j==null?void 0:j.apiStatus)} text-sm font-medium capitalize`,children:o(j==null?void 0:j.apiStatus)})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-900/50 rounded-lg border border-slate-700",children:[e.jsx("span",{className:"text-slate-400 text-sm",children:"Marketing list"}),e.jsx("span",{className:`${R(j==null?void 0:j.listStatus)} text-sm font-medium capitalize`,children:o(j==null?void 0:j.listStatus)})]}),e.jsxs("p",{className:"text-xs text-slate-500",children:["Checked ",j!=null&&j.checkedAt?new Date(j.checkedAt).toLocaleString():"not yet",".",j!=null&&j.usingDeprecatedListAlias?" Using deprecated BREVO_NEWSLETTER_LIST_ID alias.":""]})]})]})]})},Wr=({allExportStartDate:t,allExportEndDate:s,allExportLimit:n,exportingAllAnalyses:a,allExportFilterType:d,setAllExportStartDate:p,setAllExportEndDate:r,setAllExportLimit:u,setAllExportFilterType:f,handleExportAllAnalyses:c})=>e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl p-6",children:[e.jsxs("h2",{className:"font-bold text-lg mb-4 flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-indigo-400"}),"Export All Analyses"]}),e.jsx("p",{className:"text-slate-400 text-sm mb-6",children:"Export analysis data across all users in CSV format. Choose your export method below."}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3 mb-6",children:[e.jsx("button",{type:"button",onClick:()=>f("number"),"aria-pressed":d==="number",className:`p-4 rounded-xl border-2 transition-all ${d==="number"?"border-indigo-500 bg-indigo-500/10":"border-slate-700 bg-slate-900/30 hover:border-slate-600"}`,children:e.jsxs("div",{className:"text-center",children:[e.jsx(pt,{className:`w-6 h-6 mx-auto mb-2 ${d==="number"?"text-indigo-400":"text-slate-400"}`}),e.jsx("p",{className:`font-medium ${d==="number"?"text-white":"text-slate-300"}`,children:"Recent X Analyses"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Most recent analyses"})]})}),e.jsx("button",{type:"button",onClick:()=>f("date"),"aria-pressed":d==="date",className:`p-4 rounded-xl border-2 transition-all ${d==="date"?"border-indigo-500 bg-indigo-500/10":"border-slate-700 bg-slate-900/30 hover:border-slate-600"}`,children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ka,{className:`w-6 h-6 mx-auto mb-2 ${d==="date"?"text-indigo-400":"text-slate-400"}`}),e.jsx("p",{className:`font-medium ${d==="date"?"text-white":"text-slate-300"}`,children:"Specific Date"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"All analyses on one day"})]})}),e.jsx("button",{type:"button",onClick:()=>f("dateRange"),"aria-pressed":d==="dateRange",className:`p-4 rounded-xl border-2 transition-all ${d==="dateRange"?"border-indigo-500 bg-indigo-500/10":"border-slate-700 bg-slate-900/30 hover:border-slate-600"}`,children:e.jsxs("div",{className:"text-center",children:[e.jsx(Os,{className:`w-6 h-6 mx-auto mb-2 ${d==="dateRange"?"text-indigo-400":"text-slate-400"}`}),e.jsx("p",{className:`font-medium ${d==="dateRange"?"text-white":"text-slate-300"}`,children:"Date Range"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Custom time period"})]})})]}),e.jsxs("div",{className:"bg-slate-900/50 border border-slate-700 rounded-xl p-5 mb-6",children:[d==="number"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-300 mb-2",children:"Number of Recent Analyses"}),e.jsx("input",{type:"number","aria-label":"Number of recent analyses",value:n,onChange:N=>u(N.target.value),placeholder:"e.g., 100",min:"1",max:"5000",className:"w-full bg-slate-800 border border-slate-600 rounded-lg px-4 py-2.5 text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"}),e.jsx("p",{className:"text-xs text-slate-500 mt-2",children:"Export the X most recent analyses across all users"})]}),d==="date"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-300 mb-2",children:"Select Date"}),e.jsx("input",{type:"date","aria-label":"Analysis export date",value:t,onChange:N=>p(N.target.value),className:"w-full bg-slate-800 border border-slate-600 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500"}),e.jsx("p",{className:"text-xs text-slate-500 mt-2",children:"Export all analyses created on this specific date"})]}),d==="dateRange"&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-300 mb-2",children:"Start Date"}),e.jsx("input",{type:"date","aria-label":"Analysis export start date",value:t,onChange:N=>p(N.target.value),className:"w-full bg-slate-800 border border-slate-600 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-300 mb-2",children:"End Date"}),e.jsx("input",{type:"date","aria-label":"Analysis export end date",value:s,onChange:N=>r(N.target.value),className:"w-full bg-slate-800 border border-slate-600 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500"})]}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx("p",{className:"text-xs text-slate-500",children:"Export all analyses created between these dates (inclusive). Leave end date empty to export from start date until now."})})]})]}),e.jsx("button",{type:"button",onClick:c,disabled:a,className:"w-full flex items-center justify-center gap-2 bg-indigo-600 hover:bg-indigo-500 text-white font-semibold py-3 px-6 rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:a?e.jsxs(e.Fragment,{children:[e.jsx(H,{className:"w-5 h-5 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-5 h-5"}),"Export Analyses to CSV"]})}),e.jsx("div",{className:"mt-6 bg-blue-900/20 border border-blue-900/50 rounded-xl p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Re,{className:"w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"text-blue-200 font-bold mb-1",children:"Export Format"}),e.jsx("p",{className:"text-blue-200/70 leading-relaxed mb-2",children:"The CSV file will include: Date, User ID, User Email, Title, Identified As, Category, Analytics Category, Condition, Source Price, Market Value, Profit, Profitability Known, Analysis Mode, Deal Score, Deal Tier, Confidence, Source Type, Platform, Images, and Notes for each anal
20ysis."}),e.jsxs("p",{className:"text-blue-200/70 leading-relaxed",children:["Dates are interpreted as UTC calendar days. This is the ",e.jsx("code",{children:"analysis-global-v2"})," schema; it intentionally differs from ",e.jsx("code",{children:"analysis-user-v2"})," by adding user identity columns. The response manifest records exact UTC boundaries, coverage, and row limits."]})]})]})})]})}),Kr=({payingUsers:t,loadingPayingUsers:s,payingUsersError:n,payingUsersHasMore:a,payingUsersSearch:d,payingUsersTotal:p,payingUsersMeta:r,setPayingUsersSearch:u,fetchPayingUsers:f,exportPayingUsers:c,onSelectUser:N})=>{const[b,m]=Qs.useState(!1),x={ultra:"from-purple-500 to-pink-500",pro:"from-indigo-500 to-purple-500",reseller:"from-emerald-500 to-teal-500",starter:"from-blue-500 to-indigo-500"};return e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-bold text-lg flex items-center gap-2",children:[e.jsx(mt,{className:"w-5 h-5 text-amber-400"}),"Paying Users"]}),e.jsxs("p",{className:"text-sm text-slate-400",children:["Total: ",e.jsx("span",{className:"text-emerald-400 font-semibold",children:p})," subscribers"]}
20)]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:async()=>{m(!0);try{await c("all")}finally{m(!1)}},disabled:b,className:"px-3 py-1.5 bg-emerald-700 hover:bg-emerald-600 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 flex items-center gap-1.5",children:[b?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(Pe,{className:"w-4 h-4"}),"Export all"]}),d.trim()&&e.jsxs("button",{type:"button",onClick:async()=>{m(!0);try{await c("filtered")}finally{m(!1)}},disabled:b,className:"px-3 py-1.5 bg-indigo-700 hover:bg-indigo-600 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 flex items-center gap-1.5",children:[e.jsx(Pe,{className:"w-4 h-4"})," Export filtered"]}),e.jsx("button",{type:"button",onClick:()=>f(d),disabled:s,className:"px-3 py-1.5 bg-slate-700 hover:bg-slate-600 rounded-lg text-sm font-medium transition-colors disabled:opacity-50",children:s?e.jsx(H,{className:"w-4 h-4 animate-spin"}):"Refresh"})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(at,{className:"w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx("input",{type:"text","aria-label":"Search paying users",value:d,onChange:j=>u(j.target.value),onKeyDown:j=>j.key==="Enter"&&f(d),placeholder:"Prefix email/name, or exact UID...",className:"w-full bg-slate-900 border border-slate-600 rounded-lg pl-10 pr-4 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none"})]})]}),n&&e.jsx("p",{className:"m-4 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:n}),(r==null?void 0:r.sampled)&&e.jsxs("p",{className:"m-4 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-200",children:["Results are a labeled sample (",r.queryCoverage||"limited coverage","; ",r.scannedCount||0," scanned). Complete export is disabled until the required index is available."]}),s&&t.length===0?e.jsx("div",{className:"p-8 flex items-center justify-center",children:e.jsx(H,{className:"w-6 h-6 animate-spin text-indigo-400"})}):t.length===0?e.jsxs("div",{className:"p-8 text-center text-slate-400",children:[e.jsx(mt,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No paying users found"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-[600px] overflow-y-auto",children:t.map(j=>e.jsx("button",{type:"button",onClick:()=>N(j.uid),"aria-label":`Open ${j.displayName||j.email||j.uid} in Users`,className:"block w-full p-4 text-left border-b border-slate-700/50 cursor-pointer hover:bg-slate-700/30 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[j.photoURL?e.jsx("img",{src:j.photoURL,alt:j.displayName||"User avatar",className:"w-10 h-10 rounded-full"}):e.jsx("div",{className:"w-10 h-10 rounded-full bg-slate-600 flex items-center justify-center",children:e.jsx(Ge,{className:"w-5 h-5 text-slate-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"font-medium truncate",children:j.displayName||"Anonymous"}),e.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-bold bg-gradient-to-r ${x[j.subscriptionTier]||"from-gray-500 to-gray-600"} text-white uppercase`,children:j.subscriptionTier}),j.subscriptionStatus==="past_due"&&e.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-red-500/20 text-red-400 border border-red-500/30 flex items-center gap-1",children:[e.jsx(At,{className:"w-3 h-3"}),"PAST DUE"]})]}),e.jsx("p",{className:"text-sm text-slate-400 truncate",children:j.email||"No email"})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:`text-sm font-medium ${j.subscriptionStatus==="past_due"?"text-red-400":"text-slate-300"}`,children:[j.periodUsage||0,"/",j.usageLimit||0," used"]}),e.jsx("p",{className:"text-xs text-slate-500",children:j.bonusCredits>0&&e.jsxs("span",{className:"text-emerald-400",children:["+",j.bonusCredits," bonus"]})})]})]})},j.uid))}),a&&e.jsx("div",{className:"p-4 border-t border-slate-700",children:e.jsx("button",{type:"button",onClick:()=>f(d,!0),disabled:s,className:"w-full py-2 text-sm text-indigo-400 hover:bg-slate-700/30 rounded-lg transition-colors disabled:opacity-50",children:s?"Loading...":"Load more"})})]})]})},Jt=t=>typeof t=="number"?`${Math.round(t*100)}%`:"N/A",ea=t=>!t&&t!==0?"N/A":t>=1e3?`${(t/1e3).toFixed(t>=1e4?0:1)}s`:`${t}ms`,ta=t=>String(t||"general").replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase()),sa=t=>{const s=String(t||"unknown").toLowerCase();return s==="ios"?"iOS":s==="android"?"Android":s==="web"?"Web":s==="extension"?"Extension":s==="native"?"Native":"Unknown"},wt=({label:t,value:s,hint:n,icon:a})=>e.jsxs("div",{className:"rounded-lg border border-slate-700 bg-slate-900/50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-500 mb-1",children:[a&&e.jsx(a,{className:"w-3.5 h-3.5"}),t]}),e.jsx("p",{className:"text-lg font-bold text-white",children:s}),n&&e.jsx("p",{className:"text-[11px] text-slate-500 mt-0.5",children:n})]}),xs=({title:t,items:s=[],formatLabel:n=ta})=>e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-slate-500 mb-2",children:t}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.length===0?e.jsx("span",{className:"text-xs text-slate-500",children:"No tracked data yet"}):s.map(a=>e.jsxs("span",{className:"rounded-full bg-slate-900 border border-slate-700 px-2 py-1 text-xs text-slate-300",children:[e.jsx("span",{className:"text-white",children:n(a.key)}),e.jsx("span",{className:"text-slate-500 ml-1",children:a.value})]},a.key))})]}),Jr=({analyticsPayload:t,loading:s,error:n,days:a,exporting:d,onDaysChange:p,onRefresh:r,onExport:u})=>{var c,N,b,m,x,j,R;const f=(t==null?void 0:t.analytics)||{};return e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-700 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-bold text-lg flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5 text-cyan-400"}),"FlipExpert Analytics"]}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Intent routing, client source, latency, safety redirects, and follow-up quality."}),t&&e.jsxs("div",{className:"mt-1 space-y-1",children:[e.jsxs("p",{className:"text-[11px] text-slate-500",children:[t.userId?`Filtered user: ${t.userId}`:"All users",t.since?` | UTC window since ${new Date(t.since).toLocaleStr
20ing()}`:"",t.asOf?` | through ${new Date(t.asOf).toLocaleString()}`:""]}),e.jsxs("p",{className:`text-[11px] ${t.complete?"text-emerald-400":"text-amber-300"}`,children:[t.analyticsVersion===2?"Turn-event metrics":"Legacy sampled metrics",t.complete?` | Complete (${t.scannedTurns||0} turns scanned)`:` | Partial: ${(t.incompleteReasons||["coverage unavailable"]).join("; ")}`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("select",{value:a,onChange:o=>{const y=Number(o.target.value);p(y),r(y)},className:"bg-slate-900 border border-slate-600 rounded-lg px-2 py-1.5 text-sm focus:border-cyan-500 focus:ring-1 focus:ring-cyan-500 outline-none",children:[e.jsx("option",{value:7,children:"7 days"}),e.jsx("option",{value:14,children:"14 days"}),e.jsx("option",{value:30,children:"30 days"}),e.jsx("option",{value:90,children:"90 days"})]}),e.jsxs("button",{type:"button",onClick:()=>r(a),disabled:s,className:"px-3 py-1.5 bg-cyan-600/20 hover:bg-cyan-600/30 disabled:opacity-50 text-cyan-300 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex items-center gap-1",children:[s?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(Fe,{className:"w-4 h-4"}),"Refresh"]}),e.jsxs("button",{type:"button",onClick:u,disabled:d||s||!t,className:"px-3 py-1.5 bg-emerald-600/20 hover:bg-emerald-600/30 disabled:opacity-50 text-emerald-400 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex items-center gap-1",children:[d?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(Pe,{className:"w-4 h-4"}),"Export Analytics"]})]})]}),n&&e.jsx("p",{className:"m-4 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:n}),!t&&!s?e.jsx("div",{className:"p-4 text-sm text-slate-500",children:"Refresh to load FlipExpert analytics."}):e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-7 gap-3",children:[e.jsx(wt,{label:"AI Turns",value:(c=f.totalTurns)!=null?c:0,hint:`${(N=f.totalConversations)!=null?N:0} chats`,icon:bs}),e.jsx(wt,{label:"Active Users",value:(b=f.activeUsers)!=null?b:0,hint:`${(m=f.totalCreditsUsed)!=null?m:0} credits`,icon:Ge}),e.jsx(wt,{label:"Avg Latency",value:ea(f.avgLatencyMs),hint:"server side",icon:Qa}),e.jsx(wt,{label:"Support Rate",value:Jt(f.supportRate),hint:`${(x=f.supportTurns)!=null?x:0} routed`,icon:En}),e.jsx(wt,{label:"Safety Redirects",value:(j=f.safetyRedirects)!=null?j:0,hint:Jt(f.safetyRedirectRate),icon:xt}),e.jsx(wt,{label:"Action Follow-Ups",value:Jt(f.actionFollowUpRate),hint:"of suggestions",icon:In}),e.jsx(wt,{label:"Helpful Rate",value:Jt(f.helpfulRate),hint:`${(R=f.totalRatings)!=null?R:0} ratings`,icon:Cs})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-4",children:[e.jsx(xs,{title:"Top Intents",items:f.topIntents||[]}),e.jsx(xs,{title:"Categories",items:f.topCategories||[]}),e.jsx(xs,{title:"Mode Mix",items:f.modeBreakdown||[]}),e.jsx(xs,{title:"Sources",items:f.sourceBreakdown||[],formatLabel:sa})]}),(f.qualityFlags||[]).length>0&&e.jsx("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2",children:e.jsxs("div",{className:"flex items-start gap-2 text-sm text-amber-200",children:[e.jsx(At,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Watchlist"}),e.jsx("p",{className:"text-xs text-amber-100/80",children:f.qualityFlags.join(" | ")})]})]})})]})]})},Zr=({chat:t,onBack:s,onExport:n,loading:a})=>{var d;return a?e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(H,{className:"w-6 h-6 animate-spin mx-auto text-slate-400"}),e.jsx("p",{className:"text-slate-500 mt-2",children:"Loading conversation..."})]}):t?e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-700 flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:s,"aria-label":"Back to FlipExpert chats",className:"p-1.5 hover:bg-slate-700 rounded-lg transition-colors",children:e.jsx(Za,{className:"w-5 h-5 text-slate-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-white",children:t.title||"Untitled Conversation"}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-slate-500 mt-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ge,{className:"w-3 h-3"}),t.userName||"Unknown"]}),e.jsxs("span",{className:"font-mono",children:[(d=t.userId)==null?void 0:d.slice(0,12),"..."]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ss,{className:"w-3 h-3"}),t.createdAt?new Date(t.createdAt).toLocaleDateString():"N/A"]}),e.jsxs("span",{children:[t.messageCount||0," messages"]})]})]})]}),e.jsxs("button",{type:"button",onClick:()=>n(t),className:"px-3 py-1.5 bg-emerald-600/20 hover:bg-emerald-600/30 text-emerald-400 text-xs rounded-lg transition-colors flex items-center gap-1 self-start",children:[e.jsx(Pe,{className:"w-3 h-3"}),"Export Chat"]})]}),e.jsx("div",{className:"p-4 space-y-4 max-h-[70vh] overflow-y-auto",children:(t.messages||[]).map((p,r)=>e.jsx("div",{className:`flex ${p.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] rounded-xl p-3 ${p.role==="user"?"bg-indigo-600/20 border border-indigo-500/30":"bg-slate-700/50 border border-slate-600/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:`text-[10px] font-bold uppercase ${p.role==="user"?"text-indigo-400":"text-emerald-400"}`,children:p.role==="user"?"User":"FlipExpert AI"}),p.mode&&e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${p.mode==="pro"?"bg-purple-500/20 text-purple-400":"bg-blue-500/20 text-blue-400"}`,children:p.mode==="pro"?"Pro":"Fast"}),p.creditsUsed>0&&e.jsxs("span",{className:"text-[10px] text-amber-400 flex items-center gap-0.5",children:[e.jsx(pt,{className:"w-2.5 h-2.5"}),p.creditsUsed]}),p.rating&&e.jsx("span",{className:`text-[10px] flex items-center gap-0.5 ${p.rating==="up"?"text-emerald-400":"text-red-400"}`,children:p.rating==="up"?e.jsx(Cs,{className:"w-2.5 h-2.5"}):e.jsx(Wa,{className:"w-2.5 h-2.5"})})]}),e.jsx("p",{className:"text-sm text-slate-200 whitespace-pre-wrap break-words",children:p.text}),p.timestamp&&e.jsx("p",{className:"text-[10px] text-slate-500 mt-1",children:new Date(p.timestamp).toLocaleStr
20ing()}),p.category&&e.jsx("span",{className:"inline-block text-[10px] bg-slate-600/50 text-slate-400 px-1.5 py-0.5 rounded mt-1",children:p.category}),(p.intent||p.source||p.latencyMs||p.latencyMs===0||p.safetyRedirected||p.responseTruncated)&&e.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[p.intent&&e.jsx("span",{className:"inline-flex items-center text-[10px] bg-cyan-500/10 text-cyan-300 border border-cyan-500/20 px-1.5 py-0.5 rounded",children:ta(p.intent)}),p.source&&e.jsx("span",{className:"inline-flex items-center text-[10px] bg-slate-900/70 text-slate-300 border border-slate-600 px-1.5 py-0.5 rounded",children:sa(p.source)}),(p.latencyMs||p.latencyMs===0)&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] bg-slate-900/70 text-slate-300 border border-slate-600 px-1.5 py-0.5 rounded",children:[e.jsx(Qa,{className:"w-2.5 h-2.5"}),ea(p.latencyMs)]}),p.safetyRedirected&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] bg-amber-500/10 text-amber-300 border border-amber-500/20 px-1.5 py-0.5 rounded",children:[e.jsx(xt,{className:"w-2.5 h-2.5"}),"safety redirect"]}),p.responseTruncated&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] bg-orange-500/10 text-orange-300 border border-orange-500/20 px-1.5 py-0.5 rounded",children:[e.jsx(At,{className:"w-2.5 h-2.5"}),"truncated"]})]})]})},p.id||r))})]}):null},Qr=({chats:t,loadingChats:s,chatsError:n,chatsFilter:a,chatsHasMore:d,selectedChat:p,loadingChatDetail:r,exportingChats:u,chatsExportProgress:f,chatAnalytics:c,loadingChatAnalytics:N,chatAnalyticsError:b,chatAnalyticsDays:m,exportingChatAnalytics:x,setChatsFilter:j,setSelectedChat:R,setChatAnalyticsDays:o,fetchChats:y,fetchChatDetail:$,fetchChatAnalytics:P,handleExportChats:E,handleExportChatDetail:l,handleExportSingleChat:S,handleExportChatAnalytics:A,clearChatsFilter:g})=>p?e.jsx(Zr,{chat:p,onBack:()=>R(null),onExport:l,loading:r}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(Jr,{analyticsPayload:c,loading:N,error:b,days:m,exporting:x,onDaysChange:o,onRefresh:P,onExport:A}),e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-slate-700 flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-bold text-lg flex items-center gap-2",children:[e.jsx(bs,{className:"w-5 h-5 text-indigo-400"}),"FlipExpert AI Chats"]}),t.length>0&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:["Showing ",t.length," conversations"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("input",{type:"text","aria-label":"Filter FlipExpert chats by user ID",value:a,onChange:h=>j(h.target.value),placeholder:"Filter by user ID...",className:"bg-slate-900 border border-slate-600 rounded-lg px-3 py-1.5 text-sm flex-1 sm:w-48 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none"}),a&&e.jsx("button",{type:"button",onClick:()=>{g(),y(!1,""),P(m,"")},className:"px-2 py-1.5 bg-slate-700 hover:bg-slate-600 rounded-lg text-sm transition-colors",title:"Clear filter",children:e.jsx(ht,{className:"w-4 h-4"})}),e.jsxs("button",{type:"button",onClick:()=>{y(),P(m)},disabled:s,className:"px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex items-center gap-1",children:[s?e.jsx(H,{className:"w-4 h-4 animate-spin"}):null,"Search"]}),e.jsxs("button",{type:"button",onClick:E,disabled:u||t.length===0,className:"px-3 py-1.5 bg-emerald-600/20 hover:bg-emerald-600/30 disabled:opacity-50 text-emerald-400 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex items-center gap-1",children:[u?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(Pe,{className:"w-4 h-4"}),u?`Exporting ${(f==null?void 0:f.conversations)||0}…`:"Export all"]})]})]}),n&&e.jsx("p",{className:"m-4 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:n}),s&&t.length===0?e.jsx("div",{className:"p-8 text-center",children:e.jsx(H,{className:"w-6 h-6 animate-spin mx-auto text-slate-400"})}):t.length===0?e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(bs,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}
20),e.jsx("p",{children:"No conversations found"}),e.jsx("p",{className:"text-xs mt-1",children:"Click Search to load FlipExpert AI conversations"})]}):e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-900/50",children:e.jsxs("tr",{className:"text-left",children:[e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"User"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Title"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Messages"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Mode"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Intent"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Source"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"QA"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Credits"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Last Active"}),e.jsx("th",{className:"px-4 py-3 text-slate-400 font-medium",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-700/50",children:t.map(h=>{var C;return e.jsxs("tr",{className:"hover:bg-slate-700/20",children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("p",{className:"font-medium text-white",children:h.userName||"Unknown"}),e.jsx("p",{className:"text-xs text-slate-500",children:h.userEmail||""}),e.jsxs("p",{className:"text-xs text-slate-600 font-mono",children:[(C=h.userId)==null?void 0:C.slice(0,10),"..."]})]}),e.jsxs("td",{className:"px-4 py-3 max-w-[250px]",children:[e.jsx("p",{className:"text-white truncate",title:h.title,children:h.title||"Untitled"}),h.preview&&e.jsxs("p",{className:"text-xs text-slate-500 truncate mt-0.5",title:h.preview,children:[h.preview.slice(0,80),h.preview.length>80?"...":""]})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"font-medium text-white",children:h.messageCount||0})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${h.lastMode==="pro"?"bg-purple-500/20 text-purple-400":"bg-blue-500/20 text-blue-400"}`,children:h.lastMode==="pro"?"Pro":"Fast"})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-cyan-500/10 text-cyan-300 border border-cyan-500/20 whitespace-nowrap",children:ta(h.lastIntent)})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-slate-900/70 text-slate-300 border border-slate-600",children:sa(h.lastSource)})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[e.jsx("span",{className:"text-slate-300",children:ea(h.avgLatencyMs)}),h.safetyRedirects>0||h.responseTruncations>0?e.jsxs("span",{className:"text-amber-300",children:[h.safetyRedirects||0," safety / ",h.responseTruncations||0," trunc"]}):e.jsx("span",{className:"text-emerald-400",children:"clean"}),h.totalRatings>0&&e.jsxs("span",{className:"text-slate-400",children:[Jt(h.helpfulRate)," helpful"]})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("span",{className:"text-amber-400 flex items-center gap-1",children:[e.jsx(pt,{className:"w-3 h-3"}),h.totalCreditsUsed||0]})}),e.jsx("td",{className:"px-4 py-3 text-slate-400 text-xs",children:h.lastMessageAt?new Date(h.lastMessageAt).toLocaleString():"N/A"}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("button",{type:"button",onClick:()=>$(h.userId,h.id),className:"flex min-h-8 items-center gap-1 rounded-lg bg-indigo-600/20 px-2 py-1.5 text-xs text-indigo-400 transition-colors hover:bg-indigo-600/30",children:[e.jsx(Xt,{className:"w-3 h-3"}),"View"]}),e.jsx("button",{type:"button",onClick:()=>S(h),disabled:r,className:"flex min-h-8 min-w-8 items-center justify-center gap-1 rounded-lg bg-emerald-600/20 px-2 py-1.5 text-xs text-emerald-400 transition-colors hover:bg-emerald-600/30",title:"Export this conversation",children:e.jsx(Pe,{className:"w-3 h-3"})})]})})]},`${h.userId}-${h.id}`)})})]}),d&&e.jsx("div",{className:"p-4 border-t border-slate-700",children:e.jsx("button",{type:"button",onClick:()=>y(!0),disabled:s,className:"w-full py-2 text-sm text-indigo-400 hover:bg-slate-700/30 rounded-lg transition-colors disabled:opacity-50 flex items-center justify-center gap-2",children:s?e.jsxs(e.Fragment,{children:[e.jsx(H,{className:"w-4 h-4 animate-spin"}),"Loading..."]}):"Load more conversations..."})})]})]})]});
20function L(t){return Number(t||0).toLocaleString()}function ws(t){return t==null||!Number.isFinite(Number(t))?"—":`$${Number(t).toFixed(4)}`}function cn(t={}){return t.estimatedCostUnknownCount>0||t.pricingUnavailableCount>0||t.usageMetadataMissingCount>0}function Ms(t={}){return cn(t)?Number(t.estimatedCostUsd)>0?`${ws(t.estimatedCostUsd)} (partial)`:"Unknown":ws(t.estimatedCostUsd)}function Je(t){const s=String(t||"").trim().toLowerCase();return s==="openai"?"OpenAI":s==="gemini"?"Gemini":s==="serpapi"?"SerpApi":s==="soldcomps"?"SoldComps":t||"Provider"}function Ht(t){const s=Number(t||0);return s>=1024*1024?`${(s/1024/1024).toFixed(2)} MB`:s>=1024?`${Math.round(s/1024)} KB`:`${Math.round(s)} B`}function Ta(t){return`${Math.round(Number(t||0))}%`}function me(t){return t==null||!Number.isFinite(Number(t))?"Not available":`${(Number(t)*100).toFixed(1)}%`}function Yr(t={}){const s=Number(t.requestCount||0);return s?Math.round(Number(t.durationMs||0)/s):0}function Xr(t={}){const s=Number(t.requestCount||0);return s?Math.round(Number(t.cacheHitCount||0)/s*100):0}function ei(t={}){const s=Number(t.liveCallCount||0);return s?Number(t.estimatedCostUsd||0)/s:0}function Da(t={}){const s=Number(t.inputBytes||0);return s?Math.max(0,Math.round(Number(t.bytesSaved||0)/s*100)):0}function Ma(t={}){const s=Number(t.imageCount||0);return s?Math.round(Number(t.encodeDurationMs||0)/s):0}const ue=({icon:t,label:s,value:n,subtext:a,tone:d="indigo"})=>{const p={indigo:"text-indigo-300 bg-indigo-500/10 border-indigo-500/20",emerald:"text-emerald-300 bg-emerald-500/10 border-emerald-500/20",amber:"text-amber-300 bg-amber-500/10 border-amber-500/20",cyan:"text-cyan-300 bg-cyan-500/10 border-cyan-500/20"}[d]||"text-indigo-300 bg-indigo-500/10 border-indigo-500/20";return e.jsx("div",{className:"rounded-lg border border-slate-700 bg-slate-900/50 p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`rounded-lg border p-2 ${p}`,children:Qs.createElement(t,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase text-slate-500",children:s}),e.jsx("p",{className:"text-xl font-semibold text-white",children:n}),a&&e.jsx("p",{className:"text-xs text-slate-500",children:a})]})]})})},xe=({title:t,rows:s=[],empty:n="No data yet",valueKey:a="requestCount",unit:d="calls"})=>e.jsxs("div",{className:"rounded-lg border border-slate-700 bg-slate-900/40 p-4",children:[e.jsx("h3",{className:"mb-3 text-sm font-semibold text-slate-200",children:t}),s.length===0?e.jsx("p",{className:"text-sm text-slate-500",children:n}):e.jsx("div",{className:"space-y-2",children:s.slice(0,6).map(p=>e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[e.jsx("span",{className:"truncate text-slate-300",title:p.key,children:p.key}),e.jsxs("span",{className:"shrink-0 text-slate-500",children:[L(p[a])," ",d]})]},p.key))})]}),ti=({stats:t={}})=>{var n;const s=[{label:"Provider result",count:(n=t.providerResultReceivedCount)!=null?n:t.resultReceivedCount,rate:t.resultRate,denominatorCount:t.attemptedCount,denominator:"attempts"},{label:"Safe identity",count:t.safeIdentityCount,rate:t.safeIdentityRate,denominatorCount:t.resultReceivedCount,denominator:"results"},{label:"Citation-backed",count:t.citationBackedResultCount,rate:t.citationBackedRate,denominatorCount:t.resultReceivedCount,denominator:"results"},{label:"Independent target",count:t.identityTargetAvailableCount,rate:t.identityTargetAvailabilityRate,denominatorCount:t.resultReceivedCount,denominator:"results"},{label:"Identity match",count:t.identityMatchedCount,rate:t.identityMatchRate,denominatorCount:t.identityTargetAvailableCount,denominator:"targeted"},{label:"Price applied",count:t.marketEvidenceAcceptedCount,rate:t.marketEvidenceTargetedAcceptanceRate,denominatorCount:t.identityTargetAvailableCount,denominator:"targeted"}];return e.jsxs("div",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4","aria-label":"Search grounding evidence funnel",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h3",{className:"font-semibold text-white",children:"Evidence Funnel"}),e.jsx("p",{className:"mt-1 text-xs text-slate-500",children:"Each stage shows its own denominator. Missing an independent target is non-evaluable, not an identity rejection."})]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6",children:s.map(a=>e.jsxs("div",{className:"rounded-lg border border-slate-700 bg-slate-900/50 px-3 py-3",children:[e.jsx("p",{className:"text-xs text-slate-400",children:a.label}),e.jsx("p",{className:"mt-1 text-lg font-semibold text-white",children:Number(a.denominatorCount)>0?me(a.rate):"Not eligible"}),e.jsxs("p",{className:"text-xs text-slate-500",children:[L(a.count)," of ",L(a.denominatorCount)," ",a.denominator]})]},a.label))})]})},si=({telemetry:t,loadingTelemetry:s,telemetryError:n,telemetryDays:a,telemetryStartDate:d,telemetryEndDate:p,telemetryDirty:r,setTelemetryDays:u,setTelemetryStartDate:f,setTelemetryEndDate:c,fetchTelemetry:N,exportTelemetryCsv:b,exportTelemetryJsonl:m,exportTelemetryZip:x})=>{var D,ee,V,X,ae,q,te;
20const j=(t==null?void 0:t.totals)||{},R=["openai","gemini"].filter(w=>j[w]).map(w=>({provider:w,stats:j[w]||{}})),o=["soldcomps","serpapi"].filter(w=>j[w]).map(w=>({provider:w,stats:j[w]||{}})),y=(t==null?void 0:t.analysisContent)||{},$=y.totals||{},P=(t==null?void 0:t.imageEncoding)||{},E=P.totals||{},l=(t==null?void 0:t.searchGrounding)||{},S=l.totals||{},A=l.activeRevisionTotals||{},g=Number(A.requestCount||0)>0?A:S,h=S,C=Number(A.requestCount||0)>0?`current ${l.activePipelineRevision||"pipeline"} revision`:"selected date range",U=((t==null?void 0:t.daily)||[]).flatMap(w=>Object.entries(w.providers||{}).map(([v,M])=>({date:w.date,provider:v,stats:M}))),k=y.daily||[],I=P.daily||[],O=l.daily||[],Z=($.longestItemAnalyses||[]).map(w=>{var v;return{key:`${w.title||w.analysisId||"Item"} (${(v=w.index)!=null?v:0})`,wordCount:w.wordCount||0}});return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4",children:e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-bold",children:[e.jsx(Rt,{className:"h-5 w-5 text-indigo-300"}),"Provider Telemetry"]}),e.jsx("p",{className:"mt-1 text-xs text-slate-500",children:"App usage and cost estimates use the configured telemetry timezone. OpenAI billing is reported separately in UTC for the organization or configured projects; it may include activity outside this app."})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("label",{className:"text-xs text-slate-400",children:["Days",e.jsxs("select",{"aria-label":"Days",value:a,onChange:w=>u(w.target.value),disabled:!!(d||p),className:"mt-1 block rounded-lg border border-slate-600 bg-slate-900 px-3 py-2 text-sm text-white outline-none focus:border-indigo-500 disabled:opacity-50",children:[e.jsx("option",{value:"7",children:"7"}),e.jsx("option",{value:"14",children:"14"}),e.jsx("option",{value:"30",children:"30"}),e.jsx("option",{value:"90",children:"90"})]})]}),e.jsxs("label",{className:"text-xs text-slate-400",children:["Start",e.jsx("input",{type:"date",value:d,onChange:w=>f(w.target.value),className:"mt-1 block rounded-lg border border-slate-600 bg-slate-900 px-3 py-2 text-sm text-white outline-none focus:border-indigo-500"})]}),e.jsxs("label",{className:"text-xs text-slate-400",children:["End",e.jsx("input",{type:"date",value:p,onChange:w=>c(w.target.value),className:"mt-1 block rounded-lg border border-slate-600 bg-slate-900 px-3 py-2 text-sm text-white outline-none focus:border-indigo-500"})]}),e.jsxs("button",{type:"button",onClick:N,disabled:s,className:"flex items-center gap-2 rounded-lg bg-indigo-600 px-3 py-2 text-sm font-semibold text-white transition-colors hover:bg-indigo-700 disabled:opacity-50",children:[s?e.jsx(H,{className:"h-4 w-4 animate-spin"}):e.jsx(Fe,{className:"h-4 w-4"}),"Refresh"]}),e.jsxs("button",{type:"button",onClick:b,disabled:!t||r||s,className:"flex items-center gap-2 rounded-lg bg-slate-700 px-3 py-2 text-sm font-semibold text-slate-200 transition-colors hover:bg-slate-600 disabled:opacity-50",children:[e.jsx(Pe,{className:"h-4 w-4"}),"CSV v1"]}),e.jsxs("button",{type:"button",onClick:()=>m(3),disabled:!t||r||s,className:"flex items-center gap-2 rounded-lg bg-slate-700 px-3 py-2 text-sm font-semibold text-slate-200 transition-colors hover:bg-slate-600 disabled:opacity-50",children:[e.jsx(Rn,{className:"h-4 w-4"}),"JSONL v3"]}),e.jsxs("button",{type:"button",onClick:x,disabled:!t||r||s,className:"flex items-center gap-2 rounded-lg bg-slate-700 px-3 py-2 text-sm font-semibold text-slate-200 transition-colors hover:bg-slate-600 disabled:opacity-50",children:[e.jsx(st,{className:"h-4 w-4"}),"ZIP v3"]})]})]})}),n&&e.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:[e.jsx(Re,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:n})]}),r&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-200",role:"status",children:[e.jsx(Re,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:"Filters changed after the displayed data was loaded. Refresh before exporting so the file and controls cannot disagree."})]}),((D=t==null?void 0:t.openAiCosts)==null?void 0:D.status)&&t.openAiCosts.status!=="ok"&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-200",role:"status",children:[e.jsx(Re,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("span",{children:["OpenAI billing is unavailable (",t.openAiCosts.status,"). App cost estimates remain available. ",t.openAiCosts.status==="unconfigured"||t.openAiCosts.status==="unauthorized"?"A valid OpenAI admin credential is required to read billing.":"Retry to load billing."]})]}),t&&e.jsxs("p",{className:"text-xs text-slate-500",children:["Loaded ",((ee=t.resolvedFilters)==null?void 0:ee.startDate)||t.startDate," through ",((V=t.resolvedFilters)==null?void 0:V.endDate)||t.endDate," ","in ",((X=t.resolvedFilters)==null?void 0:X.timeZone)||t.timeZone||"the telemetry timezone",", as of ",new Date(t.asOf||t.generatedAt).toLocaleStr
20ing(),". CSV v1 is a legacy multi-section file; ZIP v3 contains rectangular tables and a manifest."]}),!t&&e.jsx("p",{role:"status",className:"p-6 text-slate-400",children:s?"Loading telemetry…":"Load telemetry to see recorded metrics."}),t&&e.jsxs(e.Fragment,{children:[((ae=t.openAiCosts)==null?void 0:ae.status)==="ok"&&e.jsxs("section",{"aria-label":"OpenAI billing",className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4",children:[e.jsx("h3",{className:"font-semibold text-white",children:"OpenAI reported billing (UTC)"}),e.jsx("p",{className:"mt-1 text-xl text-white",children:ws(t.openAiCosts.totalCostUsd)}),e.jsxs("p",{className:"mt-1 text-xs text-slate-400",children:[t.openAiCosts.startDate," through ",t.openAiCosts.endDate,", UTC · ",(q=t.openAiCosts.projectIds)!=null&&q.length?"Configured projects":"Entire organization","."," ","Reported as of ",new Date(t.openAiCosts.fetchedAt).toLocaleString(),". Recent billing may be incomplete. This total has a separate scope from app usage below."]}),t.openAiCosts.unsupportedCurrencyCount>0&&e.jsx("p",{className:"mt-2 text-amber-200",children:"Non-USD billing rows are excluded from this USD subtotal."})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[R.map(({provider:w,stats:v})=>e.jsx(ue,{icon:pt,label:`${Je(w)} Est. Cost`,value:Ms(v),subtext:`${L(v.requestCount)} calls, ${L(v.webSearchCallCount||v.groundingSearchRequestCount)}
20 search; ${L(v.pricingUnavailableCount)} unpriced, ${L(v.usageMetadataMissingCount)} missing usage`},`${w}-cost`)),R.map(({provider:w,stats:v})=>e.jsx(ue,{icon:_s,label:`${Je(w)} Tokens`,value:L(v.totalTokenCount),subtext:`${L(v.inputTokenCount||v.promptTokenCount)} input + ${L(v.outputTokenCount||v.candidatesTokenCount)} output; ${L(v.cacheWriteTokenCount)} cache writes`,tone:"cyan"},`${w}-tokens`)),o.map(({provider:w,stats:v})=>e.jsx(ue,{icon:Zt,label:`${Je(w)} Est. Cost`,value:Ms(v),subtext:`${L(v.liveCallCount)} live, ${cn(v)?"unit cost incomplete":`avg ${ws(ei(v))}`}${v.estimatedCostUnknownCount?`, ${L(v.estimatedCostUnknownCount)} unknown`:""}`,tone:"emerald"},`${w}-cost`)),o.map(({provider:w,stats:v})=>e.jsx(ue,{icon:at,label:`${Je(w)} Live Calls`,value:L(v.liveCallCount),subtext:`${Xr(v)}% cache, ${L(v.errorCount)} errors, ${Yr(v)}ms avg`,tone:"amber"},`${w}-live`))]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[R.map(({provider:w,stats:v})=>e.jsx(xe,{title:`${Je(w)} by Model`,rows:v.byModel||[]},`${w}-model`)),R.map(({provider:w,stats:v})=>e.jsx(xe,{title:`${Je(w)} by Source`,rows:v.bySource||[]},`${w}-source`)),R.filter(({stats:w})=>(w.byServiceTier||[]).length>0).map(({provider:w,stats:v})=>e.jsx(xe,{title:`${Je(w)} by Tier`,rows:v.byServiceTier||[]},`${w}-service-tier`)),R.filter(({stats:w})=>(w.byWebSearchContextSize||[]).length>0).map(({provider:w,stats:v})=>e.jsx(xe,{title:`${Je(w)} Search Context`,rows:v.byWebSearchContextSize||[]},`${w}-web-context`)),o.map(({provider:w,stats:v})=>e.jsx(xe,{title:`${Je(w)} by Status`,rows:v.byProviderStatus||[]},`${w}-provider-status`))]}),e.jsx("div",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-bold",children:[e.jsx(at,{className:"h-5 w-5 text-cyan-300"}),"Search Grounding Quality"]}),e.jsxs("p",{className:"mt-1 text-xs text-slate-500",children:["End-to-end outcomes for the ",C,": provider completion, citations, independent identity checks, price application, verified sold comps, failures, and latency. Breakdown panels remain range-wide so revision changes are visible."]})]})}),e.jsx(ti,{stats:g}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(ue,{icon:at,label:"Grounding Attempted",value:me(g.attemptRate),subtext:`${L(g.attemptedCount)} of ${L(g.requestCount)} analyses`,tone:"cyan"}),e.jsx(ue,{icon:xt,label:"Price Evidence Applied",value:me(g.marketEvidenceTargetedAcceptanceRate),subtext:`${me(g.marketEvidenceAcceptanceRate)} of all results; ${L(g.marketEvidenceNotEvaluableCount)} non-evaluable`,tone:"emerald"}),e.jsx(ue,{icon:Rt,label:"Grounding Used",value:me(g.useRate),subtext:`${L(g.usedCount)} analyses; ${me(g.identityUseRate)} identity use`,tone:"indigo"}),e.jsx(ue,{icon:xt,label:"Pre-main Identity Authority",value:me(g.preMainIdentityAuthorityRate),subtext:`${L(g.preMainIdentityAuthoritativeCount)} of ${L(g.requestedIdentityCount)} identity candidates could authorize price before main analysis`,tone:"indigo"}),e.jsx(ue,{icon:xt,label:"Citation-backed Results",value:me(g.citationBackedRate),subtext:`${me(g.marketCitationBackedRate)} market-relevant; ${g.averageProviderSourceCount||0} provider sources avg`,tone:"emerald"}),e.jsx(ue,{icon:Zt,label:"Grounding Price Changed",value:me(g.marketEvidencePriceChangeRate),subtext:`${L(g.marketEvidencePriceChangedCount)} changed, ${L(g.marketEvidencePriceRetainedCount)} retained; ${me(g.marketEvidencePriceEffectCoverageRate)} classified`,tone:"emerald"}),e.jsx(ue,{icon:Zt,label:"Verified Sold Coverage",value:me(g.verifiedSoldCoverage),subtext:`${L(g.compsExactVerifiedSoldCount)} exact sold; ${me(g.compsValuationEligibilityRate)} eligible when attempted`,tone:"emerald"}),e.jsx(ue,{icon:xt,label:"Eligible Sold Price Applied",value:me(g.compsPriceApplicationRate),subtext:`${L(g.compsPriceAppliedCount)} applied, ${L(g.compsEligibleNotAppliedCount)} not selected; ${me(g.compsPriceOutcomeCoverageRate)} classified`,tone:"indigo"}),e.jsx(ue,{icon:Fe,label:"Post-main Recovery",value:me(g.postMainReevaluationAcceptanceRate),subtext:`${L(g.postMainReevaluationAppliedCount)} applied of ${L(g.postMainReevaluationConsideredCount)}
20 independently rechecked`,tone:"indigo"}),e.jsx(ue,{icon:Re,label:"Incomplete Output",value:me(g.outputIncompleteRate),subtext:`${L(g.outputIncompleteCount)} incomplete; ${L((te=g.providerOutputUnknownCount)!=null?te:g.outputUnknownCount)} live unknown status`,tone:"amber"}),e.jsx(ue,{icon:Re,label:"Timeout / Error",value:`${me(g.timeoutRate)} / ${me(g.errorRate)}`,subtext:`${L(g.timeoutCount)} timeouts, ${L(g.requestErrorCount)} request errors`,tone:"amber"}),e.jsx(ue,{icon:pt,label:"Grounding Latency",value:`${L(g.averageGroundingDurationMs)}ms`,subtext:`${L(g.averageAnalysisDurationMs)}ms full analysis avg; decision ${g.averageDecisionScore||0}`,tone:"cyan"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(xe,{title:"Pipeline Revision",rows:h.byPipelineRevision||[]}),e.jsx(xe,{title:"Grounding by Provider",rows:h.byProvider||[]}),e.jsx(xe,{title:"Decision Stage",rows:h.byDecisionStage||[]}),e.jsx(xe,{title:"Grounding Decision Skips",rows:h.byDecisionSkipReason||[]}),e.jsx(xe,{title:"Evidence Outcomes",rows:h.byMarketEvidenceRejectionReason||[]}),e.jsx(xe,{title:"Grounding Price Effect",rows:h.byMarketEvidencePriceEffect||[]}),e.jsx(xe,{title:"Identity Match Reason",rows:h.byIdentityMatchReason||[]}),e.jsx(xe,{title:"Pre-main Identity Authority",rows:h.byPreMainIdentityAuthorityReason||[]}),e.jsx(xe,{title:"Identity Validation",rows:h.byGroundedIdentityValidationReason||[]}),e.jsx(xe,{title:"Output Status",rows:h.byOutputStatus||[]}),e.jsx(xe,{title:"Cache Status",rows:h.byCacheStatus||[]}),e.jsx(xe,{title:"Cache Eligibility",rows:h.byCacheEligibilityReason||[]}),e.jsx(xe,{title:"Fallback Reasons",rows:h.byFallbackReason||[]}),e.jsx(xe,{title:"Sold-Comps Status",rows:h.byCompsProviderStatus||[]}),e.jsx(xe,{title:"Eligible Sold Price Outcome",rows:h.byCompsPriceNotAppliedReason||[]}),e.jsx(xe,{title:"Policy Version",rows:h.byPolicyVersion||[]})]}),e.jsxs("div",{className:"overflow-hidden rounded-xl border border-slate-700 bg-slate-800/50",children:[e.jsxs("div",{className:"border-b border-slate-700 p-4",children:[e.jsx("h3",{className:"font-semibold text-white",children:"Daily Search Grounding Rows"}),l.generatedAt&&e.jsxs("p",{className:"mt-1 text-xs text-slate-500",children:[l.startDate," to ",l.endDate," | generated ",new Date(l.generatedAt).toLocaleString()]})]}),s&&!t?e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(H,{className:"mx-auto mb-3 h-6 w-6 animate-spin"}),"Loading telemetry"]}):O.length===0?e.jsx("div",{className:"p-8 text-center text-slate-500",children:"No search-grounding rows in this range."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-900/50 text-left text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Date"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Analyses"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Attempt / Use"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Evidence"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Citations"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Verified Sold"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Failures"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Latency"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-700/50",children:O.map(({date:w,stats:v})=>e.jsxs("tr",{className:"hover:bg-slate-700/20",children:[e.jsx("td",{className:"px-4 py-3 text-slate-300",children:w}),e.jsx("td",{className:"px-4 py-3 text-slate-300",children:L(v.requestCount)}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[me(v.attemptRate)," / ",me(v.useRate)]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[me(v.marketEvidenceTargetedAcceptanceRate)," targeted",v.marketEvidenceNotEvaluableCount>0&&e.jsxs("span",{className:"ml-2 text-xs text-slate-500",children:[L(v.marketEvidenceNotEvaluableCount)," non-evaluable"]})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[v.averageProviderSourceCount||0," avg",v.sourceMetadataMissingCount>0&&e.jsxs("span",{className:"ml-2 text-xs text-amber-300",children:[L(v.sourceMetadataMissingCount)," missing"]})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[me(v.verifiedSoldCoverage),e.jsxs("span",{className:"ml-2 text-xs text-slate-500",children:[v.averageCompsSampleSize||0," sample avg"]})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[L(v.timeoutCount)," timeout, ",L(v.requestErrorCount)," error"]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[L(v.averageGroundingDurationMs),"ms grounding",e.jsxs("span",{className:"ml-2 text-xs text-slate-500",children:[L(v.averageAnalysisDurationMs),"ms total"]})]})]},w))})]})})]}),e.jsx("div",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-bold",children:[e.jsx(st,{className:"h-5 w-5 text-emerald-300"}),"Analysis Content Telemetry"]}
20),e.jsx("p",{className:"mt-1 text-xs text-slate-500",children:"Tracks item-analysis length plus acceptance and fallback rates for optional AI narrative hints. Rejected prose is never stored in telemetry."})]})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(ue,{icon:es,label:"Narrative Accepted",value:me($.narrativeHintsAcceptanceRate),subtext:`${L($.narrativeHintsItemCount)} of ${L($.narrativeHintsEligibleItemCount)} eligible items`,tone:"emerald"}),e.jsx(ue,{icon:xt,label:"Complete Sets",value:me($.completeNarrativeHintsRate),subtext:`${L($.completeNarrativeHintsItemCount)} complete, ${L($.partialNarrativeHintsItemCount)} partial`,tone:"cyan"}),e.jsx(ue,{icon:Re,label:"Rejected Sets",value:me($.rejectedNarrativeHintsRate),subtext:`${L($.rejectedNarrativeHintsItemCount)} safely fell back`,tone:"amber"}),e.jsx(ue,{icon:Rt,label:"Rollout Disabled",value:L($.disabledNarrativeHintsItemCount),subtext:`${L($.narrativeHintFieldCount)} accepted fields total`,tone:"indigo"})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(ue,{icon:st,label:"Item Analyses",value:L($.itemAnalysisCount),subtext:`${L($.requestCount)} analyses, ${$.avgItemsPerAnalysis||0} items avg`,tone:"emerald"}),e.jsx(ue,{icon:_s,label:"Avg Item Analysis",value:`${$.avgItemAnalysisWords||0} words`,subtext:`${L($.avgItemAnalysisChars)} chars avg`,tone:"cyan"}),e.jsx(ue,{icon:pt,label:"Longest Item",value:`${L($.maxItemAnalysisWords)} words`,subtext:`${L($.maxItemAnalysisChars)} chars max, ${L($.minItemAnalysisWords)} words min`,tone:"amber"}),e.jsx(ue,{icon:Re,label:"Outliers",value:L($.itemAnalysisOutlierCount),subtext:`${L($.longItemAnalysisCount)} long, ${me($.itemAnalysisOutlierRate)} rate`,tone:"indigo"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(xe,{title:"Analysis by Mode",rows:$.byAnalysisMode||[],valueKey:"avgItemAnalysisWords",unit:"avg words"}),e.jsx(xe,{title:"Analysis by Source",rows:$.bySource||[],valueKey:"avgItemAnalysisWords",unit:"avg words"}),e.jsx(xe,{title:"Narrative Mode Latency",rows:$.byNarrativeHintsMode||[],valueKey:"avgDurationMs",unit:"ms avg"}),e.jsx(xe,{title:"Longest Item Analyses",rows:Z,valueKey:"wordCount",unit:"words"})]}),e.jsx("div",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-bold",children:[e.jsx(fs,{className:"h-5 w-5 text-cyan-300"}),"Image Encoding Telemetry"]}),e.jsx("p",{className:"mt-1 text-xs text-slate-500",children:"Tracks client-side adaptive image encoding only. No image data, URLs, or user identifiers are stored in these aggregates."})]})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(ue,{icon:fs,label:"Images Encoded",value:L(E.imageCount),subtext:`${L(E.requestCount)} analyses`,tone:"cyan"}),e.jsx(ue,{icon:Pe,label:"Output Bytes",value:Ht(E.outputBytes),subtext:`${Ht(E.inputBytes)} input, ${Ta(Da(E))} saved`,tone:"emerald"}),e.jsx(ue,{icon:Fe,label:"Re-encoded",value:L(E.reencodedImageCount),subtext:`${L(E.preservedImageCount)} preserved`,tone:"indigo"}),e.jsx(ue,{icon:Rt,label:"Avg Encode",value:`${Ma(E)}ms`,subtext:`${L(E.targetMissImageCount)} target misses, ${L(E.fallbackImageCount)} fallbacks`,tone:"amber"})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsx(xe,{title:"Images by Surface",rows:E.bySurface||[],valueKey:"imageCount",unit:"images"}),e.jsx(xe,{title:"Images by Result",rows:E.byReason||[],valueKey:"imageCount",unit:"images"}),e.jsx(xe,{title:"Images by Output MIME",rows:E.byOutputMime||[],valueKey:"imageCount",unit:"images"})]}),e.jsxs("div",{className:"overflow-hidden rounded-xl border border-slate-700 bg-slate-800/50",children:[e.jsxs("div",{className:"border-b border-slate-700 p-4",children:[e.jsx("h3",{className:"font-semibold text-white",children:"Daily Analysis Content Rows"}),y.generatedAt&&e.jsxs("p",{className:"mt-1 text-xs text-slate-500",children:[y.startDate," to ",y.endDate," | generated ",new Date(y.generatedAt).toLocaleStr
20ing()]})]}),s&&!t?e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(H,{className:"mx-auto mb-3 h-6 w-6 animate-spin"}),"Loading telemetry"]}):k.length===0?e.jsx("div",{className:"p-8 text-center text-slate-500",children:"No analysis content rows in this range."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-900/50 text-left text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Date"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Analyses"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Items"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Avg Length"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Longest"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Outliers"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Narrative"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-700/50",children:k.map(({date:w,stats:v})=>e.jsxs("tr",{className:"hover:bg-slate-700/20",children:[e.jsx("td",{className:"px-4 py-3 text-slate-300",children:w}),e.jsx("td",{className:"px-4 py-3 text-slate-300",children:L(v.requestCount)}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[L(v.itemAnalysisCount),v.emptyItemAnalysisCount>0&&e.jsxs("span",{className:"ml-2 text-xs text-amber-300",children:[L(v.emptyItemAnalysisCount)," empty"]})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[v.avgItemAnalysisWords||0," words",e.jsxs("span",{className:"ml-2 text-xs text-slate-500",children:[L(v.avgItemAnalysisChars)," chars"]})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[L(v.maxItemAnalysisWords)," words",e.jsxs("span",{className:"ml-2 text-xs text-slate-500",children:[L(v.maxItemAnalysisChars)," chars"]})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[L(v.itemAnalysisOutlierCount),v.longItemAnalysisCount>0&&e.jsxs("span",{className:"ml-2 text-xs text-amber-300",children:[L(v.longItemAnalysisCount)," long"]})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[me(v.narrativeHintsAcceptanceRate)," accepted",v.rejectedNarrativeHintsItemCount>0&&e.jsxs("span",{className:"ml-2 text-xs text-amber-300",children:[L(v.rejectedNarrativeHintsItemCount)," rejected"]})]})]},w))})]})})]}),e.jsxs("div",{className:"overflow-hidden rounded-xl border border-slate-700 bg-slate-800/50",children:[e.jsxs("div",{className:"border-b border-slate-700 p-4",children:[e.jsx("h3",{className:"font-semibold text-white",children:"Daily Provider Rows"}),t&&e.jsxs("p",{className:"mt-1 text-xs text-slate-500",children:[t.startDate," to ",t.endDate," | generated ",new Date(t.generatedAt).toLocaleString()]})]}),s&&!t?e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(H,{className:"mx-auto mb-3 h-6 w-6 animate-spin"}),"Loading telemetry"]}):U.length===0?e.jsx("div",{className:"p-8 text-center text-slate-500",children:"No telemetry rows in this range."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-900/50 text-left text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Date"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Provider"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Requests"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Estimated cost"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Tokens / Calls"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Health"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-700/50",children:U.map(({date:w,provider:v,stats:M})=>e.jsxs("tr",{className:"hover:bg-slate-700/20",children:[e.jsx("td",{className:"px-4 py-3 text-slate-300",children:w}),e.jsx("td",{className:"px-4 py-3 font-medium text-white",children:Je(v)}),e.jsx("td",{className:"px-4 py-3 text-slate-300",children:L(M.requestCount)}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[Ms(M),M.estimatedCostUnknownCount>0&&e.jsxs("span",{className:"ml-2 text-xs text-amber-300",children:[L(M.estimatedCostUnknownCount)," unknown"]})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[v==="gemini"||v==="openai"?`${L(M.totalTokenCount)} tokens, ${L(M.webSearchCallCount||M.groundingSearchQueryCount)} search`:`${L(M.liveCallCount)}
20 live, ${L(M.cacheHitCount)} cache`,v==="gemini"&&M.reportedGroundingSearchQueryCount!==M.groundingSearchQueryCount&&e.jsxs("span",{className:"ml-2 text-xs text-slate-500",children:[L(M.reportedGroundingSearchQueryCount)," exact"]})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[L(M.errorCount)," errors",(v==="serpapi"||v==="soldcomps")&&` | ${L(M.rateLimitedCount)} rate-limited`,v==="gemini"&&M.usageMetadataMissingCount>0&&e.jsxs("span",{className:"ml-2 text-xs text-amber-300",children:[L(M.usageMetadataMissingCount)," missing usage"]}),v==="gemini"&&M.groundingSearchFallbackRequestCount>0&&e.jsxs("span",{className:"ml-2 text-xs text-amber-300",children:[L(M.groundingSearchFallbackRequestCount)," estimated search"]}),v==="openai"&&M.webSearchMetadataMissingCount>0&&e.jsxs("span",{className:"ml-2 text-xs text-amber-300",children:[L(M.webSearchMetadataMissingCount)," missing search metadata"]})]})]},`${w}:${v}`))})]})})]}),e.jsxs("div",{className:"overflow-hidden rounded-xl border border-slate-700 bg-slate-800/50",children:[e.jsxs("div",{className:"border-b border-slate-700 p-4",children:[e.jsx("h3",{className:"font-semibold text-white",children:"Daily Image Encoding Rows"}),P.generatedAt&&e.jsxs("p",{className:"mt-1 text-xs text-slate-500",children:[P.startDate," to ",P.endDate," | generated ",new Date(P.generatedAt).toLocaleString()]})]}),s&&!t?e.jsxs("div",{className:"p-8 text-center text-slate-500",children:[e.jsx(H,{className:"mx-auto mb-3 h-6 w-6 animate-spin"}),"Loading telemetry"]}):I.length===0?e.jsx("div",{className:"p-8 text-center text-slate-500",children:"No image encoding rows in this range."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-900/50 text-left text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Date"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Analyses"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Images"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Input"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Output"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Saved"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Preserved / Re-encoded"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Health"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-700/50",children:I.map(({date:w,stats:v})=>e.jsxs("tr",{className:"hover:bg-slate-700/20",children:[e.jsx("td",{className:"px-4 py-3 text-slate-300",children:w}),e.jsx("td",{className:"px-4 py-3 text-slate-300",children:L(v.requestCount)}),e.jsx("td",{className:"px-4 py-3 text-slate-300",children:L(v.imageCount)}),e.jsx("td",{className:"px-4 py-3 text-slate-300",children:Ht(v.inputBytes)}),e.jsx("td",{className:"px-4 py-3 text-slate-300",children:Ht(v.outputBytes)}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[Ht(v.bytesSaved),e.jsx("span",{className:"ml-2 text-xs text-slate-500",children:Ta(Da(v))})]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[L(v.preservedImageCount)," / ",L(v.reencodedImageCount)]}),e.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[Ma(v),"ms avg",(v.targetMissImageCount>0||v.fallbackImageCount>0)&&e.jsxs("span",{className:"ml-2 text-xs text-amber-300",children:[L(v.targetMissImageCount)," misses, ",L(v.fallbackImageCount)," fallbacks"]})]})]},w))})]})})]})]})]})},La=Object.freeze({ios:"iOS app",android:"Android app",chrome_extension:"Chrome extension",firefox_extension:"Firefox extension"});function pe(t){return Math.max(0,Number(t)||0).toLocaleString()}function ai(t){const s=new Date(t);return Number.isFinite(s.getTime())?s.toLocaleString():"Unknown"}function Fa(t){const s=new Date(t);return Number.isFinite(s.getTime())?s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):"Unknown"}const Ze=({icon:t,label:s,value:n,detail:a,tone:d="indigo"})=>{const p={indigo:"border-indigo-500/20 bg-indigo-500/10 text-indigo-300",emerald:"border-emerald-500/20 bg-emerald-500/10 text-emerald-300",cyan:"border-cyan-500/20 bg-cyan-500/10 text-cyan-300",amber:"border-amber-500/20 bg-amber-500/10 text-amber-300"}[d]||"border-indigo-500/20 bg-indigo-500/10 text-indigo-300";return e.jsx("div",{className:"rounded-xl border border-slate-700 bg-slate-900/50 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`rounded-lg border p-2 ${p}`,children:Qs.createElement(t,{className:"h-4 w-4","aria-hidden":!0})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase text-slate-400",children:s}),e.jsx("p",{className:"mt-0.5 text-xl font-semibold text-white",children:n}),e.jsx("p",{className:"mt-0.5 text-xs text-slate-400",children:a})]})]})})},ni=({revenueByCurrency:t})=>{const s=Object.entries(t||{}).sort(([n],[a])=>n.localeCompare(a));return s.length===0?e.jsx("span",{className:"text-slate-500",children:"—"}):e.jsx("span",{className:"inline-flex flex-col items-end gap-0.5",children:s.map(([n,a])=>e.jsxs("span",{className:Number((a==null?void 0:a.netMinor)||0)<0?"text-amber-300":"text-emerald-300",children:[e.jsx("span",{className:"mr-1 text-[10px] font-medium uppercase text-slate-500",children:n}),Yt(a==null?void 0:a.netMinor,n)]},n))})},ms=({title:t,rows:s,dimensionKey:n,dimensionLabel:a,includeRetention:d=!0,limit:p})=>{const r=Number.isFinite(p)?s.slice(0,p):s;return e.jsxs("section",{className:"min-w-0 rounded-xl border border-slate-700 bg-slate-900/40",children:[e.jsxs("div",{className:"border-b border-slate-700 px-4 py-3",children:[e.jsx("h3",{className:"font-semibold text-white",children:t}),r.length<s.length?e.jsxs("p",{className:"mt-1 text-xs text-slate-400",children:["Showing the top ",r.length," of ",s.length," rows by signups."]}):null]}),e.jsx("div",{role:"region","aria-label":`${t} table`,tabIndex:0,className:"overflow-x-auto focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-indigo-500",children:e.jsxs("table",{className:"min-w-full text-left text-sm",children:[e.jsx("caption",{className:"sr-only",children:t}),e.jsx("thead",{className:"bg-slate-950/50 text-xs uppercase text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-4 py-3",children:a}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"Signups"}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"First analysis"}),d?e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"D7 retained"}):null,e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"Payers"}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"Net revenue"})]})}),e.jsxs("tbody",{className:"divide-y divide-slate-800",children:[r.map(u=>{var f,c;return e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"max-w-sm px-4 py-3 font-medium text-slate-200",children:e.jsx("span",{className:"block truncate",title:u[n],children:pr(u[n],n)})}),e.jsx("td",{className:"px-4 py-3 text-right text-slate-300",children:pe(u.signups)}),e.jsxs("td",{className:"px-4 py-3 text-right text-slate-300",children:[pe(u.firstAnalysisUsers)," ",e.jsxs("span",{className:"text-slate-400",children:["(",Be((f=u.rates)==null?void 0:f.signupToFirstAnalysisPct),")"]})]}),d?e.jsxs("td",{className:"px-4 py-3 text-right text-slate-300",children:[pe(u.d7Retained)," / ",pe(u.d7Eligible)," ",e.jsxs("span",{className:"text-slate-400",children:["(",Be((c=u.rates)==null?void 0:c.d7RetentionPct),")"]})]}):null,e.jsx("td",{className:"px-4 py-3 text-right text-slate-300",children:pe(u.payers)}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(ni,{revenueByCurrency:u.revenueByCurrency})})]},u[n])}),r.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:d?6:5,className:"px-4 py-8 text-center text-slate-400",children:"No qualifying cohort rows yet."})}):null]})]})})]})},ri=({report:t,reportDays:s,loadedReportDays:n,loadingReport:a,exportingMarkdown:d,reportError:p,exportError:r,reportDirty:u,setReportDays:f,fetchAcquisitionReport:c,exportAcquisitionMarkdown:N})=>{var R,o,y,$,P,E,l,S,A,g;const b=(t==null?void 0:t.overall)||{},m=b.rates||{},x=Object.keys(La),j=Object.entries(b.revenueByCurrency||{}).sort(([h],[C])=>h.localeCompare(C));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("section",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between",children:[e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-bold",children:[e.jsx(Fs,{className:"h-5 w-5 text-emerald-300","aria-hidden":"true"}),"Acquisition & Product Outcomes"]}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-slate-400",children:"Consent-aware signup cohorts joined to successful first analysis, eligible retention windows, signed-in client first use, and Stripe-webhook-confirmed commerce. Retention counts successful saved analyses on UTC calendar days; visits and logins alone do not count. Source rows are aggregate-only and never include user IDs or email addresses."})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("label",{className:"text-xs text-slate-400",children:["Signup cohort",e.jsx("select",{"aria-label":"Signup cohort",value:s,onChange:h=>f(h.target.value),className:"mt-1 block rounded-lg border border-slate-600 bg-slate-900 px-3 py-2 text-sm text-white outline-none focus:border-indigo-500",children:dr.map(h=>e.jsxs("option",{value:String(h),children:["Past ",h," days"]},h))})]}),e.jsxs("button",{type:"button",onClick:()=>c(),disabled:a,className:"flex items-center gap-2 rounded-lg bg-indigo-600 px-3 py-2 text-sm font-semibold text-white transition-colors hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-50",children:[a?e.jsx(H,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):e.jsx(Fe,{className:"h-4 w-4","aria-hidden":"true"}),t?"Run report":"Load report"]}),e.jsxs("button",{type:"button",onClick:N,disabled:!t||u||a||d,className:"flex items-center gap-2 rounded-lg bg-slate-700 px-3 py-2 text-sm font-semibold text-slate-200 transition-colors hover:bg-slate-600 disabled:cursor-not-allowed disabled:opacity-50",children:[d?e.jsx(H,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):e.jsx(Pe,{className:"h-4 w-4","aria-hidden":"true"}),"Download .md"]})]})]}),t?e.jsxs("p",{className:"mt-3 text-xs text-slate-400",children:["Generated ",e.jsx("time",{dateTime:t.generatedAt,children:ai(t.generatedAt)})," · Signup cohort ",Fa((R=t.window)==null?void 0:R.startAt),"–",Fa((o=t.window)==null?void 0:o.endAt)," · ",n||((y=t.window)==null?void 0:y.days)," days"]}):null]}),u?e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-200",children:[e.jsx(gs,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),"The selected window has changed. Run the report before using or exporting these results."]}):null,p||r?e.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:[e.jsx(Re,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsx("span",{children:p||r})]}):null,a&&!t?e.jsxs("div",{role:"status",className:"flex min-h-48 items-center justify-center gap-3 rounded-xl border border-slate-700 bg-slate-900/40 text-slate-400",children:[e.jsx(H,{className:"h-5 w-5 animate-spin text-indigo-300","aria-hidden":"true"}),"Generating the aggregate cohort report…"]}):null,!a&&!t?e.jsxs("div",{className:"rounded-xl border border-dashed border-slate-700 bg-slate-900/30 px-6 py-10 text-center",children:[e.jsx(Fs,{className:"mx-auto h-8 w-8 text-slate-500","aria-hidden":"true"}),e.jsx("h3",{className:"mt-3 font-semibold text-slate-200",children:"Load the first cohort report"}),e.jsx("p",{className:"mx-auto mt-1 max-w-xl text-sm text-slate-400",children:"The report is generated on demand because it reads account milestones across the selected signup cohort. It does not poll in the background."})]}):null,t?e.jsxs("div",{className:u?"opacity-60":"","aria-busy":a,children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ze,{icon:Pn,label:"Signups",value:pe(b.signups),detail:"Accounts in this signup cohort"}),e.jsx(Ze,{icon:xt,label:"Attributed",value:pe(b.attributedSignups),detail:`${Be(m.attributionCoveragePct)} of cohort`,tone:"cyan"}),e.jsx(Ze,{icon:at,label:"Organic search",value:pe(b.organicSignups),detail:`${Be(m.organicSharePct)} of cohort`,tone:"emerald"}),e.jsx(Ze,{icon:Un,label:"First analysis",value:pe(b.firstAnalysisUsers),detail:`${Be(m.signupToFirstAnalysisPct)}
20 of signups`,tone:"emerald"}),e.jsx(Ze,{icon:_t,label:"D1 retained",value:`${pe(b.d1Retained)} / ${pe(b.d1Eligible)}`,detail:Be(m.d1RetentionPct)}),e.jsx(Ze,{icon:_t,label:"D7 retained",value:`${pe(b.d7Retained)} / ${pe(b.d7Eligible)}`,detail:Be(m.d7RetentionPct),tone:"cyan"}),e.jsx(Ze,{icon:_t,label:"D30 retained",value:`${pe(b.d30Retained)} / ${pe(b.d30Eligible)}`,detail:Be(m.d30RetentionPct),tone:"amber"}),e.jsx(Ze,{icon:_t,label:"Week 1 retained",value:`${pe(b.week1Retained)} / ${pe(b.week1Eligible)}`,detail:Be(m.week1RetentionPct),tone:"cyan"}),e.jsx(Ze,{icon:_t,label:"Week 4 retained",value:`${pe(b.week4Retained)} / ${pe(b.week4Eligible)}`,detail:Be(m.week4RetentionPct),tone:"amber"}),e.jsx(Ze,{icon:Zt,label:"Payers",value:pe(b.payers),detail:`${Be(m.signupToPayerPct)} of signups · ${pe(b.paymentCount)} payments`,tone:"emerald"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-2",children:[e.jsxs("section",{className:"min-w-0 rounded-xl border border-slate-700 bg-slate-900/40",children:[e.jsxs("div",{className:"border-b border-slate-700 px-4 py-3",children:[e.jsxs("h3",{className:"flex items-center gap-2 font-semibold text-white",children:[e.jsx(Tn,{className:"h-4 w-4 text-indigo-300","aria-hidden":"true"})," Store click → signed-in first use"]}),e.jsx("p",{className:"mt-1 text-xs text-slate-400",children:"Observed on the same account; this is not store-confirmed installation or causal proof."})]}),e.jsx("div",{role:"region","aria-label":"Store click and signed-in first-use table",tabIndex:0,className:"overflow-x-auto focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-indigo-500",children:e.jsxs("table",{className:"min-w-full text-left text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Official-store click and signed-in client first-use observations"}),e.jsx("thead",{className:"bg-slate-950/50 text-xs uppercase text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-4 py-3",children:"Platform"}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"Click users"}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"First use"}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"Sequenced"}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"Rate"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-800",children:x.map(h=>{var C,U,k,I;return e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"px-4 py-3 font-medium text-slate-200",children:La[h]}),e.jsx("td",{className:"px-4 py-3 text-right text-slate-300",children:pe((C=b.installClickUsers)==null?void 0:C[h])}),e.jsx("td",{className:"px-4 py-3 text-right text-slate-300",children:pe((U=b.firstUse)==null?void 0:U[h])}),e.jsx("td",{className:"px-4 py-3 text-right text-slate-300",children:pe((k=b.clickThenFirstUseUsers)==null?void 0:k[h])}),e.jsx("td",{className:"px-4 py-3 text-right text-slate-300",children:Be((I=b.installClickToFirstUsePct)==null?void 0:I[h])})]},h)})})]})})]}),e.jsxs("section",{className:"min-w-0 rounded-xl border border-slate-700 bg-slate-900/40",children:[e.jsxs("div",{className:"border-b border-slate-700 px-4 py-3",children:[e.jsxs("h3",{className:"flex items-center gap-2 font-semibold text-white",children:[e.jsx(Zt,{className:"h-4 w-4 text-emerald-300","aria-hidden":"true"})," Cohort revenue by currency"]}),e.jsx("p",{className:"mt-1 text-xs text-slate-400",children:"Cumulative verified commerce through report generation. Currencies are never combined."})]}),e.jsx("div",{role:"region","aria-label":"Cohort revenue by currency table",tabIndex:0,className:"overflow-x-auto focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-indigo-500",children:e.jsxs("table",{className:"min-w-full text-left text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Gross, refunded, and net Stripe revenue by original currency"}),e.jsx("thead",{className:"bg-slate-950/50 text-xs uppercase text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-4 py-3",children:"Currency"}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"Gross"}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"Refunded"}),e.jsx("th",{scope:"col",className:"px-4 py-3 text-right",children:"Net"})]})}),e.jsxs("tbody",{className:"divide-y divide-slate-800",children:[j.map(([h,C])=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"px-4 py-3 font-medium uppercase text-slate-200",children:h}),e.jsx("td",{className:"px-4 py-3 text-right text-slate-300",children:Yt(C.grossMinor,h)}),e.jsx("td",{className:"px-4 py-3 text-right text-amber-300",children:Yt(C.refundedMinor,h)}),e.jsx("td",{className:"px-4 py-3 text-right font-medium text-emerald-300",children:Yt(C.netMinor,h)})]},h)),j.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-4 py-8 text-center text-slate-400",children:"No verified payments for this cohort yet."})}):null]})]})})]})]}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx(ms,{title:"By acquisition channel",rows:t.byChannel||[],dimensionKey:"channel",dimensionLabel:"Channel"}),e.jsx(ms,{title:"Organic search engines",rows:t.byOrganicSearchEngine||[],dimensionKey:"searchEngine",dimensionLabel:"Engine",includeRetention:!1}),e.jsx(ms,{title:"Signup methods",rows:t.bySignupMethod||[],dimensionKey:"signupMethod",dimensionLabel:"Method",includeRetention:!1}
20),e.jsx(ms,{title:"First consented content touch",rows:t.byEntryPage||[],dimensionKey:"entry",dimensionLabel:"Entry page",limit:25})]}),e.jsxs("section",{className:"mt-4 rounded-xl border border-slate-700 bg-slate-900/40 p-4",children:[e.jsxs("h3",{className:"flex items-center gap-2 font-semibold text-white",children:[e.jsx(gs,{className:"h-4 w-4 text-cyan-300","aria-hidden":"true"})," Coverage and interpretation"]}),e.jsxs("div",{className:"mt-3 grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Profiles in window"}),e.jsx("p",{className:"font-medium text-slate-200",children:pe(($=t.instrumentation)==null?void 0:$.profileCountInWindow)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Profiles attributed"}),e.jsx("p",{className:"font-medium text-slate-200",children:pe((P=t.instrumentation)==null?void 0:P.attributedProfileCount)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"First-analysis milestones"}),e.jsx("p",{className:"font-medium text-slate-200",children:pe((E=t.instrumentation)==null?void 0:E.firstAnalysisMilestoneCount)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Entry cohorts suppressed"}),e.jsx("p",{className:"font-medium text-slate-200",children:pe((l=t.privacy)==null?void 0:l.suppressedSmallEntryCohorts)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Profile load"}),e.jsx("p",{className:"font-medium text-slate-200",children:((S=t.instrumentation)==null?void 0:S.profileLoadMode)==="indexed_signup_window"?"Indexed cohort query":((A=t.instrumentation)==null?void 0:A.profileLoadMode)==="full_scan_fallback"?"Compatibility scan":"Not reported"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Snapshot cache"}),e.jsx("p",{className:"font-medium text-slate-200",children:(g=t.instrumentation)!=null&&g.profileSnapshotCacheHit?"Reused (under 30s)":"Fresh"})]})]}),e.jsx("ul",{className:"mt-4 list-disc space-y-1 pl-5 text-xs leading-relaxed text-slate-400",children:(t.warnings||[]).map((h,C)=>e.jsx("li",{children:h},`${C}-${h}`))})]})]}):null]})},dn=Object.freeze([5,10,15,20,25,30,40,50]),Ee=(t,s=4)=>Number.isFinite(t)?Number(t.toFixed(s)):null,_e=t=>t!==""&&t!==null&&t!==void 0&&Number.isFinite(Number(t))&&Number(t)>=0?Number(t):null,Pt=t=>{const s=_e(t);return s!==null&&s<=100?s/100:null};function Gt(t={}){const s=_e(t.monthlyAdSpend),n=_e(t.cpc),a=_e(t.cpm),d=Pt(t.ctrPct),p=Pt(t.landingConversionPct),r=Pt(t.signupConversionPct),u=Pt(t.signupToPaidPct),f=_e(t.expectedContributionLtvUsd),c=_e(t.expectedRevenueLtvUsd),N=_e(t.desiredProfitPerPayerUsd),b=t.trafficMode==="cpm"?"cpm":"cpc",m=b==="cpm"?a!==null&&d>0?a/(1e3*d):null:n,x=s!==null&&m>0?s/m:null,j=x!==null&&p!==null&&r!==null?x*p*r:null,R=j!==null&&u!==null?j*u:null,o=s!==null&&R>0?s/R:null,y=f,$=f!==null&&N!==null?N<=f:null,P=$?f-N:null,E=R!==null&&c!==null?R*c:null,l=R!==null&&f!==null?R*f:null,S=l!==null&&s!==null?l-s:null,A=_e(t.contributionWithinPaybackUsd),g=A!==null&&f!==null?Math.min(A,f):null,h=o===null||y===null||N===null?null:$===!1?"target_unattainable":o<P?"meets_target":o<y?"positive_below_target":"at_or_above_break_even";return{trafficMode:b,effectiveCpcUsd:Ee(m),clicks:Ee(x,2),signups:Ee(j,2),payers:Ee(R,2),cacUsd:Ee(o,2),revenueUsd:Ee(E,2),contributionUsd:Ee(l,2),roas:s>0&&E!==null?Ee(E/s,2):null,contributionRoas:s>0&&l!==null?Ee(l/s,2):null,ltvToCac:o>0&&c!==null?Ee(c/o,2):null,contributionLtvToCac:o>0&&f!==null?Ee(f/o,2):null,profitUsd:Ee(S,2),breakEvenCacUsd:Ee(y,2),targetCacUsd:Ee(P,2),paybackConstrainedCacUsd:Ee(g,2),targetProfitFeasible:$,classification:h}}function ii({cpc:t,landingConversionPct:s,signupConversionPct:n,maxCac:a}){const d=_e(t),p=Pt(s),r=Pt(n),u=_e(a);return d===null||p===null||r===null||!p||!r||!u?null:Ee(100*d/(p*r*u),2)}function li({contributionLtvUsd:t,monthlyAdSpend:s=100,cacValues:n=dn,ltvMultipliers:a=[.7,.8,.9,1,1.1,1.2]}={}){const d=_e(t),p=_e(s);return d===null||p===null?[]:a.filter(r=>Number.isFinite(r)&&r>=0).map(r=>({ltvUsd:Ee(d*r,2),multiplier:r,cells:n.filter(u=>Number.isFinite(u)&&u>0).map(u=>({cacUsd:u,profitUsd:Ee(p/u*(d*r-u),2)}))}))}const oi=Ue.isNativePlatform()?"https://www.underpriced.app/api":"/api",Ls=[30,60,90,180,365],ci={monthlyAdSpend:"100",trafficMode:"cpc",cpc:"1",cpm:"10",ctrPct:"1",landingConversionPct:"100",signupConversionPct:"10",signupToPaidPct:"5",expectedRevenueLtvUsd:"",expectedContributionLtvUsd:"",desiredProfitPerPayerUsd:"10"},$e=t=>t==null||!Number.isFinite(Number(t))?"Unavailable":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:2}).format(t),Wt=t=>t==null?"Unavailable":new Intl.NumberFormat("en-US",{maximumFractionDigits:2}).format(t),qe=t=>t==null?"Unavailable":`${Number(t).toFixed(1)}%`,ps=t=>t==null?"Unavailable":`${Number(t).toFixed(2)}×`,fe=t=>
20Number(t||0).toLocaleString();function Zs(t){const s=Object.entries(t||{});return s.length?s.map(([n,a])=>Yt(a.cashMinor,n)).join(" + "):"No recorded Stripe cash"}function Ne({label:t,value:s,detail:n,state:a="OBSERVED"}){return e.jsxs("div",{className:"rounded-xl border border-slate-700 bg-slate-900/60 p-4",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-slate-400",children:t}),e.jsx("p",{className:"mt-1 text-xl font-semibold text-white",children:s}),e.jsx("p",{className:"mt-1 text-xs text-slate-400",children:n}),e.jsx("span",{className:`mt-3 inline-block rounded px-1.5 py-0.5 text-[10px] font-semibold ${a==="OBSERVED"?"bg-emerald-500/10 text-emerald-300":a==="ASSUMPTION"?"bg-indigo-500/10 text-indigo-300":"bg-amber-500/10 text-amber-300"}`,children:a})]})}function ze({label:t,value:s,onChange:n,unit:a="",min:d=0,max:p,step:r="any",help:u}){return e.jsxs("label",{className:"block text-xs font-medium text-slate-300",children:[t,e.jsxs("span",{className:"mt-1 flex items-center rounded-lg border border-slate-600 bg-slate-950 focus-within:border-indigo-400",children:[e.jsx("input",{type:"number",inputMode:"decimal",min:d,max:p,step:r,value:s,onChange:f=>n(f.target.value),className:"w-full min-w-0 bg-transparent px-3 py-2 text-sm text-white outline-none"}),a?e.jsx("span",{className:"pr-3 text-xs text-slate-500",children:a}):null]}),u?e.jsx("span",{className:"mt-1 block font-normal text-slate-500",children:u}):null]})}function di({rows:t,basis:s,horizon:n}){return e.jsx("div",{role:"region","aria-label":`${s} cohort table`,tabIndex:0,className:"overflow-x-auto rounded-xl border border-slate-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:e.jsxs("table",{className:"min-w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-slate-950 text-slate-400",children:e.jsxs("tr",{children:[e.jsxs("th",{scope:"col",className:"px-3 py-3",children:[s==="paid"?"First recorded Stripe payment":"Signup"," cohort"]}),e.jsx("th",{scope:"col",className:"px-3 py-3 text-right",children:"N"}),e.jsx("th",{scope:"col",className:"px-3 py-3 text-right",children:"Stripe payers"}),e.jsx("th",{scope:"col",className:"px-3 py-3 text-right",children:"30d recorded paid conversion"}),s==="signup"?e.jsxs(e.Fragment,{children:[e.jsx("th",{scope:"col",className:"px-3 py-3 text-right",children:"D7 analysis activity"}),e.jsx("th",{scope:"col",className:"px-3 py-3 text-right",children:"D30 analysis activity"})]}):null,e.jsxs("th",{scope:"col",className:"px-3 py-3 text-right",children:["D",n," eligible"]}),e.jsxs("th",{scope:"col",className:"px-3 py-3 text-right",children:["D",n," Stripe cash"]}),e.jsx("th",{scope:"col",className:"px-3 py-3 text-right",children:"Cash to date"})]})}),e.jsxs("tbody",{className:"divide-y divide-slate-800 bg-slate-900/40 text-slate-200",children:[t.map(a=>{var d,p,r,u,f,c,N,b,m,x;return e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"whitespace-nowrap px-3 py-3 font-medium",children:[a.key,a.n<30?e.jsx("span",{className:"ml-2 text-amber-300",children:"small N"}):null]}),e.jsx("td",{className:"px-3 py-3 text-right",children:fe(a.n)}),e.jsx("td",{className:"px-3 py-3 text-right",children:fe(a.stripePayers)}),e.jsx("td",{className:"px-3 py-3 text-right",children:s==="paid"?"—":a.paymentTimestampComplete?a.paidWithin30Eligible?e.jsxs(e.Fragment,{children:[qe(a.paidWithin30Pct)," ",e.jsxs("span",{className:"block text-[10px] text-slate-500",children:[fe(a.paidWithin30Eligible)," eligible · 95% interval ",qe((d=a.paidWithin30Interval95)==null?void 0:d.lowerPct),"–",qe((p=a.paidWithin30Interval95)==null?void 0:p.upperPct)]})]}):"Not mature":"Payment timing incomplete"}),s==="signup"?e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-3 py-3 text-right",children:(u=(r=a.retention)==null?void 0:r[7])!=null&&u.eligible?`${qe(a.retention[7].pct)} (${fe(a.retention[7].eligible)} eligible)`:"Not mature"}),e.jsx("td",{className:"px-3 py-3 text-right",children:(c=(f=a.retention)==null?void 0:f[30])!=null&&c.eligible?`${qe(a.retention[30].pct)} (${fe(a.retention[30].eligible)} eligible)`:"Not mature"})]}):null,e.jsx("td",{className:"px-3 py-3 text-right",children:fe((b=(N=a.horizons)==null?void 0:N[n])==null?void 0:b.eligible)}),e.jsx("td",{className:"whitespace-nowrap px-3 py-3 text-right",children:(x=(m
20=a.horizons)==null?void 0:m[n])!=null&&x.eligible?a.horizons[n].refundTimingComplete?Zs(a.horizons[n].stripeCashByCurrency):"Refund timing unknown":"Not mature"}),e.jsx("td",{className:"whitespace-nowrap px-3 py-3 text-right",children:Zs(a.stripeCashByCurrency)})]},a.key)}),t.length?null:e.jsx("tr",{children:e.jsx("td",{colSpan:s==="signup"?9:7,className:"px-3 py-8 text-center text-slate-400",children:"No eligible cohort records."})})]})]})})}function Ct({title:t,rows:s}){return e.jsxs("section",{className:"min-w-0",children:[e.jsx("h4",{className:"mb-2 text-sm font-semibold text-slate-200",children:t}),e.jsx("div",{role:"region","aria-label":`${t} table`,tabIndex:0,className:"overflow-x-auto rounded-lg border border-slate-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:e.jsxs("table",{className:"min-w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-slate-950 text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Segment"}),e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"N"}),e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Stripe payers"}),e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Stripe cash"})]})}),e.jsxs("tbody",{className:"divide-y divide-slate-800 bg-slate-900/40 text-slate-200",children:[s.map(n=>e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"px-3 py-2 font-medium",children:[n.key,n.n<30?" · small N":""]}),e.jsx("td",{className:"px-3 py-2 text-right",children:fe(n.n)}),e.jsx("td",{className:"px-3 py-2 text-right",children:fe(n.stripePayers)}),e.jsx("td",{className:"whitespace-nowrap px-3 py-2 text-right",children:Zs(n.stripeCashByCurrency)})]},n.key)),s.length?null:e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-3 py-4 text-center text-slate-400",children:"No observed segments"})})]})]})})]})}function ui(){const[t,s]=i.useState(ci),[n,a]=i.useState({30:"",60:"",90:"",180:"",365:""}),[d,p]=i.useState(90),[r,u]=i.useState(dn.join(", ")),f=(y,$)=>s(P=>({...P,[y]:$})),c=i.useMemo(()=>Gt({...t,contributionWithinPaybackUsd:n[d]}),[t,n,d]),N=i.useMemo(()=>[...new Set(r.split(",").map(y=>Number(y.trim())).filter(y=>Number.isFinite(y)&&y>0&&y<=1e4))].slice(0,12),[r]),b=i.useMemo(()=>li({contributionLtvUsd:t.expectedContributionLtvUsd,monthlyAdSpend:t.monthlyAdSpend,cacValues:N}),[t.expectedContributionLtvUsd,t.monthlyAdSpend,N]),m=Ls.map(y=>({days:y,value:n[y]===""?null:Number(n[y])})),x=m.some((y,$)=>$>0&&y.value!==null&&m[$-1].value!==null&&y.value<m[$-1].value),j=[10,20,30].map(y=>{const $=1-y/100,P=Gt({...t,signupToPaidPct:t.signupToPaidPct===""?"":Number(t.signupToPaidPct)*$}),E=Gt({...t,expectedContributionLtvUsd:t.expectedContributionLtvUsd===""?"":Number(t.expectedContributionLtvUsd)*$}),l=Gt({...t,trafficMode:"cpc",cpc:c.effectiveCpcUsd===null?"":c.effectiveCpcUsd*(1+y/100)});return{drop:y,conversion:P,ltv:E,cpc:l}}),R=[100,500,1e3,5e3].map(y=>({spend:y,result:Gt({...t,monthlyAdSpend:y})})),o={meets_target:"CAC is below the target: expected contribution exceeds ad cost by more than the required profit per payer.",positive_below_target:"CAC is below break-even but misses the required profit per payer.",at_or_above_break_even:"CAC equals or exceeds assumed contribution LTV; expected profit per payer is zero or negative.",target_unattainable:"Required profit per payer exceeds assumed contribution LTV. No nonnegative CAC can meet this target."};return e.jsxs("section",{className:"space-y-4 rounded-xl border border-indigo-500/30 bg-slate-900/50 p-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"flex items-center gap-2 text-lg font-bold text-white",children:[e.jsx(za,{className:"h-5 w-5 text-indigo-300"})," CAC scenario calculator"]}),e.jsx("p",{className:"mt-1 text-xs text-slate-400",children:"ASSUMPTION · All inputs below are hypothetical. None is populated from an observed paid campaign or a measured contribution LTV."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(ze,{label:"Monthly ad spend",value:t.monthlyAdSpend,onChange:y=>f("monthlyAdSpend",y),unit:"USD"}),e.jsxs("label",{className:"block text-xs font-medium text-slate-300",children:["Traffic pricing",e.jsxs("select",{value:t.trafficMode,onChange:y=>f("trafficMode",y.target.value),className:"mt-1 w-full rounded-lg border border-slate-600 bg-slate-950 px-3 py-2 text-sm text-white",children:[e.jsx("option",{value:"cpc",children:"Direct 
20CPC"}),e.jsx("option",{value:"cpm",children:"CPM and CTR"})]})]}),t.trafficMode==="cpc"?e.jsx(ze,{label:"CPC",value:t.cpc,onChange:y=>f("cpc",y),unit:"USD / click"}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{label:"CPM",value:t.cpm,onChange:y=>f("cpm",y),unit:"USD / 1k"}),e.jsx(ze,{label:"CTR",value:t.ctrPct,onChange:y=>f("ctrPct",y),unit:"%",max:100})]}),e.jsx(ze,{label:"Landing/store arrival rate",value:t.landingConversionPct,onChange:y=>f("landingConversionPct",y),unit:"%",max:100,help:"Clicks that reach a signup surface"}),e.jsx(ze,{label:"Arrival → signup",value:t.signupConversionPct,onChange:y=>f("signupConversionPct",y),unit:"%",max:100}),e.jsx(ze,{label:"Signup → paid",value:t.signupToPaidPct,onChange:y=>f("signupToPaidPct",y),unit:"%",max:100}),e.jsx(ze,{label:"Revenue LTV per payer",value:t.expectedRevenueLtvUsd,onChange:y=>f("expectedRevenueLtvUsd",y),unit:"USD",help:"Optional assumption for ROAS"}),e.jsx(ze,{label:"Contribution LTV per payer",value:t.expectedContributionLtvUsd,onChange:y=>f("expectedContributionLtvUsd",y),unit:"USD",help:"Required for a CAC decision"}),e.jsx(ze,{label:"Required profit per payer",value:t.desiredProfitPerPayerUsd,onChange:y=>f("desiredProfitPerPayerUsd",y),unit:"USD"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ne,{label:"Break-even CAC",value:$e(c.breakEvenCacUsd),detail:"Assumed contribution LTV per payer",state:"ASSUMPTION"}),e.jsx(Ne,{label:"Target CAC",value:$e(c.targetCacUsd),detail:"Break-even less required profit",state:"ASSUMPTION"}),e.jsx(Ne,{label:"Current / assumed CAC",value:$e(c.cacUsd),detail:"Spend ÷ expected new payers",state:"ASSUMPTION"}),e.jsx(Ne,{label:"Expected profit / loss",value:$e(c.profitUsd),detail:"Expected contribution less spend",state:"ASSUMPTION"})]}),c.classification?e.jsx("p",{role:"status",className:"rounded-lg border border-indigo-500/30 bg-indigo-500/10 p-3 text-sm text-indigo-100",children:o[c.classification]}):e.jsx("p",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200",children:"Enter contribution LTV and required profit to classify the assumed CAC."}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ne,{label:"Expected clicks",value:Wt(c.clicks),detail:`Effective CPC ${$e(c.effectiveCpcUsd)}`,state:"ASSUMPTION"}),e.jsx(Ne,{label:"Signups → payers",value:`${Wt(c.signups)} → ${Wt(c.payers)}`,detail:"Expected, not observed accounts",state:"ASSUMPTION"}),e.jsx(Ne,{label:"Revenue / contribution",value:`${$e(c.revenueUsd)} / ${$e(c.contributionUsd)}`,detail:"Uses separately entered LTV assumptions",state:"ASSUMPTION"}),e.jsx(Ne,{label:"ROAS / contribution ROAS",value:`${ps(c.roas)} / ${ps(c.contributionRoas)}`,detail:`Revenue LTV:CAC ${ps(c.ltvToCac)} · contribution ${ps(c.contributionLtvToCac)}`,state:"ASSUMPTION"})]}),e.jsxs("div",{className:"rounded-xl border border-slate-700 bg-slate-950/40 p-3",children:[e.jsx("h4",{className:"font-semibold text-slate-200",children:"Payback-constrained CAC"}),e.jsx("p",{className:"mt-1 text-xs text-slate-400",children:"Enter cumulative contribution per payer by each window. These are assumptions until user-level costs and all providers are reconciled."}),e.jsx("div",{className:"mt-3 grid gap-3 sm:grid-cols-3 lg:grid-cols-5",children:Ls.map(y=>e.jsx(ze,{label:y===365?"12 months":`${y} days`,value:n[y],onChange:$=>a(P=>({...P,[y]:$})),unit:"USD"},y))}),x?e.jsx("p",{className:"mt-2 text-xs text-amber-300",children:"Cumulative contribution should not decrease across windows. Review the assumptions."}):null,e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-xs text-slate-300",children:[e.jsx("label",{htmlFor:"payback-window",children:"Desired payback window"}),e.jsx("select",{id:"payback-window",value:d,onChange:y=>p(Number(y.target.value)),className:"rounded border border-slate-600 bg-slate-900 px-2 py-1 text-white",children:Ls.map(y=>e.jsx("option",{value:y,children:y===365?"12 months":`${y} days`},y))}),e.jsxs("strong",{children:["Maximum assumed CAC: ",$e(x?null:c.paybackConstrainedCacUsd)]}),e.jsxs("span",{children:["Estimated payback: ",c.cacUsd!==null&&c.paybackConstrainedCacUsd!==null&&!x?c.cacUsd<=c.paybackConstrainedCacUsd?`within ${d} days (assumed)`:`later than ${d} days or never`:"Unavailable"]})]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"mb-2 font-semibold text-slate-200",children:"Budget scenarios"}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-slate-700",children:e.jsxs("table",{className:"min-w-full text-xs",children:[e.jsx("thead",{className:"bg-slate-950 text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left",children:"Spend"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Clicks"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Payers"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Expected profit"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-800",children:R.map(y=>e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left",children:$e(y.spend)}),e.jsx("td",{className:"px-3 py-2 text-right",children:Wt(y.result.clicks)}),e.jsx("td",{className:"px-3 py-2 text-right",children:Wt(y.result.payers)}),e.jsx("td",{className:"px-3 py-2 text-right",children:$e(y.result.profitUsd)})]},y.spend))})]})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"mb-2 font-semibold text-slate-200",children:"Minimum signup → paid conversion"}),e.jsx("p",{className:"mb-2 text-xs text-slate-400",children:"To stay at or below target CAC at representative CPCs, assuming the entered landing and signup rates."}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-slate-700",children:e.jsxs("table",{className:"min-w-full text-xs",children:[e.jsx("thead",{className:"bg-slate-950 text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left",children:"CPC"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Required paid conversion"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-800",children:[.5,1,2,3].map(y=>e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left",children:$e(y)}),e.jsx("td",{className:"px-3 py-2 text-right",children:qe(ii({cpc:y,landingConversionPct:t.landingConversionPct,signupConversionPct:t.signupConversionPct,maxCac:c.targetCacUsd}))})]},y))})]})})]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"mb-2 font-semibold text-slate-200",children:"Sensitivity: CAC × contribution LTV"}),e.jsxs("label",{className:"text-xs text-slate-400",children:["CAC values, USD (comma separated)",e.jsx("input",{value:r,onChange:y=>u(y.target.value),className:"mt-1 mb-2 w-full rounded border border-slate-600 bg-slate-950 px-3 py-2 text-white"})]}),b.length?e.jsx("div",{role:"region","aria-label":"CAC sensitivity matrix",tabIndex:0,className:"overflow-x-auto rounded-lg border border-slate-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:e.jsxs("table",{className:"min-w-full text-xs",children:[e.jsx("thead",{className:"bg-slate-950 text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-2 py-2 text-left",children:"Contribution LTV"}),N.map(y=>e.jsxs("th",{className:"px-2 py-2 text-right",children:[$e(y)," CAC"]},y))]})}),e.jsx("tbody",{children:b.map(y=>e.jsxs("tr",{children:[e.jsxs("th",{className:"whitespace-nowrap px-2 py-2 text-left",children:[$e(y.ltvUsd)," (",Math.round(y.multiplier*100),"%)"]}),y.cells.map($=>e.jsx("td",{className:`whitespace-nowrap px-2 py-2 text-right ${$.profitUsd>=0?"text-emerald-300":"text-rose-300"}`,children:$e($.profitUsd)},$.cacUsd))]},y.multiplier))})]})}):e.jsx("p",{className:"rounded border border-dashed border-slate-700 p-4 text-xs text-slate-400",children:"Enter contribution LTV to see profit at each CAC."})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"mb-2 font-semibold text-slate-200",children:"Room for error"}),e.jsx("p",{className:"mb-2 text-xs text-slate-400",children:"Monthly expected profit if each assumption changes separately."}),e.jsx("div",{role:"region","aria-label":"Assumption stress table",tabIndex:0,className:"overflow-x-auto rounded-lg border border-slate-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:e.jsxs("table",{className:"min-w-full text-xs",children:[e.jsx("thead",{className:"bg-slate-950 text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-2 py-2 text-left",children:"Change"}),e.jsx("th",{className:"px-2 py-2 text-right",children:"Paid conversion falls"}),e.jsx("th",{className:"px-2 py-2 text-right",children:"Contribution LTV falls"}),e.jsx("th",{className:"px-2 py-2 text-right",children:"CPC rises"})]})}),e.jsx("tbody",{children:j.map(y=>e.jsxs("tr",{children:[e.jsxs("th",{className:"px-2 py-2 text-left",children:[y.drop,"%"]}),e.jsx("td",{className:"px-2 py-2 text-right",children:$e(y.conversion.profitUsd)}),e.jsx("td",{className:"px-2 py-2 text-right",children:$e(y.ltv.profitUsd)}),e.jsx("td",{className:"px-2 py-2 text-right",children:$e(y.cpc.profitUsd)})]},y.drop))})]})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Expected counts are fractional because this is an expectation model. Actual campaign outcomes will be discrete and uncertain, especially at $100–$500 budgets."})]})}function xi({getAuthToken:t}){var A,g,h,C,U,k,I,O,Z,D,ee,V,X,ae,q,te,w,v,M,_;const[s,n]=i.useState(180),[a,d]=i.useState(null),[p,r]=i.useState(null),[u,f]=i.useState(!1),[c,N]=i.useState(""),[b,m]=i.useState("month"),[x,j]=i.useState("signup"),[R,o]=i.useState(30),[y,$]=i.useState(0);i.useEffect(()=>{const B=new AbortController;let J=!0;return(async()=>{var F,se;f(!0),N("");try{const ye=`${oi}/unit-economics?days=${s}${y?"&refresh=1":""}`;let oe=await t(!1);if(!oe)throw new Error("Authentication required");let be=await fetch(ye,{headers:{Authorization:`Bearer ${oe}`},signal:B.signal});(be.status===401||be.status===403)&&(oe=await t(!0),oe&&(be=await fetch(ye,{headers:{Authorization:`Bearer ${oe}`},signal:B.signal})));const ge=await be.json().catch(()=>({}));if(!be.ok)throw new Error(ge.error||"Could not load economics report");if(ge.schemaVersion!==1||((F=ge.privacy)==null?void 0:F.containsUserIds)!==!1||((se=ge.window)==null?void 0:se.days)!==s||!Array.isArray(ge.signupCohortsMonthly)||!Array.isArray(ge.paidCohortsMonthly))throw new Error("Unexpected economics report format");J&&(d(ge),r(s))}catch(ye){J&&(ye==null?void 0:ye.name)!=="AbortError"&&(d(null),N((ye==null?void 0:ye.message)||"Could not load economics report"))}finally{J&&f(!1)}})(),()=>{J=!1,B.abort()}},[s,t,y]);const P=x==="signup"?b==="week"?a==null?void 0:a.signupCohortsWeekly:a==null?void 0:a.signupCohortsMonthly:b==="week"?a==null?void 0:a.paidCohortsWeekly:a==null?void 0:a.paidCohortsMonthly,E=(h=(g=(A=a==null?void 0:a.overall)==null?void 0:A.stripeCashByCurrency)==null?void 0:g.usd)==null?void 0:h.cashMinor,l=Object.keys(((C=a==null?void 0:a.overall)==null?void 0:C.stripeCashByCurrency)||{}).length,S=((U=a==null?void 0:a.overall)==null?void 0:U.n)>0&&l===1&&Number.isFinite(E)?$e(E/100/a.overall.n):"Unavailable";return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("header",{className:"rounded-xl border border-slate-700 bg-slate-800/50 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-white",children:"Underpriced Unit Economics · Paid Acquisition"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm text-slate-400",children:"A decision view of observed acquisition cohorts and an assumption-driven ad calculator. The cash figures below cover Stripe webhook outcomes only."})]}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("label",{className:"text-xs text-slate-300",children:["Cohort window",e.jsx("select",{value:s,onChange:B=>n(Number(B.target.value)),className:"mt-1 block rounded-lg border border-slate-600 bg-slate-950 px-3 py-2 text-sm text-white",children:[30,90,180,365].map(B=>e.jsxs("option",{value:B,children:[B," days"]},B))})]}),e.jsx("button",{type:"button",onClick:()=>$(B=>B+1),disabled:u,className:"rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white disabled:opacity-50","aria-label":"Refresh unit economics report",children:e.jsx(Fe,{className:"h-4 w-4"})})]})]}),a?e.jsxs("p",{className:"mt-3 text-xs text-slate-500",children:["Generated ",new Date(a.generatedAt).toLocaleStr
20ing()," · ",fe((k=a.instrumentation)==null?void 0:k.selectedCustomerDocuments)," selected customer documents · read-only"]}):null]}),u?e.jsxs("p",{role:"status",className:"flex items-center gap-2 rounded-lg border border-slate-700 p-4 text-sm text-slate-300",children:[e.jsx(H,{className:"h-4 w-4 animate-spin"})," Loading read-only customer and payment records…"]}):null,c?e.jsxs("p",{role:"alert",className:"flex items-center gap-2 rounded-lg border border-rose-500/40 bg-rose-500/10 p-4 text-sm text-rose-200",children:[e.jsx(Re,{className:"h-4 w-4"})," ",c]}):null,a&&p===s?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-white",children:"Executive decision panel"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Selected signup cohort, N = ",fe(a.overall.n),". Values are shown only at their supported scope."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ne,{label:"Signups",value:fe(a.overall.n),detail:"Firebase profile creation"}),e.jsx(Ne,{label:"Stripe-confirmed payers",value:fe(a.overall.stripePayers),detail:"Google Play payers may be additional"}),e.jsx(Ne,{label:"30-day recorded Stripe paid conversion",value:a.overall.paymentTimestampComplete?qe(a.overall.paidWithin30Pct):"Unavailable",detail:a.overall.paymentTimestampComplete?`${fe(a.overall.paidWithin30Eligible)} mature signups · 95% interval ${qe((I=a.overall.paidWithin30Interval95)==null?void 0:I.lowerPct)}–${qe((O=a.overall.paidWithin30Interval95)==null?void 0:O.upperPct)}`:"Legacy payment timestamps can move on webhook replay",state:a.overall.paymentTimestampComplete?"OBSERVED":"INSUFFICIENT DATA"}),e.jsx(Ne,{label:"Stripe cash / signup",value:S,detail:"Observed to date · USD only if one currency"}),e.jsx(Ne,{label:"Revenue LTV",value:"Unavailable",detail:"Tax and Google Play proceeds incomplete",state:"INSUFFICIENT DATA"}),e.jsx(Ne,{label:"Contribution LTV",value:"Unavailable",detail:"Per-user variable costs and fees missing",state:"INSUFFICIENT DATA"}),e.jsx(Ne,{label:"Break-even / target CAC",value:"Unavailable",detail:"Requires expected contribution LTV",state:"INSUFFICIENT DATA"}),e.jsx(Ne,{label:"Current paid CAC / payback",value:"Unavailable",detail:"No ad spend or linked paid cohort",state:"INSUFFICIENT DATA"})]})]}),e.jsxs("section",{className:"space-y-3 rounded-xl border border-slate-700 bg-slate-900/40 p-4",children:[e.jsx("h3",{className:"text-lg font-bold text-white",children:"Cohorts"}),e.jsx("p",{className:"text-xs text-slate-400",children:"OBSERVED Stripe cash, shown in original currency. A selected D7/D30/D60/D90/D180/D365 horizon uses that many 24-hour days after signup or first recorded Stripe payment. Stripe timestamps reflect webhook recording, which may lag a charge. Horizon net cash is suppressed when refunds or legacy mutable payment timestamps prevent a reliable time curve. Only fully elapsed windows appear. Small cohorts are flagged and no projected LTV is shown."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("label",{className:"text-xs text-slate-300",children:["Cohort basis ",e.jsxs("select",{value:x,onChange:B=>j(B.target.value),className:"ml-2 rounded border border-slate-600 bg-slate-950 px-2 py-1 text-white",children:[e.jsx("option",{value:"signup",children:"Signup"}),e.jsx("option",{value:"paid",children:"First recorded Stripe payment"})]})]}),e.jsxs("label",{className:"text-xs text-slate-300",children:["Interval ",e.jsxs("select",{value:b,onChange:B=>m(B.target.value),className:"ml-2 rounded border border-slate-600 bg-slate-950 px-2 py-1 text-white",children:[e.jsx("option",{value:"month",children:"Month"}),e.jsx("option",{value:"week",children:"Week"})]})]}),e.jsxs("label",{className:"text-xs text-slate-300",children:["Cash horizon ",e.jsx("select",{value:R,onChange:B=>o(Number(B.target.value)),className:"ml-2 rounded border border-slate-600 bg-slate-950 px-2 py-1 text-white",children:[7,30,60,90,180,365].map(B=>e.jsxs("option",{value:B,children:["D",B]},B))})]})]}),e.jsx(di,{rows:P||[],basis:x,horizon:R}),e.jsxs("p",{className:"text-xs text-slate-500",children:["D1 / D7 / D30 analysis activity means a 
20successful saved analysis on that UTC day after signup. D1 overall: ",fe((D=(Z=a.overall.retention)==null?void 0:Z[1])==null?void 0:D.retained)," / ",fe((V=(ee=a.overall.retention)==null?void 0:ee[1])==null?void 0:V.eligible)," eligible (",qe((ae=(X=a.overall.retention)==null?void 0:X[1])==null?void 0:ae.pct),"). This is not subscriber survival or visit retention."]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-3",children:[e.jsx(Ct,{title:"By acquisition classification",rows:a.bySource||[]}),e.jsx(Ct,{title:"By first signed-in client use",rows:a.byFirstUsePlatform||[]}),e.jsx(Ct,{title:"By current plan",rows:a.byCurrentPlan||[]})]}),(q=a.byTaggedSource)!=null&&q.length||(te=a.byTaggedCampaign)!=null&&te.length||(w=a.byTaggedAdset)!=null&&w.length||(v=a.byTaggedCreative)!=null&&v.length?e.jsxs("div",{className:"grid gap-4 xl:grid-cols-4",children:[e.jsx(Ct,{title:"Tagged URL source · unverified",rows:a.byTaggedSource||[]}),e.jsx(Ct,{title:"Tagged campaign",rows:a.byTaggedCampaign||[]}),e.jsx(Ct,{title:"Tagged ad set",rows:a.byTaggedAdset||[]}),e.jsx(Ct,{title:"Tagged creative",rows:a.byTaggedCreative||[]})]}):null]}),e.jsxs("section",{className:"rounded-xl border border-slate-700 bg-slate-900/40 p-4",children:[e.jsx("h3",{className:"text-lg font-bold text-white",children:"Attribution coverage and paid campaigns"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ne,{label:"Known referrer / source tag",value:qe(a.overall.n?a.quality.sourceKnown/a.overall.n*100:null),detail:`${fe(a.quality.sourceKnown)} consented signups`}),e.jsx(Ne,{label:"Unknown source",value:qe(a.overall.n?a.quality.sourceUnknown/a.overall.n*100:null),detail:`${fe(a.quality.sourceUnknown)} signups`}),e.jsx(Ne,{label:"Observed ad spend",value:"Unavailable",detail:"No Meta, Google or Apple spend feed",state:"INSUFFICIENT DATA"}),e.jsx(Ne,{label:"Campaign CAC / ROAS",value:"Unavailable",detail:"No campaign-to-payer join",state:"INSUFFICIENT DATA"})]}),e.jsxs("p",{className:"mt-3 flex gap-2 text-xs text-slate-400",children:[e.jsx(gs,{className:"h-4 w-4 shrink-0"})," Known means a consented organic-search referrer or a captured UTM source tag. Content-assisted entry and click IDs without a source tag remain unknown-source. URL tags are self-reported and do not establish Meta, Google Ads, Apple Search Ads, direct, referral, or mobile install attribution. Historical campaign data is not backfilled."]})]}),e.jsx(ui,{}),e.jsxs("section",{className:"rounded-xl border border-slate-700 bg-slate-900/40 p-4",children:[e.jsx("h3",{className:"text-lg font-bold text-white",children:"Data quality and metric sources"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ne,{label:"Missing Stripe mappings",value:fe(a.quality.missingStripeMappings),detail:"Payment outcome without profile customer ID"}),e.jsx(Ne,{label:"Payment counter mismatches",value:fe(a.quality.commerceCounterMismatches),detail:"Profile totals vs event ledger"}),e.jsx(Ne,{label:"Google Play relationships",value:fe(a.quality.playStoreRelationships),detail:"Excluded from Stripe cash totals"}),e.jsx(Ne,{label:"Orphan payment events",value:fe((M=a.instrumentation)==null?void 0:M.orphanedOutcomeCount),detail:"No current profile document"})]}),e.jsxs("ul",{className:"mt-3 list-disc space-y-1 pl-5 text-xs text-slate-400",children:[e.jsx("li",{children:"Signup and current plan: Firebase profile. Activation and D1/D7/D30: saved analysis milestones. Cash and refunds: Stripe commerce outcomes."}),e.jsx("li",{children:"Google Play: RevenueCat provider relationship and partial transaction activity. Complete store proceeds, refunds and commission are unverified."}),e.jsx("li",{children:"AI/API cost: daily provider telemetry exists, but no reliable user join. Fixed operating expense is excluded from contribution and is not stored here."}),e.jsx("li",{children:"Trials, cancellations, reactivations, country, visitor-to-signup joins, campaign spend, fees, tax and currency FX need new data or reconciliation."}),e.jsxs("li",{children:[fe(a.quality.malformedOutcomeCount)," malformed Stripe outcome records; mobile activity read ",(_=a.instrumentation)!=null&&_.mobileActivityQueryComplete?"completed":"unavailable","."]}),e.jsxs("li",{children:[fe(a.quality.futureOutcomeCount)," future-dated outcomes excluded;
20 ",fe(a.quality.negativeStripeCashCustomers)," customer records have negative Stripe cash and need reconciliation."]}),e.jsxs("li",{children:[fe(a.quality.unstablePaymentTimestampCustomers)," customers have payment records without an immutable first-recorded timestamp; time-window conversion and cash are suppressed for affected cohorts."]})]})]})]}):null]})}const mi=["*"],pi=()=>{var X,ae,q,te;const t=Oa(),[s,n]=i.useState(null),[a,d]=i.useState(!1),[p,r]=i.useState(!1),[u,f]=i.useState(!1),{getAuthToken:c}=Fn(),N=Bn(c),b=Wn(c),m=Kn(c),x=Jn(c),j=Zn(c),R=Xn(c),o=tr(c),y=sr(c),$=ar(c),P=nr(c),E=or(c),l=yr(c),{searchQuery:S,fetchUsers:A,selectedUser:g,fetchUserDetails:h,clearUserDetails:C}=b,{fetchTicketCount:U}=m;i.useEffect(()=>{document.title="Admin Panel"},[]),i.useEffect(()=>{N.fetchStats()},[N.fetchStats]);const k=((ae=(X=N.stats)==null?void 0:X.access)==null?void 0:ae.capabilities)||mi,I=w=>k.includes("*")||k.includes(w),O=!!N.stats&&I("support:read");if(i.useEffect(()=>{O&&U()},[O,U]),i.useEffect(()=>{const w=()=>{O&&U()};return window.addEventListener("focus",w),()=>window.removeEventListener("focus",w)},[O,U]),i.useEffect(()=>{if(s!=="users"){r(!1);return}r(!!S.trim());const w=setTimeout(()=>{r(!1),A(S)},300);return()=>clearTimeout(w)},[S,s,A]),i.useEffect(()=>{g?h(g):C()},[g,h,C]),N.loading)return e.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:e.jsx(H,{className:"w-8 h-8 animate-spin text-indigo-500"})});if(N.error){const w=N.error.includes("admin access");return e.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Re,{className:"w-12 h-12 text-red-500 mx-auto mb-4"}),e.jsx("h1",{className:"text-xl font-bold text-white mb-2",children:w?"Access Denied":"Error"}),e.jsx("p",{className:"text-slate-400 mb-4",children:N.error}),e.jsx("button",{type:"button",onClick:()=>t("/dashboard"),className:"text-indigo-400 hover:text-indigo-300",children:"Return to Dashboard"})]})})}const Z=w=>{switch(n(w),w){case"users":break;case"tickets":m.tickets.length===0&&m.fetchTickets();break;case"promos":x.fetchPromos();break;case"analyses":j.fetchAnalyses();break;case"listing-drafts":R.fetchListingDrafts();break;case"referrals":o.fetchReferrals();break;case"paying":y.fetchPayingUsers();break;case"chats":P.fetchChats(),P.chatAnalytics||P.fetchChatAnalytics();break;case"telemetry":E.telemetry||E.fetchTelemetry();break;case"acquisition":l.report||l.fetchAcquisitionReport();break;case"marketing":$.fetchMarketingStats();break}},D=w=>{!w||w==="anonymous"||!I("users:read")||(w!==g&&C(),b.setSearchQuery(w),b.setSelectedUser(w),n("users"))},ee=w=>{!w||w==="anonymous"||!I("analytics:read")||(j.setSelectedAnalysis(null),j.setAnalysesFilter(w),n("analyses"),j.fetchAnalyses("reset",w))},V=async()=>{if(!a){d(!0);try{await N.fetchStats(!0)}finally{d(!1)}}};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-950 via-slate-900 to-slate-950 text-white",children:[e.jsx(jr,{onClose:()=>t("/dashboard")}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 py-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-bold flex items-center gap-2",children:["Platform Overview",((q=N.stats)==null?void 0:q.fromCache)&&e.jsx("span",{className:"text-[10px] bg-slate-800 text-slate-400 px-2 py-0.5 rounded-full font-medium uppercase",children:"Cached"})]}),((te=N.stats)==null?void 0:te.cachedAt)&&e.jsxs("p",{className:"text-xs text-slate-500 flex items-center gap-1.5 mt-0.5",children:[e.jsx(Ss,{className:"w-3 h-3"}),"Last updated: ",new Date(N.stats.cachedAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>f(!0),className:"flex items-center justify-center gap-2 rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-xs font-semibold text-slate-300 shadow-sm transition-all hover:bg-slate-700 hover:text-white",children:[e.jsx(Rt,{className:"h-3.5 w-3.5"})," Recent Operations"]}),e.jsxs("button",{type:"button",onClick:V,disabled:a,className:"flex items-center justify-center gap-2 bg-slate-800 hover:bg-slate-700 disabled:opacity-50 text-slate-300 hover:text-white text-xs font-semibold py-2 px-4 roun
20ded-lg border border-slate-700 transition-all shadow-sm",children:[e.jsx(Fe,{className:`w-3.5 h-3.5 ${a?"animate-spin text-indigo-400":""}`}),a?"Recomputing...":"Force Refresh Stats"]})]})]}),e.jsx(Cr,{stats:N.stats}),e.jsx(vr,{activeTab:s,onTabChange:Z,newTicketCount:m.getNewTicketCount(),capabilities:k}),!s&&e.jsx(hi,{}),s&&e.jsxs("div",{id:"admin-tab-panel",role:"tabpanel","aria-labelledby":`admin-tab-${s}`,tabIndex:0,className:"outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/60",children:[s==="users"&&e.jsx(Tr,{...b,capabilities:k,usersSearchPending:p,handleDeleteUser:()=>b.handleDeleteUser(()=>N.fetchStats(!0)),onAfterRepair:()=>N.fetchStats(!0)}),s==="tickets"&&e.jsx(Fr,{...m,capabilities:k,onViewUser:D,onViewUserAnalyses:ee,lightboxImage:j.lightboxImage,setLightboxImage:j.setLightboxImage}),s==="promos"&&e.jsx(Or,{...x,capabilities:k}),s==="analyses"&&e.jsx(Br,{...j,usageSummary:N.stats}),s==="listing-drafts"&&e.jsx(zr,{...R}),s==="ratings"&&e.jsx(Ur,{getAuthToken:c,onOpenAnalysis:w=>{n("analyses"),j.fetchAnalysisDetail({id:w.analysisId,docPath:w.analysisPath})}}),s==="referrals"&&e.jsx(Hr,{...o}),s==="marketing"&&e.jsx(Gr,{...$,capabilities:k}),s==="analysis-export"&&e.jsx(Wr,{allExportStartDate:j.allExportStartDate,allExportEndDate:j.allExportEndDate,allExportLimit:j.allExportLimit,exportingAllAnalyses:j.exportingAllAnalyses,allExportFilterType:j.allExportFilterType,setAllExportStartDate:j.setAllExportStartDate,setAllExportEndDate:j.setAllExportEndDate,setAllExportLimit:j.setAllExportLimit,setAllExportFilterType:j.setAllExportFilterType,handleExportAllAnalyses:j.handleExportAllAnalyses}),s==="paying"&&e.jsx(Kr,{...y,onSelectUser:D}),s==="chats"&&e.jsx(Qr,{...P}),s==="telemetry"&&e.jsx(si,{...E}),s==="acquisition"&&e.jsx(ri,{...l}),s==="paid-acquisition"&&e.jsx(xi,{getAuthToken:c})]})]}),e.jsx(Ir,{open:u,onClose:()=>f(!1),getAuthToken:c,capabilities:k})]})},hi=()=>e.jsxs("div",{className:"bg-slate-800/50 border border-slate-700 rounded-xl p-8 text-center",children:[e.jsx(qa,{className:"w-12 h-12 text-indigo-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-bold text-white mb-2",children:"Welcome to Admin Panel"}),e.jsx("p",{className:"text-slate-400 mb-4",children:"Select a tab above to view and manage data."}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 max-w-3xl mx-auto text-sm",children:[e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3 border border-slate-700",children:[e.jsx(Ge,{className:"w-5 h-5 text-indigo-400 mx-auto mb-1"}),e.jsx("p",{className:"text-slate-300",children:"Users"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Manage all users"})]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3 border border-slate-700",children:[e.jsx(mt,{className:"w-5 h-5 text-amber-400 mx-auto mb-1"}),e.jsx("p",{className:"text-slate-300",children:"Paying Users"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Subscribers only"})]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3 border border-slate-700",children:[e.jsx(st,{className:"w-5 h-5 text-cyan-400 mx-auto mb-1"}),e.jsx("p",{className:"text-slate-300",children:"Listing Drafts"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Generated copy"})]}),e.jsxs("div",{className:"bg-slate-900/50 rounded-lg p-3 border border-slate-700",children:[e.jsx(es,{className:"w-5 h-5 text-emerald-400 mx-auto mb-1"}),e.jsx("p",{className:"text-slate-300",children:"Referrals"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Track invites"})]})]})]}),Ei=()=>e.jsx(Ar,{children:e.jsx(pi,{})});export{Ei 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.