PageSourceSearch

https://tariffrecoveryagency.com/assets/Leads-DJBUM0y1.js

js tariffrecoveryagency.com collected 2026-09-24 13:32:17 UTC 200,696 bytes, 2 lines download raw bytes

1import{j as e,u as oe,c as Zt,k as Rn}from"./vendor-query-DUki8u-D.js";import{r as d,L as Dn,e as Rr,f as Dr}from"./vendor-react-DHU755GE.js";import{S as Pr}from"./SyncedTopScrollbar-CNqTG-oM.js";import{C as ja,a as Pn,b as Mn,c as va}from"./card-DHYvmiDl.js";import{w as je,B as L,o as T,h as G,I as gs,D as Vs,a as Hs,b as Ws,c as Ks,u as Jt,r as Tn,av as Ls,aN as En,aD as Mr,aE as fe,aF as ge,aG as _e,A as ia,C as la,E as oa,F as ca,J as rn,G as Vt,aJ as Tr}from"./App-DQmYVKnt.js";import{r as ya,i as ln,a as on,c as cn,b as Er}from"./claim-buckets-Cl_CKEqx.js";import{a6 as _s,bH as ps,L as J,R as at,a7 as Ln,b7 as Lr,q as Aa,a as gt,c2 as Yt,bW as wa,Q as $r,bc as fs,h as Qs,bV as Fr,b as Ft,c3 as Ir,_ as $n,c4 as Na,bb as dn,bd as Fn,aL as Or,S as Gt,t as In,C as On,bP as zs,T as Kt,af as un,W as mn,Z as ka,$ as $t,b2 as xs,b_ as qr,c5 as zr,c6 as Br,X as Qt,a_ as Ra,d as bs,bz as Sa,aK as Da,bQ as Pa,E as Ur,J as Vr,e as qn,c7 as hn,bC as Hr,aD as Wr,az as Kr,bL as Qr,F as xn,a0 as $s,aB as Yr,aJ as Gr,c8 as Zr,c9 as Jr,U as Xr,ca as ei,aW as ti,l as pn,aq as si,cb as ai,bB as ni,cc as ri,r as ii,B as fn,aA as li,a1 as Bs,D as oi,cd as da,aP as ci,v as di,av as ui}from"./vendor-icons-DQUIN5dH.js";import{R as zn,C as Bn,X as Un,Y as Vn,T as Hn,a as mi,f as Us,A as hi,g as Wn}from"./vendor-charts-DsctC1NR.js";import{T as xi,a as pi,b as ua,c as xe,d as fi,e as me}from"./table-uHaw-k-P.js";import{S as Ne,a as ke,b as Se,c as Ce,d as q}from"./select-DEQ3_uib.js";import{C as gn}from"./checkbox-CTRyYrqf.js";import{T as Kn,a as gi,b as _i,c as st}from"./tabs-Djw7dsBS.js";import{S as _n}from"./searchable-select-BZmh5MQG.js";import{B as bi}from"./crm-vocab-DnrV6RXz.js";import{P as ma,a as ha,b as xa}from"./popover-C6o8MEOf.js";import{A as ji,b as vi,c as yi,d as wi,e as Ni,f as ki,g as Si,h as Ci}from"./alert-dialog-D4eg6Jhx.js";import{C as Ai}from"./calendar-BV-qu9eX.js";import{S as Ri,a as bn}from"./funding-stages-UQVxNn-_.js";import{E as Di}from"./EmptyState-p9fo--HU.js";import{supabase as _}from"./client-CNze1gAi.js";import{r as Pi}from"./anchor-source-of-truth-CjWj8hjg.js";import{g as Mi,a as Ca,b as jn,f as ft,c as pa,d as Ti}from"./lead-est-recovery-DzLSo3WB.js";import{S as Ei,I as Li,C as $i}from"./IorStatusBadge-zpqOu3hl.js";import{S as Fi,a as Ii}from"./ScoringReferenceDialog-K0hpVwVz.js";import{S as Oi}from"./scroll-area-D4nk6JJE.js";import{f as Oe}from"./formatDistanceToNow-CD_R0YjW.js";import{S as ne,a as Ve,D as Ys}from"./_ui-C8SmdWlh.js";import{f as fa}from"./format-D9x0XWGR.js";import{T as qi}from"./textarea-B-TTCajr.js";import{S as zi,b as Bi,c as Ui,d as Vi}from"./sheet-IP_txfAa.js";import{D as ga,p as Hi}from"./engagement-fee-7euqvgta.js";import{S as Qn}from"./switch-DOyMpYiY.js";import{L as Wi}from"./label-DjIaEm-j.js";import{C as Ki}from"./ClaimProgressMeter-nG-TPy0s.js";import{C as Qi}from"./CrmMasterDialog-B_iBGRe9.js";import{V as Yi}from"./ViewPartnerDialog-BbUt_nzr.js";import{L as Gi}from"./LeadSourceCell-BCJ7BMfh.js";import{L as Zi}from"./LeadCrmMegaCell-XCIVJI9I.js";import{u as Ji}from"./useLeadCrmSummary-3m-gSYN3.js";import{T as Xi}from"./TestClaimBadge-D5hE5OpV.js";import{n as Wt,a as Ht,g as vn,b as yn,S as el,c as tl,A as sl,R as al}from"./claim-constants-F6TZxwZ5.js";import{u as nl}from"./useCommissionSettings-DaToM9ua.js";import{detectTestClaim as Fs}from"./test-claim-detector-C7yWOzH7.js";import{C as rl}from"./ClaimOriginBadge-Dpa5ossa.js";import{A as il}from"./AceAccessStalledBanner-D4Dj_pG_.js";import"./vendor-pdf-BQwOdAin.js";import"./error-reporter-CRL-ULrG.js";import"./breadcrumbs-CN3GC8vy.js";import"./useTheme-CHHwG8SV.js";import"./vendor-supabase-D2XPrbcR.js";import"./vendor-motion-DoyUfQ58.js";import"./index-BdQq_4o_.js";import"./index-BFcYZw7s.js";import"./command-9XjRGhO4.js";import"./isSameDay-BWv5-M0E.js";import"./subDays-BK6vuqdz.js";import"./en-US-BqCXNUOZ.js";import"./startOfMonth-D3_3nocY.js";import"./endOfMonth-B_n1vX73.js";import"./addMonths-Dw7XJecM.js";import"./differenceInCalendarMonths-BSRE4gQg.js";import"./separator-Bfjb0NJN.js";import"./getRoundingMethod-Cs3-IipQ.js";import"./useCrmMutations-Bs680D5y.js";import"./quo-deeplink-CB_LA5H-.js";import"./StatusBadge-B9-YHP1u.js";import"./async-partner-select-o9mL7vxv.js";import"./CommissionTreeView-BZudmMC8.js";import"./CommissionWaterfallCard-CMTtrrHA.js";import"./commission-simulator-BnG1RJMf.js";import"./AgreementRowActions-C0jDCGNi.js";import"./agreement-pdf-kzFV7GOn.js";import"./AgreementViewer-DAkfI7IH.js";import"./SignaturePad-B1CX7pmq.js";import"./stored-agreement-pdf-DdXVzm1i.js";import"./agreement-filename-9SsE_bIj.js";import"./stored-partner-agreement-pdf-zuVps8pX.js";import"./agreement-tokens-ymTpCioY.js";import"./parseISO-CIZr9Bmv.js";import"./comp-display-xTmOxSyi.js";import"./alert-BEPezxuP.js";import"./tra-house-D-y556jm.js";import"./radio-group-DffN1I7j.js";import"./slider-Dr1x-V-o.js";import"./date-picker-BNMI8242.js";import"./usePartnerRates-D6K4JMoF.js";import"./friendly-password-Chc-6VHn.js";import"./org-badge-aE9KoDlJ.js";import"./formatDistanceToNowStrict-B0_ltmaX.js";const wn=[{key:"7d",label:"7d",days:7},{key:"30d",label:"30d",days:30},{key:"90d",label:"90d",days:90},{key:"ytd",label:"YTD",days:null},{key:"12m",label:"12m",days:365},{key:"all",label:"All",days:null}],_a=[{key:"total",label:"All new claims",color:"hsl(var(--foreground))"},{key:"presubmit",label:"Applying",color:"#3b82f6"},{key:"presubmission",label:"Pre-Submission",color:"#8b5cf6"},{key:"anchor",label:"Processing",color:"#f59e0b"},{key:"filed",label:"Filed",color:"#06b6d4"},{key:"refund_received",label:"Refund Received",color:"#10b981"},{key:"tra_paid",label:"TRA Paid",color:"#ca8a04"},{key:"closed",label:"Closed",color:"#64748b"}];function ll({leads:a,claimDetailsMap:o,partnerLinkMap:h,fundingMap:p}
1){const[v,S]=d.useState("30d"),[c,n]=d.useState("new"),[b,f]=d.useState(new Set(["closed"])),{series:D,from:l,to:A,totals:j}=d.useMemo(()=>{const N=new Date,x=wn.find(P=>P.key===v);let z;if(x.key==="ytd")z=new Date(N.getFullYear(),0,1);else if(x.key==="all"){const P=a.reduce((H,ce)=>{const de=new Date(ce.created_at).getTime();return isFinite(de)&&de<H?de:H},Date.now());z=new Date(P)}else z=new Date(N.getTime()-(x.days??30)*864e5);const be=P=>P.toISOString().slice(0,10),R=new Map,B=[],$=new Date(z);$.setHours(0,0,0,0);const w=new Date(N);for(w.setHours(0,0,0,0);$<=w;){const P=be($);B.push(P);const H={presubmit:0,presubmission:0,anchor:0,filed:0,refund_received:0,tra_paid:0,closed:0,total:0};R.set(P,H),$.setDate($.getDate()+1)}const V={presubmit:0,presubmission:0,anchor:0,filed:0,refund_received:0,tra_paid:0,closed:0,total:0};a.forEach(P=>{var ue;const H=new Date(P.created_at);if(!isFinite(H.getTime())||H<z||H>w)return;const ce=be(H),de=R.get(ce);if(!de)return;const ve=ya({lead:P,claimDetails:o[P.id],hasProcessorLink:!!((ue=h[P.id])!=null&&ue.external_claim_id),advanceFunding:p[P.id]});de[ve]=(de[ve]||0)+1,de.total=(de.total||0)+1,V[ve]=(V[ve]||0)+1,V.total+=1});let Z=B.map(P=>({day:P,...R.get(P)}));if(c==="cumulative"){const P={presubmit:0,presubmission:0,anchor:0,filed:0,refund_received:0,tra_paid:0,closed:0,total:0};Z=Z.map(H=>(Object.keys(P).forEach(ce=>{P[ce]+=Number(H[ce]||0)}),{day:H.day,...P}))}return Z=Z.map(P=>({...P,dayLabel:new Date(P.day).toLocaleDateString("en-US",{month:"short",day:"numeric"})})),{series:Z,from:z,to:w,totals:V}},[a,o,h,p,v,c]),y=N=>{f(x=>{const z=new Set(x);return z.has(N)?z.delete(N):z.add(N),z})},k=c==="cumulative"?hi:Wn,C=`${l.toLocaleDateString(void 0,{month:"short",day:"numeric"})} – ${A.toLocaleDateString(void 0,{month:"short",day:"numeric"})}`;return e.jsxs(ja,{children:[e.jsx(Pn,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs(Mn,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(_s,{className:"h-4 w-4 text-gold"}),"Pipeline trend",e.jsxs("span",{className:"text-[11px] font-normal text-muted-foreground",children:["· ",C]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx("div",{className:"inline-flex rounded-md border border-border bg-muted/40 p-0.5",children:wn.map(N=>e.jsx("button",{onClick:()=>S(N.key),className:je("px-2 py-1 text-[11px] font-medium rounded transition",v===N.key?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:N.label},N.key))}),e.jsx("div",{className:"inline-flex rounded-md border border-border bg-muted/40 p-0.5 ml-1",children:["new","cumulative"].map(N=>e.jsx("button",{onClick:()=>n(N),className:je("px-2 py-1 text-[11px] font-medium rounded transition capitalize",c===N?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:N==="new"?"New / day":"Cumulative"},N))})]})]})}),e.jsxs(va,{className:"space-y-2",children:[e.jsx("div",{className:"h-64 sm:h-72",children:e.jsx(zn,{width:"100%",height:"100%",children:e.jsxs(k,{data:D,margin:{top:6,right:12,left:0,bottom:0},children:[e.jsx("defs",{children:_a.map(N=>e.jsxs("linearGradient",{id:`grad-${N.key}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:N.color,stopOpacity:.35}),e.jsx("stop",{offset:"100%",stopColor:N.color,stopOpacity:0})]},N.key))}),e.jsx(Bn,{strokeDasharray:"3 3",opacity:.2}),e.jsx(Un,{dataKey:"dayLabel",tick:{fontSize:10},minTickGap:24}),e.jsx(Vn,{tick:{fontSize:10},allowDecimals:!1}),e.jsx(Hn,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",fontSize:11,borderRadius:6},labelStyle:{fontWeight:600}}),_a.filter(N=>!b.has(N.key)).map(N=>c==="cumulative"?e.jsx(mi,{type:"monotone",dataKey:N.key,name:N.label,stroke:N.color,strokeWidth:N.key==="total"?2:1.5,fill:N.key==="total"?"transparent":`url(#grad-${N.key})`,dot:!1,activeDot:{r:3}},N.key):e.jsx(Us,{type:"monotone",dataKey:N.key,name:N.label,stroke:N.color,strokeWidth:N.key==="total"?2.25:1.75,dot:!1,activeDot:{r:3}},N.key))]})})}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap pt-1",children:[_a.map(N=>{const x=b.has(N.key),z=j[N.key]||0;return e.jsxs("button",{onClick:()=>y(N.key),className:je("group inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11px] transition",x?"border-border bg-muted/30 text-muted-foreground line-through":"border-border bg-card hover:border-foreground
1/40"),title:x?"Show series":"Hide series",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:N.color}}),e.jsx("span",{className:"font-medium",children:N.label}),e.jsx("span",{className:je("tabular-nums",x?"":"text-muted-foreground"),children:z.toLocaleString()})]},N.key)}),e.jsxs("div",{className:"ml-auto text-[10px] text-muted-foreground inline-flex items-center gap-1",children:[e.jsx(ps,{className:"h-3 w-3"})," Tap a series to hide / show"]})]})]})]})}const ol=["pull-anchor-claim","parse-anchor-summary-workbook","parse-anchor-ace-sources","parse-anchor-supplemental","sweep-anchor-workbooks","recategorize-anchor-docs","download-anchor-document"];function cl(){const a=oe({queryKey:["anchor-errors-list"],queryFn:async()=>{const{data:o,error:h}=await _.from("error_log").select("id, last_seen_at, source, error_type, message, details, route").in("source",ol).order("last_seen_at",{ascending:!1}).limit(200);if(h)throw h;return o||[]}});return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Last 30 days · newest 200"}),e.jsxs(L,{size:"sm",variant:"ghost",onClick:()=>a.refetch(),className:"gap-1",children:[a.isFetching?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(at,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),a.isLoading?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):(a.data||[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-12",children:"No Anchor errors logged 🎉"}):(a.data||[]).map(o=>e.jsxs("div",{className:"rounded-md border border-border bg-muted/20 p-3 space-y-1.5 text-xs",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(T,{variant:"outline",className:"text-[10px] font-mono",children:o.source}),o.error_type&&e.jsx(T,{variant:"outline",className:"text-[10px] bg-destructive/10 text-destructive border-destructive/30",children:o.error_type}),e.jsx("span",{className:"text-muted-foreground ml-auto",children:Oe(new Date(o.last_seen_at),{addSuffix:!0})})]}),e.jsx("div",{className:"text-foreground break-words whitespace-pre-wrap font-medium",children:o.message||"—"}),o.details&&e.jsxs("details",{className:"text-[10px]",children:[e.jsx("summary",{className:"cursor-pointer text-muted-foreground hover:text-foreground",children:"details"}),e.jsx("pre",{className:"mt-1 overflow-x-auto rounded bg-background/60 p-2 font-mono text-[10px]",children:JSON.stringify(o.details,null,2)})]})]},o.id))]})}function dl({rollup:a}){var n;const o=oe({queryKey:["sync-monitor-feed"],refetchInterval:3e4,queryFn:async()=>{const b=new Date(Date.now()-6048e5).toISOString(),[f,D,l,A]=await Promise.all([_.from("anchor_document_parse_log").select("id, parsed_at, lead_id, file_name, success, extraction_confidence, unknown_bucket_labels, phase_totals, error_message").gte("parsed_at",b).order("parsed_at",{ascending:!1}).limit(25),_.from("anchor_documents").select("id, lead_id, file_name, derived_kind, created_at").gte("created_at",b).order("created_at",{ascending:!1}).limit(25),_.from("error_log").select("id, source, error_type, message, last_seen_at").in("source",["pull-anchor-claim","parse-anchor-summary-workbook","parse-anchor-ace-sources","sweep-anchor-workbooks","parse-anchor-monitoring-report"]).gte("last_seen_at",b).order("last_seen_at",{ascending:!1}).limit(15),_.from("anchor_refund_receipts").select("id, lead_id, status, total, received_date, created_at").gte("created_at",b).order("created_at",{ascending:!1}).limit(15)]),j=[];return(f.data||[]).forEach(y=>j.push({at:y.parsed_at,kind:"parse",icon:y.success?gt:Ft,tone:y.success?"success":"destructive",text:`Parsed ${y.file_name||"workbook"}${y.extraction_confidence!=null?` (conf ${Math.round(y.extraction_confidence*100)}%)`:""}${!y.success&&y.error_message?` — ${y.error_message.slice(0,100)}`:""}${Array.isArray(y.unknown_bucket_labels)&&y.unknown_bucket_labels.length>0?` · ${y.unknown_bucket_labels.length} unknown labels`:""}`}
1)),(D.data||[]).forEach(y=>j.push({at:y.created_at,kind:"doc",icon:Ir,tone:y.derived_kind==="other"?"warning":"primary",text:`Ingested ${y.file_name} [${y.derived_kind}]`})),(l.data||[]).forEach(y=>{var k;return j.push({at:y.last_seen_at,kind:"error",icon:Ft,tone:"destructive",text:`${y.source}: ${((k=y.message)==null?void 0:k.slice(0,140))||"error"}`})}),(A.data||[]).forEach(y=>j.push({at:y.created_at,kind:"receipt",icon:$n,tone:y.status==="received"?"success":y.status==="rejected_no_ach"?"destructive":"warning",text:`Refund ${y.status.replace(/_/g," ")}${y.total?` — ${G(Number(y.total))}`:""}`})),j.sort((y,k)=>new Date(k.at).getTime()-new Date(y.at).getTime()).slice(0,40)}}),h=a?a.parses_ok_24h+a.parses_fail_24h>0?Math.round(a.parses_ok_24h/(a.parses_ok_24h+a.parses_fail_24h)*100):100:0,p={success:"bg-success/10 text-success border-success/30",destructive:"bg-destructive/10 text-destructive border-destructive/30",warning:"bg-warning/10 text-warning border-warning/30",primary:"bg-primary/10 text-primary border-primary/30",muted:"bg-muted text-muted-foreground border-border"},[v,S]=d.useState(!0),c=oe({queryKey:["sync-monitor-unknown-top"],refetchInterval:12e4,queryFn:async()=>{const b=new Date(Date.now()-6048e5).toISOString(),{data:f}=await _.from("anchor_documents").select("file_name").eq("derived_kind","other").eq("mirror_status","mirrored").is("removed_at",null).gte("created_at",b).limit(500),D=new Map;for(const l of f??[]){const A=(l.file_name||"unknown").replace(/^.*[\\/]/,"").replace(/\s+\(\d+\)/,"");D.set(A,(D.get(A)??0)+1)}return Array.from(D.entries()).sort((l,A)=>A[1]-l[1]).slice(0,5)}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>S(b=>!b),className:"w-full flex items-center justify-between gap-2 px-4 py-2.5 text-left hover:bg-primary/10 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:"How Anchor Sync works"})]}),v?e.jsx(Lr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Aa,{className:"h-4 w-4 text-muted-foreground"})]}),v&&e.jsxs("div",{className:"px-4 pb-3 pt-1 text-xs text-muted-foreground space-y-2 leading-relaxed",children:[e.jsxs("p",{children:["Every ",e.jsx("b",{className:"text-foreground",children:"3 hours"})," a scheduled job (",e.jsx("code",{className:"text-[10px] bg-muted rounded px-1",children:"pull-anchor-claim"}),") calls Anchor's API for every claim you have linked. For each claim we:"]}),e.jsxs("ol",{className:"list-decimal ml-4 space-y-1",children:[e.jsxs("li",{children:["Save a ",e.jsx("b",{children:"snapshot"})," of the raw payload (stage, phase totals, doc list) so we can diff future pulls."]}),e.jsxs("li",{children:[e.jsx("b",{children:"Mirror"})," any new documents into private storage so they're readable after Anchor's signed URLs expire."]}),e.jsxs("li",{children:["If a ",e.jsx("b",{children:"Summary Workbook"})," is present, kick off the parser. When both a snapshot AND a parsed summary exist, the lead flips to ",e.jsx("b",{className:"text-success",children:"Anchor-Backed"})," (safe to show clients & funders)."]}),e.jsxs("li",{children:["If a ",e.jsx("b",{children:"REV-603 / REV-615"})," monitoring report is present, kick off the refund parser to write to ",e.jsx("code",{className:"text-[10px] bg-muted rounded px-1",children:"anchor_refund_receipts"}),"."]})]}),e.jsxs("p",{children:["30 minutes after each pull, ",e.jsx("code",{className:"text-[10px] bg-muted rounded px-1",children:"sweep-anchor-workbooks"})," retries any workbook that failed the first time. Every 2 hours we refresh Anchor's status label cache. Nightly we alert Slack on unmatched filenames, mirror failures, and TRA↔Anchor drift."]}),e.jsxs("p",{children:[e.jsx("b",{className:"text-foreground",children:"Reading the header:"})," Last Pull = most recent successful call. Docs·24h = new/updated docs mirrored. Parses ✓/✗ = workbook parse results. Backed Leads = leads that hit the ",e.jsx("code",{className:"text-[10px] bg-muted rounded px-1",children:"isAnchorBacked=true"})," bar. Refunds·30d = refund receipts parsed from REV-603/615."]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(ne,{icon:gt,label:"Parse success · 24h",value:`${h}%`,hint:`${(a==null?void 0:a.parses_ok_24h)??0} ok · ${(a==null?void 0:a.parses_fail_24h)??0} failed`,tone:h>=95?"success":h>=80?"warning":"destructive"}),e.jsx(ne,{icon:Yt,label:"Unknown files awaiting review",value:(a==null?void 0:a.unknown_files)??0,hint:"New Anchor filenames the categorizer didn't recognize",tone:((a==null?void 0:a.unknown_files)??0)>0?"warning":"muted"}),e.jsx(ne,{icon:_s,label:"Refunds received · 30d",value:(a==null?void 0:a.refund_receipts_30d)??0,hint:`${(a==null?void 0:a.refund_attempted_no_ach)??0} attempted-but-no-ACH`,tone:"success"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ne,{icon:wa,label:"Avg pull duration · 24h",value:a!=null&&a.avg_pull_duration_ms_24h?`${(a.avg_pull_duration_ms_24h/1e3).toFixed(1)}s`:"—",hint:`${(a==null?void 0:a.pulls_24h)??0} pulls in last 24h`,tone:"primary"}),e.jsx(ne,{icon:$r,label:"Docs mirrored · 7d",value:(a==null?void 0:a.docs_mirrored_7d)??"—",hint:((a==null?void 0:a.docs_mirror_failed_7d)??0)>0?`${a.docs_mirror_failed_7d} mirror failures`:"no mirror failures",tone:((a==null?void 0:a.docs_mirror_failed_7d)??0)>0?"warning":"success"}),e.jsx(ne,{icon:fs,label:"Snapshot-only leads",value:(a==null?void 0:a.snapshot_only_leads)??"—",hint:"Have raw 
1snapshot but no parsed summary — not yet Anchor-Backed",tone:((a==null?void 0:a.snapshot_only_leads)??0)>0?"warning":"muted"}),e.jsx(ne,{icon:Qs,label:"Reconcile mismatches",value:(a==null?void 0:a.refund_attempted_no_ach)??0,hint:"Refund attempted but client had no ACH",tone:((a==null?void 0:a.refund_attempted_no_ach)??0)>0?"destructive":"muted"})]}),c.data&&c.data.length>0&&e.jsx(Ve,{icon:Yt,title:"Top unmatched filenames · 7d",subtitle:"Anchor sent these but the categorizer didn't recognize them. Extend the regex in _shared/anchor-doc-categorize.ts.",tone:"warning",bodyClassName:"p-0",children:e.jsx("div",{className:"divide-y divide-border",children:c.data.map(([b,f])=>e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-2 text-xs",children:[e.jsx("code",{className:"font-mono truncate flex-1",children:b}),e.jsxs(T,{variant:"outline",className:"text-[10px] bg-warning/10 text-warning border-warning/30",children:[f,"×"]})]},b))})}),e.jsx(Ve,{icon:ps,title:"What changed",subtitle:"Every parse, ingest, error, and refund receipt over the last 7 days",actions:e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"newest 40 events"}),tone:"primary",bodyClassName:"p-0",children:o.isLoading?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):(n=o.data)!=null&&n.length?e.jsx("div",{className:"divide-y divide-border",children:o.data.map((b,f)=>{const D=b.icon;return e.jsxs("div",{className:"flex items-start gap-3 px-4 py-2.5 hover:bg-muted/30 transition-colors",children:[e.jsx("span",{className:je("inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full border",p[b.tone]??p.muted),children:e.jsx(D,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"break-words text-xs text-foreground",children:b.text}),e.jsxs("div",{className:"mt-0.5 text-[10px] uppercase tracking-wider text-muted-foreground",children:[Oe(new Date(b.at),{addSuffix:!0})," · ",b.kind]})]})]},f)})}):e.jsxs("div",{className:"py-14 text-center",children:[e.jsx(Fr,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"No activity in the last 7 days."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"All quiet — Anchor hasn't sent anything new."})]})})]})}const ul={"pull-anchor-claim":{label:"Pull",cls:"bg-primary/10 text-primary border-primary/30"},"sweep-anchor-workbooks":{label:"Sweep",cls:"bg-cyan/10 text-cyan border-cyan/30"},"sync-anchor-statuses":{label:"Statuses",cls:"bg-gold/10 text-gold border-gold/30"}};function ml(){var D;const[a,o]=d.useState("all"),[h,p]=d.useState("all"),[v,S]=d.useState(""),[c,n]=d.useState(null),b=oe({queryKey:["sync-monitor-runs",a,h,v],refetchInterval:6e4,queryFn:async()=>{let l=_.from("anchor_sync_log").select("id, source, started_at, finished_at, duration_ms, status, http_status, triggered_by, lead_id, docs_seen, docs_new, docs_updated, docs_removed, snapshot_changed, summary_changed, error, created_at").order("created_at",{ascending:!1}).limit(200);a!=="all"&&(l=l.eq("source",a)),h!=="all"&&(l=l.eq("status",h)),v.trim()&&(l=l.ilike("lead_id",`${v.trim()}%`));const{data:A}=await l;return A??[]}}),f=d.useMemo(()=>{const l=b.data??[];return{total:l.length,running:l.filter(A=>A.status==="running").length,success:l.filter(A=>A.status==="success"||A.status==="ok").length,err:l.filter(A=>A.status==="error"||A.status==="failed").length}},[b.data]);return e.jsxs(e.Fragment,{children:[e.jsxs(Ve,{icon:Na,title:"Sync pulses",subtitle:`Every Anchor sync request — API pulls, sweeps, status refreshes, and manual re-runs · ${f.success} ok · ${f.err} errored · ${f.running} running`,actions:e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"newest 200 entries"}),tone:"cyan",bodyClassName:"p-0",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 p-3 border-b border-border bg-muted/20",children:[e.jsxs(Ne,{value:a,onValueChange:o,children:[e.jsx(ke,{className:"h-8 text-xs",children:e.jsx(Se,{placeholder:"Source"})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"all",children:"All sources"}),e.jsx(q,{value:"pull-anchor-claim",children:"Pull (every 3h)"}),e.jsx(q,{value:"sweep-anchor-workbooks",children:"Sweep (every 3h + 30m)"}),e.jsx(q,{value:"sync-anchor-statuses",children:"Statuses (every 2h)"})]})]}),e.jsxs(Ne,{value:h,onValueChange:p,children:[e.jsx(ke,{className:"h-8 text-xs",children:e.jsx(Se,{placeholder:"Status"})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"all",children:"All statuses"}),e.jsx(q,{value:"success",children:"Success"}),e.jsx(q,{value:"running",children:"Running"}),e.jsx(q,{value:"partial",children:"Partial"}),e.jsx(q,{value:"error",children:"Error"}),e.jsx(q,{value:"noop",children:"Noop"})]})]}),e.jsx(gs,{placeholder:"Filter by lead id prefix…",value:v,onCh
1ange:l=>S(l.target.value),className:"h-8 text-xs font-mono"})]}),b.isLoading?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):(D=b.data)!=null&&D.length?e.jsxs(Ys,{className:"rounded-none border-0",children:[e.jsx("thead",{className:"bg-muted/40 text-muted-foreground text-[10px] uppercase tracking-wider",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"When"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Source"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Trigger"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Status"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"HTTP"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Duration"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Docs"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Lead"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Error"})]})}),e.jsx("tbody",{children:b.data.map(l=>{var B;const A=l.status==="success"||l.status==="ok",j=l.status==="error"||l.status==="failed",y=l.status==="partial",k=l.status==="running",C=l.status==="noop",N=A?gt:j?Ft:k?J:C?dn:dn,x=A?"text-success":j?"text-destructive":y?"text-warning":k?"text-primary":"text-muted-foreground",z=l.http_status>=500?"text-destructive font-semibold":l.http_status===429?"text-warning font-semibold":l.http_status>=400?"text-warning":l.http_status>=200&&l.http_status<300?"text-success":"text-muted-foreground",be=ul[l.source]??{label:l.source||"—",cls:"bg-muted text-muted-foreground border-border"},R=[l.docs_seen,l.docs_new,l.docs_updated,l.docs_removed].some($=>typeof $=="number"&&$>0)?`${l.docs_seen??0}/${l.docs_new??0}/${l.docs_updated??0}${l.docs_removed?`/-${l.docs_removed}`:""}`:"—";return e.jsxs("tr",{className:"border-t border-border hover:bg-muted/30 transition-colors cursor-pointer",onClick:()=>n(l),children:[e.jsx("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",title:fa(new Date(l.created_at),"yyyy-MM-dd HH:mm:ss"),children:Oe(new Date(l.created_at),{addSuffix:!0})}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(T,{variant:"outline",className:je("text-[10px]",be.cls),children:be.label})}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(T,{variant:"outline",className:"text-[9px] capitalize",children:l.triggered_by||"—"})}),e.jsx("td",{className:je("px-3 py-2",x),children:e.jsxs("span",{className:"inline-flex items-center gap-1 font-medium capitalize",children:[e.jsx(N,{className:je("h-3 w-3",k&&"animate-spin")}),l.status||"—"]})}),e.jsx("td",{className:je("px-3 py-2 text-right tabular-nums",z),children:l.http_status??"—"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-muted-foreground text-[10px]",children:l.duration_ms?`${(l.duration_ms/1e3).toFixed(1)}s`:"—"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-[10px] text-muted-foreground",title:"seen/new/updated/removed",children:R}),e.jsx("td",{className:"px-3 py-2 font-mono text-[10px] text-muted-foreground truncate max-w-[100px]",children:((B=l.lead_id)==null?void 0:B.slice(0,8))||"—"}),e.jsx("td",{className:"px-3 py-2 text-destructive text-[10px] truncate max-w-[300px]",children:l.error||""})]},l.id)})})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-12",children:"No sync runs match these filters."})]}),e.jsx(Vs,{open:!!c,onOpenChange:l=>!l&&n(null),children:e.jsxs(Hs,{className:"max-w-2xl",children:[e.jsx(Ws,{children:e.jsxs(Ks,{className:"flex items-center gap-2 text-sm",children:[e.jsx(Na,{className:"h-4 w-4 text-cyan"})," Sync pulse detail"]})}),c&&e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(tt,{label:"Source",value:c.source}),e.jsx(tt,{label:"Status",value:c.status}),e.jsx(tt,{label:"Triggered by",value:c.triggered_by}),e.jsx(tt,{label:"HTTP",value:c.http_status??"—"}),e.jsx(tt,{label:"Started",value:c.started_at?fa(new Date(c.started_at),"yyyy-MM-dd HH:mm:ss"):"—"}),e.jsx(tt,{label:"Finished",value:c.finished_at?fa(new Date(c.finished_at),"yyyy-MM-dd HH:mm:ss"):"—"}),e.jsx(tt,{label:"Duration",value:c.duration_ms?`${(c.duration_ms/1e3).toFixed(2)}s`:"—"}),e.jsx(tt,{label:"Lead",value:c.lead_id||"—",mono:!0}),e.jsx(tt,{label:"Docs seen / new / updated / removed",value:`${c.docs_seen??0} / ${c.docs_new??0} / ${c.docs_updated??0} / ${c.docs_removed??0}`}),e.jsx(tt,{label:"Snapshot changed",value:c.snapshot_changed?"yes":"no"}),e.jsx(tt,{label:"Summary changed",value:c.summary_changed?"yes":"no"})]}),c.error&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mt-2 mb-1",children:"Error"}),e.jsx("pre",{className:"text-[11px] bg-destructive/5 text-destructive border border-destructive/20 rounded p-2 whitespace-pre-wrap font-mono",children:c.error})]})]})]})})]})}function tt({label:a,value:o,mono:h}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider text-muted-foreground",children:a}),e.jsx("div",{className:je("text-xs font-medium text-foreground break-all",h&&"font-mono"),children:String(o??"—")})]})}const hl=["ace.es001","ace.es003","ace.es501","ace.es502","ace.es504","ace.es701","ace.es702","ace.rev103","ace.rev104","calc.summary_workbook","calc.claim_workbook","submission.cape_phase1_csv","submission.phase1_2_combined_csv","submission.cape_es022","submission.image","refund.rev603_paid","refund.rev613_returned","refund.rev615_detail","irs.transcript_audit_workbook","irs.transcript_1120s_return","irs.transcript_1120s_account","
1irs.transcript_1120_return","irs.transcript_1120_account","irs.transcript_1040_return","irs.transcript_1040_account","irs.transcript_941_return","irs.transcript_941_account","irs.transcript_civil_penalty","kyb.cert_incorporation","kyb.ein_letter","agreement.engagement","agreement.8821","agreement.lpoa","agreement.7216","external.tra_marketing","external.tra_invoice","external.tra_guide","external.client_upload","other"],Et=[{id:"signed-agreement",source:"internal",pattern:"signed / 8821 / 7216 / lpoa / engagement",kind:"agreement.*"},{id:"ace-es-nnn",source:"internal",pattern:"es_001..702, rev_103..104",kind:"ace.*"},{id:"cape-es022",source:"internal",pattern:"es_022 | cape_entry_summary_report",kind:"submission.cape_es022"},{id:"phase1-csv",source:"internal",pattern:"phase 1 (& 2) csv",kind:"submission.cape_phase1_csv"},{id:"refund-rev",source:"internal",pattern:"rev-603/613/615 / trade_refund_report",kind:"refund.*"},{id:"irs-transcript",source:"internal",pattern:"1120 / 1120S / 1040 / 941 transcripts, civil penalty",kind:"irs.*"},{id:"kyb-doc",source:"internal",pattern:"certificate_of_incorporation / ein_letter / cp575",kind:"kyb.*"},{id:"calc-workbook",source:"internal",pattern:"ieepa refund calculation / summary_workbook / claim_workbook",kind:"calc.*"},{id:"tra-flyer",source:"external",pattern:"^tra_flyer",kind:"external.tra_marketing"},{id:"tra-invoice",source:"external",pattern:"^inv_YYYY_NNNNN.pdf",kind:"external.tra_invoice"},{id:"tra-guide",source:"external",pattern:"ace_entry_status_guide / final_steps / tra_master_resource / ieepa_faq",kind:"external.tra_guide"},{id:"client-upload",source:"mirrored",pattern:"dhl / fedex / ups / shipment_charges / payment_portal",kind:"external.client_upload"},{id:"fallback-other",source:"internal",pattern:"no rule matched",kind:"other"}];function xl(a,o){const h=(a||"").toLowerCase(),p=Et.find(n=>n.kind===o),v=o.split(".")[0],S=Et.find(n=>n.kind===`${v}.*`);return/^tra[_\-]?flyer/.test(h)&&Et.find(n=>n.id==="tra-flyer")||/^inv[_\-]?\d{4}/.test(h)&&Et.find(n=>n.id==="tra-invoice")||/(dhl|fedex|ups|shipment_charges|payment_portal)/.test(h)&&Et.find(n=>n.id==="client-upload")||p||S||Et[Et.length-1]}function pl({documentId:a,open:o,onClose:h}){const{toast:p}=Jt(),v=Zt(),[S,c]=d.useState(""),[n,b]=d.useState(""),[f,D]=d.useState(!1),l=oe({enabled:!!a&&o,queryKey:["anchor-doc-inspect",a],queryFn:async()=>{const{data:C}=await _.from("anchor_documents").select("id, file_name, category, category_display, derived_kind, classification_source, classification_rule_id, classification_matched_pattern, classification_overridden, mirror_status").eq("id",a).maybeSingle();return C}}),A=oe({enabled:!!a&&o,queryKey:["anchor-doc-override",a],queryFn:async()=>{const{data:C}=await _.from("anchor_classification_overrides").select("*").eq("document_id",a).maybeSingle();return C}}),j=l.data,y=d.useMemo(()=>j?xl(j.file_name,j.derived_kind||"other"):null,[j]);async function k(){if(!(!a||!S)){D(!0);try{const C=(await _.auth.getUser()).data.user,{error:N}=await _.from("anchor_classification_overrides").upsert({document_id:a,override_kind:S,override_source:"admin_manual",reason:n||null,actor_id:(C==null?void 0:C.id)??null},{onConflict:"document_id"});if(N)throw N;p({title:"Override saved",description:`Reclassified as ${S}`}),v.invalidateQueries({queryKey:["anchor-doc-inspect",a]}),v.invalidateQueries({queryKey:["sync-monitor-unknown"]}),h()}catch(C){p({title:"Failed",description:C.message,variant:"destructive"})}finally{D(!1)}}}return e.jsx(Vs,{open:o,onOpenChange:C=>!C&&h(),children:e.jsxs(Hs,{className:"max-w-2xl",children:[e.jsx(Ws,{children:e.jsxs(Ks,{className:"flex items-center gap-2 text-base",children:[e.jsx(Fn,{className:"h-4 w-4 text-primary"})," Classification inspector"]})}),l.isLoading||!j?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(J,{className:"h-4 w-4 animate-spin"})}):e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"rounded-md border border-border p-3 bg-muted/20 space-y-1",children:[e.jsx("div",{className:"font-mono text-xs break-all",children:j.file_name}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-[10px]",children:[e.jsxs(T,{variant:"outline",children:["category: ",j.category||"OTHER"]}),e.jsxs(T,{variant:"outline",children:["derived_kind: ",j.derived_kind||"other"]}),e.jsxs(T,{variant:"outline",children:["mirror: ",j.mirror_status||"—"]}
1),j.classification_overridden&&e.jsx(T,{variant:"outline",className:"bg-warning/10 text-warning border-warning/30",children:"OVERRIDDEN"})]})]}),e.jsxs("div",{className:"rounded-md border border-border p-3 space-y-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Matched rule"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(T,{variant:"outline",className:"text-[10px]",children:["id: ",j.classification_rule_id||(y==null?void 0:y.id)]}),e.jsxs(T,{variant:"outline",className:"text-[10px]",children:["source: ",j.classification_source||(y==null?void 0:y.source)]})]}),e.jsxs("div",{className:"font-mono text-[11px] text-muted-foreground break-all",children:["pattern: ",j.classification_matched_pattern||(y==null?void 0:y.pattern)]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[e.jsx("b",{children:"source"})," tells you where the file came from: ",e.jsx("code",{children:"external"})," = TRA-authored artifact mirrored back by Anchor, ",e.jsx("code",{children:"mirrored"})," = client-uploaded document Anchor is re-serving,",e.jsx("code",{children:" internal"})," = Anchor-authored data product."]})]}),e.jsxs("div",{className:"rounded-md border border-border p-3 space-y-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Override"}),e.jsxs("select",{className:"h-8 w-full rounded-md border border-border bg-background px-2 text-xs",value:S,onChange:C=>c(C.target.value),children:[e.jsx("option",{value:"",children:"— pick new derived_kind —"}),hl.map(C=>e.jsx("option",{value:C,children:C},C))]}),e.jsx(qi,{placeholder:"Why is this the right classification? (optional)",value:n,onChange:C=>b(C.target.value),className:"text-xs min-h-16"}),A.data&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Current override: ",e.jsx("code",{children:A.data.override_kind})," — ",A.data.reason||"no reason"]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(L,{size:"sm",onClick:k,disabled:!S||f,className:"gap-1.5",children:[f?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Or,{className:"h-3.5 w-3.5"}),"Save override"]})})]})]})]})})}function fl(){var D;const a=Zt(),{toast:o}=Jt(),[h,p]=d.useState(null),[v,S]=d.useState(null),c=oe({queryKey:["sync-monitor-unknown"],refetchInterval:6e4,queryFn:async()=>{const{data:l}=await _.from("anchor_documents").select("id, lead_id, file_name, category, mirror_status, file_size, created_at, mirrored_at").eq("derived_kind","other").is("removed_at",null).order("created_at",{ascending:!1}).limit(200);return l??[]}});async function n(){try{await _.functions.invoke("recategorize-anchor-docs",{body:{scope:"unknown"}}),o({title:"Recategorizing",description:"Anchor is re-classifying unknown files."}),setTimeout(()=>a.invalidateQueries({queryKey:["sync-monitor-unknown"]}),3e3)}catch(l){o({title:"Failed",description:l.message,variant:"destructive"})}}async function b(l){p(l);try{await _.functions.invoke("recategorize-anchor-docs",{body:{document_ids:[l],force_all:!0}}),o({title:"Fingerprinted",description:"Re-scanned this file."}),a.invalidateQueries({queryKey:["sync-monitor-unknown"]})}catch(A){o({title:"Failed",description:A.message,variant:"destructive"})}finally{p(null)}}async function f(l){p(l.id);try{const{error:A}=await _.from("anchor_parse_review_queue").insert({lead_id:l.lead_id,document_id:l.id,anchor_document_id:l.id,file_name:l.file_name,reason:"unknown_file_categorization",workbook_shape:"unknown",status:"pending"});if(A)throw A;o({title:"Sent to review queue",description:"An admin can approve or reject on the Needs Review tab."}),a.invalidateQueries({queryKey:["anchor-review-queue-count"]})}catch(A){o({title:"Failed",description:A.message,variant:"destructive"})}finally{p(null)}}return c.isLoading?e.jsx(Ve,{icon:Yt,title:"Unknown files",tone:"warning",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})})}):(D=c.data)!=null&&D.length?e.jsxs(Ve,{icon:Yt,title:`${c.data.length} unrecognized file${c.data.length===1?"":"s"}`,subtitle:"Extend the categorizer regex or add a filename → derived_kind mapping",tone:"warning",actions:e.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5 h-8",onClick:n,children:[e.jsx(at,{className:"h-3.5 w-3.5"})," Re-categorize"]}),bodyClassName:"p-0",children:[e.jsxs(Ys,{className:"rounded-none border-0",children:[e.jsx("thead",{className:"bg-muted/40 text-muted-foreground text-[10px] uppercase tracking-wider",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Filename"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Category"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Mirror"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Size"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Age"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Lead"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Actions"})]})}),e.jsx("tbody",{children:c.data.map(l=>{var j;const A=Math.floor((Date.now()-new Date(l.created_at).getTime())/864e5);return e.jsxs("tr",{className:"border-t border-border hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"px-3 py-2 font-mono text-[10px] break-all max-w-[420px]",children:l.file_name}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(T,{variant:"outline",className:"text-[9px]",children:l.category||"OTHER"})}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(T,{variant:"outline",className:je("text-[9px]",l.mirror_status==="mirrored"?"bg-success/10 text-success border-success/30":"bg-destructive/10 text-destructive border-destructive/30"),children:l.mirror_status||"—"})}),e.jsx("td",{className:"px-3 py-2 text-right text-muted-foreground tabular-nums",children:l.file_size?`${Math.round(l.file_size/1024)} KB`:"—"}),e.jsx("td",{className:je("px-3 py-2 whitespace-nowrap",A>3?"text-destructive font-medium":"text-muted-foreground"),children:Oe(new Date(l.created_at),{addSuffix:!0})}),e.jsx("td",{className:"px-3 py-2 font-mono text-[10px] text-muted-foreground",children:(j=l.lead_id)==null?void 0:j.slice(0,8)}),e.jsx("td",{className:"px-3 py-2 text-right whitespace-nowrap",children:e.jsxs("div",{className:"inline-flex gap-1",children:[e.jsxs(L,{size:"sm",variant:"ghost",className:"h-7 px-2 gap-1 text-[10px]",onClick:()=>S(l.id),children:[e.jsx(Gt,{className:"h-3 w-3"}),"Inspect"]}),e.jsxs(L,{size:"sm",variant:"ghost",className:"h-7 px-2 gap-1 text-[10px]",disabled:h===l.id,onClick:()=>b(l.id),children:[h===l.id?e.jsx(J,{className:"h-3 w-3 animate-spin"}):e.jsx(Fn,{className:"h-3 w-3"}),"Fingerprint"]}),e.jsxs(L,{size:"sm",variant:"ghost",className:"h-7 px-2 gap-1 text-[10px]",disabled:h===l.id,onClick:()=>f(l),children:[e.jsx(In,{className:"h-3 w-3"}),"Review"]})]})})]},l.id)})})]}),e.jsx(pl,{documentId:v,open:!!v,onClose:()=>S(null)})]}):e.jsx(Ve,{icon:gt,title:"All files classified",tone:"success",children:e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-12 w-12 items-center justify-center rounded-full bg-success/10",children:e.jsx(gt,{className:"h-6 w-6 text-success"})}),e.jsx("p",{className:"text-sm font-semibold",children:"No unknown files"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Every file Anchor has sent has been classified."})]})})}const gl={received:{label:"Received",cls:"bg-success/10 text-success border-success/30",icon:gt},partial:{label:"Partial",cls:"bg-cyan/10 text-cyan border-cyan/30",icon:Qs},attempted:{label:"Attempted",cls:"bg-warning/10 text-warning border-warning/30",icon:Kt},rejected_no_ach:{label:"Rejected · No ACH",cls:"bg-destructive/10 text-destructive border-destructive/30",icon:On},mismatch:{label:"Mismatch",cls:"bg-warning/10 text-warning border-warning/30",icon:fs}};
1function _l(){var k,C,N,x,z,be;const[a,o]=d.useState(null),[h,p]=d.useState(!1),v=Zt(),{toast:S}=Jt();async function c(){p(!0);try{const{data:R,error:B}=await _.from("anchor_documents").select("id, lead_id, file_name, derived_kind").in("derived_kind",["refund.rev603_paid","refund.rev615_detail"]).is("removed_at",null).not("lead_id","is",null);if(B)throw B;const $=R??[];if(!$.length){S({title:"Nothing to backfill",description:"No REV-603 or REV-615 documents found."});return}S({title:"Backfilling refund reports",description:`Parsing ${$.length} REV-603 / REV-615 files…`});let w=0,V=0,Z=0;for(const P of $)try{const{data:H,error:ce}=await _.functions.invoke("parse-anchor-monitoring-report",{body:{anchor_document_id:P.id,lead_id:P.lead_id}});if(ce){Z++;continue}H!=null&&H.skipped?V++:H!=null&&H.ok?w++:Z++}catch{Z++}S({title:"Backfill complete",description:`${w} parsed · ${V} already-parsed · ${Z} failed`,variant:Z>0?"destructive":"default"}),v.invalidateQueries({queryKey:["sync-monitor-receipts"]}),v.invalidateQueries({queryKey:["sync-monitor-rollup"]})}catch(R){S({title:"Backfill failed",description:R.message,variant:"destructive"})}finally{p(!1)}}const n=oe({queryKey:["sync-monitor-receipts"],refetchInterval:6e4,queryFn:async()=>{var ve;const{data:R}=await _.from("anchor_refund_receipts").select("id, lead_id, status, principal, interest, total, received_date, reconciled, reconcile_delta, reconcile_notes, updated_at, rev603_report_id, matched_rev615_report_ids").order("received_date",{ascending:!1,nullsFirst:!1}).limit(500),B=Array.from(new Set((R??[]).map(ue=>ue.lead_id).filter(Boolean)));if(B.length===0)return{rows:R??[],leadMap:new Map,feeMap:new Map,estMap:new Map,globalPct:ga};const[$,w,V,Z]=await Promise.all([_.from("leads").select("id, company_name, contact_name, contact_email").in("id",B),_.from("claim_details").select("lead_id, engagement_fee_pct, engagement_fee_pct_override").in("lead_id",B),_.from("anchor_claim_snapshots").select("lead_id, total_refund_amount, is_current, fetched_at").in("lead_id",B).eq("is_current",!0).order("fetched_at",{ascending:!1}),_.from("commission_settings").select("setting_value").eq("setting_key","default_engagement_fee_pct").maybeSingle()]),P=new Map(($.data??[]).map(ue=>[ue.id,ue])),H=new Map((w.data??[]).map(ue=>[ue.lead_id,ue])),ce=new Map;for(const ue of V.data??[])ce.has(ue.lead_id)||ce.set(ue.lead_id,Number(ue.total_refund_amount||0));const de=Number((ve=Z.data)==null?void 0:ve.setting_value)||ga;return{rows:R??[],leadMap:P,feeMap:H,estMap:ce,globalPct:de}}}),b=d.useMemo(()=>{var Z;const R=((Z=n.data)==null?void 0:Z.rows)??[],B=R.filter(P=>P.status==="received"&&P.received_date&&new Date(P.received_date)>new Date(Date.now()-30*24*3600*1e3)).reduce((P,H)=>P+Number(H.total||0),0),$=R.filter(P=>P.status==="received").reduce((P,H)=>P+Number(H.total||0),0),w=R.filter(P=>P.status==="rejected_no_ach").length,V=R.filter(P=>P.status==="mismatch").length;return{total30:B,totalYtd:$,attemptedNoAch:w,mismatches:V,count:R.length}},[n.data]),f=oe({enabled:!!a,queryKey:["receipt-detail",a],queryFn:async()=>{const{data:R}=await _.from("anchor_refund_reports").select("id, report_kind, report_date, totals, uploaded_at, doc_id").eq("lead_id",a).is("superseded_by_id",null).order("uploaded_at",{ascending:!1}),B=(R??[]).map(w=>w.id),{data:$}=B.length?await _.from("anchor_refund_line_items").select("*").in("report_id",B):{data:[]};return{reports:R??[],lines:$??[]}}});if(n.isLoading)return e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const D=((k=n.data)==null?void 0:k.rows)??[],l=((C=n.data)==null?void 0:C.leadMap)??new Map,A=((N=n.data)==null?void 0:N.feeMap)??new Map,j=((x=n.data)==null?void 0:x.estMap)??new Map,y=((z=n.data)==null?void 0:z.globalPct)??ga;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ne,{icon:$n,label:"Received · 30d",value:G(b.total30),tone:"success",hint:"Total refunded to clients in last 30 days"}),e.jsx(ne,{icon:_s,label:"Received · YTD",value:G(b.totalYtd),tone:"primary",hint:"All-time refunds confirmed by CBP"}),e.jsx(ne,{icon:On,label:"No-ACH rejections",value:b.attemptedNoAch,tone:"destructive",hint:"Refund tried but client had no ACH on file"}),e.jsx(ne,{icon:fs,label:"Reconcile mismatches",value:b.mismatches,tone:"warning",hint:"Actual differs from estimate beyond threshold"})]}),e.jsx(Ve,{icon:zs,title:"Refund receipts",subtitle:"Parsed from REV-603 and REV-615 monitoring reports · click a row for line-item detail",tone
1:"success",actions:e.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5 h-8",onClick:c,disabled:h,children:[h?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(at,{className:"h-3.5 w-3.5"}),h?"Parsing…":"Reparse all REV-603 / REV-615"]}),bodyClassName:"p-0",children:D.length===0?e.jsxs("div",{className:"py-14 text-center",children:[e.jsx(zs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"No refund reports parsed yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload a REV-603 or REV-615 to any claim and this tab will populate automatically."})]}):e.jsxs(Ys,{className:"rounded-none border-0",children:[e.jsx("thead",{className:"bg-muted/40 text-muted-foreground text-[10px] uppercase tracking-wider",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Client"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Status"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Principal"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Interest"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Total"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",title:"REV-615 line sum minus REV-603 total. Zero = perfectly reconciled.",children:"Δ vs Est."}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",title:"REV-603 report_date — date CBP disbursed the refund",children:"Received"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",title:"Contingency % owed to TRA on this claim",children:"Cont. %"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",title:"Total refund estimate from Anchor",children:"Est. Refund"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",title:"TRA fee owed on the amount received so far (Total × Cont.%)",children:"TRA Owed"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",title:"Fees still to be earned on remaining refund ((Est. − Received) × Cont.%)",children:"Outstanding"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:D.map(R=>{const B=l.get(R.lead_id),$=gl[R.status]??{label:R.status,cls:"",icon:Qs},w=$.icon,V=Number(R.reconcile_delta||0),Z=Math.abs(V)<1?"text-muted-foreground":V>0?"text-success":"text-destructive",P=[B==null?void 0:B.contact_name,B==null?void 0:B.contact_email].filter(Boolean).join(" · "),H=Hi(A.get(R.lead_id),y),ce=Number(R.total||0),de=Number(j.get(R.lead_id)||0),ve=ce*(H/100),Qe=Math.max(de-ce,0)*(H/100);return e.jsxs("tr",{className:"border-t border-border hover:bg-muted/30 transition-colors",children:[e.jsxs("td",{className:"px-3 py-2 min-w-[240px]",children:[e.jsx("div",{className:"font-semibold text-foreground",children:(B==null?void 0:B.company_name)||(B==null?void 0:B.contact_name)||e.jsx("span",{className:"text-muted-foreground italic",children:"Unknown client"})}),e.jsx("div",{className:"text-[10px] text-muted-foreground truncate max-w-[280px]",children:P||(R.lead_id?`Lead ${R.lead_id.slice(0,8)}`:"—")})]}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs(T,{variant:"outline",className:je("text-[10px] gap-1",$.cls),children:[e.jsx(w,{className:"h-3 w-3"})," ",$.label]})}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:G(Number(R.principal||0))}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-muted-foreground",children:G(Number(R.interest||0))}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums font-bold text-foreground",children:G(ce)}),e.jsx("td",{className:je("px-3 py-2 text-right tabular-nums font-medium",Z),children:R.reconcile_delta!=null?(V>0?"+":"")+G(V):"—"}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",children:R.received_date?new Date(R.received_date).toLocaleDateString():"—"}),e.jsxs("td",{className:"px-3 py-2 text-right tabular-nums",children:[H,"%"]}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-muted-foreground",children:de>0?G(de):"—"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums font-semibold text-success",children:G(ve)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-primary",children:de>0?G(Qe):"—"}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(L,{size:"sm",variant:"ghost",className:"h-7 text-xs",onClick:()=>o(R.lead_id),children:"Detail"})})]},R.id)})})]})}),e.jsx(zi,{open:!!a,onOpenChange:R=>!R&&o(null),children:e.jsxs(Bi,{side:"right",className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(Ui,{children:e.jsxs(Vi,{className:"flex items-center gap-2",children:[e.jsx(zs,{className:"h-4 w-4 text-success"}),"Refund detail"]})}),f.isLoading?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(J,{className:"h-5 w-5 animate-spin"})}
1):e.jsx("div",{className:"space-y-4 mt-4",children:(((be=f.data)==null?void 0:be.reports)??[]).map(R=>{var B;return e.jsxs("div",{className:"rounded-lg border border-border bg-card shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{variant:"outline",className:"text-[10px] uppercase font-semibold bg-primary/10 text-primary border-primary/30",children:R.report_kind}),e.jsx("span",{className:"text-xs text-muted-foreground",children:R.report_date||"—"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Oe(new Date(R.uploaded_at),{addSuffix:!0})})]}),e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx("pre",{className:"text-[10px] bg-muted/40 rounded p-2 overflow-x-auto font-mono",children:JSON.stringify(R.totals,null,2)}),R.report_kind==="rev615"&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:"Line items"}),e.jsx("div",{className:"rounded-md border border-border overflow-x-auto",children:e.jsxs("table",{className:"w-full text-[10px] font-mono",children:[e.jsx("thead",{className:"bg-muted/40 uppercase tracking-wider text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-2 py-1 font-semibold",children:"Doc #"}),e.jsx("th",{className:"text-left px-2 py-1 font-semibold",children:"Claim #"}),e.jsx("th",{className:"text-right px-2 py-1 font-semibold",children:"Principal"}),e.jsx("th",{className:"text-right px-2 py-1 font-semibold",children:"Interest"}),e.jsx("th",{className:"text-left px-2 py-1 font-semibold",children:"Port"})]})}),e.jsx("tbody",{children:(((B=f.data)==null?void 0:B.lines)??[]).filter($=>$.report_id===R.id).map($=>e.jsxs("tr",{className:"border-t border-border",children:[e.jsx("td",{className:"px-2 py-1",children:$.document_number}),e.jsx("td",{className:"px-2 py-1",children:$.claim_number}),e.jsx("td",{className:"px-2 py-1 text-right tabular-nums",children:G(Number($.refund_principal_amount||0))}),e.jsx("td",{className:"px-2 py-1 text-right tabular-nums text-muted-foreground",children:G(Number($.refund_interest_amount||0))}),e.jsx("td",{className:"px-2 py-1",children:$.port_code})]},$.id))})]})})]})]})]},R.id)})})]})})]})}function bl({rollup:a}){var j,y,k,C,N,x,z,be,R,B,$,w,V,Z,P,H,ce,de,ve,ue,Qe,kt,Xt,js,ot,vs,_t,ys,Ye,ws,bt,Ns,ct;const o=Zt(),{toast:h}=Jt(),[p,v]=d.useState(!1),[S,c]=d.useState(7),n=oe({queryKey:["anchor-sync-health-trends",S],refetchInterval:5*6e4,queryFn:async()=>{const{data:U,error:ie}=await _.rpc("anchor_sync_health_trends",{_days:S});if(ie)throw ie;return U}}),b=oe({queryKey:["anchor-sync-settings"],queryFn:async()=>{const{data:U}=await _.from("app_settings").select("key, value").in("key",["anchor_sync_paused","anchor_value_delta_alert_usd"]),ie=new Map((U??[]).map(jt=>[jt.key,jt.value]));return{paused:ie.get("anchor_sync_paused")===!0||ie.get("anchor_sync_paused")==="true",alertThreshold:Number(ie.get("anchor_value_delta_alert_usd")??5e3)}}}),f=oe({queryKey:["anchor-sync-http-stats"],refetchInterval:6e4,queryFn:async()=>{const U=new Date(Date.now()-864e5).toISOString(),{data:ie}=await _.from("anchor_sync_log").select("http_status, status").gte("created_at",U).limit(2e3),jt=(ie??[]).length,qe=(ie??[]).filter(Te=>Te.http_status>=500).length,es=(ie??[]).filter(Te=>Te.http_status>=400&&Te.http_status<500).length,ks=(ie??[]).filter(Te=>Te.http_status===429).length,Gs=(ie??[]).filter(Te=>Te.http_status>=200&&Te.http_status<300).length;return{total:jt,ok:Gs,err4xx:es,err429:ks,err5xx:qe}}});async function D(U){v(!0);try{await _.from("app_settings").upsert({key:"anchor_sync_paused",value:U},{onConflict:"key"}),h({title:U?"Anchor sync paused":"Anchor sync resumed",description:U?"Cron jobs will still fire but edge functions will short-circuit.":"3-hour cadence active."}),o.invalidateQueries({queryKey:["anchor-sync-settings"]})}catch(ie){h({title:"Failed",description:ie.message,variant:"destructive"})}finally{v(!1)}}async function l(U){await _.from("app_settings").upsert({key:"anchor_value_delta_alert_usd",value:U},{onConflict:"key"}),h({title:"Alert threshold saved",description:`Notify on workbook value changes ≥ $${U.toLocaleStr
1ing()}`})}const A=oe({queryKey:["anchor-cron-health"],refetchInterval:6e4,queryFn:async()=>{const{data:U,error:ie}=await _.rpc("anchor_cron_health");if(ie)throw ie;return U??[]}});return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ve,{icon:_s,title:"Sync health KPIs & trends",subtitle:"Parse success, drift rate, needs-review count, and per-day activity — data from the audit + drift snapshot tables",tone:"cyan",actions:e.jsx("div",{className:"inline-flex rounded-md border border-border overflow-hidden",children:[7,30].map(U=>e.jsxs("button",{onClick:()=>c(U),className:je("px-2 h-7 text-[11px] font-semibold",S===U?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted/40"),children:[U,"d"]},U))}),children:n.isLoading?e.jsx(J,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ne,{icon:un,label:"Parse success",value:`${((y=(j=n.data)==null?void 0:j.kpis)==null?void 0:y.parse_success_rate)??"—"}%`,tone:"success",hint:`${S}d window`}),e.jsx(ne,{icon:Ft,label:"Drift rate",value:`${((C=(k=n.data)==null?void 0:k.kpis)==null?void 0:C.latest_drift_rate)??0}%`,tone:(((x=(N=n.data)==null?void 0:N.kpis)==null?void 0:x.latest_drift_rate)??0)>0?"destructive":"muted",hint:`${((be=(z=n.data)==null?void 0:z.kpis)==null?void 0:be.latest_leads_drifting)??0} leads`}),e.jsx(ne,{icon:mn,label:"Needs review",value:((B=(R=n.data)==null?void 0:R.kpis)==null?void 0:B.needs_review_pending)??0,tone:(((w=($=n.data)==null?void 0:$.kpis)==null?void 0:w.needs_review_pending)??0)>0?"warning":"muted"}),e.jsx(ne,{icon:ka,label:"Field changes 24h",value:((Z=(V=n.data)==null?void 0:V.kpis)==null?void 0:Z.fields_changed_24h)??0,tone:"primary",hint:`${((H=(P=n.data)==null?void 0:P.kpis)==null?void 0:H.runs_24h)??0} runs · ${((de=(ce=n.data)==null?void 0:ce.kpis)==null?void 0:de.run_errors_24h)??0} errors`})]}),e.jsx("div",{className:"mt-4 h-48",children:e.jsx(zn,{width:"100%",height:"100%",children:e.jsxs(Wn,{data:((ve=n.data)==null?void 0:ve.daily)??[],children:[e.jsx(Bn,{strokeDasharray:"3 3",opacity:.3}),e.jsx(Un,{dataKey:"day",tick:{fontSize:10}}),e.jsx(Vn,{tick:{fontSize:10}}),e.jsx(Hn,{contentStyle:{fontSize:11}}),e.jsx(Us,{type:"monotone",dataKey:"parse_success_rate",stroke:"hsl(var(--success))",strokeWidth:2,dot:!1,name:"Parse %"}),e.jsx(Us,{type:"monotone",dataKey:"drift_rate",stroke:"hsl(var(--destructive))",strokeWidth:2,dot:!1,name:"Drift %"}),e.jsx(Us,{type:"monotone",dataKey:"leads_drifting",stroke:"hsl(var(--warning))",strokeWidth:2,dot:!1,name:"Leads drifting"})]})})})]})}),e.jsx(Ve,{icon:$t,title:"Cron health — every scheduled Anchor job",subtitle:"Live view of pg_cron: last run, status, and how overdue (if at all)",tone:"primary",bodyClassName:"p-0",children:A.isLoading?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(J,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):(ue=A.data)!=null&&ue.length?e.jsx("div",{className:"divide-y divide-border",children:A.data.map(U=>{const ie=(U.minutes_overdue??0)>30,jt=(U.minutes_overdue??0)>0&&!ie,qe=U.last_status==="failed",es=qe||ie?"bg-destructive":jt?"bg-warning":U.active?"bg-success":"bg-muted-foreground";return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsx("span",{className:je("h-2 w-2 rounded-full flex-shrink-0",es)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("code",{className:"text-xs font-mono font-semibold text-foreground",children:U.jobname}),e.jsx(T,{variant:"outline",className:"text-[9px] font-mono",children:U.schedule}),!U.active&&e.jsx(T,{variant:"outline",className:"text-[9px] bg-muted text-muted-foreground",children:"DISABLED"}),qe&&e.jsx(T,{variant:"outline",className:"text-[9px] bg-destructive/10 text-destructive border-destructive/30",children:"last: FAILED"}),ie&&e.jsxs(T,{variant:"outline",className:"text-[9px] bg-destructive/10 text-destructive border-destructive/30",children:["OVERDUE ",U.minutes_overdue,"m"]})]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:["last run: ",U.last_start_at?Oe(new Date(U.last_start_at),{addSuffix:!0}):"never",U.last_status?` · ${U.last_status}`:"",U.expected_interval_minutes?` · expected every ${U.expected_interval_minutes}m`:""]})]})]},U.jobid)})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No Anchor cron jobs found."})}),e.jsx(Ve,{icon:$t,title:"Latest run per job",subtitle:"At-a-glance last successful pull, sweep, and status refresh",tone:"cyan",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-primary",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," anchor-pull-claims"]}),e.jsx("div",{className:"mt-1.5 font-mono text-sm font-bold text-foreground",children:"every 3 hours"}),e.jsxs("div",{className:"mt-1 text-[10px] text-muted-foreground",children:["Last success: ",a!=null&&a.last_pull_at?Oe(new Date(a.last_pull_at),{addSuffix:!0}):"—"]})]}),e.jsxs("div",{className:"rounded-lg border border-border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-cyan",children:[e.jsx(wa,{className:"h-3.5 w-3.5"})," sweep-anchor-workbooks"]}),e.jsxs("div",{className:"mt-1.5 font-mono text-sm font-bold text-foreground",children:["every 3 hours ",e.jsx("span",{className:"text-muted-foreground",children:"(+30m offset)"})]}),e.jsxs("div",{className:"mt-1 text-[10px] text-muted-foreground",children:["Last success: ",a!=null&&a.last_sweep_at?Oe(new Date(a.last_sweep_at),{addSuffix:!0}):"—"]})]}),e.jsxs("div",{className:"rounded-lg border border-border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-gold",children:[e.jsx(xs,{className:"h-3.5 w-3.5"})," anchor-sync-statuses"]}),e.jsx("div",{className:"mt-1.5 font-mono text-sm font-bold text-foreground",children:"every 2 hours"}),e.jsxs("div",{className:"mt-1 text-[10px] text-muted-foreground",children:["Last success: ",a!=null&&a.last_status_sync_at?Oe(new Date(a.last_status_sync_at),{addSuffix:!0}):"—"]})]})]})}),e.jsx(Ve,{icon:xs,title:"HTTP mix — last 24h",subtitle:"Anchor API response health across every sync request",tone:"cyan",children:f.isLoading?e.jsx(J,{className:"h-4 w-4 animate-spin text-muted-foreground"}
1):e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(ne,{icon:xs,label:"Total",value:((Qe=f.data)==null?void 0:Qe.total)??0,tone:"muted"}),e.jsx(ne,{icon:un,label:"2xx OK",value:((kt=f.data)==null?void 0:kt.ok)??0,tone:"success"}),e.jsx(ne,{icon:Ft,label:"4xx",value:((Xt=f.data)==null?void 0:Xt.err4xx)??0,tone:(((js=f.data)==null?void 0:js.err4xx)??0)>0?"warning":"muted"}),e.jsx(ne,{icon:wa,label:"429 rate-limit",value:((ot=f.data)==null?void 0:ot.err429)??0,tone:(((vs=f.data)==null?void 0:vs.err429)??0)>0?"warning":"muted"}),e.jsx(ne,{icon:Ft,label:"5xx errors",value:((_t=f.data)==null?void 0:_t.err5xx)??0,tone:(((ys=f.data)==null?void 0:ys.err5xx)??0)>0?"destructive":"muted"})]})}),e.jsx(Ve,{icon:qr,title:"Controls",subtitle:"Pause the whole sync loop or tune the value-drift alert",tone:"gold",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border border-border bg-background p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 font-semibold text-sm",children:[(Ye=b.data)!=null&&Ye.paused?e.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center rounded-md bg-warning/10 text-warning",children:e.jsx(zr,{className:"h-3.5 w-3.5"})}):e.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center rounded-md bg-success/10 text-success",children:e.jsx(Br,{className:"h-3.5 w-3.5"})}),"Anchor sync"," ",e.jsx(T,{variant:"outline",className:je("text-[10px]",(ws=b.data)!=null&&ws.paused?"bg-warning/10 text-warning border-warning/30":"bg-success/10 text-success border-success/30"),children:(bt=b.data)!=null&&bt.paused?"PAUSED":"ACTIVE"})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"Set to paused during maintenance. Cron jobs still fire — edge functions honor this flag and short-circuit."})]}),e.jsx(Qn,{checked:!!((Ns=b.data)!=null&&Ns.paused),onCheckedChange:D,disabled:p})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border border-border bg-background p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 font-semibold text-sm",children:[e.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center rounded-md bg-cyan/10 text-cyan",children:e.jsx(mn,{className:"h-3.5 w-3.5"})}),"Workbook value-change alert"]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"Notify when a parsed workbook's total refund shifts by at least this amount vs. its prior version."})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"$"}),e.jsx("input",{type:"number",defaultValue:((ct=b.data)==null?void 0:ct.alertThreshold)??5e3,step:500,onBlur:U=>l(Number(U.target.value)),className:"w-28 rounded-md border border-border bg-background px-2 py-1.5 text-sm font-semibold tabular-nums focus:outline-none focus:ring-2 focus:ring-primary/40"})]})]})]})})]})}const jl={"24h":24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3};function vl(){var B,$;const[a,o]=d.useState(""),[h,p]=d.useState("all"),[v,S]=d.useState("all"),[c,n]=d.useState("7d"),[b,f]=d.useState(25),[D,l]=d.useState(0),[A,j]=d.use
1State(null),y=d.useMemo(()=>c==="all"?null:new Date(Date.now()-jl[c]).toISOString(),[c]),k=oe({queryKey:["wb-shape-opts"],queryFn:async()=>{const{data:w,error:V}=await _.rpc("anchor_workbook_shape_options");if(V)throw V;return w??[]},staleTime:5*6e4}),C=oe({queryKey:["wb-parse-feed",a,h,v,y,b,D],placeholderData:Rn,queryFn:async()=>{const{data:w,error:V}=await _.rpc("anchor_workbook_parse_feed",{_search:a||null,_status:h==="all"?null:h,_shape:v==="all"?null:v,_since:y,_until:null,_limit:b,_offset:D*b});if(V)throw V;return w??[]}}),N=C.data??[],x=((B=N[0])==null?void 0:B.total_matched)??0,z=Math.max(1,Math.ceil(Number(x)/b));function be(){o(""),p("all"),S("all"),n("7d"),l(0)}function R(w){const V=new Blob([JSON.stringify(w,null,2)],{type:"application/json"}),Z=URL.createObjectURL(V),P=document.createElement("a");P.href=Z,P.download=`workbook-${(w.file_name||w.id).replace(/[^a-z0-9._-]+/gi,"_")}.json`,P.click(),URL.revokeObjectURL(Z)}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl border border-border bg-card p-3 shadow-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[220px] flex-1",children:[e.jsx(Gt,{className:"pointer-events-none absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(gs,{value:a,onChange:w=>{o(w.target.value),l(0)},placeholder:"Search company, file, error, contact…",className:"h-9 pl-8 text-xs"})]}),e.jsxs(Ne,{value:c,onValueChange:w=>{n(w),l(0)},children:[e.jsx(ke,{className:"h-9 w-[110px] text-xs",children:e.jsx(Se,{})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"24h",children:"Last 24h"}),e.jsx(q,{value:"7d",children:"Last 7 days"}),e.jsx(q,{value:"30d",children:"Last 30 days"}),e.jsx(q,{value:"all",children:"All time"})]})]}),e.jsxs(Ne,{value:h,onValueChange:w=>{p(w),l(0)},children:[e.jsx(ke,{className:"h-9 w-[140px] text-xs",children:e.jsx(Se,{})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"all",children:"All statuses"}),e.jsx(q,{value:"success",children:"Success"}),e.jsx(q,{value:"failed",children:"Failed"}),e.jsx(q,{value:"reconciled",children:"Reconciled"}),e.jsx(q,{value:"not_reconciled",children:"Not reconciled"})]})]}),e.jsxs(Ne,{value:v,onValueChange:w=>{S(w),l(0)},children:[e.jsx(ke,{className:"h-9 w-[160px] text-xs",children:e.jsx(Se,{placeholder:"All shapes"})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"all",children:"All shapes"}),(k.data??[]).map(w=>e.jsxs(q,{value:w.shape,children:[w.shape," · ",w.cnt]},w.shape))]})]}),e.jsxs(Ne,{value:String(b),onValueChange:w=>{f(Number(w)),l(0)},children:[e.jsx(ke,{className:"h-9 w-[90px] text-xs",children:e.jsx(Se,{})}),e.jsx(Ce,{children:[10,25,50,100].map(w=>e.jsxs(q,{value:String(w),children:[w," / pg"]},w))})]}),e.jsxs(L,{size:"sm",variant:"ghost",onClick:be,className:"h-9 gap-1 text-xs",children:[e.jsx(Qt,{className:"h-3.5 w-3.5"})," Reset"]}),e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>C.refetch(),className:"h-9 gap-1 text-xs",children:[C.isFetching?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(at,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between text-[11px] text-muted-foreground",children:[e.jsx("span",{children:C.isLoading?"Loading…":`Showing ${N.length?D*b+1:0}–${D*b+N.length} of ${Number(x).toLocaleString()}`}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(L,{size:"sm",variant:"outline",disabled:D===0||C.isFetching,onClick:()=>l(w=>Math.max(0,w-1)),className:"h-7 px-2",children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsxs("span",{className:"min-w-[70px] text-center tabular-nums",children:["Page ",D+1," / ",z]}),e.jsx(L,{size:"sm",variant:"outline",disabled:D+1>=z||C.isFetching,onClick:()=>l(w=>w+1),className:"h-7 px-2",children:e.jsx(bs,{className:"h-3.5 w-3.5"})})]})]})]}),C.isLoading?e.jsx("div",{className:"flex items-center justify-center rounded-xl border bg-card py-16",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):C.error?e.jsxs("div",{className:"rounded-xl border border-rose-200 bg-rose-50 p-4 text-xs font-mono text-rose-800 dark:border-rose-900/60 dark:bg-rose-950/30 dark:text-rose-300",children:[e.jsx("div",{className:"mb-1 font-sans text-sm font-semibold not-italic",children:"Failed to load w
1orkbook parses"}),(($=C.error)==null?void 0:$.message)||String(C.error)]}):N.length?e.jsx("div",{className:"space-y-2",children:N.map(w=>{var ce,de;const V=A===w.id,Z=typeof w.extraction_confidence=="number"?w.extraction_confidence:null,P=Z!=null?Math.round(Z*100):null,H=w.success?w.reconciled===!1?"border-l-amber-500":w.reconciled===!0?"border-l-emerald-500":"border-l-slate-300":"border-l-rose-500";return e.jsxs("div",{className:`rounded-lg border border-border bg-card shadow-sm border-l-4 ${H} overflow-hidden`,children:[e.jsxs("button",{onClick:()=>j(V?null:w.id),className:"flex w-full flex-wrap items-center gap-2 px-3 py-2.5 text-left hover:bg-muted/40",children:[e.jsx(Sa,{className:"h-4 w-4 shrink-0 text-slate-500"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-semibold text-foreground",children:w.company_name||"(no lead)"}),w.workbook_shape&&e.jsx(T,{variant:"outline",className:"text-[10px] font-mono",children:w.workbook_shape}),!w.success&&e.jsx(T,{variant:"destructive",className:"text-[10px]",children:"error"}),w.reconciled===!0&&e.jsx(T,{className:"bg-emerald-100 text-emerald-800 hover:bg-emerald-100 text-[10px] border-emerald-200",children:"✓ reconciled"}),w.reconciled===!1&&e.jsx(T,{className:"bg-amber-100 text-amber-800 hover:bg-amber-100 text-[10px] border-amber-200",children:"not reconciled"}),w.fallback_used&&e.jsx(T,{variant:"outline",className:"text-[10px]",children:"fallback"})]}),e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground font-mono",children:w.file_name||"(unnamed file)"})]}),e.jsxs("div",{className:"hidden md:block text-right",children:[P!=null&&e.jsxs("div",{className:`text-xs font-bold tabular-nums ${P>=85?"text-emerald-700":P>=60?"text-amber-700":"text-rose-700"}`,children:[P,"%"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:[w.matched_bucket_count," matched · ",w.unknown_bucket_count," unknown"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[11px] text-muted-foreground whitespace-nowrap",children:Oe(new Date(w.parsed_at),{addSuffix:!0})}),((ce=w.phase_totals)==null?void 0:ce.total)!=null&&e.jsx("div",{className:"text-xs font-mono font-semibold text-foreground tabular-nums",children:G(Number(w.phase_totals.total))})]})]}),V&&e.jsxs("div",{className:"border-t border-border bg-muted/20 p-3 space-y-3",children:[w.phase_totals&&e.jsx("div",{className:"grid grid-cols-2 gap-2 md:grid-cols-6",children:["phase1","phase2","phase3","exception_review","all_potential","total"].map(ve=>{var kt;const ue=(kt=w.phase_totals)==null?void 0:kt[ve],Qe=ve==="total";return e.jsxs("div",{className:`rounded-md border px-2 py-1.5 ${Qe?"bg-primary/5 border-primary/30":"bg-background border-border"}`,children:[e.jsx("div",{className:`text-[9px] font-bold uppercase tracking-wider ${Qe?"text-primary":"text-muted-foreground"}`,children:ve.replace("_"," ")}),e.jsx("div",{className:`mt-0.5 font-mono text-xs tabular-nums ${Qe?"font-bold text-primary":ue?"text-foreground":"text-muted-foreground/50"}`,children:ue!=null?G(ue):"—"})]},ve)})}),w.error_message&&e.jsx("div",{className:"rounded-md border border-rose-200 bg-rose-50 px-3 py-2 text-[11px] font-mono text-rose-700 break-words",children:w.error_message}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-[10px] font-mono text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx("span",{className:"opacity-70",children:"lead:"})," ",w.lead_id??"—"]}
1),e.jsxs("span",{children:[e.jsx("span",{className:"opacity-70",children:"hash:"})," ",((de=w.source_file_hash)==null?void 0:de.slice(0,12))??"—"]}),Z!=null&&e.jsxs("span",{children:[e.jsx("span",{className:"opacity-70",children:"conf:"})," ",Z.toFixed(3)]}),e.jsxs(L,{size:"sm",variant:"ghost",onClick:ve=>{ve.stopPropagation(),R(w)},className:"ml-auto h-6 gap-1 px-2 text-[10px]",children:[e.jsx(Da,{className:"h-3 w-3"})," JSON"]})]})]})]},w.id)})}):e.jsx("p",{className:"rounded-xl border bg-card py-16 text-center text-sm text-muted-foreground",children:"No workbook parses match these filters."})]})}function Is({wb:a,api:o,isMismatch:h}){const p=a!=null&&o!=null?a-o:null;return e.jsxs("div",{className:"min-w-[130px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] uppercase tracking-wider text-muted-foreground",children:[e.jsx("span",{children:"WB"}),e.jsx("span",{children:"API"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 tabular-nums font-mono text-xs",children:[e.jsx("span",{className:a==null?"text-muted-foreground/50":"text-foreground",children:a!=null?G(a):"—"}),e.jsx(Pa,{className:"h-3 w-3 text-muted-foreground/60"}),e.jsx("span",{className:o==null?"text-muted-foreground/50":"text-foreground",children:o!=null?G(o):"—"})]}),p!=null&&e.jsxs("div",{className:`mt-0.5 text-right text-[10px] font-mono tabular-nums ${h?p>0?"text-amber-700 font-semibold":"text-rose-700 font-semibold":"text-emerald-700"}`,children:[h?"Δ ":"= ",p===0?"$0":`${p>0?"+":""}${G(p)}`]})]})}function yl(){var N;const{dataSourceFilter:a}=Tn(),[o,h]=d.useState(""),[p,v]=d.useState(!1),[S,c]=d.useState(25),[n,b]=d.useState(0),[f,D]=d.useState(null),l=oe({queryKey:["anchor-compare",o,p,S,n,a],placeholderData:Rn,refetchInterval:6e4,queryFn:async()=>{const{data:x,error:z}=await _.rpc("anchor_api_vs_workbook_comparison",{_search:o||null,_only_mismatches:p,_limit:S,_offset:n*S,_data_mode:a});if(z)throw z;return x??[]}}),A=oe({enabled:!l.isLoading&&(l.data??[]).length===0,queryKey:["anchor-comparison-health"],staleTime:6e4,queryFn:async()=>{const{data:x,error:z}=await _.rpc("anchor_comparison_health");if(z)throw z;return Array.isArray(x)?x[0]:x}}),j=l.data??[],y=Number(((N=j[0])==null?void 0:N.total_matched)??0),k=Math.max(1,Math.ceil(y/S)),C=d.useMemo(()=>{const x=j.filter(R=>(R.mismatch_fields??[]).length>0).length,z=j.filter(R=>R.wb_total!=null&&R.api_total==null).length,be=j.filter(R=>R.api_total!=null&&R.wb_total==null).length;return{mism:x,wbOnly:z,apiOnly:be}},[j]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"rounded-xl border border-primary/20 bg-primary/5 p-3 text-xs text-foreground/80",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Pa,{className:"h-4 w-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-foreground",children:"API vs Workbook comparison"}),e.jsxs("p",{className:"mt-0.5 text-muted-foreground",children:["For each company we show the ",e.jsx("b",{children:"most recent parsed workbook (WB)"})," alongside the"," ",e.jsx("b",{children:"most recent Anchor API snapshot"})," and any ",e.jsx("b",{children:"refund receipts"})," collected. Rows where any phase differs by more than $1 are flagged as mismatches and sorted to the top by dollar delta."]})]})]})}),e.jsxs("div",{className:"rounded-xl border border-border bg-card p-3 shadow-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[220px] flex-1",children:[e.jsx(Gt,{className:"pointer-events-none absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(gs,{value:o,onChange:x=>{h(x.target.value),b(0)},placeholder:"Search company, contact, file…",className:"h-9 pl-8 text-xs"})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-background px-3 h-9",children:[e.jsx(Qn,{id:"only-mism",checked:p,onCheckedChange:x=>{v(x),b(0)}}),e.jsx(Wi,{htmlFor:"only-mism",className:"text-xs cursor-pointer",children:"Only mismatches"})]}),e.jsxs(Ne,{value:String(S),onValueChange:x=>{c(Number(x)),b(0)},children:[e.jsx(ke,{className:"h-9 w-[90px] text-xs",children:e.jsx(Se,{})}),e.jsx(Ce,{children:[10,25,50,100].map(x=>e.jsxs(q,{value:String(x),children:[x," / pg"]},x))})]}),e.jsxs(L,{size:"sm",variant:"ghost",onClick:()=>{h(""),v(!1),b(0)},className:"h-9 gap-1 text-xs",children:[e.jsx(Qt,{className:"h-3.5 w-3.5"})," Reset"]}),e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>l.refetch(),className:"h-9 gap-1 text-xs",children:[l.isFetching?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(at,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[l.isLoading?"Loading…":`Showing ${j.length?n*S+1:0}–${n*S+j.length}
1 of ${y.toLocaleString()} company records`," · ",e.jsxs("span",{className:"text-amber-700 font-semibold",children:[C.mism," mismatched on this page"]}),C.wbOnly>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-slate-600",children:[C.wbOnly," WB-only"]})]}),C.apiOnly>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-slate-600",children:[C.apiOnly," API-only"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(L,{size:"sm",variant:"outline",disabled:n===0||l.isFetching,onClick:()=>b(x=>Math.max(0,x-1)),className:"h-7 px-2",children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsxs("span",{className:"min-w-[70px] text-center tabular-nums",children:["Page ",n+1," / ",k]}),e.jsx(L,{size:"sm",variant:"outline",disabled:n+1>=k||l.isFetching,onClick:()=>b(x=>x+1),className:"h-7 px-2",children:e.jsx(bs,{className:"h-3.5 w-3.5"})})]})]})]}),l.isLoading?e.jsx("div",{className:"flex items-center justify-center rounded-xl border bg-card py-16",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):j.length?e.jsx("div",{className:"space-y-2",children:j.map(x=>{const z=new Set(x.mismatch_fields??[]),be=z.size>0,R=f===x.lead_id,B=be?"border-l-amber-500":"border-l-emerald-500";return e.jsxs("div",{className:`rounded-lg border border-border bg-card shadow-sm border-l-4 ${B} overflow-hidden`,children:[e.jsxs("div",{className:"flex flex-wrap items-start gap-3 px-3 py-2.5",children:[e.jsx("button",{onClick:()=>D(R?null:x.lead_id),className:"flex min-w-0 flex-1 items-start gap-2 text-left hover:opacity-80",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"truncate text-sm font-semibold text-foreground",children:x.company_name||"(unnamed)"}),be?e.jsxs(T,{className:"bg-amber-100 text-amber-800 hover:bg-amber-100 border-amber-200 text-[10px] gap-1",children:[e.jsx(Kt,{className:"h-2.5 w-2.5"}),z.size," mismatch",z.size>1?"es":""," · Δ",G(x.max_abs_delta??0)]}):e.jsxs(T,{className:"bg-emerald-100 text-emerald-800 hover:bg-emerald-100 border-emerald-200 text-[10px] gap-1",children:[e.jsx(gt,{className:"h-2.5 w-2.5"}),"in sync"]}),x.wb_total==null&&e.jsx(T,{variant:"outline",className:"text-[10px]",children:"no workbook"}),x.api_total==null&&e.jsx(T,{variant:"outline",className:"text-[10px]",children:"no API snapshot"}),x.api_stage_label&&e.jsx(T,{variant:"outline",className:"text-[10px] font-mono",children:x.api_stage_label})]}),e.jsxs("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:[x.contact_name||"—",x.contact_email?` · ${x.contact_email}`:""]})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Is,{wb:x.wb_total,api:x.api_total,isMismatch:z.has("total")}),e.jsx(Is,{wb:x.wb_phase1,api:x.api_phase1,isMismatch:z.has("phase1")}),e.jsx(Is,{wb:x.wb_phase2,api:x.api_phase2,isMismatch:z.has("phase2")}),e.jsx(Is,{wb:x.wb_phase3,api:x.api_phase3_nonfiled,isMismatch:z.has("phase3")})]})]}),R&&e.jsxs("div",{className:"border-t border-border bg-muted/20 p-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-md border border-border bg-background p-3",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5",children:"Workbook (most recent)"}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx(Ue,{k:"Total",v:x.wb_total,fmt:!0}),e.jsx(Ue,{k:"Phase 1",v:x.wb_phase1,fmt:!0}),e.jsx(Ue,{k:"Phase 2",v:x.wb_phase2,fmt:!0}),e.jsx(Ue,{k:"Phase 3",v:x.wb_phase3,fmt:!0}),e.jsx("div",{className:"border-t border-border pt-1 mt-1 text-[10px] text-muted-foreground font-mono truncate",title:x.wb_source_file??"",children:x.wb_source_file||"—"}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:[x.wb_source?`source: ${x.wb_source}`:"",x.wb_version!=null?` · v${x.wb_version}`:"",x.wb_updated_at?` · ${Oe(new Date(x.wb_updated_at),{addSuffix:!0})}`:""]})]})]}),e.jsxs("div",{className:"rounded-md border border-border bg-background p-3",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5",children:"Anchor API (most recent snapshot)"}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx(Ue,{k:"Total",v:x.api_total,fmt:!0}),e.jsx(Ue,{k:"Phase 1",v:x.api_phase1,fmt:!0}),e.jsx(Ue,{k:"Phase 2",v:x.api_phase2,fmt:!0}),e.jsx(Ue,{k:"Phase 3 (nonfiled)",v:x.api_phase3_nonfiled,fmt:!0}),e.jsx(Ue,{k:"Phase 3 received",v:x.api_phase3_received,fmt:!0}),e.jsx(Ue,{k:"Entries",v:x.api_entries_total}),e.jsxs("div",{className:"text-[10px] text-muted-foreground pt-1 border-t border-border",children:[x.api_stage_label??x.api_stage??"—",x.api_updated_at?` · ${Oe(new Date(x.api_updated_at),{addSuffix:!0})}`:""]})]})]}),e.jsxs("div",{className:"rounded-md border border-border bg-background p-3",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5",children:"Refund receipts (collected)"}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx(Ue,{k:"Received total",v:x.received_total,fmt:!0}),e.jsx(Ue,{k:"Receipts",v:x.received_count}),e.jsx(Ue,{k:"Last receipt",v:x.last_receipt_at?Oe(new Date(x.last_receipt_at),{addSuffix:!0}):null}),e.jsx("div",{className:"pt-1 border-t border-border",children:x.api_total!=null&&x.received_total!=null&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["Collected ",Math.round(Number(x.received_total)/Number(x.api_total)*100),"% of API total"]})})]})]})]}),be&&e.jsxs("div",{className:"rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-[11px] text-amber-800",children:[e.jsx("b",{children:"Mismatched fields:"})," ",(x.mismatch_fields??[]).join(", "),". Investigate whether the workbook was reparsed after the API snapshot (or vice-versa) — the most authoritative source per the priority rule should win."]}),e.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono text-muted-foreground",children:[e.jsxs("span",{children:["lead: ",x.lead_id]}),e.jsxs(Dn,{to:`/command/leads/${x.lead_id}`,className:"inline-flex items-center gap-1 text-primary hover:underline",children:["Open lead ",e.jsx(Ur,{className:"h-3 w-3"})]})]})]})]},x.lead_id)})}):e.jsx("div",{className:"rounded-xl border bg-card py-10 px-4 text-center",children:e.jsxs("div",{className:"mx-auto max-w-md 
1space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No companies match these filters."}),A.data&&e.jsx("div",{className:"rounded-md border border-primary/20 bg-primary/5 p-3 text-left text-[11px] text-foreground/80",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ln,{className:"h-3.5 w-3.5 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-semibold text-foreground",children:"Diagnostic (all data, ignoring current filters)"}),e.jsxs("div",{children:["Workbook summaries: ",e.jsx("b",{children:A.data.workbook_summaries_current??0})," · API snapshots: ",e.jsx("b",{children:A.data.api_snapshots_current??0})," · Refund receipts: ",e.jsx("b",{children:A.data.refund_receipt_leads??0})," · Both WB+API: ",e.jsx("b",{children:A.data.overlap_wb_api??0})]}),A.data.workbook_sources&&e.jsxs("div",{className:"font-mono text-[10px] text-muted-foreground",children:["sources: ",JSON.stringify(A.data.workbook_sources)]}),e.jsxs("div",{className:"text-muted-foreground",children:["If those counts are > 0 but the list is empty, try clearing the search box or switching data mode (",a,")."]})]})]})})]})})]})}function Ue({k:a,v:o,fmt:h}){return e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:a}),e.jsx("span",{className:`font-mono tabular-nums ${o==null?"text-muted-foreground/50":"text-foreground"}`,children:o==null?"—":h?G(Number(o)):String(o)})]})}const wl={ignored_low_confidence_regression:"Low-confidence regression",low_confidence:"Low content confidence",unknown_shape:"Unknown workbook shape"};function Nl(){const a=Zt(),[o,h]=d.useState(null),[p,v]=d.useState(null),S=oe({queryKey:["anchor-review-queue"],refetchInterval:6e4,queryFn:async()=>{const{data:f,error:D}=await _.from("anchor_parse_review_queue").select("*, lead:leads!inner(id, company_name)").eq("status","pending").order("created_at",{ascending:!1}).limit(200);if(D)throw D;return f??[]}});async function c(f,D){v(f.id);try{const{data:{user:l}}=await _.auth.getUser(),{error:A}=await _.from("anchor_parse_review_queue").update({status:D,reviewed_by:(l==null?void 0:l.id)??null,reviewed_at:new Date().toISOString()}).eq("id",f.id);if(A)throw A;Ls({title:D==="approved"?"Approved":"Rejected",description:D==="approved"?"The proposed workbook parse is queued to be applied on next sweep.":"Marked as rejected — the current summary stays in place."}),a.invalidateQueries({queryKey:["anchor-review-queue"]})}catch(l){Ls({title:"Failed",description:(l==null?void 0:l.message)??String(l),variant:"destructive"})}finally{v(null)}}async function n(f,D){const l=f.document_id||f.anchor_document_id;if(!l){Ls({title:"No file",description:"This review row has no linked document.",variant:"destructive"});return}v(f.id+":"+D);try{const{data:A,error:j}=await _.functions.invoke("issue-anchor-doc-url",{body:{document_id:l,disposition:D}});if(j)throw j;const y=A==null?void 0:A.url;if(!y)throw new Error("No URL returned");if(D==="attachment"){const k=document.createElement("a");k.href=y,k.download=f.file_name||"anchor-file",document.body.appendChild(k),k.click(),k.remove()}else window.open(y,"_blank","noopener,noreferrer")}catch(A){Ls({title:"Couldn't open file",description:(A==null?void 0:A.message)??String(A),variant:"destructive"})}finally{v(null)}}const b=S.data??[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"rounded-xl border border-amber-200/60 bg-amber-50/60 p-3 text-xs text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-200",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Needs Review — low-confidence workbook parses"}),e.jsx("p",{className:"mt-0.5 text-amber-800/80 dark:text-amber-200/80",children:"These workbooks parsed successfully but the auto-pilot refused to overwrite the current high-confidence summary. Approve to accept the proposed values, or reject to keep the current summary and mark this file for re-classification."})]})]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:S.isLoading?"Loading…":`${b.length} pending`}),e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>S.refetch(),className:"h-8 gap-1 text-xs",children:[S.isFetching?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(at,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),S.isLoading?e.jsx("div",{className:"flex items-center justify-center rounded-xl border bg-card py-16",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):b.length?e.jsx("div",{className:"space-y-2",children:b.map(f=>{var A;const D=o===f.id,l=f.current_total!=null&&f.proposed_total!=null?f.proposed_total-f.current_total:null;return e.jsxs("div",{className:"rounded-lg border border-border bg-card shadow-sm border-l-4 border-l-amber-500 overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-start gap-3 px-3 py-2.5",children:[e.jsxs("button",{onClick:()=>h(D?null:f.id),className:"flex min-w-0 flex-1 items-start gap-2 text-left hover:opacity-80",children:[D?e.jsx(Aa,{className:"h-3.5 w-3.5 mt-1 text-muted-foreground"}):e.jsx(bs,{className:"h-3.5 w-3.5 mt-1 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"truncate text-sm font-semibold text-foreground",children:((A=f.lead)==null?void 0:A.company_name)||"(unknown lead)"}),e.jsx(T,{variant:"outline",className:"text-[10px]",children:wl[f.reason]??f.reason}
1),f.workbook_shape&&e.jsx(T,{variant:"outline",className:"text-[10px] font-mono",children:f.workbook_shape})]}),e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground font-mono",children:f.file_name||"—"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-xs",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider text-muted-foreground",children:"Current"}),e.jsx("div",{className:"font-mono tabular-nums",children:f.current_total!=null?G(f.current_total):"—"}),f.current_confidence!=null&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["conf ",Math.round(Number(f.current_confidence)*100),"%"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider text-muted-foreground",children:"Proposed"}),e.jsx("div",{className:"font-mono tabular-nums",children:f.proposed_total!=null?G(f.proposed_total):"—"}),f.proposed_confidence!=null&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["conf ",Math.round(Number(f.proposed_confidence)*100),"%"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider text-muted-foreground",children:"Δ"}),e.jsx("div",{className:`font-mono tabular-nums ${l!=null&&l<0?"text-rose-700":"text-emerald-700"}`,children:l!=null?`${l>0?"+":""}${G(l)}`:"—"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(L,{size:"sm",variant:"outline",disabled:!!p,className:"h-8 gap-1 text-xs",onClick:()=>n(f,"inline"),title:"Open the source file in a new tab",children:[p===f.id+":inline"?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Vr,{className:"h-3.5 w-3.5"}),"View"]}
1),e.jsxs(L,{size:"sm",variant:"outline",disabled:!!p,className:"h-8 gap-1 text-xs",onClick:()=>n(f,"attachment"),title:"Download the source file",children:[p===f.id+":attachment"?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Da,{className:"h-3.5 w-3.5"}),"Download"]}),e.jsxs(L,{size:"sm",variant:"outline",disabled:!!p,className:"h-8 gap-1 text-xs border-rose-200 text-rose-700 hover:bg-rose-50",onClick:()=>c(f,"rejected"),children:[e.jsx(Qt,{className:"h-3.5 w-3.5"})," Reject"]}),e.jsxs(L,{size:"sm",disabled:!!p,className:"h-8 gap-1 text-xs bg-emerald-600 hover:bg-emerald-700 text-white",onClick:()=>c(f,"approved"),children:[p===f.id?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(qn,{className:"h-3.5 w-3.5"}),"Approve"]})]})]}),D&&e.jsxs("div",{className:"border-t border-border bg-muted/20 p-3 space-y-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-muted-foreground flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("span",{children:["doc: ",f.anchor_document_id??"—"]}),e.jsxs("span",{children:["added ",Oe(new Date(f.created_at),{addSuffix:!0})]}),e.jsx(Dn,{to:`/command/leads/${f.lead_id}`,className:"text-primary hover:underline",children:"open lead →"})]}),e.jsxs("details",{className:"text-[10px] font-mono",children:[e.jsx("summary",{className:"cursor-pointer text-muted-foreground",children:"Proposed payload"}),e.jsx("pre",{className:"mt-1 max-h-64 overflow-auto rounded bg-background border border-border p-2 text-[10px]",children:JSON.stringify(f.proposed_payload,null,2)})]})]})]},f.id)})}):e.jsx("p",{className:"rounded-xl border bg-card py-16 text-center text-sm text-muted-foreground",children:"Nothing pending — the auto-pilot is caught up."})]})}function kl(){const[a,o]=d.useState(""),[h,p]=d.useState(null),v=oe({queryKey:["anchor-audit-runs",a],refetchInterval:6e4,queryFn:async()=>{let n=_.from("anchor_sync_audit_runs").select("*").order("started_at",{ascending:!1}).limit(50);a&&(n=n.or(`trigger.ilike.%${a}%,source_function.ilike.%${a}%,notes.ilike.%${a}%`));const{data:b}=await n;return b??[]}}),S=oe({enabled:!!h,queryKey:["anchor-audit-changes",h],queryFn:async()=>{const{data:n}=await _.from("anchor_sync_audit_changes").select("*").eq("run_id",h).order("changed_at",{ascending:!1}).limit(500);return n??[]}}),c=v.data??[];return e.jsx(Ve,{icon:ps,title:"Full-sync audit log",subtitle:"Every scheduled or manual Anchor sync — leads touched, workbooks parsed, and field-by-field diffs",tone:"primary",actions:e.jsxs("div",{className:"relative",children:[e.jsx(Gt,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(gs,{value:a,onChange:n=>o(n.target.value),placeholder:"trigger / source / notes",className:"h-8 pl-7 w-64 text-xs"})]}),bodyClassName:"p-0",children:v.isLoading?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(J,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):c.length?e.jsxs(Ys,{className:"rounded-none border-0",children:[e.jsx("thead",{className:"bg-muted/40 text-muted-foreground text-[10px] uppercase tracking-wider",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-semibold w-6"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Started"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Trigger"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Source"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Leads"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Workbooks"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Field changes"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"Errors"}),e.jsx("th",{className:"text-left px-3 py-2 font-semibold",children:"Status"})]})}),e.jsx("tbody",{children:c.map(n=>{var f;const b=h===n.id;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"border-t border-border hover:bg-muted/30 cursor-pointer",onClick:()=>p(b?null:n.id),children:[e.jsx("td",{className:"px-3 py-2",children:b?e.jsx(Aa,{className:"h-3.5 w-3.5"}):e.jsx(bs,{className:"h-3.5 w-3.5"})}),e.jsx("td",{className:"px-3 py-2 text-xs whitespace-nowrap",children:Oe(new Date(n.started_at),{addSuffix:!0})}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(T,{variant:"outline",className:"text-[9px]",children:n.trigger})}),e.jsx("td",{className:"px-3 py-2 font-mono text-[10px]",children:n.source_function}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:n.leads_touched}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:n.workbooks_parsed}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums font-semibold",children:n.fields_changed}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-destructive",children:n.errors||""}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(T,{variant:"outline",className:n.status==="ok"?"bg-success/10 text-success border-success/30 text-[9px]":n.status==="error"?"bg-destructive/10 text-destructive border-destructive/30 text-[9px]":"text-[9px]",children:n.status})})]},n.id),b&&e.jsx("tr",{className:"bg-muted/20",children:e.jsx("td",{colSpan:9,className:"px-4 py-3",children:S.isLoading?e.jsx(J,{className:"h-4 w-4 animate-spin text-muted-foreground"}):(f=S.data)!=null&&f.length?e.jsx("div",{className:"overflow-x-auto rounded-md border border-border bg-background",children:e.jsxs("table",{className:"w-full text-[11px]",children:[e.jsx("thead",{className:"bg-muted/40 text-muted-foreground text-[9px] uppercase",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-2 py-1.5",children:"Lead"}),e.jsx("th",{className:"text-left px-2 py-1.5",children:"Entity"}),e.jsx("th",{className:"text-left px-2 py-1.5",children:"Field"}),e.jsx("th",{className:"text-left px-2 py-1.5",children:"Old"}),e.jsx("th",{className:"text-left px-2 py-1.5",children:"New"}),e.jsx("th",{className:"text-right px-2 py-1.5",children:"Δ"}),e.jsx("th",{className:"text-left px-2 py-1.5",children:"Source"})]})}),e.jsx("tbody",{children:S.data.map(D=>{var l;return e.jsxs("tr",{className:"border-t border-border",children:[e.jsx("td",{className:"px-2 py-1 font-mono text-[10px] text-muted-foreground",children:(l=D.lead_id)==null?void 0:l.slice(0,8)}),e.jsx("td",{className:"px-2 py-1",children:D.entity}),e.jsx("td",{className:"px-2 py-1 font-mono text-[10px]",children:D.field}),e.jsx("td",{className:"px-2 py-1 line-through text-muted-foreground max-w-[240px] truncate",children:D.old_value}),e.jsx("td",{className:"px-2 py-1 font-semibold max-w-[240px] truncate",children:D.new_value}),e.jsx("td",{className:"px-2 py-1 text-right tabular-nums "+(Number(D.delta_numeric)>0?"text-success":Number(D.delta_numeric)<0?"text-destructive":""),children:D.delta_numeric??""}),e.jsx("td",{className:"px-2 py-1",children:e.jsx(T,{variant:"outline",className:"text-[8px]",children:D.source})})]},D.id)})})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No field diffs recorded for this run."})})},n.id+"-details")]})})})]}):e.jsx("p",{className:"text-center text-sm text-muted-foreground py-10",children:"No sync runs recorded yet."})})}function Sl(a){if(!a)return"—";const o=Math.max(0,Math.round((Date.now()-new Date(a).getTime())/6e4));return o<1?"just now":o<60?`${o}m ago`:o<60*24?`${Math.round(o/60)}h ago`:`${Math.round(o/1440)}d ago`}function Cl(){const[a,o]=d.useState(!1),[h,p]=d.useState("overview"),v=oe({queryKey:["sync-monitor-rollup"],refetchInterval:a?3e4:12e4,queryFn:async()=>{const{data:k,error:C}=await _.rpc("sync_monitor_rollup");if(C)throw C;return k}}),c=(oe({enabled:a,queryKey:["sync-monitor-cron-health-banner"],refetchInterval:6e4,queryFn:async()=>{const{data:k,error:C}=await _.rpc("anchor_cron_health");if(C)throw C;return k??[]}}).data??[]).filter(k=>(k.minutes_overdue??0)>30),n=v.data,b=((n==null?void 0:n.errors_24h)??0)+((n==null?void 0:n.unknown_files)??0)+((n==null?void 0:n.parses_fail_24h)??0)+((n==null?void 0:n.refund_attempted_no_ach)??0),f=((n==null?void 0:n.errors_24h)??0)>0||((n==null?void 0:n.parses_fail_24h)??0)>0?"destructive":b>0?"warning":null,D=d.useMemo(()=>
1{if(!(n!=null&&n.last_pull_at))return"—";const C=new Date(n.last_pull_at).getTime()+3*60*60*1e3,N=Math.round((C-Date.now())/6e4);return N<=0?"any minute":N<60?`~${N}m`:`~${Math.round(N/60)}h ${N%60}m`},[n==null?void 0:n.last_pull_at]);async function l(){await _.functions.invoke("pull-anchor-claim",{body:{all_anchor:!0,trigger:"sync-monitor-manual"}}),v.refetch()}const A=oe({enabled:a,queryKey:["anchor-review-queue-count"],refetchInterval:6e4,queryFn:async()=>{const{count:k,error:C}=await _.from("anchor_parse_review_queue").select("id",{count:"exact",head:!0}).eq("status","pending");if(C)throw C;return k??0}}),j=Number(A.data??0),y=[{key:"overview",label:"Overview",icon:ps},{key:"runs",label:"Pulses",icon:Na},{key:"workbook",label:"Workbook Parse",icon:Sa},{key:"compare",label:"API vs Workbook",icon:Pa},{key:"needs_review",label:"Needs Review",icon:In,badge:j>0?{count:j,tone:"warning"}:void 0},{key:"unknown",label:"Unknown Files",icon:Yt,badge:((n==null?void 0:n.unknown_files)??0)>0?{count:n.unknown_files,tone:"warning"}:void 0},{key:"errors",label:"Errors",icon:Kt,badge:((n==null?void 0:n.errors_24h)??0)>0?{count:n.errors_24h,tone:"destructive"}:void 0},{key:"receipts",label:"Refund Receipts",icon:Qs},{key:"audit",label:"Audit",icon:ps},{key:"health",label:"Health & Cadence",icon:xs}];return e.jsxs(Vs,{open:a,onOpenChange:o,children:[e.jsx(En,{asChild:!0,children:e.jsxs(L,{variant:"outline",size:"sm",title:"Anchor Sync Monitor — every anomaly, error, and change",className:je("gap-1.5 shadow-sm border-emerald-200 bg-gradient-to-b from-emerald-50 to-emerald-100/60 text-emerald-700 hover:from-emerald-100 hover:to-emerald-200/70 hover:border-emerald-300 hover:text-emerald-800 dark:border-emerald-900/60 dark:from-emerald-950/40 dark:to-emerald-900/20 dark:text-emerald-300 dark:hover:from-emerald-900/50",f==="destructive"&&"border-rose-300 from-rose-50 to-rose-100/60 text-rose-700 hover:from-rose-100 hover:to-rose-200/70 hover:border-rose-400 hover:text-rose-800 dark:border-rose-900/60 dark:from-rose-950/40 dark:to-rose-900/20 dark:text-rose-300"),children:[e.jsx(hn,{className:je("h-3.5 w-3.5",f==="destructive"&&"text-rose-600 dar
1k:text-rose-400")}),e.jsx("span",{className:"hidden sm:inline font-semibold",children:"Sync Monitor"}),e.jsx("span",{className:"sm:hidden font-semibold",children:"Monitor"}),b>0&&e.jsx(T,{variant:f==="destructive"?"destructive":"secondary",className:"ml-0.5 h-4 px-1.5 text-[10px]",children:b>99?"99+":b})]})}),e.jsxs(Hs,{className:"max-w-6xl w-[96vw] max-h-[92vh] p-0 gap-0 flex flex-col overflow-hidden bg-slate-50 dark:bg-slate-950/40",children:[e.jsxs("div",{className:"flex-shrink-0 border-b bg-card",children:[e.jsx("div",{className:"relative overflow-hidden bg-gradient-to-r from-primary/10 via-cyan/10 to-transparent px-5 py-4",children:e.jsx(Ws,{children:e.jsxs(Ks,{className:"flex flex-wrap items-center gap-2 text-base",children:[e.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg bg-primary/15 text-primary",children:e.jsx(hn,{className:"h-4 w-4"})}),e.jsx("span",{className:"font-bold text-foreground",children:"Anchor Sync Monitor"}),e.jsxs(T,{variant:"outline",className:"text-[10px] bg-background border-border font-medium",children:[e.jsx(ka,{className:"mr-1 h-2.5 w-2.5"})," every 3h · realtime"]}),(n==null?void 0:n.sync_paused)&&e.jsx(T,{variant:"outline",className:"text-[10px] bg-warning/10 text-warning border-warning/30",children:"PAUSED"}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsxs(L,{size:"sm",variant:"default",className:"gap-1.5 h-8 shadow-sm",onClick:l,children:[e.jsx(at,{className:"h-3.5 w-3.5"})," Run sync now"]}),e.jsxs(L,{size:"sm",variant:"outline",className:"gap-1 h-8 bg-background",onClick:()=>v.refetch(),children:[v.isFetching?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(at,{className:"h-3.5 w-3.5"}),"Refresh"]})]})]})})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-2 p-3 border-t border-border",children:[e.jsx(ne,{icon:$t,label:"Last pull",value:Sl(n==null?void 0:n.last_pull_at),hint:n!=null&&n.sync_paused?"sync paused":`next: ${D}`,tone:n!=null&&n.sync_paused?"warning":"primary"}),e.jsx(ne,{icon:Sa,label:"Docs · 24h",value:(n==null?void 0:n.docs_ingested_24h)??"—",tone:"primary"}),e.jsx(ne,{icon:gt,label:"Parses ✓",value:(n==null?void 0:n.parses_ok_24h)??"—",hint:"24h",tone:((n==null?void 0:n.parses_ok_24h)??0)>0?"success":"muted"}),e.jsx(ne,{icon:Kt,label:"Parses ✗",value:(n==null?void 0:n.parses_fail_24h)??0,hint:"24h",tone:((n==null?void 0:n.parses_fail_24h)??0)>0?"destructive":"muted"}),e.jsx(ne,{icon:Kt,label:"Errors · 24h",value:(n==null?void 0:n.errors_24h)??0,tone:((n==null?void 0:n.errors_24h)??0)>0?"destructive":"muted"}),e.jsx(ne,{icon:Yt,label:"Unknown files",value:(n==null?void 0:n.unknown_files)??0,tone:((n==null?void 0:n.unknown_files)??0)>0?"warning":"muted"}),e.jsx(ne,{icon:Hr,label:"Backed leads",value:(n==null?void 0:n.backed_leads)??"—",tone:"cyan"}),e.jsx(ne,{icon:_s,label:"Refunds · 30d",value:(n==null?void 0:n.refund_receipts_30d)??0,hint:n!=null&&n.refund_attempted_no_ach?`${n.refund_attempted_no_ach} no-ACH`:void 0,tone:"success"})]}),c.length>0&&e.jsxs("div",{className:"border-t border-destructive/30 bg-destructive/10 px-4 py-2 text-xs text-destructive flex items-start gap-2",children:[e.jsx(Kt,{className:"h-3.5 w-3.5 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"font-semibold",children:"Cron tick missed —"})," ",c.map((k,C)=>e.jsxs("span",{children:[e.jsx("code",{className:"font-mono",children:k.jobname})," last ran ",k.minutes_since_last_run,"m ago (expected every ",k.expected_interval_minutes,"m)",C<c.length-1?"; ":""]},k.jobid)),". Check the Health tab."]})]})]}),e.jsxs(Kn,{value:h,onValueChange:p,className:"flex flex-col flex-1 min-h-0",children:[e.jsx("div",{className:"border-b border-border bg-card px-3 flex-shrink-0 overflow-x-auto",children:e.jsx(gi,{className:"h-11 bg-transparent p-0 gap-1",children:y.map(k=>{const C=k.icon;return e.jsxs(_i,{value:k.key,className:je("gap-1.5 h-10 px-3 rounded-b-none border-b-2 border-transparent","data-[state=active]:border-primary data-[state=active]:bg-background data-[state=active]:text-primary","data-[state=active]:shadow-none data-[state=active]:font-semibold","text-muted-foreground hover:text-foreground transition-colors"),children:[e.jsx(C,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"whitespace-nowrap",children:k.label}),k.badge&&e.jsx(T,{variant:k.badge.tone==="destructive"?"destructive":"secondary",className:je("ml-1 h-4 px-1 text-[9px]",k.badge.tone==="warning"&&"bg-warning/15 text-warning border border-warning/30"),children:k.badge.count})]},k.key)})})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-slate-50 dark:bg-slate-950/40",children:e.jsxs("div",{className:"p-4",children:[e.jsx(st,{value:"overview",className:"mt-0",children:e.jsx(dl,{rollup:n??null})}),e.jsx(st,{value:"runs",className:"mt-0",children:e.jsx(ml,{})}),e.jsx(st,{value:"workbook",className:"mt-0",children:e.jsx(vl,{})}),e.jsx(st,{value:"compare",className:"mt-0",children:e.jsx(yl,{})}),e.jsx(st,{value:"unknown",className:"mt-0",children:e.jsx(fl,{})}),e.jsx(st,{value:"errors",className:"mt-0",children:e.jsx("div",{className:"rounded-lg border border-border bg-card shadow-sm p-4",children:e.jsx(cl,{})})}),e.jsx(st,{value:"needs_review",className:"mt-0",children:e.jsx(Nl,{})}),e.jsx(st,{value:"receipts",className:"mt-0",children:e.jsx(_l,{})}),e.jsx(st,{value:"audit",className:"mt-0",children:e.jsx(kl,{})}),e.jsx(st,{value:"health",className:"mt-0",children:e.jsx(bl,{rollup:n??null})})]})})]})]})]})}const Al=["ALL_POTENTIAL","PHASE_1","PHASE_2","PHASE_3_HOLD","EXCEPTION_REVIEW","CAPE_READY_CSV","TOTAL_SUPPORTED","PENDING_UNLIQ","RELIQ_80_DAY","OPERATIONAL_390_DAY"];function Rl(){var A;const[a,o]=d.useState(!1),{toast:h}=Jt(),p=Zt(),v=oe({enabled:a,queryKey:["adpl-unknowns"],queryFn:async()=>{const{data:j}=await _.from("anchor_document_parse_log").select("unknown_bucket_labels, file_name, parsed_at").not("unknown_bucket_labels","is",null).order("parsed_at",{ascending:!1}).limit(300);return j||[]}}),S=oe({enabled:a,queryKey:["bucket-label-mappings"],queryFn:async()=>{const{data:j}=await _.from("anchor_bucket_label_mappings").select("*").order("updated_at",{ascending:!1});return j||[]}}),c=d.useMemo(()=>new Set((S.data||[]).map(j=>j.label_normalized)),[S.data]),n=d.useMemo(()=>{const j=new Map;for(const y of v.data||[]){const k=Array.isArray(y.unknown_bucket_labels)?y.unknown_bucket_labels:[];for(const C of k){const N=typeof C=="string"?C:C.raw_label,x=typeof C=="object"&&C.normalized_label?C.normalized_label:String(N||"").toLowerCase().trim();if(!x||c.has(x))continue;const z=j.get(x);z?z.count++:j.set(x,{raw:String(N),sample_file:y.file_name||"",count:1})}}return[...j.entries()].sort((y,k)=>k[1].count-y[1].count)}
1,[v.data,c]),[b,f]=d.useState({});async function D(j,y){const k=b[j];if(!k)return;const{error:C}=await _.from("anchor_bucket_label_mappings").upsert({label_normalized:j,raw_label_sample:y,canonical_bucket:k,status:"active"},{onConflict:"label_normalized"});C?h({title:"Save failed",description:C.message,variant:"destructive"}):(h({title:"Mapping saved",description:`"${y}" → ${k}`}),p.invalidateQueries({queryKey:["bucket-label-mappings"]}),p.invalidateQueries({queryKey:["adpl-unknowns"]}))}async function l(j){const{error:y}=await _.from("anchor_bucket_label_mappings").delete().eq("id",j);y?h({title:"Delete failed",description:y.message,variant:"destructive"}):p.invalidateQueries({queryKey:["bucket-label-mappings"]})}return e.jsxs(Vs,{open:a,onOpenChange:o,children:[e.jsx(En,{asChild:!0,children:e.jsxs(L,{variant:"outline",size:"sm",title:"Map unknown workbook labels to canonical buckets",className:"gap-1.5 shadow-sm border-amber-200 bg-gradient-to-b from-amber-50 to-amber-100/60 text-amber-700 hover:from-amber-100 hover:to-amber-200/70 hover:border-amber-300 hover:text-amber-800 dark:border-amber-900/60 dark:from-amber-950/40 dark:to-amber-900/20 dark:text-amber-300 dark:hover:from-amber-900/50",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline font-semibold",children:"Label Mapper"}),e.jsx("span",{className:"sm:hidden font-semibold",children:"Labels"}),n.length>0&&e.jsx(T,{variant:"destructive",className:"ml-1 h-4 px-1.5 text-[10px]",children:n.length})]})}),e.jsxs(Hs,{className:"max-w-3xl max-h-[85vh]",children:[e.jsx(Ws,{children:e.jsxs(Ks,{className:"flex items-center gap-2",children:["Bucket Label Mapper",e.jsx(L,{size:"sm",variant:"ghost",className:"ml-auto",onClick:()=>{v.refetch(),S.refetch()},children:v.isFetching?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(at,{className:"h-3.5 w-3.5"})})]})}),e.jsxs(Oi,{className:"h-[70vh] pr-3",children:[e.jsxs("section",{className:"mb-6",children:[e.jsx("h3",{className:"text-sm font-semibold mb-2",children:"Unmapped labels detected"}),n.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No unmapped labels — every parsed workbook was fully recognized 🎉"}):e.jsx("div",{className:"space-y-2",children:n.map(([j,y])=>e.jsxs("div",{className:"flex items-center gap-2 rounded border bg-muted/20 p-2 text-xs",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-mono truncate",children:['"',y.raw,'"']}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["seen ×",y.count," · e.g. ",y.sample_file]})]}),e.jsxs(Ne,{value:b[j]||"",onValueChange:k=>f(C=>({...C,[j]:k})),children:[e.jsx(ke,{className:"w-52 h-8",children:e.jsx(Se,{placeholder:"Map to bucket…"})}),e.jsx(Ce,{children:Al.map(k=>e.jsx(q,{value:k,children:k},k))})]}),e.jsx(L,{size:"sm",onClick:()=>D(j,y.raw),disabled:!b[j],children:"Save"})]},j))})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"text-sm font-semibold mb-2",children:["Active mappings (",((A=S.data)==null?void 0:A.length)??0,")"]}),e.jsx("div",{className:"space-y-1.5",children:(S.data||[]).map(j=>e.jsxs("div",{className:"flex items-center gap-2 rounded border bg-background p-2 text-xs",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-mono truncate",children:['"',j.raw_label_sample??j.label_normalized,'"']}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["→ ",j.canonical_bucket]})]}),e.jsx(L,{size:"sm",variant:"ghost",onClick:()=>l(j.id),children:e.jsx(Kr,{className:"h-3.5 w-3.5 text-destructive"})})]},j.id))})]})]})]})]})}const $e=a=>{const o=Number(a);return Number.isFinite(o)&&o>0?o:0};function Lt(a,o){return a&&($e(a.eligible)||$e(a.filed))||$e(o==null?void 0:o.refund_amount)}function Nt(a){const{lead:o,claimDetails:h,entries:p}=a,v=Mi(o,h);return v.source!=="none"&&v.amount>0?v.amount:Ca(o,h,p,{skipAnchor:!0}).amount||0}function ba(a,o){const{lead:h,claimDetails:p,anchorRefund:v,advanceFunding:S}=o;switch(a){case"presubmit":case"presubmission":return Nt(o);case"anchor":{const c=Lt(v,p);return c>0?c:Nt(o)}case"filed":{const c=Math.max(Lt(v,p),$e(p==null?void 0:p.refund_amount),$e(v==null?void 0:v.phase1),$e(v==null?void 0:v.echo));return c>0?c:Nt(o)}case"not_ior":{const c=Lt(v,p);return c>0?c:Nt(o)}case"funding":{const c=$e(S==null?void 0:S.advance_amount);if(c>0)return c;const n=Lt(v,p);return n>0?n:Nt(o)}case"refund_received":{const c=$e(p==null?void 0:p.refund_amount);if(c>0)return c;const n=Lt(v,p);return n>0?n:Nt(o)}case"tra_paid":{const c=$e(o.invoicePaidAmount);if(c>0)return c;const n=$e(p==null?void 0:p.tra_paid_amount)||$e(p==null?void 0:p.tra_payment_amount);if(n>0)return n;const b=$e(p==null?void 0:p.engagement_fee_pct_override)||$e(h==null?void 0:h.engagement_fee_pct)||.2;return($e(p==null?void 0:p.refund_amount)||Lt(v,p))*b}case"closed":{const c=$e(p==null?void 0:p.refund_amount);if(c>0)return c;const n=Lt(v,p);return n>0?n:Nt(o)}default:return Nt(o)}}const Nn=["new","account_created","application_in_progress","details_submitted","agreements_pending","documents_pending","identity_verification_required","ace_access_pending","ace_access_granted"],Dl={new:"New",account_created:"Account",application_in_progress:"Applying",details_submitted:"Details",agreements_pending:"Agreements",documents_pending:"Docs",identity_verification_required:"ID Verify",ace_access_pending:"ACE",ace_access_granted:"ACE✓"};function kn(a){const o=Wt(a||""),h=["identity_verification_in_progress","identity_verification_failed","identity_verification_incomplete"].includes(o)?"identity_verification_required":["ace_access_skipped","ace_access_confirmed"].includes(o)?"ace_access_granted":o,p=Nn.indexOf(h);return p<0?null:{idx:p+1,total:Nn.length,label:Dl[h]||h}}const hs=25,Pl=["All","direct","partner","referral","broker"],Ml=["All","any_intent","standard","no_funding","active_deal","no_deal"],Tl=["Hide Likely Test","All","Possible+","Likely Test"];function Sn(a){const o=S=>{if(S==null)return 0;if(typeof S=="number")return isFinite(S)?S:0;const c=parseFloat(String(S).replace(/[^0-9.\-]/g,""));return isNaN(c)?0:c},h=o(a==null?void 0:a.import_value_2025);if(h>0)return{value:h,derived:!1,source:"Intake 2025"};const p=o(a==null?void 0:a.import_value_2026);if(p>0)return{value:p,derived:!1,source:"Intake 2026"};const v=o(a==null?void 0:a.duties_paid_2025)+o(a==null?void 0:a.duties_paid_2026)+o(a==null?void 0:a.total_duties_paid);return v>
10?{value:v/.08,derived:!0,source:`Derived from $${v.toLocaleString()} duties paid ÷ 8% est. effective rate`}:null}function Cn(a){return a.source==="claim_details"||a.source==="self_reported"?"Client-entered":a.source==="entries"?"Uploaded entries":a.source==="duties_paid_country"||a.source==="duties_paid_only"?"Client-entered duties":a.source==="import_value_duties_paid"?"Client-entered duties + import":a.source==="import_value_only"?"Client-entered import est.":"Original estimate"}function El(a,o){if(a.source===o.source)return!0;const h=Math.abs(a.low-o.low)<1,p=Math.abs(a.high-o.high)<1;return!!(h&&p||a.midpoint>0&&o.midpoint>0&&Math.abs(a.midpoint-o.midpoint)/Math.max(a.midpoint,o.midpoint)<.02)}const Ll=new Set(["self_reported","claim_details","entries"]);function $l({originalEst:a,systemEst:o}){const h=Ll.has(a.source)&&!a.isProjection,p=a.amount>0&&h,v=o.amount>0;if(!p&&!v)return a.amount>0?e.jsxs("div",{className:"flex flex-col items-start gap-0.5 min-w-[130px]",children:[e.jsxs("span",{className:"text-sm font-semibold text-cyan whitespace-nowrap flex items-center gap-1",children:[e.jsx(Bs,{size:11})," ",ft(a)]}),e.jsxs("span",{className:"text-[9px] uppercase tracking-wider leading-[0.9rem] text-cyan/80",children:["System est. · ",pa(a.confidenceLabel).toLowerCase()]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"});const S=p&&v&&El(a,o);if(S||!(p&&v&&!S)){const n=p?a:o,b=!p;return e.jsx("div",{className:"flex flex-col items-start gap-0.5 min-w-[130px]",children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs("div",{className:"flex flex-col items-start",children:[e.jsxs("span",{className:`text-sm font-semibold whitespace-nowrap flex items-center gap-1 ${b?"text-cyan":"text-foreground"}`,children:[b&&e.jsx(Bs,{size:11}),ft(n)]}),e.jsxs("span",{className:`text-[9px] uppercase tracking-wider leading-[0.9rem] ${b?"text-cyan/80":"text-muted-foreground"}`,children:[b?"System est.":Cn(n)," · ",pa(n.confidenceLabel).toLowerCase()]})]})}),e.jsxs(_e,{side:"top",className:"text-xs max-w-[280px]",children:[e.jsx("div",{className:"font-semibold mb-0.5",children:n.method}),e.jsx("div",{className:"text-muted-foreground",children:n.label}),e.jsxs("div",{className:"mt-1",children:["Value: ",e.jsx("strong",{children:ft(n,!1)})]}),S&&e.jsx("div",{className:"mt-1 text-[10px] text-muted-foreground italic",children:"Client-entered value matches system estimate."})]})]})})}return e.jsxs("div",{className:"flex flex-col items-start gap-1 min-w-[130px]",children:[e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs("div",{className:"flex flex-col items-start",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground whitespace-nowrap",children:ft(a)}),e.jsxs("span",{className:"text-[9px] uppercase tracking-wider leading-[0.9rem] text-muted-foreground",children:[Cn(a)," · ",pa(a.confidenceLabel).toLowerCase()]})]})}),e.jsxs(_e,{side:"top",className:"text-xs max-w-[280px]",children:[e.jsx("div",{className:"font-semibold mb-0.5",children:a.method}),e.jsx("div",{className:"text-muted-foreground",children:a.label}),e.jsxs("div",{className:"mt-1",children:["Value: ",e.jsx("strong",{children:ft(a,!1)})]})]})]}),e.jsx("hr",{className:"w-full border-border/40"}),e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs("div",{className:"flex flex-col items-start",children:[e.jsxs("span",{className:"text-[9px] uppercase tracking-wider leading-[0.9rem] text-cyan flex items-center gap-1",children:[e.jsx(Bs,{size:10})," System Est."]}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider leading-[0.9rem] text-cyan whitespace-nowrap",children:ft(o)})]})}),e.jsxs(_e,{side:"top",className:"text-xs max-w-[280px]",children:[e.jsx("div",{className:"font-semibold mb-0.5",children:o.method}),e.jsx("div",{className:"text-muted-foreground",children:o.label}),e.jsxs("div",{className:"mt-1",children:["Range: ",e.jsx("strong",{children:ft(o,!1)})]}),e.jsxs("div",{children:["Weighted: ",e.jsxs("strong",{children:["$",Math.round(o.weightedOpportunity).toLocaleString()]})]})]})]})]})}const Fl=(a,o)=>`${a||""} ${o||""}`.toUpperCase().replace(/[^A-Z0-9]+/g,"_");function Yn(a,o){const h=Fl(a,o);return h?h.includes("ACTIVE_CLAIM")||h.includes("SIGN_SUBMIT")||h.includes("SIGN_AND_SUBMIT")||h.includes("CLAIM_SUBMISSION")||h.includes("CLAIM_SUBMITTED")?!0:h.includes("FILE_REVIEW")||h.includes("REVIEW")?!1:/(^|_)(FILED|CBP|PROTEST|REFUND|REV603|REV613)(_|$)/.test(h)||h.includes("SUBMITTED_TO_CBP")||h.includes("CAPE_SUBMITTED"):!1}function Os(a,o){return!Yn(a,o)}const qs=Er,An=sl.filter(a=>!al[a]);function yc(){var Ja,Xa;const{dataSourceFilter:a}=Tn(),o=Rr(),{toast:h}
1=Jt(),[p,v]=Dr(),S=p.get("view")||"presubmit",[c,n]=d.useState(S),b=d.useRef(null);d.useEffect(()=>{const s=new URLSearchParams(p);s.get("view")!==c&&(s.set("view",c),v(s,{replace:!0})),is(1)},[c]),d.useEffect(()=>{S!==c&&n(S)},[S]);const[f,D]=d.useState([]),[l,A]=d.useState([]),[j,y]=d.useState({}),[k,C]=d.useState({}),[N,x]=d.useState({}),[z,be]=d.useState({}),[R,B]=d.useState({}),[$,w]=d.useState({}),[V,Z]=d.useState({}),[P,H]=d.useState({}),[ce,de]=d.useState({}),[ve,ue]=d.useState({}),[Qe,kt]=d.useState({}),[Xt,js]=d.useState({}),[ot,vs]=d.useState({}),[_t,ys]=d.useState({}),[Ye,ws]=d.useState({}),[bt,Ns]=d.useState({}),[ct,U]=d.useState({}),[ie,jt]=d.useState({}),[qe,es]=d.useState({}),[ks,Gs]=d.useState({}),[Te,Gn]=d.useState(null),[Ma,Zn]=d.useState({}),[Jn,Ta]=d.useState(!0),[Ea,La]=d.useState(!1),{settings:Zs}=nl(),[vt,Xn]=d.useState(""),[ts,er]=d.useState("All"),[St,tr]=d.useState("All"),[It,sr]=d.useState("All"),[dt,ar]=d.useState("All"),[ss,nr]=d.useState("All"),[Ge,rr]=d.useState("Hide Likely Test"),[as,ir]=d.useState("All"),[Ct,lr]=d.useState("All"),[At,or]=d.useState("All"),[ut,$a]=d.useState("started"),[Ee,Ss]=d.useState({}),[Cs,Fa]=d.useState("started"),[ns,Ia]=d.useState("desc"),[Y,Oa]=d.useState(new Set),[Re,Rt]=d.useState(new Set),[nt,Js]=d.useState(""),[cr,As]=d.useState(!1),[Xs,qa]=d.useState([]),[dr,ea]=d.useState(!1),[rs,za]=d.useState(""),[ur,Rs]=d.useState(!1),[yt,ta]=d.useState(""),[mr,is]=d.useState(1);d.useEffect(()=>{(async()=>{try{const{data:m}=await _.rpc("get_case_managers");if(Array.isArray(m)&&m.length){const E=new Map;for(const g of m)E.has(g.user_id)||E.set(g.user_id,g);qa(Array.from(E.values()).map(g=>({user_id:g.user_id,name:g.full_name||g.name,email:g.email})));return}}catch{}const{data:s}=await _.from("user_roles").select("user_id, role").in("role",["case_manager","admin"]),u=Array.from(new Set((s??[]).map(m=>m.user_id)));if(u.length){const{data:m}=await _.from("profiles").select("user_id, email, full_name").in("user_id",u);qa((m??[]).map(E=>({user_id:E.user_id,email:E.email,name:E.full_name})))}})()},[]);const rt=async()=>{var sn;const[s,u,m,E,g,O,re,K,ee,De,Q,t,F,ye,Ae,Fe,Ze]=await Promise.all([_.from("leads").select("*").eq("data_source",a).order("created_at",{ascending:!1}).range(0,4999),_.from("affiliates").select("id, full_name, email, phone, company, slug, upline_affiliate_id, organization_id, comp_model, pool_pct, created_at").eq("data_source",a).limit(2e4),_.from("advance_funding").select("*").eq("data_source",a),_.from("cape_batches").select("lead_id, status, batch_number, total_refund, entries_count").eq("data_source",a).order("created_at",{ascending:!1}),_.from("protests").select("lead_id, status, protest_number, amount_at_issue").eq("data_source",a).order("created_at",{ascending:!1}),_.from("organizations").select("id, company_short_name, slug, internal_logo_url, internal_icon_url, favicon_url, is_default"),_.from("claim_details").select("lead_id, estimated_recovery, qualification_score, funding_stage, refund_amount, refund_received_date, external_case_numbers, engagement_fee_pct_override, funding_only, tra_payment_channel, tra_payment_status, tra_paid_at").eq("data_source",a),_.from("claim_entries").select("lead_id, ieepa_duties, estimated_refund, entry_date, liquidation_status, liquidation_date, protest_deadline").eq("data_source",a),_.from("partner_claim_links").select("lead_id, partner_id, external_claim_id, external_status, last_synced_at"),_.from("claim_agreements").select("lead_id, status, voided_at"),_.from("lead_documents").select("lead_id, document_type, is_current"),_.from("funding_applications").select("id, lead_id, status, created_at").order("created_at",{ascending:!1}),_.from("lead_activity_log").select("lead_id, action, new_status, created_at").order("created_at",{ascending:!1}).range(0,9999),_.from("anchor_claim_snapshots").select("lead_id, estimated_refund, phase_1_filed_amount, phase_2_eligible_amount, phase_3_nonfiled_amount, total_refund_amount, stage, stage_label, fetched_at, anchor_updated_at").eq("is_current",!0),_.from("anchor_processing_summaries").select("lead_id, payload, version").eq("is_current",!0),_.rpc("admin_anchor_lead_milestones"),_.from("anchor_refund_receipts").select("lead_id, status, total, received_date, updated_at")]);D(s.data||[]);const Be=u.data||[],Pt=new Set(Be.map(i=>i.id)),Je=Array.from(new Set((s.data||[]).map(i=>i.affiliate_id).filter(i=>!!i&&!Pt.has(i))));let ze=Be;if(Je.length>0){const{data:i}=await _.from("affiliates").select("id, full_name, email, phone, 
1company, slug, upline_affiliate_id, organization_id, comp_model, pool_pct, created_at").in("id",Je);i&&i.length&&(ze=[...Be,...i])}A(ze);const Xe={};(m.data||[]).forEach(i=>{Xe[i.lead_id]=i}),C(Xe);const{data:r}=await _.from("tra_invoices").select("lead_id, status, amount_paid, total, amount_due").eq("data_source",a).eq("status","paid"),I={};(r||[]).forEach(i=>{if(!(i!=null&&i.lead_id))return;const M=Number(i.amount_paid)||Number(i.total)||Number(i.amount_due)||0;I[i.lead_id]=(I[i.lead_id]||0)+(Number.isFinite(M)?M:0)}),x(I);const te={};(t.data||[]).forEach(i=>{i!=null&&i.lead_id&&!te[i.lead_id]&&(te[i.lead_id]={id:i.id,status:i.status})}),js(te);const Pe={};(E.data||[]).forEach(i=>{Pe[i.lead_id]||(Pe[i.lead_id]=i)}),be(Pe);const Me={};(g.data||[]).forEach(i=>{Me[i.lead_id]||(Me[i.lead_id]=i)}),B(Me);const pe={};(O.data||[]).forEach(i=>{pe[i.id]=i}),y(pe);const le={};(re.data||[]).forEach(i=>{le[i.lead_id]=i}),w(le);const Le={};(K.data||[]).forEach(i=>{var M;(Le[M=i.lead_id]||(Le[M]=[])).push(i)}),Z(Le);const Ie={};(ee.data||[]).forEach(i=>{const M=Ie[i.lead_id];(!M||(i.last_synced_at||"")>(M.last_synced_at||""))&&(Ie[i.lead_id]=i)}),H(Ie);const He={};(De.data||[]).forEach(i=>{var se;if(i.voided_at)return;const M=He[se=i.lead_id]||(He[se]={signed:0,total:0});M.total++,["signed","countersigned"].includes(i.status)&&M.signed++}),de(He);const We={},xt={},os=new Set(["entry_summary","ace_es003","ace_es701","ace_es702","ace_rev103","ace_rev104","ace_raw","ace_report","ace_screenshot","ace_data","cape_phase1_csv"]);(Q.data||[]).forEach(i=>{We[i.lead_id]=(We[i.lead_id]||0)+1,i.is_current!==!1&&os.has(i.document_type)&&(xt[i.lead_id]=(xt[i.lead_id]||0)+1)}),ue(We),kt(xt);const et={},Mt={},Ke={};(F.data||[]).forEach(i=>{var M,se;i!=null&&i.lead_id&&(Mt[i.lead_id]||(Mt[i.lead_id]=i.created_at),!et[i.lead_id]&&i.new_status&&(et[i.lead_id]=i.created_at),i.new_status==="submitted_to_processor"?(Ke[M=i.lead_id]||(Ke[M]={})).submitted=i.created_at:i.new_status==="filed_with_cbp"&&((Ke[se=i.lead_id]||(Ke[se]={})).filed=i.created_at))});const he=(Fe==null?void 0:Fe.data)||[],qt={};for(const i of he)i!=null&&i.lead_id&&(qt[i.lead_id]={first_seen_at:i.first_seen_at,first_filed_at:i.first_filed_at});for(const i of s.data||[]){const M=qt[i.id],se=Ke[sn=i.id]||(Ke[sn]={});!se.submitted&&(M!=null&&M.first_seen_at)&&(se.submitted=M.first_seen_at),se.filed||(se.filed=(M==null?void 0:M.first_filed_at)||i.anchor_backed_at||void 0),et[i.id]||(i.status==="filed_with_cbp"&&se.filed?et[i.id]=se.filed:i.status==="submitted_to_processor"&&se.submitted&&(et[i.id]=se.submitted))}vs(et),ys(Mt),ws(Ke);const Ps={},zt={},Bt={},cs=i=>{const M=Number(i);return Number.isFinite(M)&&M>0?M:void 0};(ye.data||[]).forEach(i=>{i!=null&&i.lead_id&&(zt[i.lead_id]=i,Ps[i.lead_id]={hasSnapshot:!0,estimatedRefund:cs(i.estimated_refund),stage:i.stage,stageLabel:i.stage_label,fetchedAt:i.fetched_at,anchorUpdatedAt:i.anchor_updated_at})}),U(Ps);const Ms={},Ts={};(Ae.data||[]).forEach(i=>{i!=null&&i.lead_id&&(Ms[i.lead_id]=!0,Bt[i.lead_id]={payload:i.payload},typeof i.version=="number"&&(Ts[i.lead_id]=i.version))}),jt(Ms);const pt={};new Set([...Object.keys(zt),...Object.keys(Bt)]).forEach(i=>{var Tt,ds,us,an;const M=zt[i],se=Bt[i],W=Pi(M,se),ae={};W.total!=null&&(W.totalSource==="anchor_direct"||W.totalSource==="anchor_direct_computed"||W.totalSource==="anchor_summary"||W.totalSource==="anchor_derived")&&(ae.eligible=W.total),W.phase1!=null&&(W.phase1Source==="anchor_direct"||W.phase1Source==="anchor_summary"||W.phase1Source==="anchor_derived")&&(ae.phase1=W.phase1),W.phase2!=null&&(W.phase2Source==="anchor_direct"||W.phase2Source==="anchor_summary")&&(ae.phase2=W.phase2),W.phase3!=null&&(W.phase3Source==="anchor_direct"||W.phase3Source==="anchor_summary")&&(ae.phase3=W.phase3,ae.phase3Source=W.phase3Source==="anchor_direct"?"api":"workbook"),W.apiTotal!=null&&(ae.apiTotal=W.apiTotal,ae.hasApiTotal=!0),W.apiPhase1!=null&&W.apiPhase1>0&&(ae.apiPhase1=W.apiPhase1,ae.hasApiPhase1=!0),W.apiPhase2!=null&&W.apiPhase2>0&&(ae.apiPhase2=W.apiPhase2,ae.hasApiPhase2=!0);const Ut=cs(M==null?void 0:M.estimated_refund);if(Ut&&(Yn(M==null?void 0:M.stage,M==null?void 0:M.stage_label)?ae.filed=Ut:(ae.echo=Ut,ae.echoStage=(M==null?void 0:M.stage_label)||(M==null?void 0:M.stage)||"File Review")),se&&se.payload){const we=se.payload;if(typeof we.phase3_amount=="number"&&we.phase3_amount>0&&(ae.phase3=we.phase3_amount,ae.phase3Source="workbook"),we.workbook_shape&&(ae.workbookShape=we.workbook_shape),typeof we.extraction_confidence=="number"&&(ae.extractionConfidence=we.extraction_confidence),typeof we.dataset_health_score=="number"&&(ae.datasetHealthScore=we.dataset_health_score),![we.total_eligible_refund_ieepa,we.phase1_eligible_amount,we.phase2_amount,we.phase3_amount,we.all_potential_amount,we.total_recoverable,(Tt=we.derived)==null?void 0:Tt.total_ieepa_recoverable_duty,(ds=we.derived)==null?void 0:ds.phase1_recoverable_duty].some(ms=>typeof ms=="number"&&ms>0)&&!ae.apiTotal&&!ae.apiPhase1){ae.parsedZero=!0;
1const ms=((us=we.derived)==null?void 0:us.entries_count)??0,nn=((an=we.derived)==null?void 0:an.liquidated_count)??0;ae.parsedZeroReason=ms===0?"Workbook parsed · no entries analyzed":`Workbook parsed · ${ms} entries analyzed · $0 CAPE-eligible${nn?` (${nn} liquidated)`:""}`,ae.workbookVersion=Ts[i]}}pt[i]=ae}),es(pt);const Es={};(Ze.data||[]).forEach(i=>{var W;if(!(i!=null&&i.lead_id))return;const M=Es[W=i.lead_id]||(Es[W]={totalReceived:0,count:0,latestDate:null,latestStatus:null,hasNoAch:!1,hasMismatch:!1,hasPartial:!1,hasReceived:!1});M.count+=1,(i.status==="received"||i.status==="partial")&&(M.totalReceived+=Number(i.total||0)),i.status==="received"&&(M.hasReceived=!0),i.status==="partial"&&(M.hasPartial=!0),i.status==="rejected_no_ach"&&(M.hasNoAch=!0),i.status==="mismatch"&&(M.hasMismatch=!0);const se=i.received_date||i.updated_at;se&&(!M.latestDate||se>M.latestDate)&&(M.latestDate=se,M.latestStatus=i.status)}),Gs(Es),(async()=>{var ae,Ut;const i=Object.keys(pt);if(!i.length)return;const{data:M,error:se}=await _.rpc("admin_leads_refund_rollup",{_lead_ids:i});if(se||!Array.isArray(M))return;let W=0;for(const Tt of M){const ds=((ae=pt[Tt.lead_id])==null?void 0:ae.eligible)??((Ut=pt[Tt.lead_id])==null?void 0:Ut.filed)??0,us=Number(Tt.resolved_total??0);Math.abs((ds||0)-us)>1&&(W++,W<=5&&console.warn("[anchor-refund-drift] client resolver disagrees with admin_leads_refund_rollup RPC",{lead_id:Tt.lead_id,client:ds,server:us}))}W>0&&console.warn(`[anchor-refund-drift] ${W} lead(s) diverged between client and server resolver`)})(),_.from("anchor_sync_log").select("finished_at, triggered_by").eq("source","pull-anchor-claim").eq("status","success").not("finished_at","is",null).order("finished_at",{ascending:!1}).limit(1).maybeSingle().then(({data:i})=>{i&&Gn({finished_at:i.finished_at,triggered_by:i.triggered_by})});const{data:Cr}=await _.from("brokers").select("id, full_name, company_name, data_source").eq("data_source",a).order("company_name",{ascending:!0}),en={};(Cr||[]).forEach(i=>{en[i.id]=i}),Ns(en);const{data:Ar}=await _.from("lead_tags").select("lead_id, tag_key").eq("is_active",!0).in("tag_key",["ace_issue_not_started","ace_issue_waiting_on_client","ace_issue_applied"]),ra={},tn=["ace_issue_not_started","ace_issue_waiting_on_client","ace_issue_applied"];(Ar||[]).forEach(i=>{const M=i.tag_key,se=ra[i.lead_id];(!se||tn.indexOf(M)<tn.indexOf(se))&&(ra[i.lead_id]=M)}),Zn(ra),Ta(!1)};d.useEffect(()=>{Ta(!0),rt()},[a]);const mt=d.useMemo(()=>Object.fromEntries(l.map(s=>[s.id,s])),[l]),Ba=d.useMemo(()=>l.filter(s=>f.some(u=>u.affiliate_id===s.id)),[l,f]),Ua=d.useMemo(()=>Object.values(bt),[bt]),hr=Ua.length>0,Va=d.useMemo(()=>{const s=new Set;return f.forEach(u=>{u.organization_id&&s.add(u.organization_id);const m=u.affiliate_id?mt[u.affiliate_id]:null;m!=null&&m.organization_id&&s.add(m.organization_id)}),Array.from(s).map(u=>j[u]).filter(Boolean)},[f,mt,j]),ls=d.useMemo(()=>f.filter(s=>{var I,te,Pe,Me;const u=!!((I=P[s.id])!=null&&I.external_claim_id);if(ln(s,$[s.id]))return!1;if(c==="funding"){if(!on(s,$[s.id],k[s.id]))return!1}else if(c==="filed"){if(!cn({lead:s,claimDetails:$[s.id],invoicePaid:(N[s.id]||0)>0}))return!1}else if(ya({lead:s,claimDetails:$[s.id],hasProcessorLink:u,advanceFunding:k[s.id],invoicePaid:(N[s.id]||0)>0})!==c)return!1;const m=!vt||((te=s.company_name)==null?void 0:te.toLowerCase().includes(vt.toLowerCase()))||((Pe=s.contact_name)==null?void 0:Pe.toLowerCase().includes(vt.toLowerCase()))||((Me=s.contact_email)==null?void 0:Me.toLowerCase().includes(vt.toLowerCase()))||(s.case_number||"").includes(vt.toLowerCase()),E=Wt(s.status),g=ts==="All"||E===ts,O=St==="All"||St==="referral"&&!!s.affiliate_id||St==="broker"&&!!(s.assisted_by_broker_id||s.broker_id)||s.source===St,re=It==="All"||s.affiliate_id===It,K=String(s.funding_intent||"").trim(),ee=!!k[s.id],De=dt==="All"?!0:dt==="any_intent"?K&&K!=="standard"&&K!=="no_funding":dt==="standard"?K==="standard":dt==="no_funding"?!K||K==="no_funding":dt==="active_deal"?ee:dt==="no_deal"?!ee:!0,Q=ct[s.id],t=!!(Q!=null&&Q.hasSnapshot)&&Os(Q.stage,Q.stageLabel),F=!!(Q!=null&&Q.hasSnapshot)&&!!ie[s.id]&&!t,ye=ss==="All"?!0:ss==="Yes"?F:!F,Ae=s.affiliate_id?mt[s.affiliate_id]:null,Fe=s.organization_id||(Ae==null?void 0:Ae.organization_id)||null,Ze=as==="All"||Fe===as,Be=s.assisted_by_broker_id||s.broker_id||null,Pt=Ct==="All"?!0:Ct==="__none__"?!Be:Be===Ct;let Je=!0;if(Ge!=="All"){const pe=Fs(s,Ae),le=pe.level==="strong"||!!s.admin_marked_test,Le=pe.flagged||!!s.admin_marked_test;Je=Ge==="Hide Likely Test"?!le:Ge==="Likely Test"?le:Le}const ze=Ma[s.id],Xe=At==="All"?!0:At==="any"?!!ze:At==="none"?!ze:ze===At;let r=!0;if(Ee.from||Ee.to){const pe=Ye[s.id]||{},le=ut==="started"?s.created_at:ut==="submitted"?pe.submitted:ut==="filed"?pe.filed:null;if(!le)r=!1;else{const Le=new Date(le).getTime();if(Ee.from&&Le<Ee.from.getTime()&&(r=!1),Ee.to){const Ie=new Date(Ee.to);Ie.setHours(23,59,59,999),Le>Ie.getTime()&&(r=!1)}}}return m&&g&&O&&re&&De&&ye&&Ze&&Pt&&Je&&Xe&&r}
1),[f,c,vt,ts,St,It,dt,ss,as,Ct,Ge,At,Ma,k,N,mt,$,P,V,ce,ct,ie,ut,Ee,Ye]),sa=d.useMemo(()=>{const s=g=>g?new Date(g).getTime():null,u=g=>{var re;const O=qe[g]||{};return O.filed??O.apiTotal??O.eligible??((re=ct[g])==null?void 0:re.estimatedRefund)??null},m=g=>{const O=Ye[g.id]||{};switch(Cs){case"submitted":return s(O.submitted)??s(ot[g.id]);case"filed":return s(O.filed);case"started":return s(g.created_at);case"status_changed":return s(ot[g.id])??s(g.updated_at);case"last_activity":return s(_t[g.id])??s(g.updated_at);case"refund":return u(g.id);case"company":return(g.company_name||g.contact_name||"").toLowerCase();default:return null}},E=ns==="asc"?1:-1;return[...ls].sort((g,O)=>{const re=m(g),K=m(O);return re==null&&K==null?0:re==null?1:K==null?-1:typeof re=="string"||typeof K=="string"?String(re).localeCompare(String(K))*E:(Number(re)-Number(K))*E})},[ls,Cs,ns,Ye,ot,_t,qe,ct]),wt=Math.max(1,Math.ceil(sa.length/hs)),it=Math.min(mr,wt),ht=sa.slice((it-1)*hs,it*hs),xr=d.useMemo(()=>ht.map(s=>s.id),[ht]),Ha=Ji(xr),[pr,aa]=d.useState(null),[na,Wa]=d.useState(null);d.useEffect(()=>{is(1)},[vt,ts,St,It,dt,ss,as,Ct,Ge,At,ut,Ee,Cs,ns]);const Dt=d.useMemo(()=>{const s=[{value:"started",label:"App Started"}];return["presubmission","anchor","filed","not_ior","funding","refund_received","tra_paid","closed"].includes(c)&&s.push({value:"submitted",label:"App Submitted"}),["filed","not_ior","funding","refund_received","tra_paid","closed"].includes(c)&&s.push({value:"filed",label:"Filed"}),s},[c]),fr=d.useMemo(()=>{const s=[];return Dt.some(u=>u.value==="submitted")&&s.push({value:"submitted",label:"Submitted for processing"}),Dt.some(u=>u.value==="filed")&&s.push({value:"filed",label:"Filed with CBP"}),s.push({value:"started",label:"App started"},{value:"status_changed",label:"Status changed"},{value:"last_activity",label:"Last activity"},{value:"refund",label:"Refund amount"},{value:"company",label:"Company name"}),s},[Dt]);d.useEffect(()=>{Dt.find(m=>m.value===ut)||($a("started"),Ss({}));const s=c==="filed"||c==="not_ior"?"filed":["presubmission","anchor","funding","refund_received","tra_paid","closed"].includes(c)?"submitted":"started";Fa(s),Ia("desc");const u=new Set;c==="filed"&&u.add("est_ieepa"),(c==="presubmit"||c==="presubmission")&&(u.add("anchor"),u.add("refund")),["filed","not_ior","refund_received","tra_paid","closed"].includes(c)||u.add("receipts"),Oa(u)},[c]);const X=d.useMemo(()=>{const s={presubmit:{count:0,value:0,linked:0},presubmission:{count:0,value:0,linked:0},anchor:{count:0,value:0,linked:0},filed:{count:0,value:0,linked:0},not_ior:{count:0,value:0,linked:0},refund_received:{count:0,value:0,refunded:0},tra_paid:{count:0,value:0,invoiced:0,byChannel:{advance_funded:0,ar_sold:0,direct_billed:0,mixed:0}},funding:{count:0,value:0,activeDeals:0},closed:{count:0,value:0,refunded:0}};return f.forEach(u=>{if(ln(u,$[u.id]))return;if(Ge!=="All"){const t=u.affiliate_id?mt[u.affiliate_id]:null,F=Fs(u,t),ye=F.level==="strong"||!!u.admin_marked_test,Ae=F.flagged||!!u.admin_marked_test;if(Ge==="Hide Likely Test"&&ye||Ge==="Likely Test"&&!ye||Ge==="Possible+"&&!Ae)return}const m=$[u.id],E=V[u.id]||[],g=P[u.id],O=k[u.id],re=qe[u.id],K=N[u.id]||0,ee=ya({lead:u,claimDetails:m,hasProcessorLink:!!(g!=null&&g.external_claim_id),advanceFunding:O,invoicePaid:K>0});cn({lead:u,claimDetails:m,invoicePaid:K>0})&&ee!=="filed"&&(s.filed.count++,s.filed.value+=ba("filed",{lead:u,claimDetails:m,entries:E,advanceFunding:O,anchorRefund:re,invoicePaidAmount:K}),g&&s.filed.linked++);const Q=s[ee];if(Q){if(Q.count++,Q.value+=ba(ee,{lead:u,claimDetails:m,entries:E,advanceFunding:O,anchorRefund:re,invoicePaidAmount:K}),ee==="presubmit"&&g&&s.presubmit.linked++,ee==="presubmission"&&g&&s.presubmission.linked++,ee==="anchor"&&g&&s.anchor.linked++,ee==="filed"&&g&&s.filed.linked++,ee==="not_ior"&&g&&s.not_ior.linked++,ee==="refund_received"&&(m!=null&&m.refund_amount)&&s.refund_received.refunded++,ee==="tra_paid"){K>0&&s.tra_paid.invoiced++;const t=(m==null?void 0:m.tra_payment_channel)||(K>0?"direct_billed":"advance_funded");s.tra_paid.byChannel[t]=(s.tra_paid.byChannel[t]||0)+1}ee==="closed"&&(m!=null&&m.refund_amount)&&s.closed.refunded++}on(u,m,O)&&(s.funding.count++,s.funding.value+=ba("funding",{lead:u,claimDetails:m,entries:E,advanceFunding:O,anchorRefund:re}),O!=null&&O.status&&!["declined","cancelled","expired"].includes(O.status)&&s.funding.activeDeals++)}),s},[f,$,V,k,N,P,qe,Ge,mt]);X.presubmit.count,X.presubmission.count,X.anchor.count,X.filed.count,X.not_ior.count,X.refund_received.count,X.tra_paid.c
1ount,X.funding.count,X.closed.count;const gr=s=>Rt(u=>{const m=new Set(u);return m.has(s)?m.delete(s):m.add(s),m}),_r=()=>Rt(Re.size===ht.length?new Set:new Set(ht.map(s=>s.id))),br=async()=>{if(!nt||Re.size===0)return;const s=Array.from(Re),{error:u}=await _.from("leads").update({status:nt}).in("id",s);if(u){h({title:"Error",description:u.message,variant:"destructive"});return}const m=(await _.auth.getUser()).data.user;await Promise.all([_.from("audit_log").insert(s.map(E=>({user_id:(m==null?void 0:m.id)||null,user_email:(m==null?void 0:m.email)||null,action:"bulk_status_change",entity_type:"lead",entity_id:E,details:{new_status:nt,bulk_count:s.length}}))),_.from("lead_activity_log").insert(s.map(E=>({lead_id:E,action:"status_change",new_status:nt,notes:`Bulk status change to ${Ht[nt]||nt}`,user_id:(m==null?void 0:m.id)||null})))]),h({title:`${s.length} claims updated to ${Ht[nt]}`}),Rt(new Set),Js(""),rt()},Ka=async s=>{if(Re.size===0)return;const u=Array.from(Re),{error:m}=await _.rpc("admin_mark_leads_test",{p_lead_ids:u,p_marked:s});if(m){h({title:"Error",description:m.message,variant:"destructive"});return}h({title:s?`Marked ${u.length} claim(s) as likely test`:`Cleared test flag on ${u.length} claim(s)`}),Rt(new Set),rt()},jr=async()=>{var re,K;if(!rs||Re.size===0)return;const s=Array.from(Re),u=rs==="__none__"?null:rs,m=(await _.auth.getUser()).data.user,E=new Date().toISOString(),{error:g}=await _.from("leads").update({assigned_case_manager_id:u,assigned_by_user_id:(m==null?void 0:m.id)??null,assigned_at:E,last_reassigned_at:E}).in("id",s);if(g){h({title:"Error",description:g.message,variant:"destructive"});return}const O=u?((re=Xs.find(ee=>ee.user_id===u))==null?void 0:re.name)||((K=Xs.find(ee=>ee.user_id===u))==null?void 0:K.email)||"user":"Unassigned";await _.from("lead_crm_activity").insert(s.map(ee=>({lead_id:ee,activity_type:"owner_change",notes:`Bulk reassign → ${O}`,meta:{to_user:u,bulk_count:s.length,actor_user_id:(m==null?void 0:m.id)??null},created_by:(m==null?void 0:m.id)??null}))),h({title:`${s.length} claim(s) reassigned to ${O}`}),ea(!1),za(""),Rt(new Set),rt()},vr=async()=>{if(!yt||Re.size===0)return;const s=Array.from(Re),u=(await _.auth.getUser()).data.user,{data:m}=await _.from("leads").select("id, blocker_tags").in("id",s),E=(m??[]).map(g=>{const O=Array.isArray(g.blocker_tags)?g.blocker_tags:[];return O.includes(yt)?null:{id:g.id,next:[...O,yt]}}).filter(Boolean);if(E.length===0){h({title:`All selected already have "${yt}"`}),Rs(!1),ta("");return}await Promise.all(E.map(g=>_.from("leads").update({blocker_tags:g.next}).eq("id",g.id))),await _.from("lead_crm_activity").insert(E.map(g=>({lead_id:g.id,activity_type:"tag_added",notes:yt,meta:{bulk_count:E.length,actor_user_id:(u==null?void 0:u.id)??null},created_by:(u==null?void 0:u.id)??null}))),h({title:`Tagged ${E.length} claim(s) "${yt}"`}),Rs(!1),ta(""),Rt(new Set),rt()},yr=()=>{const s=t=>t==null||t===""?"":Number(t),u=t=>t?new Date(t).toLocaleDateString():"",m=t=>t?new Date(t).toLocaleString():"",g=[{header:"Case #",get:({l:t})=>t.case_number||""},{header:"Claim Type",get:({l:t,cd:F})=>F!=null&&F.funding_only?"Funding Only":yn(t.claim_type)},{header:"Claim Type Detail",get:({l:t})=>vn(t.claim_type)},{header:"Test Flagged",get:({test:t,l:F})=>t.flagged||F.admin_marked_test?"Yes":"No"},{header:"Test Score",get:({test:t})=>t.score},{header:"Test Reasons",get:({test:t})=>t.reasons.join("; ")},{header:"Admin Marked Test",get:({l:t})=>t.admin_marked_test?"Yes":"No"},{header:"Entries Parsed",get:({ents:t})=>t.length},{header:"Entry Source Files Uploaded",get:({l:t})=>Qe[t.id]||0},{header:"Company",get:({l:t})=>t.company_name||""},{header:"Contact",get:({l:t})=>t.contact_name||""},{header:"Email",get:({l:t})=>t.contact_email||""},{header:"Phone",get:({l:t})=>t.phone||""},{header:"EIN",get:({l:t})=>t.ein||""},{header:"Import Value",get:({iv:t})=>t?s(t.value):""},{header:"Import Value Derived",get:({iv:t})=>t!=null&&t.derived?"Yes":t?"No":""},{header:"Import Value Source",get:({iv:t})=>t!=null&&t.derived?t.source:""},{header:"Original/Client Est. IEEPA",key:"est_ieepa",get:({originalEst:t})=>t.amount>0?ft(t,!1):""},{header:"System Est. IEEPA",key:"est_ieepa",get:({systemEst:t})=>t.amount>0?ft(t,!1):""},{header:"Est. Source",key:"est_ieepa",get:({originalEst:t})=>t.amount>0?t.source:""},{header:"Qualification Score",get:({cd:t,l:F})=>(t==null?void 0:t.qualification_score)??Ti(F)},{header:"CRM Open Tasks",key:"crm",get:({crm:t})=>(t==null?void 0:t.openTasks)??""},{header:"CRM Overdue Tasks",key:"crm",get:({crm:t})=>(t==null?void 0:t.overdueTasks)??""},{header:"CRM Next Task",key:"crm",get:({crm:t})=>t!=null&&t.nextTask?`${t.nextTask.title}${t.nextTask.due_at?` (due ${u(t.nextTask.due_at)})`:""}`:""},{header:"CRM Tags",key:"crm",get:({crm:t})=>((t==null?void 0:t.tags)||[]).map(F=>F.label).join("; ")},{header:"CRM Latest Note",key:"crm",get:({crm:t})=>{var F,ye;return((F=t==null?void 0:t.pinnedNote)==null?void 0:F.note)||((ye=t==null?void 0:t.latestNote)==null?void 0:ye.note)||""}},{header:"CRM Last Activity",key:"crm",get:({crm:t})=>t!=null&&t.latestActivity?`${t.latestActivity.type} — ${m(t.latestActivity.created_at)}`:""},{header:"Anchor State",key:"anchor",get:({anchor:t})=>t.label},{header:"Anchor External Status",key:"anchor",get:({link:t})=>((t==null?void 0:t.external_status)||"").replace(/_/g," ")},{header:"Anchor Last Synced",key:"anchor",get:({anchor:t})=>u(t.syncedAt)},{header:"App Progress Step",get:({intakeStep:t})=>t?`${t.idx}/${t.total} · ${t.label}`:""},{header:"Refund Total",key:"refund",get:({r:t,cd:F})=>s((t==null?void 0:t.eligible)??(t==null?void 0:t.apiTotal)??(t==null?void 0:t.filed)??(F==null?void 0:F.refund_amount))},{header:"Refund Total Source",key:"refund",get:({r:t,cd:F})=>t!=null&&t.eligible?"Anchor Total (API)":t!=null&&t.apiTotal?"Anchor Total (API rollup)":t!=null&&t.filed?"Anchor Filed":F!=null&&F.refund_amount?"Refund Received":t!=null&&t.parsedZero?"Workbook · $0 eligible":""},{header:"Refund Phase 3 (incl.)",key:"refund",get:({r:t})=>s(t==null?void 0:t.phase3)},{header:"Workbook Shape",key:"refund",get:({r:t})=>t!=null&&t.workbookShape&&t.workbookShape!=="unknown"?t.workbookShape.replace(/_/g," "):""},{header:"Refund Received Date",key:"refund",get:({cd:t})=>u(t==null?void 0:t.refund_received_date)},{header:"Phase 1",key:"phase1",get:({r:t})=>s((t==null?void 0:t.phase1)??(t==null?void 0:t.apiPhase1))},{header:"Phase 1 Source",key:"phase1",get:({r:t})=>t!=null&&t.phase1?"Anchor Filed (Workbook)":t!=null&&t.apiPhase1?"Anchor Filed (API)":""},{header:"Phase 2",key:"phase2",get:({r:t})=>s((t==null?void 0:t.phase2)??(t==null?void 0:t.apiPhase2))},{header:"Phase 2 Source",key:"phase2",get:({r:t})=>t!=null&&t.phase2?"Anchor Eligible (Workbook)":t!=null&&t.apiPhase2?"Anchor Eligible (API)":""},{header:"Phase 3",key:"phase3",get:({r:t})=>s(t==null?void 0:t.phase3)},{header:"Phase 3 Source",key:"phase3",get:({r:t})=>t!=null&&t.phase3?t.phase3Source==="api"?"Anchor Non-Filed (API)":"Anchor Non-Filed (Workbook)":""},{header:"Receipts Received",key:"receipts",get:({rcpt:t})=>s(t==null?void 0:t.totalReceived)},{header:"Receipts Status",key:"receipts",get:({rcpt:t})=>t?t.hasReceived?"Received":t.hasPartial?"Partial":t.hasNoAch?"No ACH":t.hasMismatch?"Mismatch":t.latestStatus||"Attempted":""},{header:"Receipts Count",key:"receipts",get:({rcpt:t})=>(t==null?void 0:t.count)??""},{header:"Receipts Latest Date",key:"receipts",get:({rcpt:t})=>u(t==null?void 0:t.latestDate)},{header:"Funding Intent",get:({l:t})=>t.funding_intent||""},{header:"Wants Funding (intake)",get:({l:t})=>t.sell_interest||""},{header:"Cash Urgency (intake)",get:({l:t})=>t.cash_urgency||""},{header:"Funding Application Status",get:({fundApp:t})=>t?String(t.status).replace(/_/g," "):""},{header:"Funding Stage",get:({cd:t})=>t!=null&&t.funding_stage?bn[t.funding_stage]||t.funding_stage:""},{header:"Funding Deal Status",get:({fund:t})=>((t==null?void 0:t.status)||"").replace(/_/g," ")},{header:"Advance Amount",get:({fund:t})=>s(t==null?void 0:t.advance_amount)},{header:"Status",get:({l:t})=>Ht[Wt(t.status)]||t.status},{header:"App Started",key:"dates",get:({l:t})=>u(t.created_at)},{header:"App Submitted",key:"dates",get:({l:t})=>{var F;return u((F=Ye[t.id])==null?void 0:F.submitted)}},{header:"Filed",key:"dates",get:({l:t})=>{var F;return u((F=Ye[t.id])==null?void 0:F.filed)}},{header:"Days in Status",key:"days_in_status",get:({daysInStatus:t})=>t??""},{header:"Stalled",key:"days_in_status",get:({stalled:t})=>t?"Yes":"No"},{header:"Status Changed At",key:"days_in_status",get:({statusChangedAt:t})=>m(t)},{header:"Last Activity (days)",key:"last_activity",get:({lastActDays:t})=>t??""},{header:"Last Activity At",key:"last_activity",get:({lastActAt:t})=>m(t)},{header:"Contingency %",key:"contingency",get:({contingencyPct:t})=>t},{header:"Contingency Override",key:"contingency",get:({contingencyOverride:t})=>t!=null?"Yes":"No"},{header:"Source",key:"source",get:({l:t,partner:F})=>F?"referral":t.source||"direct"},{header:"Partner Name",key:"source",get:({partner:t})=>(t==null?void 0:t.full_name)||""},{header:"Partner Company",key:"source",get:({partner:t})=>(t==null?void 0:t.company)||""},{header:"Partner Slug",key:"source",get:({partner:t})=>(t==null?void 0:t.slug)||""},{header:"Partner Email",key:"source",get:({partner:t})=>(t==null?void 0:t.email)||""},{header:"Partner Phone",key:"source",get:({partner:t})=>(t==null?void 0:t.phone)||""}
1,{header:"Partner Comp Model",key:"source",get:({partner:t})=>(t==null?void 0:t.comp_model)||""},{header:"Partner Pool %",key:"source",get:({partner:t})=>(t==null?void 0:t.pool_pct)??""},{header:"Organization",key:"source",get:({org:t})=>(t==null?void 0:t.company_short_name)||""},{header:"UTM Source",key:"source",get:({l:t})=>t.utm_source||""},{header:"UTM Campaign",key:"source",get:({l:t})=>t.utm_campaign||""},{header:"Ref Slug",key:"source",get:({l:t})=>t.ref_slug||""},{header:"Broker",key:"broker",get:({broker:t})=>(t==null?void 0:t.company_name)||(t==null?void 0:t.full_name)||""},{header:"Broker Contact",key:"broker",get:({broker:t})=>(t==null?void 0:t.full_name)||""},{header:"Updated (days ago)",key:"updated",get:({days:t})=>t},{header:"Created",get:({l:t})=>m(t.created_at)},{header:"Updated",get:({l:t})=>m(t.updated_at)}].filter(t=>!t.key||!Y.has(t.key)),O=g.map(t=>t.header),re=sa.map(t=>{const F=t.affiliate_id?mt[t.affiliate_id]:null,ye=t.organization_id||(F==null?void 0:F.organization_id)||null,Ae=ye?j[ye]:null,Fe=$[t.id],Ze=V[t.id]||[],Be=Ca(t,Fe,Ze,{skipAnchor:!0}),Pt=jn(t),Je=Fs(t,F),ze=P[t.id],Xe=k[t.id],r=Xt[t.id],I=qe[t.id],te=ks[t.id],Pe=Ha[t.id],Me=t.assisted_by_broker_id||t.broker_id||null,pe=Me?bt[Me]:null,le=Sn(t),Le=kn(t.status),Ie=ot[t.id]||t.created_at,He=Ie?Math.max(0,Math.floor((Date.now()-new Date(Ie).getTime())/864e5)):null,We=(He??0)>=14&&qs(t.status)!=="closed",xt=_t[t.id]||t.last_activity_at||t.created_at,os=xt?Math.max(0,Math.floor((Date.now()-new Date(xt).getTime())/864e5)):null,et=(Fe==null?void 0:Fe.engagement_fee_pct_override)!=null?Number(Fe.engagement_fee_pct_override):null,Mt=et??Number(Zs.default_engagement_fee_pct||20),Ke=Math.max(0,Math.ceil((Date.now()-new Date(t.updated_at).getTime())/864e5)),he=ct[t.id],qt=!!(he!=null&&he.hasSnapshot),Ps=!!ie[t.id],zt=qt&&Os(he==null?void 0:he.stage,he==null?void 0:he.stageLabel),Bt=((he==null?void 0:he.stageLabel)||(he==null?void 0:he.stage)||"").toString().replace(/_/g," ").trim().toLowerCase().replace(/\b\w/g,pt=>pt.toUpperCase()),cs=/^active claim/i.test(Bt)?"Active Claim":Bt,Ms={label:qt&&Ps&&!zt?cs||"Active Claim":qt?cs||(zt?"File Review":"Synced"):ze?"Pushed":"Preliminary",syncedAt:(ze==null?void 0:ze.last_synced_at)||(he==null?void 0:he.fetchedAt)||(he==null?void 0:he.anchorUpdatedAt)||null},Ts={l:t,partner:F,org:Ae,cd:Fe,ents:Ze,originalEst:Be,systemEst:Pt,test:Je,link:ze,fund:Xe,fundApp:r,r:I,rcpt:te,crm:Pe,broker:pe,iv:le,intakeStep:Le,statusChangedAt:Ie,daysInStatus:He,stalled:We,lastActAt:xt,lastActDays:os,contingencyOverride:et,contingencyPct:Mt,days:Ke,anchor:Ms};return g.map(pt=>pt.get(Ts))}),K="\uFEFF"+[O,...re].map(t=>t.map(F=>`"${String(F??"").replace(/"/g,'""')}"`).join(",")).join(`
2`),ee=new Blob([K],{type:"text/csv;charset=utf-8;"}),De=URL.createObjectURL(ee),Q=document.createElement("a");Q.href=De,Q.download=`claims-${c}-${new Date().toISOString().split("T")[0]}.csv`,Q.click(),URL.revokeObjectURL(De),h({title:"Export ready",description:`${re.length} claim(s) · ${O.length} columns downloaded.`})},wr=async()=>{La(!0);try{const{data:s,error:u}=await _.functions.invoke("pull-anchor-claim",{body:{all_anchor:!0,triggered_by:"admin_ui_bulk_sync"}});if(u)throw u;const m=Array.isArray(s==null?void 0:s.results)?s.results:[],E=m.filter(O=>O.status==="success").length,g=m.filter(O=>O.status!=="success").length;h({title:"Anchor sync complete",description:`${E} synced${g?` · ${g} failed`:""}${m.length===0?" (queued in background)":""}`}),rt()}catch(s){h({title:"Anchor sync failed",description:s.message,variant:"destructive"})}La(!1)},[Qa,Ya]=d.useState(!1),[lt,Ot]=d.useState(null),Nr=async s=>{var u,m,E,g,O,re;Ot(null),Ya(!0);try{const K=await _.functions.invoke("recategorize-anchor-docs",{body:{force_all:s==="all",batch_size:1e3}});if(K.error)throw K.error;const ee=((u=K.data)==null?void 0:u.changed)??0,De=((m=K.data)==null?void 0:m.scanned)??0;h({title:"Re-categorization done",description:`Scanned ${De} · updated ${ee}`});const Q=await _.functions.invoke("sweep-anchor-workbooks",{body:{mode:s}});if(Q.error)throw Q.error;
2const t=((E=Q.data)==null?void 0:E.leads)??0,F=((g=Q.data)==null?void 0:g.changed)??0,ye=((O=Q.data)==null?void 0:O.skipped)??0,Ae=((re=Q.data)==null?void 0:re.errors)??0;h({title:`Re-parse complete (${s})`,description:`${t} claims processed${ye?` · ${ye} skipped (unchanged)`:""} · ${F} refreshed${Ae?` · ${Ae} errors`:""}`}),rt()}catch(K){h({title:"Re-parse failed",description:K.message,variant:"destructive"})}Ya(!1)};if(Jn)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(J,{className:"h-6 w-6 animate-spin text-muted-foreground"})});const Ds=c==="anchor",kr=c==="funding",Sr=c==="presubmit",Ga=c==="presubmission",Za=c==="filed";return e.jsxs(Mr,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsxs("h1",{className:"font-display font-semibold text-xl sm:text-2xl text-foreground flex items-center gap-2",children:[e.jsx(Qr,{className:"h-5 w-5 sm:h-6 sm:w-6 text-gold"})," Claim Management"]}),(Te==null?void 0:Te.finished_at)&&(()=>{const s=new Date(Te.finished_at).getTime(),u=Math.max(0,Math.round((Date.now()-s)/6e4)),m=u<1?"just now":u<60?`${u}m ago`:u<60*24?`${Math.round(u/60)}h ago`:`${Math.round(u/1440)}d ago`,E=u<60;return e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs("span",{className:`inline-flex items-center gap-1.5 self-start rounded-full border px-2 py-0.5 text-[10px] font-medium tracking-wide uppercase transition ${E?"border-success/40 bg-success/10 text-success":"border-border bg-muted/40 text-muted-foreground"}`,children:[e.jsx(at,{className:`h-3 w-3 ${E?"text-success":""}`}),"Last Anchor sync · ",m,E&&e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-success animate-pulse"})]})}),e.jsxs(_e,{side:"bottom",className:"text-xs",children:[e.jsx("div",{children:new Date(Te.finished_at).toLocaleString()}),e.jsxs("div",{className:"text-muted-foreground",children:["Trigger: ",Te.triggered_by||"—"]})]})]})})()]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(L,{variant:"outline",size:"sm",disabled:Ea,onClick:wr,title:"Pull latest stage, refund fields, and documents for every anchor-linked claim",className:"gap-1.5 border-blue-200 bg-gradient-to-b from-blue-50 to-blue-100/60 text-blue-700 hover:from-blue-100 hover:to-blue-200/70 hover:border-blue-300 hover:text-blue-800 shadow-sm dark:border-blue-900/60 dark:from-blue-950/40 dark:to-blue-900/20 dark:text-blue-300 dark:hover:from-blue-900/50",children:[Ea?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(at,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline font-semibold",children:"Sync with Anchor"}),e.jsx("span",{className:"sm:hidden font-semibold",children:"Anchor"})]}),e.jsxs(ia,{children:[e.jsx(la,{asChild:!0,children:e.jsxs(L,{variant:"outline",size:"sm",disabled:Qa,title:"Re-classify mirrored documents and re-run the Summary Workbook parser. Pick a scope to conserve resources.",className:"gap-1.5 border-violet-200 bg-gradient-to-b from-violet-50 to-violet-100/60 text-violet-700 hover:from-violet-100 hover:to-violet-200/70 hover:border-violet-300 hover:text-violet-800 shadow-sm dark:border-violet-900/60 dark:from-violet-950/40 dark:to-violet-900/20 dark:text-violet-300 dark:hover:from-violet-900/50",children:[Qa?e.jsx(J,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(xn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline font-semibold",children:"Re-parse Docs"}),e.jsx("span",{className:"sm:hidden font-semibold",children:"Re-parse"})]})}),e.jsxs(oa,{align:"end",className:"w-72",children:[e.jsx(ca,{children:"Re-parse scope"}),e.jsx(rn,{}),e.jsxs(Vt,{onSelect:()=>Ot("new"),className:"flex-col items-start gap-0.5",children:[e.jsx("span",{className:"font-medium",children:"New only"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Claims with no processed summary yet. Cheapest."})]}),e.jsxs(Vt,{onSelect:()=>Ot("changed"),className:"flex-col items-start gap-0.5",children:[e.jsx("span",{className:"font-medium",children:"Changed / updated"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Only files whose hash isn't in a successful parse log yet."})]}),e.jsxs(Vt,{onSelect:()=>Ot("affected"),className:"flex-col items-start gap-0.5",children:[e.jsx("span",{className:"font-medium",children:"Affected only"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Re-parse claims whose last parse looks unhealthy (low confidence, unknown labels, unreconciled, missing fields). Auto-heals problem parses."})]}),e.jsx(rn,{}),e.jsxs(Vt,{onSelect:()=>Ot("all"),className:"flex-col items-start gap-0.5",children:[e.jsx("span",{className:"font-medium",children:"All docs (force)"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Force re-parse everything. Use after parser upgrades."})]})]})]}),e.jsx(ji,{open:lt!==null,onOpenChange:s=>{s||Ot(null)},children:e.jsxs(vi,{children:[e.jsxs(yi,{children:[e.jsxs(wi,{children:["Re-parse ",lt==="all"?"all documents":lt==="changed"?"changed/updated files":lt==="affected"?"affected claims only":"new claims only","?"]}),e.jsxs(Ni,{children:[lt==="all"&&"Every mirrored Anchor document will be re-categorized and every Summary/Claim/ACE 
2workbook re-parsed. This is the heaviest option — use after parser upgrades or when troubleshooting.",lt==="changed"&&"Only files whose current sha256 hash is missing from a successful, reconciled parse log entry will be re-parsed. Skips claims where nothing has changed.",lt==="affected"&&"Only claims whose latest parse log shows a problem — low extraction confidence, unknown bucket labels, missing required fields, unreconciled totals, or low fingerprint confidence. Cheapest way to auto-heal problem parses.",lt==="new"&&"Only claims with no anchor_processing_summaries row yet. Fastest — picks up brand new claims.",e.jsx("br",{}),e.jsx("br",{}),"Safe to run — nothing is deleted."]})]}),e.jsxs(ki,{children:[e.jsx(Si,{children:"Cancel"}),e.jsx(Ci,{onClick:()=>lt&&Nr(lt),children:"Run"})]})]})}),e.jsx(Cl,{}),e.jsx(Rl,{}),e.jsx(Fi,{}),e.jsx(Ii,{}),e.jsxs(L,{variant:"outline",size:"sm",onClick:yr,className:"gap-1.5 border-slate-300 bg-gradient-to-b from-slate-50 to-slate-100/70 text-slate-700 hover:from-slate-100 hover:to-slate-200/70 hover:border-slate-400 hover:text-slate-900 shadow-sm dark:border-slate-700 dark:from-slate-800/60 dark:to-slate-900/40 dark:text-slate-200 dark:hover:from-slate-800",children:[e.jsx(Da,{className:"h-4 w-4"})," ",e.jsx("span",{className:"hidden sm:inline font-semibold",children:"Export "}),e.jsx("span",{className:"font-semibold",children:"CSV"})]})]})]}),e.jsx(ll,{leads:f,claimDetailsMap:$,partnerLinkMap:P,fundingMap:k}),e.jsxs(Kn,{value:c,onValueChange:s=>n(s),children:[(()=>{const s=m=>G(m,{compact:!0}),u=[{key:"presubmit",label:"Applying",icon:xn,count:X.presubmit.count,value:X.presubmit.value,sub:`${X.presubmit.linked} pushed to processor`,accent:"text-blue-500"},{key:"presubmission",label:"Pre-Submission",icon:$s,count:X.presubmission.count,value:X.presubmission.value,sub:`${X.presubmission.linked} linked before submission`,accent:"text-violet-500"},{key:"anchor",label:"Processing",icon:Yr,count:X.anchor.count,value:X.anchor.value,sub:`${X.anchor.linked} linked w/ external case #`,accent:"text-amber-500"},{key:"filed",label:"Filed",icon:Gr,count:X.filed.count,value:X.filed.value,sub:`${X.filed.linked} linked w/ external case #`,accent:"text-cyan-500"},{key:"not_ior",label:"Non-IOR",icon:fs,count:X.not_ior.count,value:X.not_ior.value,sub:"Client is not the Importer of Record",accent:"text-rose-500"},{key:"tra_paid",label:"Paid",icon:Zr,count:X.tra_paid.count,value:X.tra_paid.value,sub:(()=>{const m=X.tra_paid.byChannel,E=m.advance_funded||0,g=m.ar_sold||0,O=m.direct_billed||0;return!E&&!g&&!O?"no payments collected":`${E} adv · ${g} AR · ${O} invoiced`})(),accent:"text-gold"},{key:"closed",label:"Closed",icon:zs,count:X.closed.count,value:X.closed.value,sub:`${X.closed.refunded} refund${X.closed.refunded===1?"":"s"} received`,accent:"text-gold"}];return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 xl:grid-cols-7 gap-3",children:u.map(m=>{const E=c===m.key,g=m.icon;return e.jsxs("button",{type:"button",onClick:()=>n(m.key),className:`text-left rounded-lg border bg-card p-4 transition-all hover:shadow-md hover:border-gold/40 focus:outline-none focus:ring-2 focus:ring-gold/50 ${E?"border-gold ring-2 ring-gold/30 shadow-sm":"border-border"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(g,{className:`h-4 w-4 ${m.accent}`}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:m.label})]}),e.jsx(T,{variant:"secondary",className:"text-[10px]",children:m.count})]}),e.jsx("div",{className:"text-2xl font-display font-semibold text-foreground leading-tight",children:s(m.value)}),e.jsx("div",{className:"text-[11px] text-muted-foreground mt-1 truncate",children:m.sub})]},m.key)})})})(),e.jsxs(st,{value:c,className:"mt-3",children:[Re.size>0&&e.jsx(ja,{className:"border-gold/30 bg-gold/5 mb-3",children:e.jsxs(va,{className:"p-3 flex items-center gap-3 flex-wrap",children:[e.jsx(Jr,{className:"h-4 w-4 text-gold"}),e.jsxs("span",{className:"text-sm font-medium",children:[Re.size," selected"]}),e.jsxs(Ne,{value:nt,onValueChange:Js,children:[e.jsx(ke,{className:"w-44 h-8",children:e.jsx(Se,{placeholder:"Set status..."})}),e.jsx(Ce,{children:An.map(s=>e.jsx(q,{value:s,children:Ht[s]},s))})]}),e.jsx(L,{size:"sm",onClick:()=>As(!0),disabled:!nt,className:"bg-gold text-gold-foreground hover:bg-gold/90",children:"Apply"}),e.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5 border-rose-500/40 text-rose-600 hover:bg-rose-500/10",onClick:()=>{Js("not_ior"),As(!0)},children:[e.jsx(fs,{className:"h-3.5 w-3.5"})," Mark Non-IOR"]}),e.jsxs(ma,{open:dr,onOpenChange:ea,children:[e.jsx(ha,{asChild:!0,children:e.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"})," Assign"]})}),e.jsxs(xa,{align:"start",className:"w-72 p-3 bg-popover z-50",children:[e.jsxs("div",{className:"text-xs font-medium mb-2 text-muted-foreground",children:["Reassign ",Re.size," claim(s) to…"]}),e.jsxs(Ne,{value:rs,onValueChange:za,children:[e.jsx(ke,{className:"h-8",children:e.jsx(Se,{placeholder:"Pick case manager…"})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"__none__",children:"— Unassign —"}),Xs.map(s=>e.jsx(q,{value:s.user_id,children:s.name||s.email||s.user_id}
2,s.user_id))]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-3",children:[e.jsx(L,{size:"sm",variant:"ghost",onClick:()=>ea(!1),children:"Cancel"}),e.jsx(L,{size:"sm",onClick:jr,disabled:!rs,children:"Apply"})]})]})]}),e.jsxs(ma,{open:ur,onOpenChange:Rs,children:[e.jsx(ha,{asChild:!0,children:e.jsxs(L,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(ei,{className:"h-3.5 w-3.5"})," Add tag"]})}),e.jsxs(xa,{align:"start",className:"w-72 p-3 bg-popover z-50",children:[e.jsxs("div",{className:"text-xs font-medium mb-2 text-muted-foreground",children:["Add tag to ",Re.size," claim(s)"]}),e.jsxs(Ne,{value:yt,onValueChange:ta,children:[e.jsx(ke,{className:"h-8",children:e.jsx(Se,{placeholder:"Pick tag…"})}),e.jsx(Ce,{className:"max-h-72",children:bi.map(s=>e.jsx(q,{value:s,children:s},s))})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-3",children:[e.jsx(L,{size:"sm",variant:"ghost",onClick:()=>Rs(!1),children:"Cancel"}),e.jsx(L,{size:"sm",onClick:vr,disabled:!yt,children:"Apply"})]})]})]}),e.jsxs(ia,{children:[e.jsx(la,{asChild:!0,children:e.jsxs(L,{size:"sm",variant:"outline",className:"gap-1",children:[e.jsx(ti,{className:"h-4 w-4"})," Manage"]})}),e.jsxs(oa,{align:"start",children:[e.jsx(ca,{children:"Test flag"}),e.jsxs(Vt,{onClick:()=>Ka(!0),children:[e.jsx(pn,{className:"h-4 w-4 mr-2"})," Mark as likely test"]}),e.jsxs(Vt,{onClick:()=>Ka(!1),children:[e.jsx(Qt,{className:"h-4 w-4 mr-2"})," Clear test flag"]})]})]}),e.jsx(L,{size:"sm",variant:"ghost",onClick:()=>Rt(new Set),children:"Clear"})]})}),e.jsx(Ei,{open:cr,onOpenChange:As,currentStatus:"(multiple)",newStatus:nt,companyName:`${Re.size} lead(s)`,onConfirm:()=>{As(!1),br()}}),e.jsxs(ja,{children:[e.jsx(Pn,{children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs(Mn,{className:"text-sm font-medium",children:[ls.length," Claims · ",Sr?"Our portal work":Ga?"ID verification / ACE gates before processor submission":Ds?"Submitted for processing":kr?"Funding pathway (parallel)":"Closed / Disqualified"]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gt,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(gs,{placeholder:"Search...",className:"pl-9 w-48",value:vt,onChange:s=>Xn(s.target.value)})]}),e.jsxs(ma,{children:[e.jsx(ha,{asChild:!0,children:e.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5 h-10",children:[e.jsx(si,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs",children:Ee.from?`${(Ja=Dt.find(s=>s.value===ut))==null?void 0:Ja.label}: ${Ee.from.toLocaleDateString()}${Ee.to?`–${Ee.to.toLocaleDateString()}`:""}`:"Date range"}),(Ee.from||Ee.to)&&e.jsx(Qt,{className:"h-3 w-3 ml-1 hover:text-destructive",onClick:s=>{s.stopPropagation(),Ss({})}})]})}),e.jsx(xa,{className:"w-auto p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground mb-1.5",children:"Search by date"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Dt.map(s=>e.jsx(L,{type:"button",size:"sm",variant:ut===s.value?"default":"outline",className:"h-7 text-xs",onClick:()=>$a(s.value),children:s.label},s.value))})]}),e.jsx(Ai,{mode:"range",selected:{from:Ee.from,to:Ee.to},onSelect:s=>Ss({from:s==null?void 0:s.from,to:s==null?void 0:s.to}),numberOfMonths:2}),e.jsxs("div",{className:"flex justify-between gap-2 pt-1 border-t",children:[e.jsx(L,{type:"button",variant:"ghost",size:"sm",className:"text-xs",onClick:()=>Ss({}),children:"Clear"}),e.jsxs("p",{className:"text-[10px] text-muted-foreground self-center",children:["Searches the ",e.jsx("strong",{children:(Xa=Dt.find(s=>s.value===ut))==null?void 0:Xa.label})," date for this bucket."]})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(Ne,{value:Cs,onValueChange:s=>Fa(s),children:[e.jsx(ke,{className:"w-[190px]",children:e.jsx(Se,{placeholder:"Sort by"})}),e.jsx(Ce,{children:fr.map(s=>e.jsxs(q,{value:s.value,children:["Sort: ",s.label]},s.value))})]}),e.jsx(L,{variant:"outline",size:"icon",className:"h-10 w-10 shrink-0",title:ns==="desc"?"Newest / highest first":"Oldest / lowest first",onClick:()=>Ia(s=>s==="desc"?"asc":"desc"),children:ns==="desc"?e.jsx(ai,{className:"h-4 w-4"}):e.jsx(ni,{className:"h-4 w-4"})})]}),e.jsxs(Ne,{value:ts,onValueChange:er,children:[e.jsx(ke,{className:"w-44",children:e.jsx(Se,{})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"All",children:"All Statuses"}),An.filter(s=>qs(s)===c).map(s=>e.jsx(q,{value:s,children:Ht[s]},s))]})]}),e.jsxs(Ne,{value:St,onValueChange:tr,children:[e.jsx(ke,{className:"w-32",children:e.jsx(Se,{})}),e.jsx(Ce,{children:Pl.map(s=>e.jsx(q,{value:s,children:s==="All"?"All Sources":s.charAt(0).toUpperCase()+s.slice(1)},s))})]}),e.jsxs(Ne,{value:dt,onValueChange:ar,children:[e.jsx(ke,{className:"w-36",children:e.jsx(Se,{})}),e.jsx(Ce,{children:Ml.map(s=>{const u=s==="All"?"All Funding":s==="any_intent"?"Opted-in (any)":s==="standard"?"Standard (no funding)":s==="no_funding"?"Not set":s==="active_deal"?"Has active deal":s==="no_deal"?"No active deal":s;return e.jsx(q,{value:s,children:u},s)})})]}),e.jsxs(Ne,{value:Ge,onValueChange:s=>rr(s),children:[e.jsx(ke,{className:"w-36",children:e.jsx(Se,{})}),e.jsx(Ce,{children:Tl.map(s=>e.jsx(q,{value:s,children:s==="All"?"All (incl. test)":s},s))})]}),(Ga||Ds)&&e.jsxs(Ne,{value:At,onValueChange:s=>or(s),children:[e.jsx(ke,{className:"w-48",children:e.jsx(Se,{})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"All",children:"All ACE Blockers"}),e.jsx(q,{value:"any",children:"Any ACE Blocker"}),e.jsx(q,{value:"none",children:"No ACE Blocker"}),e.jsx(q,{value:"ace_issue_not_started",children:"ACE: Not Started"}),e.jsx(q,{value:"ace_issue_waiting_on_client",children:"ACE: Waiting on Client"}),e.jsx(q,{value:"ace_issue_applied",children:"ACE: Applied (waiting CBP)"})]})]}),e.jsxs(Ne,{value:ss,onValueChange:s=>nr(s),children:[e.jsx(ke,{className:"w-36",children:e.jsx(Se,{})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"All",children:"All (Anchor)"}),e.jsx(q,{value:"Yes",children:"Anchor-backed"}),e.jsx(q,{value:"No",children:"Preliminary only"})]})]}),Va.length>0&&e.jsxs(Ne,{value:as,onValueChange:ir,children:[e.jsx(ke,{className:"w-40",children:e.jsx(Se,{placeholder:"All Orgs"})}),e.jsxs(Ce,{children:[e.jsx(q,{value:"All",children:"All Orgs"}),Va.map(s=>
2e.jsx(q,{value:s.id,children:s.company_short_name},s.id))]})]}),Ba.length>0&&e.jsx("div",{className:"w-56",children:e.jsx(_n,{value:It==="All"?"":It,onChange:s=>sr(s||"All"),allowClear:!0,clearLabel:"All Partners",placeholder:"All Partners",searchPlaceholder:"Search partners...",options:Ba.map(s=>({value:s.id,label:s.full_name||s.company||s.email||"—",hint:[s.company,s.email].filter(Boolean).join(" · ")}))})}),hr&&e.jsx("div",{className:"w-56",children:e.jsx(_n,{value:Ct==="All"?"":Ct,onChange:s=>lr(s||"All"),allowClear:!0,clearLabel:"All Brokers",placeholder:"All Brokers",searchPlaceholder:"Search brokers...",options:[{value:"__none__",label:"— No broker —"},...Ua.map(s=>({value:s.id,label:s.company_name||s.full_name||"Broker",hint:s.company_name&&s.full_name?s.full_name:void 0}))]})}),e.jsxs(ia,{children:[e.jsx(la,{asChild:!0,children:e.jsxs(L,{variant:"outline",size:"sm",className:"gap-1.5 h-10",children:[e.jsx(ri,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs",children:"Columns"})]})}),e.jsxs(oa,{align:"end",className:"w-48",children:[e.jsx(ca,{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:"Show / hide columns"}),[{key:"est_ieepa",label:"Est. IEEPA"},{key:"anchor",label:"Anchor"},{key:"refund",label:"Refund (Total)"},{key:"phase1",label:"Phase 1"},{key:"phase2",label:"Phase 2"},{key:"phase3",label:"Phase 3"},{key:"receipts",label:"Refund Receipts"},{key:"dates",label:"Dates"},{key:"days_in_status",label:"Days in Status"},{key:"last_activity",label:"Last Activity"},{key:"contingency",label:"Contingency"},{key:"source",label:"Source"},{key:"broker",label:"Broker"},{key:"updated",label:"Updated"},{key:"crm",label:"CRM Snapshot"}].map(s=>e.jsx(Tr,{checked:!Y.has(s.key),onCheckedChange:u=>{Oa(m=>{const E=new Set(m);return u?E.delete(s.key):E.add(s.key),E})},onSelect:u=>u.preventDefault(),children:s.label},s.key))]})]})]})]})}
2),e.jsxs(va,{className:"p-0",children:[e.jsx(Pr,{targetRef:b,deps:[ht.length,Y.size,c]}),e.jsx("div",{ref:b,className:"overflow-x-auto",children:e.jsxs(xi,{className:"[&_td]:py-1.5 [&_td]:px-2 [&_th]:px-2 [&_th]:py-2 text-xs",children:[e.jsx(pi,{children:e.jsxs(ua,{children:[e.jsx(xe,{className:"w-10",children:e.jsx(gn,{checked:Re.size===ht.length&&ht.length>0,onCheckedChange:_r})}),e.jsx(xe,{className:"whitespace-nowrap",children:"Case #"}),e.jsx(xe,{className:"whitespace-nowrap",children:"Company / Contact"}),e.jsx(xe,{className:"whitespace-nowrap",children:"Import Value"}),!Y.has("est_ieepa")&&e.jsx(xe,{className:"whitespace-nowrap",children:"Est. IEEPA"}),!Y.has("crm")&&e.jsx(xe,{className:"whitespace-nowrap",children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("span",{className:"cursor-help",children:"CRM"})}),e.jsx(_e,{className:"text-xs max-w-[280px]",children:"CRM status at a glance. Click the chevron to expand a mega-view with tasks, follow-up, tags, activity, and full notes + Anchor notes timelines."})]})}),!Y.has("anchor")&&e.jsx(xe,{children:"Anchor"}),!Ds&&!Za&&e.jsx(xe,{children:"App Progress"}),!Y.has("refund")&&e.jsxs(xe,{className:"whitespace-nowrap",children:["Refund ",e.jsx("span",{className:"text-[10px] text-muted-foreground font-normal",children:"(Total)"})]}),!Y.has("phase1")&&e.jsx(xe,{className:"whitespace-nowrap",children:"Phase 1"}),!Y.has("phase2")&&e.jsx(xe,{className:"whitespace-nowrap",children:"Phase 2"}),!Y.has("phase3")&&e.jsx(xe,{className:"whitespace-nowrap",children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("span",{className:"cursor-help",children:"Phase 3"})}),e.jsxs(_e,{className:"text-xs max-w-[280px]",children:["Phase 3 (non-filed / post-liquidation) IEEPA duties from Anchor — API ",e.jsx("code",{children:"phase_3_nonfiled_amount"})," or the parsed workbook. Already included in the Refund (Total) figure."]})]})}),!Y.has("receipts")&&e.jsx(xe,{className:"whitespace-nowrap",children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("span",{className:"cursor-help",children:"Refund Receipts"})}),e.jsx(_e,{className:"text-xs max-w-[280px]",children:"Parsed from REV-603/615 monitoring reports. Shows total actually received from CBP, count of receipts, and flags no-ACH rejections or reconciliation mismatches."})]})}),e.jsx(xe,{children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("span",{className:"cursor-help",children:"Funding"})}),e.jsxs(_e,{className:"text-xs max-w-[280px]",children:["Client's intake answers — ",e.jsx("code",{children:"sell_interest"})," (interest in advance funding) and ",e.jsx("code",{children:"cash_urgency"})," (how urgent). Secondary chip shows live deal stage when a funding application or ",e.jsx("code",{children:"advance_funding"})," deal exists."]})]})}),e.jsx(xe,{children:"Status"}),!Y.has("dates")&&e.jsx(xe,{children:"Dates"}),!Y.has("days_in_status")&&e.jsx(xe,{children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("span",{className:"cursor-help",children:"Days in Status"})}),e.jsx(_e,{className:"text-xs max-w-[260px]",children:"Days since the lead's current status was set. Highlights when ≥14d (stalled)."})]})}),!Y.has("last_activity")&&e.jsx(xe,{children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("span",{className:"cursor-help",children:"Last Activity"})}),e.jsx(_e,{className:"text-xs max-w-[260px]",children:"Most recent activity-log entry on this claim (client edits, status changes, doc uploads)."})]})}),!Y.has("contingency")&&e.jsx(xe,{children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("span",{className:"cursor-help",children:"Contingency"})}),e.jsxs(_e,{className:"text-xs max-w-[260px]",children:["Engagement contingency %. Defaults to Admin Settings (",e.jsx("code",{children:"default_engagement_fee_pct"}),"); per-claim overrides are flagged."]})]})}),!Y.has("source")&&e.jsx(xe,{children:"Source"}),!Y.has("broker")&&e.jsx(xe,{children:"Broker"}),!Y.has("updated")&&e.jsx(xe,{children:"Updated"}),e.jsx(xe,{})]})}),e.jsxs(fi,{children:[ht.map(s=>{const u=s.affiliate_id?mt[s.affiliate_id]:null,m=s.organization_id||(u==null?void 0:u.organization_id)||null,E=m?j[m]:null,g=$[s.id],O=V[s.id]||[],re=Ca(s,g,O,{skipAnchor:!0}),K=jn(s),ee=Fs(s,u),De=P[s.id],Q=k[s.id],t=Xt[s.id],F=Math.max(0,Math.ceil((Date.now()-new Date(s.updated_at).getTime())/864e5)),ye=ot[s.id]||s.created_at,Ae=ye?Math.max(0,Math.floor((Date.now()-new Date(ye).getTime())/864e5)):null,Fe=(Ae??0)>=14&&qs(s.status)!=="closed",Ze=_t[s.id]||s.last_activity_at||s.created_at,Be=Ze?Math.max(0,Math.floor((Date.now()-new Date(Ze).getTime())/864e5)):null,Pt=(Be??0)>=7&&qs(s.status)!=="closed",Je=(g==null?void 0:g.engagement_fee_pct_override)!=null?Number(g.engagement_fee_pct_override):null,ze=Je??Number(Zs.default_engagement_fee_pct||20),Xe=kn(s.status);
2return e.jsxs(ua,{className:`cursor-pointer ${Re.has(s.id)?"bg-gold/5":""}`,onClick:()=>o(`/command/leads/${s.id}`),children:[e.jsx(me,{onClick:r=>r.stopPropagation(),children:e.jsx(gn,{checked:Re.has(s.id),onCheckedChange:()=>gr(s.id)})}),e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("span",{className:"font-mono text-xs font-bold text-foreground",children:["#",s.case_number]}),g!=null&&g.funding_only?e.jsx("span",{className:"inline-flex items-center gap-1 rounded-sm bg-emerald-500/15 text-emerald-700 dark:text-emerald-400 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider w-fit",title:"Standalone advance-funding application — not a tariff refund claim",children:"Funding Only"}):e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-sm bg-primary/10 text-primary px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider w-fit",title:vn(s.claim_type),children:[yn(s.claim_type),s.claim_type==="advance_funding"?" + Funding Interest":" Claim"]}),ee.flagged&&e.jsx(Xi,{result:ee}),e.jsx(Li,{isIor:s.is_ior,paidPartyNames:s.ior_numbers}),s.admin_marked_test&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-sm bg-amber-500/15 text-amber-700 dark:text-amber-400 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider w-fit",title:"Manually flagged as test by an admin",children:[e.jsx(pn,{className:"h-2.5 w-2.5"})," Test (manual)"]})]})}),e.jsx(me,{children:e.jsxs("div",{className:"max-w-[220px]",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.company_name||"—"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.contact_name}),e.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:s.contact_email}),s.phone&&e.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:s.phone}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[e.jsx(rl,{lead:s}),u&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-sm bg-gold/15 text-gold px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-wider",title:`Referred by ${u.full_name||u.company||u.email||"partner"}${s.ref_slug?` via ${s.ref_slug}`:""}`,children:[e.jsx(ii,{className:"h-2.5 w-2.5"})," Referred"]}),e.jsx(il,{status:s.status,leadId:s.id}),s.assisted_by_broker_id&&(()=>{const r=bt[s.assisted_by_broker_id],I=r&&(r.company_name||r.full_name)||"broker";return e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-sm bg-primary/10 text-primary px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-wider",title:`Application assisted by ${(r==null?void 0:r.full_name)||"this broker"}`,children:[e.jsx(fn,{className:"h-2.5 w-2.5"})," ",I]})})(),(()=>{const r=Qe[s.id]||0,I=O.length>0;if(!r&&!I)return null;const te=r?`Client uploaded ${r} entry-source file${r===1?"":"s"}${I?` · ${O.length} parsed entries`:""}`:`${O.length} parsed entries on file`;return e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-sm bg-emerald-500/15 text-emerald-700 dark:text-emerald-400 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider",title:te,children:[e.jsx(li,{className:"h-2.5 w-2.5"}),r?"Entries Source Confirmed":"Entries On File"]})})()]})]})}),e.jsx(me,{className:"text-sm",children:(()=>{const r=Sn(s);return r?r.derived?e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 text-cyan",children:[e.jsx(Bs,{className:"h-3 w-3"}),G(r.value)]})}),e.jsxs(_e,{side:"top",className:"text-xs max-w-[260px]",children:[e.jsx("div",{className:"font-semibold mb-0.5",children:"Derived import value"}),e.jsx("div",{className:"text-muted-foreground",children:r.source})]})]}):G(r.value):e.jsx("span",{className:"text-muted-foreground",children:"—"})})()}),!Y.has("est_ieepa")&&e.jsx(me,{children:e.jsx($l,{originalEst:re,systemEst:K})}),!Y.has("crm")&&e.jsx(me,{onClick:r=>r.stopPropagation(),children:e.jsx(Zi,{lead:s,summary:Ha[s.id],onOpenCrm:()=>aa(s.id)})}),!Y.has("anchor")&&e.jsx(me,{children:(()=>{const r=ct[s.id],I=!!(r!=null&&r.hasSnapshot),te=!!ie[s.id],Pe=(De==null?void 0:De.external_status)||null,Me=(De==null?void 0:De.last_synced_at)||(r==null?void 0:r.fetchedAt)||(r==null?void 0:r.anchorUpdatedAt)||null;let pe,le;const Le=I&&Os(r==null?void 0:r.stage,r==null?void 0:r.stageLabel),Ie=((r==null?void 0:r.stageLabel)||(r==null?void 0:r.stage)||"").toString().replace(/_/g," ").trim().toLowerCase().replace(/\b\w/g,Mt=>Mt.toUpperCase()),He=/^active claim/i.test(Ie)?"Active Claim":Ie;I&&te&&!Le?(le=He||"Active Claim",pe=e.jsxs(T,{variant:"outline",className:"gap-1 bg-success/10 text-success border-success/30 text-[10px] whitespace-nowrap justify-center",children:[e.jsx($s,{className:"h-3 w-3"})," ",le]})):I?(le=He||(Le?"File Review":"Synced"),pe=e.jsxs(T,{variant:"outline",className:"gap-1 bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-500/30 text-[10px] whitespace-nowrap justify-center",children:[e.jsx($s,{className:"h-3 w-3"})," ",le]})):De?(le="Pushed",pe=e.jsxs(T,{variant:"outline",className:"gap-1 bg-primary/10 text-primary border-primary/30 text-[10px] whitespace-nowrap justify-center",children:[e.jsx($s,{className:"h-3 w-3"})," ",le]})):(le="Preliminary",pe=e.jsx(T,{variant:"outline",className:"gap-1 text-[10px] text-muted-foreground border-muted-foreground
2/20 whitespace-nowrap justify-center",children:"Preliminary"}));const We=Pe?Pe.replace(/_/g," ").trim():"",xt=/^active claim/i.test(le),os=/^active claim/i.test(We),et=!!We&&We.toLowerCase()!==le.toLowerCase()&&!(xt&&os);return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[pe,et&&e.jsx("span",{className:"text-[9px] uppercase tracking-wide text-muted-foreground font-medium whitespace-nowrap",children:We}),(r==null?void 0:r.estimatedRefund)&&Os(r.stage,r.stageLabel)&&e.jsx("span",{className:"text-[9px] uppercase tracking-wide text-amber-700 dark:text-amber-400 font-medium whitespace-nowrap",children:"estimate echo ignored"}),Me&&e.jsxs("span",{className:"text-[10px] text-muted-foreground leading-tight inline-flex items-center gap-1 whitespace-nowrap mt-1",children:[e.jsx($t,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"whitespace-nowrap",children:["Synced: ",new Date(Me).toLocaleDateString()]})]})]})})()}),!Ds&&!Za&&e.jsx(me,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(Ki,{status:s.status,compact:!0,scope:"app"}),Xe&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Step ",Xe.idx,"/",Xe.total," · ",Xe.label]})]})}),!Y.has("refund")&&e.jsx(me,{className:"text-sm",children:(()=>{const r=qe[s.id],I=(r==null?void 0:r.eligible)??(r==null?void 0:r.apiTotal)??(r==null?void 0:r.filed)??(g==null?void 0:g.refund_amount);if(!I)return r!=null&&r.parsedZero?e.jsxs("div",{className:"flex flex-col gap-0.5",title:r.parsedZeroReason,children:[e.jsx("span",{className:"text-sm font-semibold text-muted-foreground whitespace-nowrap",children:"$0"}),e.jsxs("span",{className:"text-[9px] uppercase tracking-wider text-muted-foreground font-medium whitespace-nowrap",children:["Workbook v",r.workbookVersion??"?"," · $0 eligible"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"});const te=r!=null&&r.eligible?"Anchor Total (API)":r!=null&&r.apiTotal?"Anchor Total (API rollup)":r!=null&&r.filed?"Anchor Filed":"Refund Received";return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("span",{className:"text-sm font-semibold text-foreground flex items-center gap-1 whitespace-nowrap",children:[e.jsx(gt,{className:"h-3.5 w-3.5 text-success fill-success/15"}),G(I)]}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider text-success font-medium whitespace-nowrap",children:te}),(r==null?void 0:r.phase3)&&r.phase3>0&&e.jsxs("span",{className:"text-[9px] uppercase tracking-wider text-primary font-medium whitespace-nowrap",title:"Phase 3 refund is included in the total (Anchor API includes P1 + P2 + P3).",children:["incl. Phase 3: ",G(r.phase3)]}),(r==null?void 0:r.workbookShape)&&r.workbookShape!=="unknown"&&e.jsx("span",{className:"text-[9px] uppercase tracking-wider text-muted-foreground font-medium whitespace-nowrap",title:`Detected workbook format: ${r.workbookShape}${r.datasetHealthScore!=null?` · Health ${r.datasetHealthScore}%`:""}${r.extractionConfidence!=null?` · Confidence ${Math.round(r.extractionConfidence*100)}%`:""}`,children:r.workbookShape.replace(/_/g," ")}),(g==null?void 0:g.refund_received_date)&&e.jsxs("span",{className:"text-[9px] text-muted-foreground",children:["received ",new Date(g.refund_received_date).toLocaleDateString()]})]})})()}),!Y.has("phase1")&&e.jsx(me,{className:"text-sm",children:(()=>{const r=qe[s.id],I=(r==null?void 0:r.phase1)??(r==null?void 0:r.apiPhase1);return I?e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground whitespace-nowrap",children:G(I)}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider text-success font-medium whitespace-nowrap",children:r!=null&&r.phase1?"Anchor Filed (Workbook)":"Anchor Filed (API)"})]}):r!=null&&r.parsedZero?e.jsxs("div",{className:"flex flex-col gap-0.5",title:r.parsedZeroReason,children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"$0"}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider text-muted-foreground font-medium whitespace-nowrap",children:"Nothing eligible"})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})()}),!Y.has("phase2")&&e.jsx(me,{className:"text-sm",children:(()=>{const r=qe[s.id],I=(r==null?void 0:r.phase2)??(r==null?void 0:r.apiPhase2);return I?e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground whitespace-nowrap",children:G(I)}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider text-success font-medium whitespace-nowrap",children:r!=null&&r.phase2?"Anchor Eligible (Workbook)":"Anchor Eligible (API)"})]}):(r!=null&&r.eligible||r!=null&&r.apiTotal)&&(r!=null&&r.phase1||r!=null&&r.apiPhase1)?e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"$0"}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider text-success font-medium whitespace-nowrap",children:"Anchor Eligible"})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})()}),!Y.has("phase3")&&e.jsx(me,{className:"text-sm",children:(()=>{const r=qe[s.id],I=r==null?void 0:r.phase3;return I?e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground whitespace-nowrap",children:G(I)}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider text-success font-medium whitespace-nowrap",children:r.phase3Source==="api"?"Anchor Non-Filed (API)":"Anchor Non-Filed (Workbook)"})]}):r!=null&&r.eligible||r!=null&&r.apiTotal?e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"$0"}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider text-muted-foreground font-medium whitespace-nowrap",children:"No Phase 3"})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})()}),!Y.has("receipts")&&e.jsx(me,{className:"text-sm",children:(()=>{const r=ks[s.id];if(!r)return e.jsx("span",{className:"text-muted-foreground",children:"—"});
2const I=r.hasReceived?"received":r.hasPartial?"partial":r.hasNoAch?"rejected_no_ach":r.hasMismatch?"mismatch":r.latestStatus||"attempted",te=I==="received"?{label:"Received",cls:"bg-success/10 text-success border-success/30"}:I==="partial"?{label:"Partial",cls:"bg-cyan/10 text-cyan border-cyan/30"}:I==="rejected_no_ach"?{label:"No ACH",cls:"bg-destructive/10 text-destructive border-destructive/30"}:I==="mismatch"?{label:"Mismatch",cls:"bg-warning/10 text-warning border-warning/30"}:{label:"Attempted",cls:"bg-warning/10 text-warning border-warning/30"};return e.jsxs("div",{className:"flex flex-col gap-0.5 min-w-[110px]",children:[e.jsx("span",{className:"text-sm font-semibold tabular-nums text-foreground whitespace-nowrap",children:r.totalReceived>0?G(r.totalReceived):"—"}),e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(T,{variant:"outline",className:`text-[9px] leading-none py-0.5 px-1.5 ${te.cls}`,children:te.label}),e.jsxs("span",{className:"text-[9px] text-muted-foreground whitespace-nowrap",children:[r.count," ",r.count===1?"receipt":"receipts"]})]}),r.latestDate&&e.jsx("span",{className:"text-[9px] text-muted-foreground whitespace-nowrap",children:new Date(r.latestDate).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"2-digit"})})]})})()}),e.jsx(me,{children:(()=>{const r=String(s.sell_interest||"").toLowerCase().trim(),I=String(s.cash_urgency||"").toLowerCase().trim(),te=String(s.funding_intent||"").toLowerCase().trim(),Pe=!!(r||I||te&&te!=="standard"&&te!=="no_funding"),Me=r.startsWith("yes")?"Yes":r.startsWith("maybe")?"Maybe":r.startsWith("no")?"No":r,pe=r.startsWith("yes")?qn:r.startsWith("maybe")?oi:r.startsWith("no")?Qt:da,le=r.startsWith("yes")?"bg-success/10 text-success border-success/30":r.startsWith("maybe")?"bg-cyan/10 text-cyan border-cyan/30":(r.startsWith("no"),"bg-muted text-muted-foreground border-muted-foreground/20"),Le=I?I.charAt(0).toUpperCase()+I.slice(1):"",Ie=I==="high"?ui:I==="medium"?xs:I==="low"?da:da,He=I==="high"?"bg-destructive/10 text-destructive border-destructive/30":I==="medium"?"bg-gold/10 text-gold border-gold/30":"bg-muted text-muted-foreground border-muted-foreground/20",We=!!Q||(g==null?void 0:g.funding_stage)&&g.funding_stage!=="no_funding";return e.jsxs("div",{className:"flex flex-col items-start gap-1 min-w-[120px]",children:[Pe?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[te&&te!=="standard"&&te!=="no_funding"&&!r&&e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs(T,{variant:"outline",className:"text-[10px] leading-none py-0.5 px-1.5 gap-0.5 font-medium bg-success/10 text-success border-success/30",children:[e.jsx(ci,{className:"h-3 w-3"}),te==="buyout"?"Buyout":te.replace(/_/g," ")]})}),e.jsx(_e,{className:"text-xs",children:"Funding intent captured from application"})]}),r&&e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs(T,{variant:"outline",className:`text-[10px] leading-none py-0.5 px-1.5 gap-0.5 font-medium ${le}`,children:[e.jsx(pe,{className:"h-3 w-3"}),Me]})}),e.jsx(_e,{className:"text-xs",children:"Wants funding (intake)"})]}),I&&e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs(T,{variant:"outline",className:`text-[10px] leading-none py-0.5 px-1.5 gap-0.5 font-medium ${He}`,children:[e.jsx(Ie,{className:"h-3 w-3"}),Le]})}),e.jsx(_e,{className:"text-xs",children:"Cash urgency (intake)"})]})]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"}),t&&e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs(T,{variant:"outline",className:"text-[9px] leading-none py-0.5 px-1.5 capitalize w-fit border-primary/30 text-primary",children:["App: ",String(t.status).replace(/_/g," ")]})}),e.jsx(_e,{className:"text-xs",children:"Standalone funding application status"})]}),We&&e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx(T,{variant:"outline",className:`text-[9px] leading-none py-0.5 px-1.5 capitalize w-fit ${g!=null&&g.funding_stage&&Ri[g.funding_stage]||""}`,children:g!=null&&g.funding_stage?bn[g.funding_stage]||g.funding_stage:String((Q==null?void 0:Q.status)||"").replace(/_/g," ")})}),e.jsx(_e,{className:"text-xs",children:Q!=null&&Q.advance_amount?e.jsxs(e.Fragment,{children:["Advance: ",e.jsx("strong",{children:G(Q.advance_amount)})]}):"Live deal stage"})]})]})})()}),e.jsx(me,{children:e.jsx(T,{variant:"secondary",className:`text-[11px] py-0.5 px-2 whitespace-nowrap ${el[Wt(s.status)]||""}`,children:tl[Wt(s.status)]||Ht[Wt(s.status)]||s.status})}),!Y.has("dates")&&e.jsx(me,{children:(()=>{var Me,pe;const r=s.created_at,I=(Me=Ye[s.id])==null?void 0:Me.submitted,te=(pe=Ye[s.id])==null?void 0:pe.filed,Pe=le=>le?new Date(le).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"2-digit"}):null;return e.jsxs("div",{className:"text-[10px] space-y-0.5 leading-tight",children:[r&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground whitespace-nowrap",children:[e.jsx($t,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"whitespace-nowrap",children:["App Started: ",e.jsx("span",{className:"text-foreground",children:Pe(r)})]})]}),I&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground whitespace-nowrap",children:[e.jsx($t,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"whitespace-nowrap",children:["App Submitted: ",e.jsx("span",{className:"text-foreground",children:Pe(I)})]})]}),te&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground whitespace-nowrap",children:[e.jsx($t,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"whitespace-nowrap",children:["Filed: ",e.jsx("span",{className:"text-foreground",children:Pe(te)})]})]})]})})()}),!Y.has("days_in_status")&&e.jsx(me,{children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs(T,{variant:"outline",className:`text-[10px] tabular-nums ${Fe?"border-destructive/40 bg-destructive/10 text-destructive":(Ae??0)>=7?"border-gold/40 bg-gold/10 text-gold":"border-border text-muted-foreground"}`,children:[Ae==null?"—":`${Ae}d`,Fe?" · stalled":""]})}),e.jsxs(_e,{side:"top",className:"text-xs",children:[ye?e.jsxs(e.Fragment,{children:["Status set: ",new Date(ye).toLocaleStr
2ing()]}):"No status change recorded",ot[s.id]?"":" (no activity-log entry — using claim created date)"]})]})}),!Y.has("last_activity")&&e.jsx(me,{children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("span",{className:`text-[11px] ${Pt?"text-destructive font-medium":"text-muted-foreground"}`,children:Be==null?"—":Be===0?"today":`${Be}d ago`})}),e.jsxs(_e,{side:"top",className:"text-xs",children:[Ze?e.jsxs(e.Fragment,{children:["Last activity: ",new Date(Ze).toLocaleString()]}):"No activity recorded",_t[s.id]?"":" (from claim record)"]})]})}),!Y.has("contingency")&&e.jsx(me,{children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs(T,{variant:"outline",className:`text-[10px] tabular-nums ${Je!=null?"border-cyan/40 bg-cyan/10 text-cyan":"border-border text-foreground"}`,children:[ze,"%"]})}),e.jsx(_e,{side:"top",className:"text-xs max-w-[260px]",children:Je!=null?e.jsxs(e.Fragment,{children:["Per-claim override applied. Default is ",Zs.default_engagement_fee_pct,"%."]}):e.jsx(e.Fragment,{children:"Default engagement contingency from Admin Settings."})})]})}),!Y.has("source")&&e.jsx(me,{className:"align-top",children:e.jsx(Gi,{lead:s,partner:u,org:E,onPartnerClick:u?r=>Wa(r):void 0})}),!Y.has("broker")&&e.jsx(me,{children:s.assisted_by_broker_id||s.broker_id?(()=>{const r=s.broker||bt[s.assisted_by_broker_id||s.broker_id];return e.jsxs("div",{className:"text-xs space-y-0.5 max-w-[180px]",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fn,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"font-medium text-foreground truncate",children:(r==null?void 0:r.company_name)||(r==null?void 0:r.full_name)||"Broker"})]}),(r==null?void 0:r.company_name)&&(r==null?void 0:r.full_name)&&e.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:r.full_name})]})})():e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),!Y.has("updated")&&e.jsx(me,{className:"text-muted-foreground text-xs",children:e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("span",{children:F===0?"today":`${F}d`})}),e.jsxs(_e,{side:"top",className:"text-xs",children:["Updated ",new Date(s.updated_at).toLocaleString(),e.jsx("br",{}),"Created ",new Date(s.created_at).toLocaleDateString()]})]})}),e.jsx(me,{onClick:r=>r.stopPropagation(),children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(fe,{children:[e.jsx(ge,{asChild:!0,children:e.jsx(L,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>aa(s.id),children:e.jsx(di,{className:"h-3.5 w-3.5"})})}),e.jsx(_e,{side:"top",className:"text-xs",children:"Open CRM dialog"})]}),e.jsx($i,{lead:s,onChanged:rt})]})})]},s.id)}),ht.length===0&&e.jsx(ua,{children:e.jsx(me,{colSpan:25,className:"p-0",children:e.jsx(Di,{icon:Gt,title:"No claims found",description:"Try adjusting your search or filters."})})})]})]})}),wt>1&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-border",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",(it-1)*hs+1,"–",Math.min(it*hs,ls.length)," of ",ls.length]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(L,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>is(s=>Math.max(1,s-1)),disabled:it<=1,children:e.jsx(Ra,{className:"h-4 w-4"})}),Array.from({length:Math.min(5,wt)},(s,u)=>{let m;return wt<=5||it<=3?m=u+1:it>=wt-2?m=wt-4+u:m=it-2+u,e.jsx(L,{variant:m===it?"default":"ghost",size:"icon",className:"h-8 w-8 text-xs",onClick:()=>is(m),children:m},m)}),e.jsx(L,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>is(s=>Math.min(wt,s+1)),disabled:it>=wt,children:e.jsx(bs,{className:"h-4 w-4"})})]})]})]})]})]})]})]}),e.jsx(Qi,{leadId:pr,onClose:()=>aa(null),onChanged:rt}),na&&e.jsx(Yi,{open:!!na,onOpenChange:s=>{s||Wa(null)},affiliate:mt[na]||null,allAffiliates:l,onChanged:rt})]})}export{yc 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.