1import{j as e}from"./ui-CRfrqFYg.js";import{r as N,L as de,h as He}from"./vendor-BWGWb13B.js";import{A as Ee}from"./AdminLayout-GJDoX4mo.js";import{P as Ke}from"./page-container-xKpZk12n.js";import{Q as I,B as S,h as se,s as h,a as w,e as k,g as p,bc as M,aW as ze,cc as ve,cq as be,b3 as me,cd as Ne,b as T,d as A,L as B,D as Ue,z as We,J as Qe,K as Ve,N as Ge,aX as Je,a7 as ue,bD as Ye,bI as X,eo as F,e6 as Xe,be as _e,aT as Q,bC as we,dw as Ze,E as es,p as ss,u as P,ai as ke,O as te,ep as D,c1 as ts,eq as as,c2 as rs,bb as ns,b9 as ne,dS as Se,aZ as Ce,dC as pe,ac as is,C as xe,bX as ls,m as cs,a2 as os,a3 as ds,a4 as ms,a5 as us,a6 as xs,T as ie,_ as le,r as U,$ as R,q as ce,t as L,P as hs,bk as gs,br as qe,aj as ps,y as De,G as fs,dV as js,l as ys,k as vs,a8 as bs,a9 as Ns,aa as J,ab as Y}from"./index-DL2CIW7t.js";import{u as q,a as H,b as Ie}from"./query-BfS8OGlq.js";import{i as ae,M as fe,Y as _s,g as ws,b as ks,aa as Ss,ab as Cs}from"./GlobalSearchDialog-DaO6IUqb.js";import{R as Te,X as qs,Y as Ds,T as Ae,B as Is}from"./generateCategoricalChart-CsXSN63y.js";import{B as Ts}from"./BarChart-BMryEvQO.js";import{C as As}from"./CartesianGrid-BB1A-oCJ.js";import{C as W,s as oe,I as re}from"./dates-CYSaORGK.js";import{C as Rs}from"./copy-BPUJlJnK.js";import{L as Ls,a as Fs}from"./LineChart-SnsHEfmp.js";import"./rocket-BGHNjPoG.js";import"./useStripeMode-CRBopKQn.js";import"./motion-dpBNAuY6.js";import"./chrome-BTaOdbeC.js";import"./crosshair-CvOyu8Mf.js";import"./ellipsis-DyD3S9Ov.js";import"./wifi-off-CIcChNab.js";import"./refresh-ccw-Dy4sV11r.js";import"./key-CW80570D.js";import"./pen-tkD2419m.js";import"./printer-CqnWYUTP.js";import"./radio-Cx0UCA5p.js";import"./useDebounce-BEJW-TSj.js";import"./stripe-BqCuezgc.js";async function Re(){const{count:n,error:o}=await h.from("data_integrity_alerts").select("id",{count:"exact",head:!0}).eq("alert_type","ledger_reconciliation").eq("severity","critical").filter("details->>code","eq","stripe_mismatch").is("resolved_at",null);if(o)throw o;return n??0}async function Ps(){const{data:n,error:o}=await h.from("data_integrity_alerts").select("id, alert_type, details").eq("severity","critical").is("resolved_at",null);if(o)throw o;return(n??[]).filter(m=>!(m.alert_type==="ledger_reconciliation"&&(m.details??{}).code==="stripe_mismatch")).length}function Bs({onReviewNow:n}){const{data:o}=q({queryKey:["data-integrity-critical-count"],refetchInterval:6e4,queryFn:Re}),{data:a}=q({queryKey:["data-integrity-other-critical-count"],refetchInterval:6e4,queryFn:Ps}),m=o??0,i=a??0;return m>0?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-destructive/40 bg-destructive/5 px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(I,{className:"h-5 w-5 text-destructive shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:[m," critical financial alert",m===1?"":"s"," need review"]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:"Ledger â Stripe mismatch detected. Open Financial Integrity to triage."})]})]}),e.jsx(S,{size:"sm",variant:"destructive",onClick:n,children:"Review now"})]}),i>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-amber-500/40 bg-amber-500/5 px-4 py-2 text-xs text-amber-700 dark:text-amber-400",children:[e.jsx(I,{className:"h-4 w-4 shrink-0"}),i," other critical alert",i===1?"":"s"," unresolved â see Financial Integrity / System Health tabs."]})]}):i>0?e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-amber-500/40 bg-amber-500/5 px-4 py-2 text-xs text-amber-700 dark:text-amber-400",children:[e.jsx(I,{className:"h-4 w-4 shrink-0"}),i," critical alert",i===1?"":"s"," unresolved outside the ledger lane â see Financial Integrity / System Health tabs."]}):e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsx(se,{className:"h-4 w-4 text-emerald-600"}),"No critical financial alerts. Routine checks continue in the background."]})}function Os(){return q({queryKey:["data-integrity-critical-count"],refetchInterval:6e4,queryFn:Re})}function $s(){const[n,o]=N.useState(!1),{data:a,isLoading:m}=q({queryKey:["data-integrity-overview"],queryFn:async()=>{const i=W(oe(new Date,30),"yyyy-MM-dd"),{data:c}=await h.from("analytics_rollups_daily").select("rollup_date, views").gte("rollup_date",i).order("rollup_date",{ascending:!0}),s={};
1(c||[]).forEach(g=>{s[g.rollup_date]=(s[g.rollup_date]||0)+(g.views||0)});const t=Object.entries(s).map(([g,$])=>({date:g,events:$})).sort((g,$)=>g.date.localeCompare($.date)),l=new Set;for(let g=0;g<30;g++)l.add(W(oe(new Date,g),"yyyy-MM-dd"));const x=new Set(Object.keys(s)),r=[...l].filter(g=>!x.has(g)).length,{count:j}=await h.from("analytics_event_anomalies").select("*",{count:"exact",head:!0}).is("resolved_at",null),{data:f}=await h.from("analytics_rollups_daily").select("operator_id").eq("source_context","operator_site").gte("rollup_date",i),C=new Set((f||[]).map(g=>g.operator_id)).size,{data:u}=await h.from("analytics_rollups_daily").select("operator_id").eq("source_context","embed").gte("rollup_date",i),v=new Set((u||[]).map(g=>g.operator_id)).size,{count:_}=await h.from("operators").select("*",{count:"exact",head:!0}).eq("status","approved"),y=(_||0)>0?v/(_||1)*100:0;return{dailyIngestion:t,missingDays:r,anomalyCount:j||0,sdkInstallations:C,embedAdoptionRate:y,totalOperators:_||0}}});return m?e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[1,2,3,4].map(i=>e.jsx(w,{className:"border-border/60",children:e.jsx(k,{className:"pt-4 pb-4",children:e.jsx("div",{className:"h-16 bg-muted animate-pulse rounded"})})},i))}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(w,{className:"border-border/60",children:e.jsxs(k,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(ae,{className:"h-3.5 w-3.5"})," Missing Rollup Days"]}),e.jsx("p",{className:"text-2xl font-bold",children:a?.missingDays||0}),(a?.missingDays||0)===0?e.jsxs(p,{variant:"outline",className:"text-emerald-600 mt-1 text-[10px]",children:[e.jsx(M,{className:"h-3 w-3 mr-1"}),"Healthy"]}):e.jsxs(p,{variant:"destructive",className:"mt-1 text-[10px]",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),"Gaps"]})]})}),e.jsx(w,{className:"border-border/60",children:e.jsxs(k,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(ze,{className:"h-3.5 w-3.5"})," Unresolved Anomalies"]}),e.jsx("p",{className:"text-2xl font-bold",children:a?.anomalyCount||0})]})}),e.jsx(w,{className:"border-border/60",children:e.jsxs(k,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(fe,{className:"h-3.5 w-3.5"})," SDK Installations"]}),e.jsx("p",{className:"text-2xl font-bold",children:a?.sdkInstallations||0}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["of ",a?.totalOperators," operators"]})]})}),e.jsx(w,{className:"border-border/60",children:e.jsxs(k,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(fe,{className:"h-3.5 w-3.5"})," Embed Adoption"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[(a?.embedAdoptionRate||0).toFixed(0),"%"]})]})})]}),e.jsxs(ve,{open:n,onOpenChange:o,children:[e.jsx(be,{asChild:!0,children:e.jsxs(S,{variant:"ghost",size:"sm",className:"text-xs gap-1.5 h-7 px-2",children:[e.jsx(me,{className:`h-3.5 w-3.5 transition-transform ${n?"rotate-180":""}`}),n?"Hide":"Show"," 30-day ingestion chart"]})}),e.jsx(Ne,{children:e.jsx(w,{className:"border-border/60 mt-2",children:e.jsx(k,{className:"pt-4",children:(a?.dailyIngestion?.length||0)>0?e.jsx(Te,{width:"100%",height:200,children:e.jsxs(Ts,{data:a.dailyIngestion,children:[e.jsx(As,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(qs,{dataKey:"date",tick:{fontSize:10},tickFormatter:i=>W(new Date(i),"MMM d"),className:"fill-muted-foreground"}),e.jsx(Ds,{tick:{fontSize:11},className:"fill-muted-foreground"}),e.jsx(Ae,{labelFormatter:i=>W(new Date(i),"MMM d, yyyy"),contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8}}),e.jsx(Is,{dataKey:"events",fill:"hsl(var(--primary))",radius:[2,2,0,0]})]})}):e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No ingestion data"})})})})]})]})}async function je(n){try{if(n instanceof Xe){const o=await n.context.json(),a=[o?.error,o?.code?`(code: ${o.code})`:null,o?.details,o?.hint?`hint: ${o.hint}
1`:null].filter(Boolean);if(a.length)return a.join(" â ")}}catch{}return n?.message||String(n)}const Ms={critical:"destructive",warning:"default",info:"secondary"},ye={critical:0,warning:1,info:2};function Hs(){const[n,o]=N.useState(!1),[a,m]=N.useState(null),[i,c]=N.useState("drift"),[s,t]=N.useState("auto"),[l,x]=N.useState(null),[r,j]=N.useState(null),[f,C]=N.useState(""),[u,v]=N.useState(""),[_,y]=N.useState(!1),{data:g,refetch:$}=q({queryKey:["ledger-reconciliation-alerts"],queryFn:async()=>{const{data:d,error:b}=await h.from("data_integrity_alerts").select("id, severity, message, details, created_at, resolved_at, last_seen_at, occurrence_count").eq("alert_type","ledger_reconciliation").is("resolved_at",null).order("created_at",{ascending:!1}).limit(500);if(b)throw b;const O=(d||[]).slice();return O.sort((G,z)=>{const he=ye[G.severity]??9,ge=ye[z.severity]??9;return he!==ge?he-ge:(z.created_at||"").localeCompare(G.created_at||"")}),O}}),V=(g??[]).filter(d=>d.severity==="critical"&&d.details?.code==="stripe_mismatch").length,Le=Array.from(new Set((g??[]).map(d=>
1d.details?.code).filter(Boolean))),E=s==="auto"?V>0?"stripe_mismatch":"all":s,K=(g??[]).filter(d=>E==="all"?!0:d.details?.code===E);async function Fe(){o(!0);try{const{data:d,error:b}=await X("reconcile-ledger-vs-stripe",{body:{mode:i,limit:500}},{flow:"ledger_reconciliation_run"});if(b)throw b;m(d),await $(),F({title:"Reconciliation complete",description:`Scanned ${d?.scanned??0} rows.`})}catch(d){F({title:"Reconciliation failed",description:d?.message||String(d),variant:"destructive"})}finally{o(!1)}}async function Pe(d){const{data:b}=await h.auth.getUser(),{error:O}=await h.from("data_integrity_alerts").update({resolved_at:new Date().toISOString(),resolved_by:b.user?.id??null}).eq("id",d);O?F({title:"Acknowledge failed",description:O.message,variant:"destructive"}):$()}async function Be(d){const b=(g??[]).filter(z=>z.details?.code===d).map(z=>z.id);if(!b.length||!confirm(`Acknowledge ${b.length} open "${d}" alerts? This only closes the alert rows â no financial data is modified.`))return;const{data:O}=await h.auth.getUser(),{error:G}=await h.from("data_integrity_alerts").update({resolved_at:new Date().toISOString(),resolved_by:O.user?.id??null}).in("id",b);G?F({title:"Bulk acknowledge failed",description:G.message,variant:"destructive"}):(F({title:"Acknowledged",description:`Closed ${b.length} ${d} alerts.`}),$())}async function Oe(){const d=(g??[]).filter(b=>b.severity==="critical"&&b.details?.code==="stripe_mismatch").map(b=>b.details?.booking_id).filter(Boolean);if(!d.length){F({title:"No critical stripe_mismatch alerts to investigate"});return}o(!0);try{const{data:b,error:O}=await X("reconcile-stripe-pi-forensics",{body:{booking_ids:d}},{flow:"ledger_forensics_run"});if(O)throw O;await $(),F({title:"Forensics complete",description:`${b?.count??0} bookings analyzed â see new info/warning rows below for hints.`})}catch(b){F({title:"Forensics failed",description:b?.message||String(b),variant:"destructive"})}finally{o(!1)}}async function $e(d){x(d),j(null),C(""),v(""),y(!0);try{const{data:b,error:O}=await X("apply-ledger-correction",{body:{alert_id:d.id,dry_run:!0}},{flow:"ledger_correction_dry_run"});if(O)throw O;j(b)}catch(b){F({title:"Dry-run failed",description:await je(b),variant:"destructive"}),x(null)}finally{y(!1)}}async function Me(){if(l){y(!0);try{const{data:d,error:b}=await X("apply-ledger-correction",{body:{alert_id:l.id,dry_run:!1,notes:f,confirmation_token:u}},{flow:"ledger_correction_apply"});if(b)throw b;if(d?.error)throw new Error(d.error);F({title:"Correction applied",description:`Inserted reconciliation_adjustment ${d?.transaction_id??""}`}),x(null),await $()}catch(d){F({title:"Apply failed",description:await je(d),variant:"destructive"})}finally{y(!1)}}}return e.jsxs(w,{id:"ledger-reconciliation",className:"scroll-mt-24",children:[e.jsx(T,{children:e.jsxs(A,{className:"flex items-center gap-2",children:[e.jsx(se,{className:"h-5 w-5"}),"Ledger â Stripe Reconciliation",e.jsx(p,{variant:"secondary",className:"ml-2",children:"read-only"})]})}),e.jsxs(k,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Cross-checks ",e.jsx("code",{children:"booking_transactions"})," (original_charge) against Stripe PaymentIntent amounts. Discrepancies are queued here for admin review. No mutations are ever made to ledger rows or Stripe."]}),e.jsxs("div",{className:"rounded-md border border-border/60 bg-muted/30 p-3 text-xs text-muted-foreground space-y-1",children:[e.jsxs("div",{className:"font-medium text-foreground",children:["How to triage a ",e.jsx("code",{children:"stripe_mismatch"})," alert"]}),e.jsxs("ol",{className:"list-decimal pl-5 space-y-0.5",children:[e.jsxs("li",{children:[e.jsx("span",{className:"text-foreground",children:"Propose correction"})," â runs a dry-run that shows the exact delta between local ledger and Stripe. No writes."]}),e.jsx("li",{children:"Review the dry-run plan and confirm Stripe is the source of truth."}),e.jsxs("li",{children:["Click ",e.jsx("span",{className:"text-foreground",children:"Apply"})," to insert the offsetting ledger row."]}),e.jsxs("li",{children:["If the alert is non-actionable (legacy, off-platform, expected), click ",e.jsx("span",{className:"text-foreground",children:"Ack"})," â or use the bulk acknowledge action to close a whole category at once."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("select",{value:i,onChange:d=>c(d.target.value),className:"text-sm border rounded px-2 py-1 bg-background",disabled:n,children:[e.jsx("option",{value:"drift",children:"Drift only (faster)"}),e.jsx("option",{value:"all",children:"All original_charge rows"})]}),e.jsxs(S,{onClick:Fe,disabled:n,children:[n&&e.jsx(B,{className:"h-4 w-4 mr-2 animate-spin"}),"Run reconciliation"]}),e.jsx(S,{variant:"outline",onClick:Oe,disabled:n,children:"Run PI forensics on critical alerts"})]}),a&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm space-y-1",children:[e.jsxs("div",{className:"font-medium",children:["Last run · ",a.stripe_mode," mode"]}),e.jsxs("div",{children:["Scanned: ",a.scanned," · Alerts written: ",a.alerts_written]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:Object.entries(a.by_code).map(([d,b])=>
1e.jsxs(p,{variant:d==="ok"?"secondary":d==="stripe_mismatch"?"destructive":"default",children:[d,": ",b]},d))}),a.next_cursor&&e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"More results available â re-run to continue."})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2 flex-wrap",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Open alerts (",K.length,K.length!==(g?.length??0)&&` of ${g?.length??0}`,")",V>0&&e.jsxs(p,{variant:"destructive",className:"ml-2",children:[V," critical"]})]}),e.jsxs("select",{value:s,onChange:d=>t(d.target.value),className:"text-xs border rounded px-2 py-1 bg-background",children:[e.jsx("option",{value:"auto",children:"Auto (critical first)"}),e.jsx("option",{value:"all",children:"All codes"}),Le.map(d=>e.jsx("option",{value:d,children:d},d))]}),E!=="all"&&E!=="stripe_mismatch"&&K.length>0&&e.jsxs(S,{size:"sm",variant:"outline",onClick:()=>Be(E),children:["Acknowledge all ",E," (",K.length,")"]})]}),e.jsxs("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:[K.map(d=>e.jsxs("div",{className:"flex items-start gap-2 rounded border p-2 text-sm",children:[e.jsx(p,{variant:Ms[d.severity]||"default",children:d.severity}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-mono text-xs truncate flex items-center gap-2",children:[e.jsxs("span",{className:"truncate",children:[d.details?.code," · booking ",d.details?.booking_id]}),(d.occurrence_count??1)>1&&e.jsxs(p,{variant:"secondary",className:"text-[10px] px-1.5 py-0 shrink-0",children:["seen Ã",d.occurrence_count]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ledger ",d.details?.ledger_total," · stripe ",d.details?.stripe_amount??"?"," · fee ",d.details?.ledger_fee,d.last_seen_at&&d.last_seen_at!==d.created_at&&e.jsxs("span",{className:"ml-2 opacity-70",children:["· last ",new Date(d.last_seen_at).toLocaleString()]})]})]}),d.severity==="critical"&&d.details?.code==="stripe_mismatch"&&e.jsx(S,{size:"sm",variant:"outline",onClick:()=>$e(d),children:"Propose correction"}),e.jsx(S,{size:"sm",variant:"ghost",onClick:()=>Pe(d.id),children:"Ack"})]},d.id)),!K.length&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"No open reconciliation alerts."})]})]})]}),e.jsx(Ue,{open:!!l,onOpenChange:d=>!d&&x(null),children:e.jsxs(We,{className:"max-w-xl",children:[e.jsxs(Qe,{children:[e.jsx(Ve,{children:"Propose ledger correction"}),e.jsxs(Ge,{children:["This inserts a single ",e.jsx("code",{children:"reconciliation_adjustment"})," ledger row to align the booking's ledger total with Stripe's authoritative net (gross â refunds).",e.jsx("strong",{children:" No money is moved."})," Stripe is not modified."]})]}),_&&!r&&e.jsxs("div",{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[e.jsx(B,{className:"h-4 w-4 animate-spin"})," Re-checking against Stripeâ¦"]}),r?.plan&&e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"rounded border bg-muted/30 p-3 font-mono text-xs space-y-1",children:[e.jsxs("div",{children:["booking: ",r.plan.booking_id]}),e.jsxs("div",{children:["PI: ",r.plan.payment_intent_id]}),e.jsxs("div",{children:["stripe gross: ",r.plan.stripe_gross]}),e.jsxs("div",{children:["stripe refunds: ",r.plan.stripe_refunds_sum]}),e.jsxs("div",{children:["stripe net: ",e.jsx("strong",{children:r.plan.stripe_net})]}),e.jsxs("div",{children:["current ledger: ",r.plan.current_ledger_total]}),e.jsxs("div",{className:r.plan.required_adjustment_delta===0?"":"text-amber-600",children:["required delta: ",e.jsx("strong",{children:r.plan.required_adjustment_delta})]})]}),r.plan.stripe_connected_account_id?e.jsx("a",{href:`https://dashboard.stripe.com/${r.plan.stripe_connected_account_id}/payments/${r.plan.payment_intent_id}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline underline-offset-2 hover:no-underline",children:"View on Stripe (connected account) â"}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"View on Stripe unavailable â connected account unknown"}),r.plan.required_adjustment_delta===0?e.jsx("div",{className:"text-xs text-muted-foreground",children:"No adjustment needed â ledger already matches Stripe net."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium",children:"Admin notes (required, audit trail)"}),e.jsx(Je,{value:f,onChange:d=>C(d.target.value),placeholder:"Why is this adjustment justified? Reference Stripe events, modify-booking history, etc.",rows:3})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-medium",children:["Type ",e.jsx("code",{children:r.confirmation_required})," to confirm"]}),e.jsx(ue,{value:u,onChange:d=>v(d.target.value),placeholder:r.confirmation_required})]})]})]}),e.jsxs(Ye,{children:[e.jsx(S,{variant:"ghost",onClick:()=>x(null),disabled:_,children:"Cancel"}),e.jsxs(S,{onClick:Me,disabled:_||!r?.plan||r.plan.required_adjustment_delta===0||f.trim().length<5||u!==r?.confirmation_required,
1children:[_&&e.jsx(B,{className:"h-4 w-4 mr-2 animate-spin"}),"Apply ledger-only correction"]})]})]})})]})}function Es(){const{isAdmin:n}=_e(),{toast:o}=we(),a=H(),[m,i]=N.useState(!1),{data:c,isLoading:s}=q({queryKey:["ledger-backfill-runs"],queryFn:async()=>{const{data:u,error:v}=await h.from("ledger_backfill_runs").select("*").order("ran_at",{ascending:!1}).limit(30);if(v)throw v;return u||[]},refetchInterval:6e4}),t=c?.[0],l=(c||[]).filter(u=>!u.dry_run),x=l.filter(u=>Date.now()-new Date(u.ran_at).getTime()<7*864e5).reduce((u,v)=>u+v.inserted,0),j=(l.find(u=>u.inserted_booking_numbers?.length>0)?.inserted_booking_numbers||[]).slice(0,5),f=t?.missing_total??0;async function C(){i(!0);try{const{data:u,error:v}=await h.functions.invoke("backfill-original-charge-ledger",{body:{dry_run:!1,limit:100}});if(v)throw v;o({title:"Backfill complete",description:`Inserted ${u?.inserted??0} of ${u?.missing_total??0} missing rows.`}),a.invalidateQueries({queryKey:["ledger-backfill-runs"]})}catch(u){o({title:"Backfill failed",description:u?.message||"Unknown error",variant:"destructive"})}finally{i(!1)}}return e.jsxs(w,{children:[e.jsxs(T,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs("div",{children:[e.jsxs(A,{className:"text-base flex items-center gap-2",children:[e.jsx(ae,{className:"h-4 w-4"}),"Ledger Integrity (original_charge)"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Booking transaction ledger backfill â runs daily at 03:30 UTC."})]}),n&&e.jsxs(S,{size:"sm",variant:"outline",onClick:C,disabled:m,children:[m?e.jsx(B,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Q,{className:"h-3.5 w-3.5 mr-1.5"}),"Backfill now"]})]}),e.jsx(k,{children:s?e.jsx("div",{className:"h-24 bg-muted animate-pulse rounded"}):e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Currently missing"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:f}),f===0?e.jsxs(p,{variant:"outline",className:"text-green-600 mt-1",children:[e.jsx(M,{className:"h-3 w-3 mr-1"}),"Healthy"]}):e.jsxs(p,{variant:"destructive",className:"mt-1",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),"Drift"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inserted (7d)"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:x}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"via cron + manual"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Last run"}),e.jsx("div",{className:"text-sm font-medium mt-1",children:t?re(new Date(t.ran_at),{addSuffix:!0}):"Never"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:t?`${t.triggered_by}${t.dry_run?" (dry)":""}`:"â"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Recent backfills"}),j.length===0?e.jsx("div",{className:"text-sm text-muted-foreground mt-1",children:"None"}):e.jsx("ul",{className:"text-xs space-y-0.5 mt-1",children:j.map(u=>e.jsx("li",{children:e.jsx(de,{to:`/admin/bookings?search=${encodeURIComponent(u)}`,className:"text-primary hover:underline font-mono",children:u})},u))})]})]})})]})}const Z=n=>`${n<0?"-":""}$${(Math.abs(n)/100).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`;function Ks(){const{data:n,isLoading:o}=q({queryKey:["booking-order-drift-summary"],queryFn:async()=>{const{data:c,error:s}=await h.rpc("get_booking_drift_summary");if(s)throw s;const t=Array.isArray(c)?c[0]:c;return t?{total_drift_rows:Number(t.total_drift_rows??0),order_booking_gap_rows:Number(t.order_booking_gap_rows??0),lineitem_gap_rows:Number(t.lineitem_gap_rows??0),total_drift_cents:Number(t.total_drift_cents??0)}:null},refetchInterval:6e4}),{data:a}=q({queryKey:["booking-order-drift-top"],queryFn:async()=>{const{data:c,error:s}=await h.from("booking_order_drift_audit").select("booking_id, booking_number, order_number, order_source, order_total_cents, booking_total_cents, order_booking_drift_cents, booking_line
1item_drift_cents").order("booked_at",{ascending:!1}).limit(8);if(s)throw s;return c||[]}}),m=n?.total_drift_rows??0,i=m===0;return e.jsxs(w,{children:[e.jsxs(T,{className:"pb-3",children:[e.jsxs(A,{className:"text-base flex items-center gap-2",children:[e.jsx(Ze,{className:"h-4 w-4"}),"Booking â Order Drift"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:`Bookings whose order total disagrees with the booking row, or whose line items don't sum to the booking subtotal. Root cause of "Drift" badges on Booking Details.`})]}),e.jsx(k,{className:"space-y-4",children:o?e.jsx("div",{className:"h-20 bg-muted animate-pulse rounded"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total drifted"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:m}),i?e.jsxs(p,{variant:"outline",className:"text-green-600 mt-1",children:[e.jsx(M,{className:"h-3 w-3 mr-1"}),"Healthy"]}):e.jsxs(p,{variant:"outline",className:"border-warning text-warning mt-1",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),"Investigate"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Order > Booking"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:n?.order_booking_gap_rows??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"missing add-ons / fees"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Booking â line items"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:n?.lineitem_gap_rows??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"subtotal not re-fanned"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total $ drifted"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:Z(n?.total_drift_cents??0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"absolute, all-time"})]})]}),!i&&a&&a.length>0&&e.jsxs("div",{className:"border-t pt-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Most recent drifted bookings"}),e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.map(c=>e.jsxs("li",{className:"flex items-center justify-between gap-2 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(de,{to:`/admin/bookings?search=${encodeURIComponent(c.booking_number)}`,className:"text-primary hover:underline font-mono",children:c.booking_number}),e.jsxs("span",{className:"text-muted-foreground truncate",children:[c.order_number??"â"," (",c.order_source??"?",")"]})]}),e.jsxs("div",{className:"flex items-center gap-3 tabular-nums",children:[e.jsxs("span",{className:"text-muted-foreground",children:["ord ",Z(c.order_total_cents??0)]}),e.jsxs("span",{className:"text-muted-foreground",children:["bk ",Z(c.booking_total_cents)]}),e.jsxs("span",{className:"text-warning font-semibold",children:["Î ",Z(c.order_booking_drift_cents)]}),e.jsx(es,{className:"h-3 w-3 text-muted-foreground"})]})]},c.booking_id))})]})]})})]})}function zs(){const n=H(),{data:o,isLoading:a}=q({queryKey:["stripe-amount-drift-anomalies"],refetchInterval:6e4,queryFn:async()=>{const{data:c,error:s}=await h.from("data_integrity_anomalies").select("id, message, severity, details, detected_at").eq("anomaly_type","stripe_amount_drift").is("resolved_at",null).order("detected_at",{ascending:!1}).limit(25);if(s)throw s;return c??[]}}),m=async c=>{const{error:s}=await h.from("data_integrity_anomalies").update({resolved_at:new Date().toISOString()}).eq("id",c);if(s){P.error("Could not resolve: "+s.message);return}P.success("Marked resolved"),n.invalidateQueries({queryKey:["stripe-amount-drift-anomalies"]})},i=o??[];return e.jsxs(w,{id:"stripe-amount-drift",className:"border-border/60",children:[e.jsx(T,{className:"pb-3",children:e.jsxs(A,{className:"text-sm font-semibold flex items-center gap-2",children:[i.length>0?e.jsx(I,{className:"h-4 w-4 text-destructive"}):e.jsx(se,{className:"h-4 w-4 text-emerald-600"}),"Stripe amount drift",i.length>0&&e.jsx(p,{variant:"destructive",className:"h-5 px-1.5 text-[10px]",children:i.length})]})}),e.jsxs(k,{className:"space-y-2",children:[a&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Loadingâ¦"}),!a&&i.length===0&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"No unresolved charge-vs-booking mismatches. The pre-payment parity guard blocks new ones before a PaymentIntent is created."}),i.map(c=>{const s=c.details??{},t=s.booking_id??null;return e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-destructive",children:c.message}),e.jsxs("div",{className:"text-[11px] text-muted-foreground break-all",children:[s.code?`${s.code} · `:"",t?`booking ${t}
1 · `:"",new Date(c.detected_at).toLocaleString()]})]}),e.jsxs(S,{size:"sm",variant:"outline",className:"shrink-0",onClick:()=>m(c.id),children:[e.jsx(ss,{className:"h-3.5 w-3.5 mr-1"}),"Resolve"]})]},c.id)})]})]})}function Us(){const{data:n,isLoading:o}=q({queryKey:["financial-guard-bypass-log"],refetchInterval:12e4,queryFn:async()=>{const{data:a,error:m}=await h.from("financial_guard_bypass_log").select("*").order("created_at",{ascending:!1}).limit(25);if(m)throw m;return a??[]}});return e.jsxs(w,{children:[e.jsxs(T,{className:"flex flex-row items-center gap-2 space-y-0",children:[e.jsx(ke,{className:"h-4 w-4 text-amber-600"}),e.jsx(A,{className:"text-sm",children:"Financial guard bypass log"})]}),e.jsx(k,{children:o?e.jsx("div",{className:"text-xs text-muted-foreground",children:"Loadingâ¦"}):!n||n.length===0?e.jsx("div",{className:"text-xs text-muted-foreground",children:"No bypasses in the recent window. Ledger invariant trigger is fully in effect."}):e.jsx("ul",{className:"text-xs space-y-1",children:n.map(a=>e.jsxs("li",{className:"flex justify-between gap-3 border-b border-border/40 pb-1",children:[e.jsxs("span",{className:"truncate",children:[e.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:a.booking_id?.slice(0,8)})," ",a.reconciliation_reason||e.jsx("em",{className:"text-destructive",children:"no reason"})]}),e.jsx("span",{className:"text-muted-foreground shrink-0",children:a.created_at?re(new Date(a.created_at),{addSuffix:!0}):""})]},a.id))})})]})}function Ws(){const n=H(),[o,a]=N.useState(!1),[m,i]=N.useState(!1);async function c(){a(!0);try{const{data:t,error:l}=await X("reconcile-ledger-vs-stripe",{body:{mode:"drift",limit:500}},{flow:"ledger_reconciliation_run"});if(l)throw l;n.invalidateQueries({queryKey:["ledger-reconciliation-alerts"]}),n.invalidateQueries({queryKey:["data-integrity-critical-count"]}),F({title:"Reconciliation complete",description:`Scanned ${t?.scanned??0} rows · ${t?.alerts_written??0} new alerts.`})}catch(t){F({title:"Reconciliation failed",description:t?.message||String(t),variant:"destructive"})}finally{a(!1)}}async function s(){i(!0);try{const{data:t,error:l}=await h.functions.invoke("backfill-original-charge-ledger",{body:{dry_run:!1,limit:100}});if(l)throw l;n.invalidateQueries({queryKey:["ledger-backfill-runs"]}),F({title:"Backfill complete",description:`Inserted ${t?.inserted??0} of ${t?.missing_total??0} missing rows.`})}catch(t){F({title:"Backfill failed",description:t?.message||"Unknown error",variant:"destructive"})}finally{i(!1)}}return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border/60 bg-muted/20 px-4 py-2.5",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Maintenance actions · run on demand outside the scheduled cron cadence."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(S,{size:"sm",variant:"outline",onClick:c,disabled:o,children:[o?e.jsx(B,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Q,{className:"h-3.5 w-3.5 mr-1.5"}),"Re-run reconciliation"]}),e.jsxs(S,{size:"sm",variant:"outline",onClick:s,disabled:m,children:[m?e.jsx(B,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(ae,{className:"h-3.5 w-3.5 mr-1.5"}),"Backfill ledger now"]})]})]})}const Qs={line_items_subtotal_mismatch:"Line items vs subtotal",booking_total_component_mismatch:"Booking components vs total",order_rollup_drift:"Order rollup vs bookings",order_status_drift:"Order status vs bookings",settled_but_unledgered:"Settled without ledger row",booking_order_state_disagreement:"Booking vs order payment state",duplicate_notification:"Duplicate notifications (24h)",stale_financial_anomalies:"Stale anomalies (>24h)"};function Vs(){const n=H(),[o,a]=N.useState(!1),{data:m,isLoading:i}=q({queryKey:["financial-integrity-sweep-last-run"],queryFn:async()=>{const{data:r,error:j}=await h.from("health_check_results").select("id, status, anomaly_count, details, created_at").eq("check_type","financial_integrity_sweep").order("created_at",{ascending:!1}).limit(1).maybeSingle();if(j)throw j;return r}}),c=async()=>{a(!0);try{const{error:r}=await h.functions.invoke("financial-integrity-sweep",{body:{}});if(r)throw r;await n.invalidateQueries({queryKey:["financial-integrity-sweep-last-run"]}),P.success("Financial sweep complete")}catch(r){P.error(r?.message||"Sweep failed")}finally{a(!1)}},s=m?.details??{},t=s.counts??{},l=m?.anomaly_count??0,x=!!m&&l===0&&m.status!=="error";return e.jsxs(w,{id:"financial-sweep",children:[e.jsxs(T,{className:"flex flex-row items-start justify-between gap-3 space-y-0",children:[e.jsxs("div",{children:[e.jsxs(A,{className:"text-base flex items-center gap-2",children:[x?e.jsx(se,{className:"h-4 w-4 text-primary"}):e.jsx(I,{className:"h-4 w-4 text-destructive"}),"Financial Sweep"]}),e.jsx(te,{children:"Nightly cross-check of booking line items, booking totals, order rollups and order statuses. Ru
1ns ~04:30 ET."})]}),e.jsxs(S,{size:"sm",variant:"outline",onClick:c,disabled:o,children:[o?e.jsx(B,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Q,{className:"h-3.5 w-3.5 mr-1.5"}),"Run now"]})]}),e.jsx(k,{className:"space-y-3",children:i?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading last runâ¦"}):m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Last run ",new Date(m.created_at).toLocaleString()]}),e.jsx(p,{variant:x?"secondary":"destructive",children:m.status==="error"?"Error":x?"Clean":`${l} finding(s)`}),typeof s.bookings_checked=="number"&&e.jsxs("span",{children:["· ",s.bookings_checked," bookings / ",s.orders_checked??0," orders checked"]})]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:Object.entries(Qs).map(([r,j])=>{const f=Number(t[r]??0);return e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border/60 px-3 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:j}),e.jsx("span",{className:f>0?"font-semibold text-destructive":"text-muted-foreground",children:f})]},r)})})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"No sweep has run yet. Use âRun nowâ to execute the first pass."})})]})}function Gs(){return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{}),e.jsx(D,{name:"FinancialSweepTile",children:e.jsx(Vs,{})}),e.jsx(D,{name:"StripeAmountDriftTile",children:e.jsx(zs,{})}),e.jsx(D,{name:"BookingOrderDriftTile",children:e.jsx(Ks,{})}),e.jsx(D,{name:"LedgerReconciliationTile",children:e.jsx(Hs,{})}),e.jsx(D,{name:"LedgerHealthTile",children:e.jsx(Es,{})}),e.jsx(D,{name:"GuardBypassLogTile",children:e.jsx(Us,{})})]})}const Js=1e3,Ys={apple_pay:e.jsx(pe,{className:"h-3 w-3"}),google_pay:e.jsx(pe,{className:"h-3 w-3"}),link:e.jsx(Se,{className:"h-3 w-3"}),card:e.jsx(Ce,{className:"h-3 w-3"})},Xs={apple_pay:"Apple Pay",google_pay:"Google Pay",link:"Stripe Link",card:"Card"};function Zs(){const{data:n,isLoading:o}=q({queryKey:["admin-cart-pi-statuses"],queryFn:async()=>{const{data:u,error:v}=await h.from("bookings").select("last_pi_status").not("last_pi_status","is",null).neq("last_pi_status","succeeded").gte("created_at",new Date(Date.now()-2592e6).toISOString());if(v)throw v;const _={};return(u||[]).forEach(y=>{const g=y.last_pi_status||"unknown";_[g]=(_[g]||0)+1}),Object.entries(_).map(([y,g])=>({last_pi_status:y,count:g})).sort((y,g)=>g.count-y.count)},refetchInterval:6e4}),{data:a,isLoading:m}=q({queryKey:["admin-cart-wallet-mix"],queryFn:async()=>{const{data:u,error:v}=await h.from("bookings").select("wallet_payment_method").eq("payment_status","captured").gte("created_at",new Date(Date.now()-2592e6).toISOString());if(v)throw v;const _={};return(u||[]).forEach(y=>{const g=y.wallet_payment_method||"unknown";_[g]=(_[g]||0)+1}),Object.entries(_).map(([y,g])=>({wallet_payment_method:y,count:g})).sort((y,g)=>g.count-y.count)},refetchInterval:6e4}),{data:i,isLoading:c}=q({queryKey:["admin-recon-runs"],queryFn:async()=>{const{data:u,error:v}=await h.from("reconciliation_log").select("id, ran_at, booking_id, rows_corrected, delta_cents_adjusted, notes").order("ran_at",{ascending:!1}).limit(5);if(v)throw v;return u||[]},refetchInterval:6e4}),s=H(),[t,l]=N.useState(!1),x=a?.filter(u=>["apple_pay","google_pay","link"].includes(u.wallet_payment_method||"")).reduce((u,v)=>u+v.count,0)||0,r=a?.reduce((u,v)=>u+v.count,0)||0,j=r>0?Math.round(x/r*100):0,f=i?.find(u=>Math.abs(u.delta_cents_adjusted??0)>=Js),C=async()=>{l(!0);try{const{data:u,error:v}=await h.functions.invoke("reconcile-stripe-transactions",{body:{manual:!0}});if(v)throw v;P.success(`Reconciliation complete: ${u?.rows_corrected??0} rows, $${((u?.delta_cents_adjusted??0)/100).toFixed(2)} adjusted`),s.invalidateQueries({queryKey:["admin-recon-runs"]})}catch(u){P.error(`Reconciliation failed: ${u instanceof Error?u.message:String(u)}`)}finally{l(!1)}};return e.jsxs("div",{className:"space-y-4",children:[f&&e.jsxs(ts,{variant:"destructive",children:[e.jsx(I,{className:"h-4 w-4"}),e.jsx(as,{children:"Financial drift detected"}),e.jsxs(rs,{children:["Last reconciliation adjusted $",(Math.abs(f.delta_cents_adjusted??0)/100).toFixed(2)," ","across ",f.rows_corrected??0," rows on ",new Date(f.ran_at).toLocaleStr
1ing(),". Review ",f.booking_id?`booking ${f.booking_id}`:"the run notes"," below."]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(S,{size:"sm",variant:"outline",onClick:C,disabled:t,children:[t?e.jsx(B,{className:"h-3 w-3 mr-2 animate-spin"}):e.jsx(Q,{className:"h-3 w-3 mr-2"}),"Run reconciliation now"]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsxs(w,{children:[e.jsx(T,{className:"pb-3",children:e.jsxs(A,{className:"text-sm flex items-center gap-2",children:[e.jsx(ns,{className:"h-4 w-4 text-amber-500"}),"Stuck Payment Intents (30d)"]})}),e.jsx(k,{children:o?e.jsx(ne,{className:"h-24 w-full"}):n&&n.length>0?e.jsxs("div",{className:"space-y-2",children:[n.map(u=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("code",{className:"text-xs text-muted-foreground",children:u.last_pi_status}),e.jsx(p,{variant:"outline",children:u.count})]},u.last_pi_status)),e.jsxs("p",{className:"text-xs text-muted-foreground pt-2",children:["Bookings whose last PaymentIntent state is not ",e.jsx("code",{children:"succeeded"}),". High counts of"," ",e.jsx("code",{children:"requires_payment_method"})," indicate card declines."]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No stuck payments â all PIs succeeded."})})]}),e.jsxs(w,{children:[e.jsx(T,{className:"pb-3",children:e.jsxs(A,{className:"text-sm flex items-center gap-2",children:[e.jsx(Se,{className:"h-4 w-4 text-emerald-500"}),"Wallet Mix (30d)"]})}),e.jsx(k,{children:m?e.jsx(ne,{className:"h-24 w-full"}):a&&a.length>0?e.jsxs("div",{className:"space-y-2",children:[a.map(u=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[Ys[u.wallet_payment_method||""]||e.jsx(Ce,{className:"h-3 w-3"}),Xs[u.wallet_payment_method||""]||u.wallet_payment_method||"Unknown"]}),e.jsx(p,{variant:"secondary",children:u.count})]},u.wallet_payment_method)),e.jsxs("p",{className:"text-xs text-muted-foreground pt-2",children:[j,"% via Apple Pay / Google Pay / Link."]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No captured bookings in window."})})]}),e.jsxs(w,{children:[e.jsx(T,{className:"pb-3",children:e.jsx(A,{className:"text-sm",children:"Reconciliation (last 5 runs)"})}),e.jsx(k,{children:c?e.jsx(ne,{className:"h-24 w-full"}):i&&i.length>0?e.jsx("div",{className:"space-y-2",children:i.map(u=>e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:new Date(u.ran_at).toLocaleString()}),e.jsxs("span",{className:"flex gap-2",children:[e.jsxs(p,{variant:"outline",children:[u.rows_corrected??0," rows"]}),e.jsxs(p,{variant:(u.delta_cents_adjusted??0)!==0?"default":"secondary",children:["$",((u.delta_cents_adjusted??0)/100).toFixed(2)," adj"]})]})]},u.id))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No reconciliation runs yet."})})]})]})]})}const et={pass:e.jsx(xe,{className:"h-4 w-4 text-green-600"}),warn:e.jsx(I,{className:"h-4 w-4 text-amber-600"}),fail:e.jsx(ls,{className:"h-4 w-4 text-destructive"}),info:e.jsx(cs,{className:"h-4 w-4 text-muted-foreground"})},st={pass:"default",warn:"secondary",fail:"destructive",info:"outline"};function tt(){const[n,o]=N.useState("experiences.rockonrr.com"),[a,m]=N.useState(!1),[i,c]=N.useState(null),s=async()=>{if(n.trim()){m(!0),c(null);try{const{data:x,error:r}=await h.functions.invoke("diagnose-apple-pay",{body:{domain:n.trim()}});if(r)throw r;if(!x?.ok)throw new Error(x?.error||"Diagnostics failed");c(x)}catch(x){F({title:"Diagnostics failed",description:x?.message||"Unknown error",variant:"destructive"})}finally{m(!1)}}},t=async()=>{i&&(await navigator.clipboard.writeText(JSON.stringify(i,null,2)),F({title:"Copied diagnostics JSON to clipboard"}))},l=i?i.checks.reduce((x,r)=>(x[r.status]=(x[r.status]||0)+1,x),{}):null;return e.jsxs(w,{children:[e.jsxs(T,{children:[e.jsxs(A,{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"h-5 w-5"}),"Apple Pay Diagnostics"]}),e.jsx(te,{children:"One-click report verifying domain file, platform & operator registrations, and PaymentIntent config. Use this to find out exactly why Apple Pay isn't showing at checkout."})]}),e.jsxs(k,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(is,{htmlFor:"apd-diag-domain",children:"Checkout domain"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ue,{id:"apd-diag-domain",value:n,onChange:x=>o(x.target.value),placeholder:"experiences.rockonrr.com",disabled:a}),e.jsx(S,{onClick:s,disabled:a||!n.trim(),children:a?e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}),"Running..."]}):"Run Diagnostics"})]})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[e.jsxs(p,{variant:"outline",children:["Stripe mode: ",i.stripe_mode]}),e.jsxs(p,{variant:"outline",children:["Domain: ",i.domain]}),l&&e.jsxs(e.Fragment,{children:[l.pass?e.jsxs(p,{className:"bg-green-600",children:[l.pass," pass"]}):null,l.warn?e.jsxs(p,{variant:"secondary",children:[l.warn," warn"]}):null,l.fail?e.jsxs(p,{variant:"destructive",children:[l.fail," fail"]}):null,l.info?e.jsxs(p,{variant:"outline",children:[l.info," info"]}):null]}),e.jsxs(S,{size:"sm",variant:"ghost",className:"ml-auto",onClick:t,children:[e.jsx(Rs,{className:"h-3.5 w-3.5 mr-1"}),"Copy JSON"]})]}),e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-sm",children:[e.jsx("strong",{children:"Summary:"})," ",i.summary]}),e.jsx("div",{className:"space-y-2",children:i.checks.map(x=>e.jsx("div",{className:"rounded-md border p-3 space-y-1",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:et[x.status]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:x.label}),e.jsx(p,{variant:st[x.status],className:"text-xs uppercase",children:x.status})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:x.detail}),x.fix&&e.jsxs("p",{className:"text-sm mt-1",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Fix:"})," ",e.jsx("span",{className:"text-muted-foreground",children:x.fix})]}),x.meta&&Object.keys(x.meta).length>0&&e.jsxs("details",{className:"mt-2",children:[e.jsx("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Details"}),e.jsx("pre",{className:"text-xs bg-muted/60 rounded p-2 mt-1 overflow-x-auto",children:JSON.stringify(x.meta,null,2)})]})]})]})},x.id))})]})]})]})}function at(){const[n,o]=N.useState(null),[a,m]=N.useState(null),i=async c=>{o(c?"dry":"live");try{const{data:s,error:t}=await h.functions.invoke("backfill-failed-payment-errors",{body:{dry_run:c,limit:500}});if(t)throw t;m(s),P.success(c?`Dry-run: ${s.scanned} scanned, would update ${s.scanned-s.skipped}`:`Backfilled ${s.updated} of ${s.scanned}`)}catch(s){P.error(s?.message||"Backfill failed")}finally{o(null)}};return e.jsxs(w,{children:[e.jsxs(T,{children:[e.jsx(A,{className:"text-base",children:"Backfill failed-payment reasons"}),e.jsxs(te,{children:["Pulls historical Stripe decline reasons into ",e.jsx("code",{children:"bookings.last_payment_error"}),' so the unified payment badge tooltips work on legacy "Failed" rows.']})]}),e.jsxs(k,{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(S,{variant:"outline",disabled:!!n,onClick:()=>i(!0),children:[n==="dry"&&e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}),"Dry-run"]}),e.jsxs(S,{disabled:!!n,onClick:()=>i(!1),children:[n==="live"&&e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}),"Run live"]})]}),a&&e.jsx("div",{className:"text-xs text-muted-foreground rounded-md border bg-muted/30 p-3 font-mono whitespace-pre-wrap",children:JSON.stringify(a,null,2)})]})]})}const rt=(n,o)=>
1`${(n/100).toLocaleString(void 0,{style:"currency",currency:(o||"usd").toUpperCase()})}`;function ee({label:n,counts:o}){const a=Object.entries(o);return a.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:n}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(([m,i])=>e.jsxs(p,{variant:"secondary",className:"font-mono text-[11px]",children:[m,": ",i]},m))})]}):null}function nt(){const[n,o]=N.useState(""),[a,m]=N.useState(()=>new Date(Date.now()-90*24*60*60*1e3).toISOString().slice(0,10)),[i,c]=N.useState(!1),[s,t]=N.useState(null),{data:l}=q({queryKey:["admin-operator-picker-simple"],queryFn:async()=>{const{data:r}=await h.from("operators").select("id, business_name").order("business_name").limit(500);return r||[]}}),x=async()=>{if(!n){P.error("Pick an operator first");return}c(!0);try{const{data:r,error:j}=await h.functions.invoke("stripe-operator-payment-diagnostic",{body:{operator_id:n,since:new Date(a).toISOString(),limit:100}});if(j)throw j;const f=r;t(f),f.error?P.error(f.message||f.error):P.success(`${f.summary?.total??0} payment attempts inspected`)}catch(r){P.error(r?.message||"Diagnostic failed")}finally{c(!1)}};return e.jsxs(w,{id:"stripe-operator-payment-diagnostic",children:[e.jsxs(T,{children:[e.jsx(A,{className:"text-base",children:"Operator payment attempt inspector"}),e.jsx(te,{children:"Read-only. Reads Stripe payment attempts on one operator's connected account to show where checkouts stopped â extra verification step, no card entered, not confirmed, or blocked. Nothing is charged, changed or saved."})]}),e.jsxs(k,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("div",{className:"min-w-[240px] flex-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Operator"}),e.jsxs(os,{value:n,onValueChange:o,children:[e.jsx(ds,{children:e.jsx(ms,{placeholder:"Select an operatorâ¦"})}),e.jsx(us,{children:(l||[]).map(r=>e.jsx(xs,{value:r.id,children:r.business_name||r.id},r.id))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Since"}),e.jsx(ue,{type:"date",value:a,onChange:r=>m(r.target.value),className:"w-[160px]"})]}),e.jsxs(S,{onClick:x,disabled:i||!n,children:[i&&e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}),"Run diagnostic"]})]}),s?.error&&e.jsxs("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[e.jsx("span",{className:"font-medium",children:s.error})," â ",s.message]}),s?.summary&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[s.business_name," · ",s.connected_account_id," · ",s.stripe_mode," mode ·"," ",s.summary.total," attempts since ",s.since?.slice(0,10),s.has_more?" (more available â narrow the date range)":""]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(ee,{label:"By status",counts:s.summary.by_status}),e.jsx(ee,{label:"By required next step",counts:s.summary.by_next_action_type}),e.jsx(ee,{label:"Reached a card charge",counts:{yes:s.summary.with_charge,no:s.summary.without_charge}}),e.jsx(ee,{label:"Charge outcome",counts:s.summary.by_charge_outcome_type})]})]}),!!s?.payment_intents?.length&&e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs(ie,{children:[e.jsx(le,{children:e.jsxs(U,{children:[e.jsx(R,{children:"Created"}),e.jsx(R,{children:"Booking"}),e.jsx(R,{className:"text-right",children:"Amount"}),e.jsx(R,{children:"Status"}),e.jsx(R,{children:"Next step"}),e.jsx(R,{children:"Error"}),e.jsx(R,{children:"Charge outcome"})]})}),e.jsx(ce,{children:s.payment_intents.map(r=>e.jsxs(U,{children:[e.jsx(L,{className:"whitespace-nowrap text-xs",children:new Date(r.created).toLocaleString()}),e.jsx(L,{className:"text-xs",children:r.booking_number||"â"}),e.jsx(L,{className:"text-right tabular-nums text-xs",children:rt(r.amount,r.currency)}),e.jsx(L,{className:"text-xs font-mono",children:r.status}),e.jsx(L,{className:"text-xs font-mono",children:r.next_action_type||"â"}),e.jsx(L,{className:"max-w-[260px] text-xs",children:r.last_payment_error_code||r.last_payment_error_decline_code?e.jsx("span",{title:r.last_payment_error_message||"",children:r.last_payment_error_decline_code||r.last_payment_error_code}):r.cancellation_reason||"â"}),e.jsx(L,{className:"text-xs",children:r.charge?[r.charge.outcome_type,r.charge.outcome_reason,r.charge.outcome_risk_level].filter(
1Boolean).join(" · "):"â"})]},r.id))})]})})]})]})}function it(){return e.jsxs("div",{className:"space-y-6",children:[e.jsx(D,{name:"CartDropOffDiagnostics",children:e.jsx(Zs,{})}),e.jsx(D,{name:"ApplePayDiagnostics",children:e.jsx(tt,{})}),e.jsx(D,{name:"FailedPaymentBackfillTile",children:e.jsx(at,{})}),e.jsx(D,{name:"StripeOperatorPaymentDiagnostic",children:e.jsx(nt,{})})]})}function lt(){return q({queryKey:["admin-fareharbor-backlog"],staleTime:6e4,refetchInterval:6e4,queryFn:async()=>{const[n,o]=await Promise.all([h.rpc("get_admin_fareharbor_backlog_summary"),h.rpc("get_admin_fareharbor_backlog_daily",{_days:30})]);if(n.error)throw n.error;if(o.error)throw o.error;const a=n.data?.[0]??{},m=Number(a.needs_price_total??0),i=Number(a.price_unavailable_total??0),c=a.last_drained_at??null,s=new Map;for(let j=29;j>=0;j--){const f=oe(new Date,j).toISOString().slice(0,10);s.set(f,{needsPrice:0,priceUnavailable:0})}for(const j of o.data??[]){const f=typeof j.day=="string"?j.day:String(j.day);s.has(f)&&s.set(f,{needsPrice:Number(j.needs_price??0),priceUnavailable:Number(j.price_unavailable??0)})}const t=Array.from(s.values()),l=t.slice(-7).reduce((j,f)=>j+f.needsPrice,0)/7,x=t.slice(-14,-7).reduce((j,f)=>j+f.needsPrice,0)/7,r=x>0?Math.round((l-x)/x*100):null;return{needsPriceTotal:m,priceUnavailableTotal:i,lastDrainedAt:c,daily30:t,trendPct:r}}})}function ct(){const{isAdmin:n}=_e(),{toast:o}=we(),a=H(),[m,i]=N.useState(!1),{data:c,isLoading:s}=lt(),t=c?.needsPriceTotal??0,l=c?.priceUnavailableTotal??0,x=t<=25?"green":t<=250?"amber":"red",r=x==="green"?e.jsxs(p,{variant:"outline",className:"text-green-600 mt-1",children:[e.jsx(M,{className:"h-3 w-3 mr-1"}),"Healthy"]}):x==="amber"?e.jsxs(p,{variant:"outline",className:"text-amber-600 border-amber-600 mt-1",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),"Draining"]}):e.jsxs(p,{variant:"destructive",className:"mt-1",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),"Backlog"]});async function j(){i(!0);try{const{data:y,error:g}=await h.functions.invoke("backfill-fareharbor-prices",{body:{}});if(g)throw g;o({title:"Drain triggered",description:`${y?.fixed??0} listings priced this batch. Cron will continue every 5 min.`}),a.invalidateQueries({queryKey:["admin-fareharbor-backlog"]})}catch(y){o({title:"Drain failed",description:y?.message||"Unknown error",variant:"destructive"})}finally{i(!1)}}const[f,C]=N.useState(!1);async function u(){if(confirm(`Reset ${l.toLocaleString()} terminal (price_unavailable) FareHarbor listings back to 'needs_price' so the drainer retries them? 2 3Safe to run â batched 500 at a time and self-chained.`)){C(!0);try{const{data:y,error:g}=await h.functions.invoke("resurrect-fareharbor-price-terminal",{body:{batch_size:500}});if(g)throw g;o({title:"Terminal rows re-queued",description:`${y?.resurrected??0} rows moved back to needs_price. Chained job will continue for the remaining ${y?.remaining_terminal??0}.`}),a.invalidateQueries({queryKey:["admin-fareharbor-backlog"]})}catch(y){o({title:"Resurrect failed",description:y?.message||"Unknown error",variant:"destructive"})}finally{C(!1)}}}const v=(c?.daily30??[]).map((y,g)=>({i:g,v:y.needsPrice})),_=c?.trendPct;return e.jsxs(w,{children:[e.jsxs(T,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs("div",{children:[e.jsxs(A,{className:"text-base flex items-center gap-2",children:[e.jsx(ae,{className:"h-4 w-4"}),"FareHarbor Price Backlog"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Listings awaiting price re-scrape. Drainer cron runs every 5 min."})]}),n&&e.jsxs("div",{className:"flex items-center gap-2",children:[l>0&&e.jsxs(S,{size:"sm",variant:"outline",onClick:u,disabled:f,title:"Reset price_unavailable rows back to needs_price so the drainer retries them",children:[f?e.jsx(B,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Q,{className:"h-3.5 w-3.5 mr-1.5"}),"Re-queue terminal (",l.toLocaleString(),")"]}),e.jsxs(S,{size:"sm",variant:"outline",onClick:j,disabled:m,children:[m?e.jsx(B,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Q,{className:"h-3.5 w-3.5 mr-1.5"}),"Drain now"]})]})]}),e.jsx(k,{children:s?e.jsx("div",{className:"h-24 bg-muted animate-pulse rounded"}):e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Needs price"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:t.toLocaleStr
3ing()}),r]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Terminal (price_unavailable)"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:l.toLocaleString()}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["retried ",3,"Ã â review"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Last drained"}),e.jsx("div",{className:"text-sm font-medium mt-1",children:c?.lastDrainedAt?re(new Date(c.lastDrainedAt),{addSuffix:!0}):"Never"}),_!=null&&e.jsxs("p",{className:`text-xs mt-1 inline-flex items-center gap-1 ${_<0?"text-green-600":_>0?"text-red-600":"text-muted-foreground"}`,children:[_<0?e.jsx(ws,{className:"h-3 w-3"}):_>0?e.jsx(hs,{className:"h-3 w-3"}):null,_>0?"+":"",_,"% vs prior 7d"]})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"30-day trend"}),e.jsx("div",{className:"h-12",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(Ls,{data:v,children:[e.jsx(Ae,{contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:6,fontSize:11},labelFormatter:()=>"",formatter:y=>[y,"needs_price"]}),e.jsx(Fs,{type:"monotone",dataKey:"v",stroke:"hsl(var(--primary))",strokeWidth:2,dot:!1})]})})})]})]})})]})}function ot(){return e.jsx("div",{className:"space-y-6",children:e.jsx(D,{name:"FareHarborBacklogTile",children:e.jsx(ct,{})})})}function dt(){const{data:n,isLoading:o}=q({queryKey:["seo-completeness"],queryFn:async()=>{const[{count:a},{count:m},{count:i},{count:c},{count:s},{count:t}]=await Promise.all([h.from("blog_posts").select("*",{count:"exact",head:!0}).eq("status","published"),h.from("blog_posts").select("*",{count:"exact",head:!0}).eq("status","published").not("h1","is",null),h.from("blog_posts").select("*",{count:"exact",head:!0}).eq("status","published").not("meta_title","is",null),h.from("blog_posts").select("*",{count:"exact",head:!0}).eq("status","published").not("hero_image_url","is",null),h.from("blog_posts").select("*",{count:"exact",head:!0}).eq("status","published").not("hero_alt_text","is",null),h.from("blog_posts").select("*",{count:"exact",head:!0}).eq("status","published").not("faq_json","is",null)]),[{count:l},{count:x},{count:r},{count:j},{count:f},{count:C},{count:u}]=await Promise.all([h.from("listings").select("*",{count:"exact",head:!0}).eq("status","active"),h.from("listings").select("*",{count:"exact",head:!0}).eq("status","active").not("h1","is",null),h.from("listings").select("*",{count:"exact",head:!0}).eq("status","active").not("seo_title","is",null),h.from("listings").select("*",{count:"exact",head:!0}).eq("status","active").not("meta_description","is",null),h.from("listings").select("*",{count:"exact",head:!0}).eq("status","active").not("image_url","is",null),h.from("listings").select("*",{count:"exact",head:!0}).eq("status","active").not("image_alts_json","is",null),h.from("listings").select("*",{count:"exact",head:!0}).eq("status","active").not("faqs_json","is",null)]),[{count:v},{count:_},{count:y},{count:g},{count:$},{count:V}]=await Promise.all([h.from("regions").select("*",{count:"exact",head:!0}).gt("listing_count",0),h.from("regions").select("*",{count:"exact",head:!0}).gt("listing_count",0).not("h1_title","is",null),h.from("regions").select("*",{count:"exact",head:!0}).gt("listing_count",0).not("meta_title","is",null),h.from("regions").select("*",{count:"exact",head:!0}).gt("listing_count",0).not("meta_description","is",null),h.from("regions").select("*",{count:"exact",head:!0}).gt("listing_count",0).or("image_url.not.is.null,hero_bg_url.not.is.null"),h.from("regions").select("*",{count:"exact",head:!0}).gt("listing_count",0).not("faq_json","is",null)]);return[{surface:"Blog posts",total:a||0,metrics:[{label:"H1",ok:m||0},{label:"Meta title",ok:i||0},{label:"Image",ok:c||0},{label:"Alt text",ok:s||0},{label:"FAQ schema",ok:t||0}]},{surface:"Listings",total:l||0,metrics:[{label:"H1",ok:x||0},{label:"Meta title",ok:r||0},{label:"Meta description",ok:j||0},{label:"Image",ok:f||0},{label:"Alt text",ok:C||0},{label:"FAQ schema",ok:u||0}]},{surface:"Regions",total:v||0,metrics:[{label:"H1",ok:_||0},{label:"Meta title",ok:y||0},{label:"Meta description",ok:g||0},{label:"Image",ok:$||0},{label:"FAQ schema",ok:V||0}]}]}});return e.jsxs(w,{children:[e.jsx(T,{children:e.jsxs(A,{className:"text-base flex items-center gap-2",children:[e.jsx(gs,{className:"h-4 w-4"})," SEO Completeness"]})}),e.jsx(k,{children:o?e.jsx("div",{className:"h-32 bg-muted animate-pulse rounded"}):e.jsx("div",{className:"grid gap-6 md:grid-cols-3",children:n?.map(a=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm",children:a.surface}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[a.total," total"]})]}),a.metrics.map(m=>{const i=a.total>
30?m.ok/a.total*100:0,c=a.total-m.ok;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:m.label}),e.jsx("div",{className:"flex items-center gap-2",children:c===0?e.jsxs(p,{variant:"outline",className:"h-5 px-1.5",children:[e.jsx(xe,{className:"h-3 w-3 mr-1"}),"100%"]}):e.jsxs(p,{variant:"secondary",className:"h-5 px-1.5",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),c," missing"]})})]}),e.jsx(qe,{value:i,className:"h-1.5"})]},m.label)})]},a.surface))})})]})}function mt(){const n=q({queryKey:["prerender-canary"],queryFn:async()=>{const{data:s,error:t}=await h.functions.invoke("prerender-canary");if(t)throw t;return s},refetchInterval:3e5}),[o,a]=N.useState(!1),m=q({queryKey:["prerender-canary-alerts"],queryFn:async()=>{const s=new Date(Date.now()-864e5).toISOString(),{data:t,error:l}=await h.from("data_integrity_alerts").select("id, surface, message, severity, created_at, resolved_at, details").eq("alert_type","prerender_canary").is("resolved_at",null).or(`severity.eq.critical,and(severity.eq.warning,created_at.gte.${s})`).order("created_at",{ascending:!1}).limit(50);if(l)throw l;return t||[]}}),i=n.data?.ok===!0,c=n.data?.results||[];return e.jsxs(w,{children:[e.jsx(T,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(A,{className:"text-base flex items-center gap-2",children:[e.jsx(ks,{className:"h-4 w-4"})," Prerender Health (Bot Crawlability)"]}),n.isLoading?e.jsxs(p,{variant:"outline",children:[e.jsx(ps,{className:"h-3 w-3 mr-1 animate-pulse"}),"Probingâ¦"]}):i?e.jsxs(p,{variant:"outline",children:[e.jsx(M,{className:"h-3 w-3 mr-1"}),"All surfaces healthy"]}):e.jsxs(p,{variant:"destructive",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),"Failures detected"]})]})}),e.jsxs(k,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[c.map(s=>e.jsxs("div",{className:"border rounded-lg p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium capitalize text-sm",children:s.surface}),s.ok?e.jsxs(p,{variant:"outline",className:"text-xs",children:[e.jsx(M,{className:"h-3 w-3 mr-1"}),"OK"]}):e.jsxs(p,{variant:"destructive",className:"text-xs",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),"FAIL"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",title:s.slug,children:["/",s.surface,"/",s.slug]}),e.jsxs("div",{className:"flex flex-wrap gap-1 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["HTTP ",s.status]}),e.jsxs("span",{children:["· ",(s.body_length/1024).toFixed(1)," KB"]}),e.jsxs("span",{children:["· ",s.jsonld_blocks," JSON-LD"]}),s.has_h1&&e.jsx("span",{children:"· H1 â"}),s.has_title&&e.jsx("span",{children:"· title â"})]}),s.failures.length>0&&e.jsx("p",{className:"text-xs text-destructive",children:s.failures.join(", ")})]},s.surface)),!n.isLoading&&c.length===0&&e.jsx("p",{className:"col-span-3 text-center text-muted-foreground text-sm py-4",children:"No canary results yet."})]}),(()=>{const s=m.data||[],t=s.filter(r=>r.severity==="critical"),l=s.filter(r=>r.severity==="warning");if(t.length===0&&l.length===0)return null;const x=(r,j)=>{const f=r.details?.slug,C=j==="critical"?"border-destructive":"border-amber-500";return e.jsxs("div",{className:`text-xs flex items-start gap-2 border-l-2 ${C} pl-2 py-1`,children:[e.jsx(p,{variant:"outline",className:"text-xs",children:r.surface}),f&&e.jsx("code",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono truncate max-w-[180px]",title:f,children:f}),e.jsx("span",{className:"text-muted-foreground flex-1",children:r.message}),e.jsx("span",{className:"text-muted-foreground whitespace-nowrap",children:new Date(r.created_at).toLocaleString()})]},r.id)};return e.jsxs("div",{className:"space-y-3",children:[t.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(I,{className:"h-3.5 w-3.5 text-destructive"}),"Critical regressions (",t.length,")"]}),e.jsx("div",{className:"space-y-1 max-h-40 overflow-y-auto",children:t.map(r=>x(r,"critical"))})]}),l.length>0&&e.jsxs("div",{children:[e.jsxs(S,{variant:"ghost",size:"sm",className:"h-auto p-0 text-sm font-medium hover:bg-transparent",onClick:()=>a(r=>!r),children:[o?e.jsx(me,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(De,{className:"h-3.5 w-3.5 mr-1"}),"Recent transient warnings (",l.length,", last 24h)"]}),o&&e.jsx("div",{className:"space-y-1 max-h-40 overflow-y-auto mt-2",children:l.map(r=>x(r,"warning"))})]})]})})(),n.data?.checked_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last probed: ",new Date(n.data.checked_at).toLocaleStr
3ing()," · Auto-refreshes every 5 min"]})]})]})}function ut(){const n=H(),[o,a]=N.useState(!1),{data:m,isLoading:i}=q({queryKey:["indexnow-coverage"],queryFn:async()=>{const{data:s}=await h.from("indexing_submissions").select("blog_post_id, listing_id, region_id, status, source").eq("status","success").like("source","indexnow_%"),t=new Set,l=new Set,x=new Set;(s||[]).forEach(C=>{C.blog_post_id&&t.add(C.blog_post_id),C.listing_id&&l.add(C.listing_id),C.region_id&&x.add(C.region_id)});const[{count:r},{count:j},{count:f}]=await Promise.all([h.from("blog_posts").select("*",{count:"exact",head:!0}).eq("status","published"),h.from("listings").select("*",{count:"exact",head:!0}).eq("status","active"),h.from("regions").select("*",{count:"exact",head:!0}).gt("listing_count",0)]);return[{label:"Blog posts",total:r||0,pinged:t.size},{label:"Listings",total:j||0,pinged:l.size},{label:"Regions",total:f||0,pinged:x.size}]}}),c=Ie({mutationFn:async s=>{a(!0);const{data:t,error:l}=await h.functions.invoke("backfill-indexnow",{body:{surface:"all",dry_run:s,limit:5e3}});if(l)throw l;return t},onSuccess:(s,t)=>{a(!1),t?P.success("Dry run complete â see console for details"):(P.success("IndexNow backfill submitted"),n.invalidateQueries({queryKey:["indexnow-coverage"]})),console.log("[backfill-indexnow] result",s)},onError:s=>{a(!1),P.error(`Backfill failed: ${s?.message||"unknown"}`)}});return e.jsxs(w,{children:[e.jsxs(T,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(A,{className:"text-base flex items-center gap-2",children:[e.jsx(fs,{className:"h-4 w-4"})," IndexNow Coverage"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(S,{size:"sm",variant:"outline",disabled:o,onClick:()=>c.mutate(!0),children:"Dry run"}),e.jsx(S,{size:"sm",disabled:o,onClick:()=>c.mutate(!1),children:o?e.jsx(B,{className:"h-3 w-3 animate-spin"}):"Backfill now"})]})]}),e.jsx(k,{children:i?e.jsx("div",{className:"h-24 bg-muted animate-pulse rounded"}):e.jsxs("div",{className:"space-y-3",children:[(m||[]).map(s=>{const t=s.total>0?Math.round(s.pinged/s.total*100):0,l=t>=90,x=t>=50&&t<90;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:s.label}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-muted-foreground tabular-nums",children:[s.pinged.toLocaleString()," / ",s.total.toLocaleString()]}),l?e.jsxs(p,{variant:"outline",className:"text-success",children:[e.jsx(xe,{className:"h-3 w-3 mr-1"}),t,"%"]}):x?e.jsxs(p,{variant:"secondary",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),t,"%"]}):e.jsxs(p,{variant:"destructive",children:[e.jsx(I,{className:"h-3 w-3 mr-1"}),t,"%"]})]})]}),e.jsx(qe,{value:t,className:"h-1.5"})]},s.label)}),e.jsx("p",{className:"text-xs text-muted-foreground pt-2",children:'IndexNow announces new and updated URLs to Bing & Yandex within minutes. Use "Backfill now" to submit any active content that was published before the integration shipped.'})]})})]})}function xt(){return e.jsxs("div",{className:"space-y-6",children:[e.jsx(D,{name:"SeoCompletenessWidget",children:e.jsx(dt,{})}),e.jsx(D,{name:"PrerenderHealthWidget",children:e.jsx(mt,{})}),e.jsx(D,{name:"IndexNowCoverageWidget",children:e.jsx(ut,{})})]})}function ht(){const n=H(),{data:o,isLoading:a}=q({queryKey:["analytics-anomalies"],queryFn:async()=>{const{data:t,error:l}=await h.from("analytics_event_anomalies").select("*").order("flagged_at",{ascending:!1}).limit(50);if(l)throw l;return t||[]}}),m=Ie({mutationFn:async t=>{const{data:{user:l}}=await h.auth.getUser(),{error:x}=await h.from("analytics_event_anomalies").update({resolved_at:new Date().toISOString(),resolved_by:l?.id||null}).eq("id",t);if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["analytics-anomalies"]}),P.success("Anomaly resolved")}});if(a)return e.jsx(w,{children:e.jsx(k,{className:"pt-6",children:e.jsx("div",{className:"h-48 bg-muted animate-pulse rounded"})})});const i=o?.filter(t=>!t.resolved_at).length||0,c={};(o||[]).filter(t=>
3!t.resolved_at&&t.ip_hash).forEach(t=>{const l=t.ip_hash;c[l]||(c[l]={count:0,totalEvents:0,latestFlag:t.flagged_at}),c[l].count++,c[l].totalEvents+=t.event_count,t.flagged_at>c[l].latestFlag&&(c[l].latestFlag=t.flagged_at)});const s=Object.entries(c).filter(([t,l])=>l.count>1).sort((t,l)=>l[1].totalEvents-t[1].totalEvents);return e.jsxs("div",{className:"space-y-6",children:[s.length>0&&e.jsxs(w,{children:[e.jsx(T,{children:e.jsxs(A,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ss,{className:"h-5 w-5 text-amber-500"}),"Suspicious IP Clusters",e.jsxs(p,{variant:"destructive",className:"ml-2",children:[s.length," clusters"]})]})}),e.jsx(k,{children:e.jsxs(ie,{children:[e.jsx(le,{children:e.jsxs(U,{children:[e.jsx(R,{children:"IP Hash"}),e.jsx(R,{className:"text-right",children:"Anomalies"}),e.jsx(R,{className:"text-right",children:"Total Events"}),e.jsx(R,{children:"Latest Flag"})]})}),e.jsx(ce,{children:s.map(([t,l])=>e.jsxs(U,{children:[e.jsxs(L,{className:"font-mono text-xs",children:[t.slice(0,16),"â¦"]}),e.jsx(L,{className:"text-right font-bold",children:l.count}),e.jsx(L,{className:"text-right",children:l.totalEvents}),e.jsx(L,{className:"text-sm",children:W(new Date(l.latestFlag),"MMM d, HH:mm")})]},t))})]})})]}),e.jsxs(w,{children:[e.jsx(T,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(A,{className:"flex items-center gap-2 text-base",children:[e.jsx(ke,{className:"h-5 w-5 text-destructive"}),"Anomaly Monitor"]}),i>0&&e.jsxs(p,{variant:"destructive",children:[i," unresolved"]})]})}),e.jsx(k,{children:!o||o.length===0?e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground gap-2",children:[e.jsx(M,{className:"h-5 w-5 text-green-500"}),"No anomalies detected"]}):e.jsxs(ie,{children:[e.jsx(le,{children:e.jsxs(U,{children:[e.jsx(R,{children:"Type"}),e.jsx(R,{children:"Visitor ID"}),e.jsx(R,{children:"IP Hash"}),e.jsx(R,{className:"text-right",children:"Events"}),e.jsx(R,{children:"Flagged"}),e.jsx(R,{children:"Status"}),e.jsx(R,{})]})}),e.jsx(ce,{children:o.map(t=>e.jsxs(U,{children:[e.jsx(L,{children:e.jsx(p,{variant:t.anomaly_type==="rate_limit_exceeded"?"destructive":"secondary",children:t.anomaly_type})}),e.jsx(L,{className:"font-mono text-xs",children:t.visitor_id?.slice(0,12)||"â"}),e.jsx(L,{className:"font-mono text-xs",children:t.ip_hash?.slice(0,12)||"â"}),e.jsx(L,{className:"text-right",children:t.event_count}),e.jsx(L,{className:"text-sm",children:W(new Date(t.flagged_at),"MMM d, HH:mm")}),e.jsx(L,{children:t.resolved_at?e.jsx(p,{variant:"outline",className:"text-green-600",children:"Resolved"}):e.jsx(p,{variant:"destructive",children:"Active"})}),e.jsx(L,{children:!t.resolved_at&&e.jsx(S,{size:"sm",variant:"ghost",onClick:()=>m.mutate(t.id),disabled:m.isPending,children:"Resolve"})})]},t.id))})]})})]})]})}function gt(){const[n,o]=N.useState(null),{data:a,isLoading:m}=q({queryKey:["health-check-results"],queryFn:async()=>{const{data:s,error:t}=await h.from("health_check_results").select("*").order("created_at",{ascending:!1}).limit(20);if(t)throw t;return s},refetchInterval:6e4});if(m)return e.jsx(w,{children:e.jsx(k,{className:"pt-6",children:e.jsx("div",{className:"h-32 bg-muted animate-pulse rounded"})})});const i=new Map;for(const s of a||[]){const t=`${s.check_type}:${s.check_name}`;i.has(t)||i.set(t,s)}const c=[...i.values()].reduce((s,t)=>s+(t.anomaly_count||0),0);return e.jsxs(w,{children:[e.jsx(T,{children:e.jsxs(A,{className:"text-base flex items-center gap-2",children:[e.jsx(Cs,{className:"h-4 w-4"}),"Health Check Results",c===0?e.jsxs(p,{variant:"outline",className:"text-green-600 ml-auto",children:[e.jsx(M,{className:"h-3 w-3 mr-1"})," All Clear"]}):e.jsxs(p,{variant:"destructive",className:"ml-auto",children:[e.jsx(I,{className:"h-3 w-3 mr-1"})," ",c," anomalies"]})]})}),e.jsx(k,{children:!a||a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No health check results yet. Checks run every 6 hours automatically."}):e.jsx(js,{className:"max-h-[400px]",children:e.jsx("div",{className:"space-y-2",children:[...i.values()].map(s=>e.jsxs(ve,{open:n===s.id,onOpenChange:t=>o(t?s.id:null),children:[e.jsx(be,{className:"w-full",children:e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s.anomaly_count>0?e.jsx(I,{className:"h-4 w-4 text-destructive shrink-0"}):e.jsx(M,{className:"h-4 w-4 text-green-600 shrink-0"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:s.check_name}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ys,{className:"h-3 w-3"}),re(new Date(s.created_at),{addSuffix:!0})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s.anomaly_count>0&&e.jsxs(p,{variant:"destructive",className:"text-xs",children:[s.anomaly_count," found"]}
3),e.jsx(p,{variant:"outline",className:"text-xs capitalize",children:s.check_type}),e.jsx(me,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Ne,{children:e.jsx("div",{className:"p-3 ml-7 text-sm",children:s.details?e.jsx("pre",{className:"bg-muted p-3 rounded text-xs overflow-x-auto max-h-48",children:JSON.stringify(s.details,null,2)}):e.jsx("p",{className:"text-muted-foreground",children:"No details available"})})})]},s.id))})})})]})}function pt(){return e.jsxs("div",{className:"space-y-6",children:[e.jsx(D,{name:"AnomalyMonitor",children:e.jsx(ht,{})}),e.jsx(D,{name:"HealthCheckResults",children:e.jsx(gt,{})})]})}const ft=["financial","payments","backlogs","crawl","health"];function Ut(){const[n,o]=He(),{data:a=0}=Os(),m=a>0?"financial":"health",i=n.get("tab"),c=N.useMemo(()=>ft.includes(i)?i:m,[i,m]),s=l=>{const x=new URLSearchParams(n);x.set("tab",l),o(x,{replace:!0})},t=()=>{c!=="financial"&&s("financial"),requestAnimationFrame(()=>{setTimeout(()=>{const l=document.getElementById("ledger-reconciliation");l&&l.scrollIntoView({behavior:"smooth",block:"start"})},60)})};return e.jsx(Ee,{title:"Data Integrity",subtitle:"Unified monitoring across financial, payment, backlog, crawl, and system health surfaces",children:e.jsxs(Ke,{maxWidth:"2xl",className:"py-6 space-y-6",children:[e.jsx(Bs,{onReviewNow:t}),e.jsxs(de,{to:"/admin/data-integrity/regions",className:"flex items-center justify-between rounded-lg border border-border/60 bg-muted/30 px-4 py-3 hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(vs,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Region Taxonomy Integrity"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Resolve ambiguous regions, coord drift, and missing state attribution"})]})]}),e.jsx(De,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx($s,{}),e.jsxs(bs,{value:c,onValueChange:s,className:"space-y-6",children:[e.jsx("div",{className:"sticky top-0 z-10 -mx-4 sm:-mx-6 px-4 sm:px-6 py-2 bg-background/95 backdrop-blur border-b border-border/60",children:e.jsxs(Ns,{className:"h-auto p-1 flex flex-wrap gap-1",children:[e.jsxs(J,{value:"financial",className:"gap-2",children:["Financial Integrity",a>0&&e.jsx(p,{variant:"destructive",className:"h-5 px-1.5 text-[10px]",children:a})]}),e.jsx(J,{value:"payments",children:"Payments & Checkout"}),e.jsx(J,{value:"backlogs",children:"Integrations & Backlogs"}),e.jsx(J,{value:"crawl",children:"Crawl & SEO Health"}),e.jsx(J,{value:"health",children:"System Health"})]})}),e.jsx(Y,{value:"financial",className:"mt-0",children:e.jsx(D,{name:"FinancialTab",children:e.jsx(Gs,{})})}),e.jsx(Y,{value:"payments",className:"mt-0",children:e.jsx(D,{name:"PaymentsTab",children:e.jsx(it,{})})}),e.jsx(Y,{value:"backlogs",className:"mt-0",children:e.jsx(D,{name:"BacklogsTab",children:e.jsx(ot,{})})}),e.jsx(Y,{value:"crawl",className:"mt-0",children:e.jsx(D,{name:"CrawlSeoTab",children:e.jsx(xt,{})})}),e.jsx(Y,{value:"health",className:"mt-0",children:e.jsx(D,{name:"SystemHealthTab",children:e.jsx(pt,{})})})]})]})})}export{Ut 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.