PageSourceSearch

https://tariffrecoveryagency.com/assets/LeadDetail-B6Ir8s-d.js

js tariffrecoveryagency.com collected 2026-10-01 23:58:13 UTC 128,639 bytes, 2 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CrmCommsPanel-nS76Es73.js","assets/vendor-query-DUki8u-D.js","assets/vendor-react-DHU755GE.js","assets/client-Dy2P3he-.js","assets/vendor-supabase-D2XPrbcR.js","assets/card-B_TKe1rC.js","assets/App-DNURBdOM.js","assets/vendor-pdf-DHUBMtDJ.js","assets/error-reporter-EYiXaqJQ.js","assets/breadcrumbs-CN3GC8vy.js","assets/vendor-charts-DsctC1NR.js","assets/vendor-icons-D7GmeyGG.js","assets/useTheme-DEq4C3Xf.js","assets/vendor-motion-DoyUfQ58.js","assets/textarea-Pc8lpgfp.js","assets/select-BJ2LQ1BA.js","assets/index-BdQq_4o_.js","assets/index-BFcYZw7s.js","assets/quo-deeplink-CB_LA5H-.js","assets/AnchorProcessingTab-D0yUsLh6.js","assets/formatDistanceToNow-CD_R0YjW.js","assets/getRoundingMethod-Cs3-IipQ.js","assets/en-US-BqCXNUOZ.js","assets/differenceInCalendarMonths-BSRE4gQg.js","assets/endOfMonth-B_n1vX73.js","assets/format-D9x0XWGR.js","assets/tabs-DO2x6V1p.js","assets/accordion-CaRQoKh5.js","assets/index-DP9v6o89.js","assets/scroll-area-C5uKDqac.js","assets/xlsx-B6sNpj_1.js","assets/anchor-doc-grouping-CO1E2bA6.js","assets/IorStatusBadge-C_jp2Po1.js","assets/alert-dialog-COU3YwVl.js","assets/claim-constants-F6TZxwZ5.js","assets/label-CQkxHeEJ.js","assets/lead-est-recovery-DzLSo3WB.js","assets/TestClaimBadge-jKoFjITi.js","assets/test-claim-detector-C7yWOzH7.js","assets/alert-DrXqJ_mR.js","assets/separator-BGBKlkSh.js","assets/checkbox-eIxR81FC.js","assets/AgreementCardTile-BGJqjejQ.js","assets/AgreementSignDialog-BYllgCNq.js","assets/AgreementViewer-BacWGjDw.js","assets/SignaturePad-Ca2_wxMG.js","assets/agreement-pdf-B8dWl2Jr.js","assets/stored-agreement-pdf-CVgd7AlI.js","assets/agreement-filename-9SsE_bIj.js","assets/CommissionWaterfallCard-DAdmpulL.js","assets/switch-D3dXx0E2.js","assets/commission-simulator-BnG1RJMf.js","assets/useCommissionSettings-DzLA0olu.js","assets/IdentityWaiverToggle-CqEE9Ob9.js","assets/ClaimProgressMeter-DJ1VpGgr.js","assets/collapsible-BMB_LUcl.js","assets/useAnchorClaim-CuWUzBDb.js","assets/anchor-source-of-truth-CjWj8hjg.js","assets/AceAccessStalledBanner-CCvhv7Ab.js","assets/claim-buckets-Cl_CKEqx.js","assets/AnchorProcessingTab-Bu5q60D-.css","assets/EntriesTab-pDlYBVhL.js","assets/table-BpuyeSw8.js","assets/date-picker-DXAtzP_K.js","assets/calendar-BbCNGX3_.js","assets/isSameDay-BWv5-M0E.js","assets/subDays-BK6vuqdz.js","assets/startOfMonth-D3_3nocY.js","assets/addMonths-Dw7XJecM.js","assets/popover-DAwJgSl1.js","assets/parseISO-CIZr9Bmv.js","assets/CapeReadiness-nFeSbDQt.js","assets/ScoringBreakdown-DJ6VDrav.js","assets/progress-CJLwRXFJ.js","assets/LiquidationAnalysis-BtUOYMns.js","assets/CommissionsTab-dcz8dxus.js","assets/async-partner-select-D7bPdIxE.js","assets/command-CBhwoYW6.js","assets/CommissionAuditLog-DYeQaLra.js","assets/BrokerInclusionPanel-DhqMmMen.js","assets/broker-resolution-nX8F8SfX.js","assets/BrokerOverrideCard-CkEaMU03.js","assets/ClaimConversation-BhWEhiRg.js","assets/formatDistanceToNowStrict-B0_ltmaX.js","assets/DocumentAnalysis-CHm9BRR0.js","assets/RefundReconciliation-DbgR2bMK.js","assets/DocumentVersionHistory-DXRYEjCr.js","assets/EntityEmailTimeline-CdMtIujJ.js","assets/CAPEBatchManager-Cqf9-fS-.js","assets/ProtestManager-DEF-n4Ou.js","assets/CITCaseManager-BQ9Gj4nT.js","assets/ACEAccountManager-BxoAmsVL.js","assets/CBPInteractions-B7l1ITYE.js","assets/EligibilityMatrix-CmpXYGRK.js","assets/ACECredentialManager-wXpU7d4y.js","assets/RPAJobManager-Djzyk0bw.js","assets/ACEReportETL-CR-0vrL7.js","assets/useTariffPrograms-zn46sdOS.js","assets/email-triggers-Bp6XbLok.js"])))=>i.map(i=>d[i]);
2import{_ as $}from"./vendor-pdf-DHUBMtDJ.js";import{j as e}from"./vendor-query-DUki8u-D.js";import{w as ze,o as R,u as Bt,D as fs,a as bs,b as _s,c as vs,d as ys,I as Ae,e as Ws,B as k,h as X,aD as Se,aE as Pe,aF as ke,aG as Te,av as Hs,aQ as F,g as Gs,s as St}from"./App-DNURBdOM.js";import{r as b,j as Ys,f as Ks,e as Qs}from"./vendor-react-DHU755GE.js";import{I as Zs,C as Js,S as Xs}from"./IorStatusBadge-C_jp2Po1.js";import{T as ea}from"./TestClaimBadge-jKoFjITi.js";import{detectTestClaim as ta}from"./test-claim-detector-C7yWOzH7.js";import{A as sa,b as aa,a as na}from"./alert-DrXqJ_mR.js";import{h as ia,i as Pt,j as Qt,a as Ee,k as kt,b as ra,S as la,A as Zt,R as oa,C as Jt,l as ca}from"./claim-constants-F6TZxwZ5.js";import{supabase as g}from"./client-Dy2P3he-.js";import{C as W,c as Y,a as Z,b as J,d as me}from"./card-B_TKe1rC.js";import{L as ee}from"./label-CQkxHeEJ.js";import{T as Dt}from"./textarea-Pc8lpgfp.js";import{S as _e,a as ve,b as ye,c as je,d as ie}from"./select-BJ2LQ1BA.js";
2import{T as da,a as ma,b as ua,c as L}from"./tabs-DO2x6V1p.js";import{S as Tt}from"./separator-BGBKlkSh.js";import{C as ha}from"./checkbox-eIxR81FC.js";import{e as pa,d as xa,r as Xt,h as es,a as ga,f as fa,c as ba,i as _a}from"./lead-est-recovery-DzLSo3WB.js";import{A as va,a as ya}from"./AgreementCardTile-BGJqjejQ.js";import{A as ja}from"./AgreementSignDialog-BYllgCNq.js";import{D as qt,a9 as we,G as pt,$ as Ne,c2 as ts,i as Ue,ay as ss,T as He,a1 as js,b as Na,bc as wa,L as Ie,bL as Ca,bf as Aa,V as Ea,S as Sa,_ as Ve,q as Ns,d as ws,a as ue,K as ut,f as Pa,E as ka,Y as Ta,j as Lt,bH as $t,a7 as We,bm as Cs,v as Ia,z as Ra,Q as st,aa as As,an as ht,a0 as Da,aK as dt,a8 as qa,R as as,n as ns,N as $a,F as Me,aJ as tt,bw as Ba,cD as is,bP as La,a2 as Oa,cE as Fa,a6 as rs,r as Ma,bC as Va,aM as za,ao as ls,aB as os,cg as cs,aL as ds,aZ as ms,C as It}from"./vendor-icons-D7GmeyGG.js";import{C as Ua}from"./CommissionWaterfallCard-DAdmpulL.js";import{h as Wa}from"./error-reporter-EYiXaqJQ.js";import{f as Ha}from"./useCommissionSettings-DzLA0olu.js";import{S as Ga}from"./scroll-area-C5uKDqac.js";import{I as Ya}from"./IdentityWaiverToggle-CqEE9Ob9.js";import{C as Ka}from"./ClaimProgressMeter-DJ1VpGgr.js";import{C as Qa,a as Za,b as Ja}from"./collapsible-BMB_LUcl.js";import{u as Xa}from"./useAnchorClaim-CuWUzBDb.js";import{f as en}from"./formatDistanceToNow-CD_R0YjW.js";import{g as tn}from"./anchor-source-of-truth-CjWj8hjg.js";import{a as Es,b as Rt,p as sn,c as an}from"./AceAccessStalledBanner-CCvhv7Ab.js";const nn=({score:s,size:n="sm"})=>{const m=x=>x>=75?"bg-success/10 text-success border-success/20":x>=50?"bg-gold/10 text-gold border-gold/20":x>=25?"bg-primary/10 text-primary border-primary/20":"bg-destructive/10 text-destructive border-destructive/20";return e.jsx("span",{className:ze("inline-flex items-center gap-1 font-bold border rounded-full",m(s),n==="sm"?"text-[10px] px-2 py-0.5":"text-xs px-2.5 py-1"),children:s})},rn=({lead:s,entries:n,agreements:m=[]})=>{const[x,i]=b.useState([]);b.useEffect(()=>{if(n.length===0)return;const p=n.map(j=>j.entry_number);g.from("claim_entries").select("entry_number, lead_id").in("entry_number",p).neq("lead_id",s.id).then(({data:j})=>{j&&j.length>0&&i(j)})},[n,s.id]);const c=[];pa(s,n).forEach(p=>{c.push({icon:qt,label:`Verify: ${p.label}`,description:p.description,severity:"warning"})}),s.prior_disclosure_needed==="yes"?c.push({icon:we,label:"Prior Disclosure Required",description:"Client indicated potential compliance issues. File Prior Disclosure (19 CFR §162.74) BEFORE any protest to avoid penalties.",severity:"critical"}):s.prior_disclosure_needed==="unsure"&&c.push({icon:we,label:"Evaluate Prior Disclosure Need",description:"Client is unsure about compliance issues. Conduct compliance review before filing.",severity:"warning"}),(s.goods_reexported==="yes"||s.goods_reexported==="manufacturing")&&c.push({icon:pt,label:"Duty Drawback Eligible",description:`Client ${s.goods_reexported==="manufacturing"?"manufactures for export":"re-exports goods"} — evaluate drawback program in addition to IEEPA refund.`,severity:"info"}),n.filter(p=>p.liquidation_status==="liquidated").forEach(p=>{const j=p.protest_deadline||(p.liquidation_date?ia(p.liquidation_date).toISOString():null);if(!j)return;const M=Pt(j),V=Qt(M);V==="critical"?c.push({icon:Ne,label:`Entry ${p.entry_number}: ${M}d to protest deadline`,description:`Protest must be filed by ${new Date(j).toLocaleDateString()} or this entry's duties are unrecoverable.`,severity:"critical"}):V==="warning"&&c.push({icon:Ne,label:`Entry ${p.entry_number}: ${M}d to protest deadline`,description:"Approaching deadline — prioritize filing.",severity:"warning"})}),n.filter(p=>p.protest_denial_date&&p.cit_summons_deadline).forEach(p=>{const j=Pt(p.cit_summons_deadline),M=Qt(j);(M==="critical"||M==="warning")&&c.push({icon:Ne,label:`Entry ${p.entry_number}: ${j}d to CIT summons deadline`,description:"180 days from protest denial to file at Court of International Trade.",severity:M==="critical"?"critical":"warning"})}),m.filter(p=>p.agreement_type==="poa"&&p.expires_at&&p.status!=="voided").forEach(p=>{const j=Pt(p.expires_at);j<=30&&j>0?c.push({icon:ts,label:`POA expires in ${j} days`,description:`Power of Attorney expires ${new Date(p.expires_at).toLocaleDateString()} — renewal needed to continue filing.`,severity:j<=14?"critical":"warning"}):j<=0&&c.push({icon:ts,label:"POA expired",description:`Power of Attorney expired ${new Date(p.expires_at).toLocaleDateString()}
2 — cannot file until renewed.`,severity:"critical"})}),s.ein||c.push({icon:Ue,label:"Missing EIN",description:"Employer Identification Number required for CBP filing.",severity:"info"}),(!s.is_ior||s.is_ior==="unsure")&&c.push({icon:qt,label:"Confirm IOR status",description:"Refunds flow to the Importer of Record — confirm who the IOR is.",severity:"info"}),(!s.ace_access||s.ace_access!=="yes")&&c.push({icon:Ue,label:"Verify ACE portal access",description:"ACE portal access required for entry data and filing.",severity:"info"}),(!s.ach_enrolled||s.ach_enrolled!=="yes")&&c.push({icon:Ue,label:"ACH/eDIS enrollment",description:"Electronic refund disbursement required by CBP as of Feb 2026.",severity:"info"});const f=n.map(p=>p.entry_number),v=f.filter((p,j)=>f.indexOf(p)!==j);if(v.length>0&&c.push({icon:ss,label:`${v.length} duplicate entry number(s) within this claim`,description:`Entries ${[...new Set(v)].join(", ")} appear multiple times — verify and remove duplicates.`,severity:"warning"}),x.length>0){const p=[...new Set(x.map(j=>j.entry_number))];c.push({icon:ss,label:`${p.length} entry number(s) found in OTHER claims`,description:`Entry ${p.join(", ")} also appear in other claims. Filing the same entry twice = automatic CBP denial. Investigate immediately.`,severity:"critical"})}if(c.length===0)return null;const _={critical:0,warning:1,info:2};c.sort((p,j)=>_[p.severity]-_[j.severity]);const A={critical:"border-destructive/30 bg-destructive/5",warning:"border-gold/30 bg-gold/5",info:"border-primary/30 bg-primary/5"},w={critical:"text-destructive",warning:"text-gold",info:"text-primary"};return e.jsx(W,{className:"border-gold/30 bg-gold/5",children:e.jsxs(Y,{className:"pt-4 pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(He,{className:"h-4 w-4 text-gold"}),e.jsxs("p",{className:"text-sm font-semibold text-foreground",children:["Action Items (",c.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:c.map((p,j)=>e.jsxs("div",{className:ze("flex items-start gap-2.5 p-2.5 rounded-lg border",A[p.severity]),children:[e.jsx(p.icon,{className:ze("h-4 w-4 mt-0.5 shrink-0",w[p.severity])}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:p.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:p.description})]}),e.jsx(R,{variant:"outline",className:ze("ml-auto shrink-0 text-[10px] capitalize",p.severity==="critical"?"border-destructive/30 text-destructive":p.severity==="warning"?"border-gold/30 text-gold":"border-primary/30 text-primary"),children:p.severity})]},j))})]})})},ln=({open:s,onOpenChange:n,leadId:m,companyName:x,currentOverridePct:i,hasSignedEngagement:c,onSuccess:d})=>{const{toast:t}=Bt(),[E,f]=b.useState(20),[v,_]=b.useState(""),[A,w]=b.useState(""),[p,j]=b.useState(!1);b.useEffect(()=>{s&&(_(i!=null?String(i):""),w(""),Ha().then(D=>{f(parseFloat(D.default_engagement_fee_pct)||20)}))},[s,i]);const M=Number(v),V=v.trim()!==""&&!Number.isNaN(M)&&M>0&&M<=50,Re=i??E,T=V&&M===Re,Ce=async()=>{if(!V){t({title:"Enter a percentage between 1 and 50",variant:"destructive"});return}if(!A.trim()){t({title:"Reason required",description:"Provide a brief reason for the audit log.",variant:"destructive"});return}j(!0);try{const{data:D,error:he}=await g.rpc("admin_override_contingency_fee",{_lead_id:m,_new_pct:M,_reason:A.trim()});if(he)throw he;const P=(D==null?void 0:D.voided_agreements)??0;t({title:"Contingency fee overridden",description:P>0?`Set to ${M}%. ${P} prior Consulting Agreement${P===1?"":"s"} voided — client must e-sign the new version.`:`Set to ${M}%. New Consulting Agreement will be issued on the client's next visit.`}),d==null||d(),n(!1)}catch(D){t({title:"Override failed",description:Wa(D),variant:"destructive"})}finally{j(!1)}};return e.jsx(fs,{open:s,onOpenChange:D=>{p||n(D)},children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(vs,{className:"font-display flex items-center gap-2",children:[e.jsx(js,{className:"h-5 w-5 text-gold"})," Override Contingency Fee"]}),e.jsxs(ys,{children:[x?e.jsxs(e.Fragment,{children:["For ",e.jsx("strong",{children:x}),". "]}):null,"Sets a per-claim contingency % that flows into the Consulting Agreement Section C.2 and the commission waterfall."]})]}),e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsx(W,{className:"border-l-4 border-l-gold/60",children:e.jsxs(Y,{className:"p-3 text-xs space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Global default"}),e.jsxs("span",{className:"font-mono",children:[E,"%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Current effective"}),e.jsxs("span",{className:"font-mono font-semibold",children:[Re,"%"]})]}),V&&!T&&e.jsxs("div",{className:"flex justify-between text-foreground",children:[e.jsx("span",{children:"New"}),e.jsxs("span",{className:"font-mono font-semibold text-gold",children:[M,"%"]})]})]})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"New Contingency %"}),e.jsx(Ae,{type:"number",step:"0.01",min:"1",max:"50",placeholder:"e.g. 22",value:v,onCh
2ange:D=>_(D.target.value),className:"mt-1"}),v&&!V&&e.jsxs("p",{className:"text-[10px] text-destructive mt-1 flex items-center gap-1",children:[e.jsx(Na,{className:"h-3 w-3"})," Must be between 1 and 50"]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Reason (audit log) *"}),e.jsx(Dt,{rows:2,placeholder:"Negotiated rate for enterprise client; approved by …",value:A,onChange:D=>w(D.target.value),className:"mt-1"})]}),c&&e.jsxs("div",{className:"flex gap-2 p-3 rounded-lg border border-destructive/30 bg-destructive/5 text-xs",children:[e.jsx(wa,{className:"h-4 w-4 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-destructive",children:"Existing signed agreement will be voided"}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:"The client will be required to e-sign a new Consulting Agreement reflecting the new fee on their next portal visit."})]})]})]}),e.jsxs(Ws,{children:[e.jsx(k,{variant:"outline",onClick:()=>n(!1),disabled:p,children:"Cancel"}),e.jsxs(k,{onClick:Ce,disabled:!V||!A.trim()||p||T,className:"bg-primary text-primary-foreground gap-1.5",children:[p?e.jsx(Ie,{className:"h-4 w-4 animate-spin"}):null,c?"Override & Void Agreement":"Apply Override"]})]})]})})},us={client:{label:"Client",className:"border-primary/30 text-primary",icon:Lt},admin:{label:"Admin",className:"border-gold/30 text-gold",icon:Ue},system:{label:"System",className:"border-muted-foreground/30 text-muted-foreground",icon:ut},cbp:{label:"CBP",className:"border-destructive/30 text-destructive",icon:pt},legal:{label:"Legal",className:"border-cyan-500/30 text-cyan-500",icon:we},"admin/legal":{label:"Admin/Legal",className:"border-gold/30 text-gold",icon:we}},on=({lead:s,entries:n,agreements:m,checklist:x,funding:i,aceAccount:c,onNavigateTab:d,isDialog:t,open:E,onOpenChange:f})=>{const v=(s==null?void 0:s.status)||"new",_=m.filter(o=>["signed","countersigned"].includes(o.status)&&o.status!=="voided"),A=x.filter(o=>o.required),w=A.filter(o=>o.completed),p=(c==null?void 0:c.verification_status)==="verified",j=(c==null?void 0:c.ach_enrolled)&&(c==null?void 0:c.ach_verified_at),M=n.length>0,V=n.filter(o=>(o.ieepa_duties||0)>0),Re=n.reduce((o,se)=>o+(se.ieepa_duties||0),0),T=["new","account_created","application_in_progress","details_submitted","agreements_pending","documents_pending","identity_verification_required","identity_verification_in_progress","ace_access_pending","ace_access_granted","ace_access_confirmed","ready_for_review","in_review","approved","filed_with_cbp","protest_filed","protest_denied","further_review","cit_filed","cit_resolved","refund_received","closed_paid"],Ce=T.indexOf(v),D=o=>Ce>=T.indexOf(o),he=[{phase:"Phase 1",title:"Client Onboarding",icon:Ca,color:"text-primary",bg:"bg-primary/10",statuses:["new","account_created","details_submitted"],steps:[{label:"Application received",who:"system",auto:!0,detail:"Client submitted intake form on website with company info, import volumes, and IEEPA duties.",done:!0,targetTab:"overview"},{label:"Account created",who:"system",auto:!0,detail:"System auto-creates portal account when client verifies email. They can now log in and track their claim.",done:D("account_created")||!!s.user_id,targetTab:"overview"},{label:"Company details completed",who:"client",detail:"Client fills in EIN, IOR numbers, ACE access, and import history in their portal.",done:D("details_submitted"),targetTab:"overview",substeps:[{label:"Company name & EIN",done:!!s.ein,help:"Employer Identification Number — required for CBP filing"},{label:"IOR (Importer of Record) confirmed",done:s.is_ior==="yes",help:"Refunds go to the IOR."},{label:"ACE portal access confirmed",done:s.ace_access==="yes",targetTab:"credentials"}]}]},{phase:"Phase 2",title:"Agreements & Qualification",icon:Aa,color:"text-gold",bg:"bg-gold/10",statuses:["agreements_pending"],steps:[{label:"Client reviews & signs agreements",who:"client",detail:`Client logs into their portal and signs the Engagement Letter, POA, and Contingency Fee Agreement electronically. ${_.length}/${m.length} signed.`,done:_.length===m.length&&m.length>0,targetTab:"agreements",substeps:m.map(o=>({label:`${o.title} — ${o.status}`,done:["signed","countersigned"].includes(o.status),targetTab:"agreements"}))}
2,{label:"Admin countersigns agreements",who:"admin",detail:"Review and countersign each client-signed agreement. Click the agreement card → review → Countersign.",done:m.filter(o=>o.status==="countersigned").length===m.length&&m.length>0,targetTab:"agreements"}]},{phase:"Phase 3",title:"Document Collection & ACE Setup",icon:Ea,color:"text-success",bg:"bg-success/10",statuses:["documents_pending","identity_verification_required","identity_verification_in_progress","ace_access_pending","ace_access_granted"],steps:[{label:"Client uploads documents",who:"client",detail:`Required: CBP 7501, Commercial Invoice, Packing List, BOL, ACE data, Proof of Duty Payment, POA, ACH Enrollment. ${w.length}/${A.length} complete.`,done:w.length===A.length&&A.length>0,targetTab:"documents",substeps:A.map(o=>({label:o.label,done:o.completed,help:o.description,targetTab:"documents"}))},{label:"Review uploaded documents",who:"admin",detail:"Approve or reject each document. Rejected docs notify the client to re-upload.",done:w.length===A.length&&A.length>0,targetTab:"documents"},{label:"Set up ACE credentials & verify account",who:"admin",detail:"Store ACE credentials, verify portal access, confirm ACH refund enrollment, and eDIS enrollment.",done:p&&!!j,targetTab:"ace_account",substeps:[{label:"ACE credentials stored",done:!!c,targetTab:"credentials"},{label:"ACE account verified",done:p,targetTab:"ace_account"},{label:"ACH refund enrollment",done:!!j,targetTab:"ace_account"},{label:"eDIS enrollment",done:c==null?void 0:c.edis_enrolled,targetTab:"ace_account"}]},{label:"Import entry data via RPA",who:"system",auto:!0,detail:`Pull entry summaries from ACE Portal via RPA automation. ${n.length} entries loaded, ${V.length} IEEPA-eligible.`,done:M,targetTab:"rpa"}]},{phase:"Phase 4",title:"Review & Filing",icon:Sa,color:"text-primary",bg:"bg-primary/10",statuses:["ready_for_review","in_review","approved"],steps:[{label:"Admin deep review & scoring",who:"admin",detail:"Check Scoring tab for qualification score. Review Liquidation tab for protest deadlines. Check Eligibility tab for filing pathways.",done:D("approved"),targetTab:"scoring"},{label:"Approve claim for filing",who:"admin",detail:"When satisfied with data quality and eligibility, change status to 'Approved'. This unlocks CAPE filing.",done:D("approved"),targetTab:"overview"},{label:"Build CAPE declaration",who:"admin",detail:`Select eligible entries (${V.length} with ${X(Re)} IEEPA duties), validate data, and generate CAPE CSV.`,done:D("filed_with_cbp"),targetTab:"cape"},{label:"Submit CAPE to CBP",who:"system",auto:!0,detail:"Upload CAPE CSV via ACE Portal. Can be done via RPA automation or manually.",done:D("filed_with_cbp"),targetTab:"cape"}]},{phase:"Phase 5",title:"CBP Processing & Disputes",icon:Ne,color:"text-gold",bg:"bg-gold/10",statuses:["filed_with_cbp","protest_filed","further_review","cit_filed","cit_resolved"],steps:[{label:"CBP reviews declaration",who:"cbp",detail:"CBP validates entries and calculates refund. Typical processing: 30-90 days. System auto-polls for status updates.",done:D("refund_received"),targetTab:"cbp_log"},{label:"File protest (if denied)",who:"admin/legal",detail:"If CAPE is denied, file formal protest (19 USC §1514) within 180 days of liquidation. Check Liquidation tab for deadlines.",done:D("further_review")&&Ce>T.indexOf("protest_filed"),targetTab:"protests"},{label:"CIT litigation (if protest denied)",who:"legal",detail:"File summons at Court of International Trade within 180 days of protest denial. Requires outside counsel.",done:D("cit_resolved")&&Ce>T.indexOf("cit_filed"),targetTab:"cit"}]},{phase:"Phase 6",title:"Refund & Payout",icon:Ve,color:"text-success",bg:"bg-success/10",statuses:["refund_received","closed_paid"],steps:[{label:"Refund received via ACH",who:"cbp",detail:"CBP deposits refund via ACH (5-10 business days). Verify amount in Reconciliation tab.",done:D("refund_received"),targetTab:"reconciliation"},{label:"Calculate fee & pay client",who:"admin",detail:"Calculate contingency fee, generate final report, process client payout.",done:D("closed_paid"),targetTab:"reconciliation"}
2,{label:"Close case",who:"admin",detail:"Change status to 'Closed — Paid'. Broker/affiliate commissions trigger automatically.",done:D("closed_paid"),targetTab:"overview"}]}],P=he.findIndex(o=>o.statuses.includes(v)),[at,le]=b.useState(new Set(he.map((o,se)=>se))),xt=o=>{le(se=>{const oe=new Set(se);return oe.has(o)?oe.delete(o):oe.add(o),oe})},De=o=>{o&&d&&(f&&f(!1),d(o))},Ge=e.jsxs("div",{className:"space-y-4",children:[he.map((o,se)=>{const oe=o.icon,pe=se===P,N=se<P,qe=o.steps.every(z=>z.done),gt=o.steps.filter(z=>z.done).length,Ye=at.has(se),Q=pe?o.steps.findIndex(z=>!z.done):-1;return e.jsxs("div",{className:`rounded-xl border transition-all ${pe?"border-gold/40 bg-gold/[0.03] shadow-sm shadow-gold/10":qe||N?"border-success/30 bg-success/[0.02]":"border-border"}`,children:[e.jsxs("button",{onClick:()=>xt(se),className:`w-full flex items-center gap-3 px-5 py-4 text-left hover:bg-muted/20 transition-colors rounded-xl ${Ye?"rounded-b-none":""}`,children:[e.jsx("div",{className:`h-10 w-10 rounded-xl flex items-center justify-center shrink-0 ${o.bg}`,children:e.jsx(oe,{className:`h-5 w-5 ${o.color}`})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-semibold text-foreground text-sm",children:[o.phase,": ",o.title]}),pe&&e.jsx(R,{className:"bg-gold text-gold-foreground text-[9px] px-1.5",children:"CURRENT"}),(qe||N)&&e.jsx(R,{className:"bg-success/10 text-success text-[9px] px-1.5 border border-success/20",children:"COMPLETE"})]})}),e.jsxs(R,{variant:"outline",className:`text-[10px] shrink-0 mr-2 ${qe||N?"border-success/30 text-success":pe?"border-gold/30 text-gold":""}`,children:[gt,"/",o.steps.length]}),Ye?e.jsx(Ns,{className:"h-4 w-4 text-muted-foreground shrink-0"}):e.jsx(ws,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),Ye&&e.jsx("div",{className:"px-5 pb-5 space-y-3 ml-2",children:o.steps.map((z,Ke)=>{const Qe=us[z.who]||us.system,Ze=Qe.icon,$e=pe&&Ke===Q;return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center pt-1",children:[z.done?e.jsx(ue,{className:"h-4 w-4 text-success shrink-0"}):$e?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-gold bg-gold/20 shrink-0"}),e.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 bg-gold rounded-full animate-pulse"})]}):e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0"}),Ke<o.steps.length-1&&e.jsx("div",{className:"w-0.5 flex-1 bg-border mt-1"})]}),e.jsxs("div",{className:"pb-3 flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:`text-sm font-medium ${z.done?"text-muted-foreground":"text-foreground"}`,children:z.label}),e.jsxs(R,{variant:"outline",className:`text-[9px] px-1.5 ${Qe.className}`,children:[z.auto&&e.jsx(ut,{className:"h-2.5 w-2.5 mr-0.5"}),e.jsx(Ze,{className:"h-2.5 w-2.5 mr-0.5"}),Qe.label]}),$e&&e.jsx(R,{className:"bg-gold/10 text-gold text-[9px] border-gold/30 animate-pulse",children:"ACTION NEEDED"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 leading-relaxed",children:z.detail}),z.substeps&&z.substeps.length>0&&(z.done||$e||pe)&&e.jsx("div",{className:"mt-2 space-y-1.5 ml-1",children:z.substeps.map((ce,ft)=>e.jsxs("div",{className:"flex items-center gap-2 group",children:[ce.done?e.jsx(ue,{className:"h-3 w-3 text-success shrink-0"}):e.jsx(Pa,{className:"h-3 w-3 text-muted-foreground/40 shrink-0"}),e.jsx("span",{className:`text-[11px] leading-normal ${ce.done?"text-muted-foreground line-through":"text-foreground"}`,children:ce.label}),ce.help&&e.jsx(Se,{children:e.jsxs(Pe,{children:[e.jsx(ke,{children:e.jsx(qt,{className:"h-2.5 w-2.5 text-muted-foreground/40"})}),e.jsx(Te,{side:"right",className:"max-w-[240px] text-[11px]",children:ce.help})]})}),!ce.done&&ce.targetTab&&d&&e.jsxs(k,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[10px] text-primary opacity-0 group-hover:opacity-100 transition-opacity",onClick:bt=>{bt.stopPropagation(),De(ce.targetTab)},children:["Go ",e.jsx(ka,{className:"h-2.5 w-2.5 ml-0.5"})]})]},ft))}),$e&&z.targetTab&&d&&e.jsxs(k,{size:"sm",variant:"outline",className:"mt-2.5 h-7 text-xs gap-1.5 border-gold/30 text-gold hover:bg-gold/10",onClick:()=>De(z.targetTab),children:[e.jsx(Ta,{className:"h-3 w-3"})," Go to ",z.label.split(" ")[0]]})]})]},Ke)})})]},o.phase)}),e.jsxs("div",{className:"rounded-lg border border-border p-4",children:[e.jsx("p",{className:"text-xs font-semibold text-foreground mb-2",children:"Who Does What"}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Lt,{className:"h-3 w-3 text-primary"})," ",e.jsx("span",{className:"text-primary font-medium",children:"Client"})," — acts in their portal"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ue,{className:"h-3 w-3 text-gold"})," ",e.jsx("span",{className:"text-gold font-medium",children:"Admin"})," — you do this"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ut,{className:"h-3 w-3 text-muted-foreground"})," ",e.jsx("span",{className:"text-muted-foreground font-medium",children:"System"})," — automated"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(pt,{className:"h-3 w-3 text-destructive"})," ",e.jsx("span",{className:"text-destructive font-medium",children:"CBP"})," — U.S. Customs"]}
2),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(we,{className:"h-3 w-3 text-cyan-500"})," ",e.jsx("span",{className:"text-cyan-500 font-medium",children:"Legal"})," — outside counsel"]})]})]})]});return t&&E!==void 0&&f?e.jsx(fs,{open:E,onOpenChange:f,children:e.jsxs(bs,{className:"max-w-3xl max-h-[85vh] p-0",children:[e.jsxs(_s,{className:"px-6 pt-6 pb-4 border-b border-border",children:[e.jsxs(vs,{className:"flex items-center gap-2 text-xl",children:[e.jsx($t,{className:"h-5 w-5 text-gold"}),"Claim Action Center"]}),e.jsxs(ys,{className:"flex items-center gap-2",children:["Live status tracker — what's done, what's next, and who needs to act.",e.jsx(R,{className:"bg-gold/10 text-gold border-gold/30 text-[10px]",children:Ee[v]||v})]})]}),e.jsx(Ga,{className:"max-h-[calc(85vh-120px)]",children:e.jsx("div",{className:"px-6 py-4",children:Ge})})]})}):Ge},wi=({title:s,children:n,variant:m="info"})=>{const x={info:"border-primary/20 bg-primary/5",warning:"border-gold/20 bg-gold/5",success:"border-success/20 bg-success/5"},i={info:"text-primary",warning:"text-gold",success:"text-success"};return e.jsx("div",{className:`p-3 rounded-lg border ${x[m]}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(We,{className:`h-4 w-4 mt-0.5 shrink-0 ${i[m]}`}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-foreground",children:s}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5 space-y-1",children:n})]})]})})},cn=({status:s})=>{const m={new:{whatItMeans:"A new application was submitted through the website. The client may or may not have created an account yet.",whatToDo:"Review the intake data for completeness. If the lead looks qualified, the system will auto-create their account when they verify their email.",whoActs:"System (auto) → Admin (review)"},account_created:{whatItMeans:"The client has verified their email and can now access the client portal.",whatToDo:"Wait for the client to complete their company details in the portal. You can send a reminder if they haven't logged in within 48 hours.",whoActs:"Client → fills in details"},details_submitted:{whatItMeans:"The client has provided their company info, import data, and tariff details.",whatToDo:"Generate and send engagement agreements (Consulting Agreement, POA, Contingency Fee). Use the Agreements tab to create from templates.",whoActs:"Admin → creates agreements; Client → signs"},agreements_pending:{whatItMeans:"Agreements have been sent to the client for signature.",whatToDo:"Monitor for signatures. The client signs in their portal. After all are signed, admin countersigns. Consider a follow-up call if unsigned after 3 days.",whoActs:"Client → signs; Admin → countersigns"},agreements_signed:{whatItMeans:"All agreements are signed. The engagement is legally binding.",whatToDo:"Begin document collection. The client uploads documents through their portal. Also set up ACE credentials and run the RPA automation to pull entry data.",whoActs:"Client → uploads docs; Admin → ACE setup & RPA"},documents_pending:{whatItMeans:"Some required documents are still outstanding.",whatToDo:"Check the Documents tab to see what's missing. Send the client reminders. Review uploaded documents for quality.",whoActs:"Client → uploads; Admin → reviews"},documents_uploaded:{whatItMeans:"All required documents have been uploaded.",whatToDo:"Review all documents for completeness and accuracy. Verify entry data. Run the qualification score. If everything checks out, submit for review.",whoActs:"Admin → review & submit"},in_review:{whatItMeans:"The claim is under active admin review.",whatToDo:"Analyze entry data, check IEEPA eligibility, verify liquidation statuses, and determine filing strategy (CAPE, PSC, or protest). Update qualification score.",whoActs:"Admin → deep review"},approved:{whatItMeans:"The claim is qualified and approved for CBP filing.",whatToDo:"Build the CAPE declaration CSV. Select eligible entries, validate data quality, and prepare the filing package.",whoActs:"Admin → CAPE prep"},filed_with_cbp:{whatItMeans:"The CAPE declaration has been submitted to CBP.",whatToDo:"Monitor CAPE status via automated polling. Typical processing: 30-90 days. No action needed unless CBP requests additional information.",whoActs:"System → auto-polls; CBP → processes"},protest_filed:{whatItMeans:"A formal protest has been filed with CBP challenging their duty assessment.",whatToDo:"Monitor protest status. CBP has up to 2 years to decide. Track the protest deadline. Prepare for possible Further Review or CIT filing.",whoActs:"
2CBP → decides; Legal → monitors"},refund_received:{whatItMeans:"CBP has approved the refund and deposited it via ACH.",whatToDo:"Verify the refund amount matches the claim. Calculate contingency fee. Process client payout. Generate final reconciliation report.",whoActs:"Admin → reconcile & payout"},closed_paid:{whatItMeans:"The refund has been paid to the client and the case is closed.",whatToDo:"No further action needed. The case is complete. Commission payments to brokers/affiliates are triggered automatically.",whoActs:"Complete ✓"}}[s];if(!m)return null;const x=[{icon:We,label:"What This Means",text:m.whatItMeans,color:"text-primary",bg:"bg-primary/5 border-primary/15",iconBg:"bg-primary/10"},{icon:Cs,label:"What To Do Next",text:m.whatToDo,color:"text-gold",bg:"bg-gold/5 border-gold/15",iconBg:"bg-gold/10"},{icon:Ia,label:"Who Acts",text:m.whoActs,color:"text-success",bg:"bg-success/5 border-success/15",iconBg:"bg-success/10"}];return e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx(Ra,{className:"h-4 w-4 text-primary"}),e.jsxs("p",{className:"text-sm font-semibold text-foreground",children:["Process Guide — ",s.replace(/_/g," ").replace(/\b\w/g,i=>i.toUpperCase())]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:x.map(i=>{const c=i.icon;return e.jsxs("div",{className:`rounded-lg border p-4 ${i.bg}`,children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-2.5",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg flex items-center justify-center ${i.iconBg}`,children:e.jsx(c,{className:`h-4 w-4 ${i.color}`})}),e.jsx("p",{className:`text-[11px] font-bold uppercase tracking-wider ${i.color}`,children:i.label})]}),e.jsx("p",{className:"text-[13px] text-foreground leading-relaxed",children:i.text})]},i.label)})})]})},dn={entries:({entries:s,status:n})=>{if(s.length===0)return{title:"Import entry data first",text:"This claim has no entries yet. Go to 'RPA Jobs' to auto-pull from ACE, use 'CSV Import' to upload an ACE report, or add entries manually. Entry data drives everything — eligibility, CAPE filing, liquidation analysis, and scoring.",variant:"warning"};const m=s.filter(x=>x.status==="pending").length;return m>0?{title:`${m} entries need review`,text:"Review entry data for accuracy — check HTS codes, duty amounts, and liquidation dates. Mark verified entries. Then check the Eligibility tab to see which filing pathways are available.",variant:"info"}:null},eligibility:({entries:s})=>s.length===0?{title:"No entries to analyze",text:"Import entries first from the Entries tab. Eligibility is computed automatically once entries are loaded.",variant:"warning"}:null,cape:({entries:s,status:n})=>{const m=s.filter(x=>(x.ieepa_duties||0)>0);return s.length===0?{title:"Need entries first",text:"Import entries before creating CAPE batches.",variant:"warning"}:m.length===0?{title:"No IEEPA-eligible entries",text:"None of the current entries have IEEPA duties. CAPE filing requires IEEPA-specific duties.",variant:"warning"}:["approved","in_review","ready_for_review"].includes(n)?{title:"Ready to build CAPE declaration",text:`You have ${m.length} entries with IEEPA duties. Click 'Create Batch' to select entries, validate data, and generate the CAPE CSV for CBP submission.`,variant:"success"}:null},liquidation:({entries:s})=>s.length===0?{title:"No entries to analyze",text:"Import entries from the Entries tab first.",variant:"warning"}:{title:"Understanding Liquidation",text:"Liquidation is when CBP finalizes duty amounts. After liquidation, you have 180 days to file a protest. Unliquidated entries can use PSC (Pre-Summary Correction). This tab shows deadline urgency for all entries.",variant:"info"},protests:({entries:s})=>s.length===0?{title:"No entries for protests",text:"Import entries first. Protests challenge CBP's duty assessment on liquidated entries.",variant:"warning"}:{title:"When to file a protest",text:"File a formal protest (19 USC §1514) when CBP denies a CAPE claim or when you need to challenge duty assessment on liquidated entries. Must file within 180 days of liquidation. Check the Liquidation tab for deadline urgency.",variant:"info"},cit:()=>({title:"Court of International Trade",text:"CIT litigation is the last resort after a protest is denied. You must file a summons within 180 days of protest denial. This requires outside legal counsel. Only create a CIT case when a protest has been formally denied by CBP.",variant:"info"}),ace_account:({aceAccount:s})=>{if(!s)return{title:"Set up ACE account",text:"Create an ACE account record to track the client's CBP portal access, ACH refund enrollment, and eDIS status. All three are required before filing with CBP.",variant:"warning"};const n=[];return s.verification_status!=="verified"&&n.push("ACE not verified"),s.ach_enrolled||n.push("ACH not enrolled"),s.edis_enrolled||n.push("eDIS not enrolled"),n.length>0?{title:`${n.length} blocker(s) remaining`,text:`Before filing: ${n.join(", ")}. All three (ACE verified, ACH enrolled, eDIS enrolled) must be complete.`,variant:"warning"}:{title:"ACE account is ready",text:"All prerequisites met — ACE verified, ACH enrolled, eDIS enrolled. Ready for CBP submission.",variant:"success"}},credentials:()=>({title:"ACE Portal Credentials",text:"Store the client's ACE portal username and password here. These 
2credentials are encrypted and used by RPA automation to log into CBP's ACE portal and download entry data. Never share these credentials outside this system.",variant:"info"}),rpa:()=>({title:"RPA Automation",text:"RPA (Robotic Process Automation) automates ACE portal tasks — downloading entry summaries, checking liquidation status, and syncing data. Launch a job to pull the latest entry data. Results appear in the Entries tab.",variant:"info"}),reconciliation:({status:s})=>s==="refund_received"||s==="closed_paid"?{title:"Reconcile the refund",text:"Compare the actual refund amount from CBP against estimated refund. Calculate the contingency fee. Generate the final reconciliation report. Then process client payout and change status to 'Closed — Paid'.",variant:"success"}:{title:"Reconciliation",text:"This tab is used after CBP deposits the refund. It compares actual vs. estimated amounts, calculates fees, and tracks payouts. It will become active when the claim reaches 'Refund Received' status.",variant:"info"},scoring:()=>({title:"Qualification Scoring",text:"The qualification score (0-100) rates how strong this claim is. It factors in IEEPA duty amounts, liquidation status, documentation completeness, and client cooperation. Higher scores = faster processing and better filing outcomes.",variant:"info"}),documents:({checklist:s})=>{const n=s.filter(x=>x.required),m=n.filter(x=>x.completed).length;return n.length>0&&m<n.length?{title:`${n.length-m} documents still needed`,text:"Review uploaded documents and approve/reject them. Rejected documents notify the client to re-upload. All required documents must be complete before filing with CBP.",variant:"warning"}:n.length>0&&m===n.length?{title:"All required documents collected",text:"All required documents are uploaded and approved. Ready to proceed to the review phase.",variant:"success"}:null},agreements:({agreements:s})=>{const n=s.filter(x=>["draft","sent"].includes(x.status)),m=s.filter(x=>x.status==="signed");return n.length>0?{title:`${n.length} agreement(s) awaiting client signature`,text:"The client signs agreements in their portal (Consulting Agreement, POA, Contingency Fee). Once signed, you'll need to countersign each one to make them legally binding.",variant:"warning"}:m.length>0?{title:`${m.length} agreement(s) need your countersignature`,text:"Click the agreement card below → review → Countersign. This makes the agreement legally binding.",variant:"warning"}:null}},ne=s=>{const n=dn[s.tab];if(!n)return null;const m=n(s);if(!m)return null;const x={info:"border-primary/20 bg-primary/5",warning:"border-gold/20 bg-gold/5",success:"border-success/20 bg-success/5"},i={info:"text-primary",warning:"text-gold",success:"text-success"},d={info:We,warning:He,success:Cs}[m.variant];return e.jsx("div",{className:`p-3 rounded-lg border mb-4 ${x[m.variant]}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(d,{className:`h-4 w-4 mt-0.5 shrink-0 ${i[m.variant]}`}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-foreground",children:m.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 leading-relaxed",children:m.text})]})]})})},hs=new Date("2026-02-24");function mn(s){const n=(s||"").toUpperCase().trim();return["CHINA","CN","HONG KONG","HK"].includes(n)?new Date("2025-02-04"):["CANADA","CA","MEXICO","MX"].includes(n)?new Date("2025-03-04"):new Date("2025-04-05")}const un=new Set(["warehouse","re-warehouse","warehouse_withdrawal","ie_warehouse","06","21","22","23"]),ps=365,hn=(s,n)=>Math.floor((n.getTime()-s.getTime())/864e5),mt=s=>{if(s==null)return 0;if(typeof s=="number")return isFinite(s)?s:0;const n=parseFloat(String(s).replace(/[^0-9.\-]/g,""));return isNaN(n)?0:n};function pn(s,n=new Date){if(mt(s==null?void 0:s.ieepa_duties)<=0)return{phase:"excluded",label:"No IEEPA exposure",reason:"Entry has no IEEPA duties on file — nothing to recover.",isImmediatelyRefundable:!1,isRecoverableWithAction:!1};const x=String((s==null?void 0:s.entry_type)||"").toLowerCase().trim();if(un.has(x))return{phase:"excluded",label:"FTZ / Warehouse",reason:`Entry type "${s==null?void 0:s.entry_type}" (FTZ/Warehouse) is excluded from IEEPA refunds under CBP CSMS guidance.`,isImmediatelyRefundable:!1,isRecoverableWithAction:!1};if(s!=null&&s.entry_date){const v=new Date(s.entry_date),_=mn(s==null?void 0:s.country_of_origin);if(v<_||v>hs)return{phase:"excluded",label:"Outside IEEPA window",reason:`Entry date ${v.toISOString().slice(0,10)} falls outside the IEEPA coverage window for ${(s==null?void 0:s.country_of_origin)||"this country"} (${_.toISOString().slice(0,10)} → ${hs.toISOString().slice(0,10)}).`,isImmediatelyRefundable:!1,isRecoverableWithAction:!1}}if((s==null?void 0:s.procedural_posture)==="administratively_barred")return{phase:"excluded",label:"Administratively barred",reason:"Entry was administratively flagged as barred from refund recovery.",isImmediatelyRefundable:!1,isRecoverableWithAction:!1};if(s!=null&&s.has_ad_cvd)return{phase:"cit",label:"CIT · AD/CVD entanglement",reason:"Entry contains AD/CVD lines. CBP CAPE Phase 1 excludes AD/CVD; recovery requires Court of International Trade litigation.",isImmediatelyRefundable:!1,isRecoverableWithAction:!0}
2;const i=String((s==null?void 0:s.liquidation_status)||"").toLowerCase().trim(),c=s!=null&&s.protest_deadline?new Date(s.protest_deadline):null,d=s!=null&&s.entry_date?new Date(s.entry_date):null,t=s!=null&&s.liquidation_date?new Date(s.liquidation_date):null,E=i==="liquidated"||t!=null;if(i==="suspended"||!!(s!=null&&s.suspension_code))return{phase:"phase_2",label:"Phase 2 · Suspended",reason:"Liquidation is suspended (likely pending CBP review). Refund becomes available once CBP lifts suspension and liquidates the entry. Per CBP CSMS, PSC may not be used to initiate an IEEPA refund request.",isImmediatelyRefundable:!1,isRecoverableWithAction:!0};if(E){const v=c||(t?new Date(t.getTime()+15552e6):null);return v&&v<n?{phase:"cit",label:"CIT · Protest expired",reason:`180-day protest deadline (${v.toISOString().slice(0,10)}) has passed. Recovery requires CIT litigation.`,isImmediatelyRefundable:!1,isRecoverableWithAction:!0}:{phase:"phase_1",label:"Phase 1 · CAPE-ready",reason:`Entry is liquidated${t?` on ${t.toISOString().slice(0,10)}`:""}, within the 180-day protest window, IEEPA-only, no AD/CVD. Eligible for immediate refund via CBP CAPE bulk-CSV upload.`,isImmediatelyRefundable:!0,isRecoverableWithAction:!1}}if(d){const v=hn(d,n);if(v>ps&&!(s!=null&&s.extension_code)&&!(s!=null&&s.suspension_code)){const _=new Date(d.getTime()+ps*864e5),A=new Date(_.getTime()+180*864e5);return A<n?{phase:"cit",label:"CIT · Deemed-liq protest expired",reason:`Entry is ${v} days old with no liquidation — deemed liquidated by operation of law on ~${_.toISOString().slice(0,10)}. The 180-day protest window expired ~${A.toISOString().slice(0,10)}. CIT-only.`,isImmediatelyRefundable:!1,isRecoverableWithAction:!0}:{phase:"phase_3",label:"Phase 3 · Deemed liquidation",reason:`Entry is ${v} days old (≥365) with no liquidation, suspension, or extension on file — deemed liquidated by operation of law per 19 U.S.C. §1504(a) on ~${_.toISOString().slice(0,10)}. Refund rights must be preserved via a formal protest under 19 U.S.C. §1514 before ~${A.toISOString().slice(0,10)}.`,isImmediatelyRefundable:!1,isRecoverableWithAction:!0}}}return{phase:"phase_2",label:"Phase 2 · Unliquidated",reason:"Entry has not yet liquidated and is still within CBP's normal processing window. Submit through CAPE once CBP liquidates the entry. Per CBP CSMS, PSC may not be used to initiate an IEEPA refund request.",isImmediatelyRefundable:!1,isRecoverableWithAction:!0}}function Ss(s,n=new Date){const m=c=>({phase:c,entries:[],count:0,ieepaTotal:0,s301Total:0,s232Total:0,combinedTotal:0}),x={phase_1:m("phase_1"),phase_2:m("phase_2"),phase_3:m("phase_3"),cit:m("cit"),excluded:m("excluded")};for(const c of s){const d=pn(c,n),t=x[d.phase];t.entries.push({...c,_phaseClassification:d}),t.count+=1,t.ieepaTotal+=mt(c==null?void 0:c.ieepa_duties),t.s301Total+=mt(c==null?void 0:c.section_301_duties),t.s232Total+=mt(c==null?void 0:c.section_232_duties),t.combinedTotal=t.ieepaTotal+t.s301Total+t.s232Total}const i=x.phase_1.count+x.phase_2.count+x.phase_3.count+x.cit.count;return{byPhase:x,totalEntries:s.length,totalImpactedEntries:i,totalEligibleRefund:x.phase_1.ieepaTotal,totalFilableNow:x.phase_1.ieepaTotal+x.phase_3.ieepaTotal,totalRecoverableRefund:x.phase_1.ieepaTotal+x.phase_2.ieepaTotal+x.phase_3.ieepaTotal,totalLitigationOnly:x.cit.ieepaTotal,totalExcluded:x.excluded.ieepaTotal}}const xn={phase_1:{label:"Phase 1 · CAPE-ready",shortLabel:"Phase 1",tagline:"Refundable now via CBP CAPE",description:"Liquidated entries inside the 180-day protest window with IEEPA-only exposure (no AD/CVD, no FTZ/warehouse). These are pushed to CBP via the CAPE bulk-CSV upload — the fastest refund path.",recoveryPath:"CBP CAPE bulk upload (immediate)",badgeClass:"bg-success/15 text-success border-success/30",cardAccentClass:"border-success/40 bg-success/5",iconName:"CheckCircle2",priority:1},phase_2:{label:"Phase 2 · Awaiting liquidation",shortLabel:"Phase 2",tagline:"Wait for CBP to liquidate",description:"Unliquidated or suspended entries with valid IEEPA exposure. Refund becomes available once CBP liquidates the entry — at which point it moves to Phase 1. Per CBP CSMS, a Post-Summary Correction (PSC) may NOT be used to initiate an IEEPA refund request.",recoveryPath:"Wait for CBP liquidation, then file via CAPE",badgeClass:"bg-info/15 text-info border-info/30",cardAccentClass:"border-info/40 bg-info/5",iconName:"Clock",priority:2},phase_3:{label:"Phase 3 · Deemed liquidation",shortLabel:"Phase 3",tagline:"Refund via formal protest (19 USC §1514)",description:"Entries that have reached one year (365 days) from the entry date with no liquidation, extension, suspension, or other applicable status event — deemed liquidated by operation of law under 19 U.S.C. §1504(a). Refund rights are preserved through a formal CBP protest under 19 U.S.C. §1514, filed within 180 days of the deemed-liquidation date.",recoveryPath:"Formal CBP protest (19 USC §1514)",badgeClass:"bg-warning/15 text-warning border-warning/30",cardAccentClass:"border-warning/40 bg-warning/5",iconName:"AlertTriangle",priority:3},cit:{label:"CIT · Litigation only",shortLabel:"CIT",tagline:"Recovery via Court of International Trade",description:"Entries past the 180-day protest deadline or entangled with AD/CVD lines. CBP CAPE and protest paths are no longer available — recovery requires CIT litigation. Higher cost and longer timeline but still recoverable.",recoveryPath:"Court of International Trade case",badgeClass:"bg-destructive/15 text-destructive border-destructive/30",cardAccentClass:"border-destructive/40 bg-destructive/5",iconName:"Scale",priority:4},excluded:{label:"Excluded",shortLabel:"Excluded",tagline:"Not refundable under IEEPA program",description:"Entries that don't qualify for any IEEPA refund path: FTZ/warehouse entry types, dates outside IEEPA coverage windows, zero IEEPA duties, or administratively barred.",recoveryPath:"Not refundable",badgeClass:"bg-muted text-muted-foreground border-border",cardAccentClass:"border-border bg-muted/30",iconName:"Ban",priority:5}}
2,gn={phase_1:ue,phase_2:Ne,phase_3:He,cit:we,excluded:As},fn=({phase:s,bucket:n,compact:m,defaultOpen:x=!1})=>{const i=xn[s],c=gn[s],[d,t]=b.useState(x);return n.count===0?null:e.jsx(Qa,{open:d,onOpenChange:t,children:e.jsxs("div",{className:ze("rounded-lg border p-3 transition-colors",i.cardAccentClass),children:[e.jsx(Za,{asChild:!0,children:e.jsxs("button",{className:"w-full flex items-start gap-3 text-left",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:e.jsx(c,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm",children:i.label}),e.jsxs(R,{variant:"outline",className:ze("text-[10px] font-mono",i.badgeClass),children:[n.count," ",n.count===1?"entry":"entries"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-base font-bold tabular-nums",children:X(n.ieepaTotal)}),!m&&n.combinedTotal>n.ieepaTotal&&e.jsxs("div",{className:"text-[10px] text-muted-foreground tabular-nums",children:["+",X(n.combinedTotal-n.ieepaTotal)," S301/232"]})]})]}),!m&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i.tagline}),e.jsxs("div",{className:"text-[10px] text-muted-foreground/80 mt-1 flex items-center gap-1",children:[d?e.jsx(Ns,{className:"h-3 w-3"}):e.jsx(ws,{className:"h-3 w-3"}),d?"Hide details":`View ${n.count} ${n.count===1?"entry":"entries"} & recovery path`]})]})]})}),e.jsxs(Ja,{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"text-xs text-foreground/90 bg-background/60 rounded p-2.5 border border-border/40",children:[e.jsx("p",{className:"font-medium mb-1",children:"What this means"}),e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:i.description}),e.jsxs("p",{className:"mt-2 pt-2 border-t border-border/40",children:[e.jsx("span",{className:"font-medium",children:"Recovery path:"})," ",e.jsx("span",{className:"text-muted-foreground",children:i.recoveryPath})]})]}),n.entries.length>0&&e.jsxs("div",{className:"max-h-48 overflow-y-auto space-y-1",children:[n.entries.slice(0,50).map((E,f)=>e.jsxs("div",{className:"text-[11px] flex items-center justify-between gap-2 px-2 py-1 rounded bg-background/40 border border-border/30",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"font-mono",children:E.entry_number||"—"}),E.entry_date&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",new Date(E.entry_date).toLocaleDateString()]}),E.country_of_origin&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",E.country_of_origin]})]}),e.jsx("span",{className:"font-semibold tabular-nums shrink-0",children:X(Number(E.ieepa_duties||0))})]},E.id||f)),n.entries.length>50&&e.jsxs("p",{className:"text-[10px] text-muted-foreground text-center py-1",children:["+ ",n.entries.length-50," more"]})]})]})]})})};function bn({entries:s,anchorClaim:n,compact:m=!1,hideEmptyExcluded:x=!0,className:i}){const c=b.useMemo(()=>Ss(s),[s]),d=!!(n!=null&&n.isAnchorBacked),t=!!(n&&(n.totalRecoverable!=null||n.phase1Eligible!=null||n.totalEntriesImpacted!=null)),E=!!(n&&(n.phase2Amount!=null||n.phase3Amount!=null)),f=d&&(n==null?void 0:n.phase1Eligible)!=null?n.phase1Eligible:c.totalFilableNow,v=d&&(n==null?void 0:n.effectiveTotalRecoverable)!=null?n.effectiveTotalRecoverable:c.totalRecoverableRefund,_=d&&(n==null?void 0:n.totalEntriesImpacted)!=null?n.totalEntriesImpacted:c.totalImpactedEntries,A=d&&(n==null?void 0:n.totalEntriesImpacted)!=null?n.totalEntriesImpacted:c.totalEntries,w=["phase_1","phase_2","phase_3","cit","excluded"];return d&&!t?e.jsxs(W,{className:i,children:[e.jsxs(Z,{className:"pb-3",children:[e.jsxs(J,{className:"text-sm font-bold flex items-center gap-1.5",children:[e.jsx(st,{className:"h-4 w-4 text-primary"})," Refund Phase Breakdown"]}),e.jsx(me,{className:"text-xs",children:"Anchor-backed claim detected — per-entry phase breakdown is pending the Claim Workbook entry parse."})]}),e.jsx(Y,{children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Re-parse the Anchor workbook to populate authoritative phase totals and entry buckets. Legacy TRA entry phases are intentionally hidden here."})})]}):c.totalEntries===0&&!d?e.jsxs(W,{className:i,children:[e.jsx(Z,{className:"pb-3",children:e.jsxs(J,{className:"text-sm font-bold flex items-center gap-1.5",children:[e.jsx(st,{className:"h-4 w-4 text-primary"})," Refund Phase Breakdown"]})}),e.jsx(Y,{children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"No entries on file yet. Phase classification will appear once ACE entry data is loaded."})})]}):e.jsxs(W,{className:i,children:[e.jsx(Z,{className:"pb-3",children:e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{children:[e.jsxs(J,{className:"text-sm font-bold flex items-center gap-1.5",children:[e.jsx(st,{className:"h-4 w-4 text-primary"}
2)," Refund Phase Breakdown",e.jsx(Se,{children:e.jsxs(Pe,{children:[e.jsx(ke,{asChild:!0,children:e.jsx(We,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsx(Te,{className:"max-w-sm",children:e.jsxs("p",{className:"text-xs leading-relaxed",children:["CBP defines four IEEPA refund pathways. ",e.jsx("strong",{children:"Phase 1"})," is immediate via CAPE.",e.jsx("strong",{children:" Phase 2"})," waits for liquidation. ",e.jsx("strong",{children:"Phase 3"})," uses a formal protest on deemed-liquidated entries. ",e.jsx("strong",{children:"CIT"})," is litigation for past-deadline or AD/CVD entries."]})})]})})]}),e.jsxs(me,{className:"text-xs",children:[_," of ",A," entries have IEEPA exposure"]})]})})}),e.jsxs(Y,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-success/30 bg-success/5 p-2.5",children:[e.jsxs("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide font-medium flex items-center gap-1",children:["Filable with CBP now",e.jsx(Se,{children:e.jsxs(Pe,{children:[e.jsx(ke,{asChild:!0,children:e.jsx(We,{className:"h-2.5 w-2.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Te,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:"Phase 1 (CAPE bulk upload) + Phase 3 (formal protest on deemed-liquidated entries). Both can be filed with CBP today."})})]})})]}),e.jsx("p",{className:"text-lg font-bold text-success tabular-nums",children:X(f)}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:d?"Anchor Phase 1 eligible":"Phase 1 (CAPE) + Phase 3 (protest)"})]}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-2.5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide font-medium",children:"Total recoverable"}),e.jsx("p",{className:"text-lg font-bold text-primary tabular-nums",children:X(v)}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:d?`Anchor Summary Workbook v${(n==null?void 0:n.summaryVersion)??1}`:"Phase 1 + 2 + 3 (excl. CIT)"})]})]}),d&&!E?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground",children:"Detailed Anchor phase rows are pending Claim Workbook entry parsing. Legacy TRA phase buckets are intentionally hidden."}):e.jsx("div",{className:"space-y-2",children:w.map(p=>{const j=c.byPhase[p];return x&&p==="excluded"&&j.count===0?null:e.jsx(fn,{phase:p,bucket:j,compact:m,defaultOpen:p==="phase_1"&&j.count>0&&!m},p)})}),c.totalLitigationOnly>0&&e.jsxs("p",{className:"text-[10px] text-muted-foreground pt-1 border-t border-border/60",children:[e.jsx(we,{className:"inline h-3 w-3 mr-0.5"}),"Additional ",e.jsx("strong",{className:"text-foreground",children:X(c.totalLitigationOnly)})," recoverable via CIT litigation (longer timeline, higher cost)."]})]})]})}const _n={"anchor.badge.backed":"Anchor-backed","anchor.badge.backed_compact":"Anchor","anchor.badge.synced":"Anchor synced","anchor.badge.synced_compact":"Synced","anchor.badge.preliminary":"Preliminary","anchor.badge.stale":"Anchor — stale","anchor.badge.stale_compact":"Stale","anchor.aria.backed":"Anchor-backed claim — numbers confirmed by processor","anchor.aria.synced":"Anchor synced — snapshot present, full summary pending","anchor.aria.preliminary":"Preliminary claim — not yet processed by Anchor","anchor.aria.stale":"Anchor data is older than the freshness threshold","anchor.tooltip.backed_prefix":"Backed by Anchor — Summary Workbook v","anchor.tooltip.synced_prefix":"Snapshot present, no parsed Summary Workbook yet","anchor.tooltip.preliminary":"TRA preliminary data only — not yet processed by Anchor.","anchor.tooltip.stale_suffix":"Last sync exceeds freshness threshold; refresh recommended.","anchor.tooltip.synced_relative":"synced","anchor.changes.title":"What Anchor refined","anchor.changes.empty":"Anchor matched TRA's preliminary numbers — no changes.","anchor.changes.from":"Preliminary","anchor.changes.to":"Anchor","anchor.empty.no_data.title":"Preliminary — pending Anchor verification","anchor.empty.no_data.body":"We're still showing TRA's intake numbers. Once Anchor finishes due-diligence we'll surface their confirmed amounts here.","anchor.empty.not_authorized.title":"Anchor details not available","anchor.empty.not_authorized.body":"You don't have access to Anchor-confirmed numbers for this claim. Contact your representative if you believe this is in error.","anchor.packet.button":"Download Anchor Packet","anchor.packet.menu":"Download Anchor Packet (PDF)","anchor.packet.unavailable":"Packet available once claim is Anchor-backed","anchor.packet.generating":"Building packet…","anchor.packet.error":"Could not generate packet"};function O(s,n){return _n[s]}function vn({data:s,compact:n=!1,className:m}){if(!s)return e.jsxs(R,{variant:"outline",role:"status","aria-label":O("anch
2or.aria.preliminary"),className:`gap-1 bg-muted text-muted-foreground border-border ${m||""}`,children:[e.jsx(Ne,{className:"h-3 w-3","aria-hidden":"true"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide",children:O("anchor.badge.preliminary")})]});const{isAnchorBacked:x,hasSnapshot:i,isStale:c,lastSyncedAt:d,summaryVersion:t}=s,E=d?en(new Date(d),{addSuffix:!0}):null;let f,v,_=ht,A,w;return x&&c?(f=O(n?"anchor.badge.stale_compact":"anchor.badge.stale"),v="bg-warning/10 text-warning-foreground border-warning/40",_=He,A=`${O("anchor.tooltip.backed_prefix")}${t??1} — ${O("anchor.tooltip.stale_suffix")}`,w=O("anchor.aria.stale")):x?(f=O(n?"anchor.badge.backed_compact":"anchor.badge.backed"),v="bg-success/10 text-success border-success/30",_=Da,A=`${O("anchor.tooltip.backed_prefix")}${t??1}${E?` · ${O("anchor.tooltip.synced_relative")} ${E}`:""}.`,w=O("anchor.aria.backed")):i?(f=O(n?"anchor.badge.synced_compact":"anchor.badge.synced"),v="bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-500/30",_=ht,A=`${O("anchor.tooltip.synced_prefix")}${E?` · ${O("anchor.tooltip.synced_relative")} ${E}`:""}.`,w=O("anchor.aria.synced")):(f=O("anchor.badge.preliminary"),v="bg-muted text-muted-foreground border-border",_=Ne,A=O("anchor.tooltip.preliminary"),w=O("anchor.aria.preliminary")),e.jsx(Se,{children:e.jsxs(Pe,{children:[e.jsx(ke,{asChild:!0,children:e.jsxs(R,{variant:"outline",role:"status","aria-label":w,className:`gap-1 ${v} ${m||""}`,children:[e.jsx(_,{className:"h-3 w-3","aria-hidden":"true"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide",children:f})]})}),e.jsx(Te,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:A})})]})})}function yn({leadId:s,enabled:n,variant:m="outline",size:x="sm",iconOnly:i=!1,className:c}){const[d,t]=b.useState(!1),E=async()=>{t(!0);try{const{data:v,error:_}=await g.functions.invoke("export-anchor-packet",{body:{lead_id:s}});if(_)throw _;const A=v==null?void 0:v.url;if(!A)throw new Error((v==null?void 0:v.error)||"No URL returned");window.open(A,"_blank","noopener,noreferrer")}catch(v){Hs({title:O("anchor.packet.error"),description:(v==null?void 0:v.message)??"",variant:"destructive"})}finally{t(!1)}},f=O(n?"anchor.packet.button":"anchor.packet.unavailable");return e.jsxs(k,{type:"button",variant:m,size:x,disabled:!n||d,onClick:E,className:c,"aria-label":f,title:f,children:[d?e.jsx(Ie,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):e.jsx(dt,{className:"h-4 w-4","aria-hidden":"true"}),!i&&e.jsx("span",{className:"ml-1.5",children:O(d?"anchor.packet.generating":"anchor.packet.button")})]})}const be={none:{label:"No ACE blocker — clear",short:"Clear",severity:"info"},...Object.fromEntries(Es.map(s=>[s,{label:Rt[s].label,short:Rt[s].short,severity:Rt[s].severity}]))};function jn({leadId:s,compact:n}){const[m,x]=b.useState(null),[i,c]=b.useState(null),[d,t]=b.useState(!1),[E,f]=b.useState(!0),{toast:v}=Bt(),_=async()=>{f(!0);const{data:w}=await g.from("lead_tags").select("tag_key").eq("lead_id",s).eq("is_active",!0).in("tag_key",Es),p=(w||[]).map(M=>M.tag_key),j=sn(p);x(j),c(j??"none"),f(!1)};b.useEffect(()=>{s&&_()},[s]);const A=async()=>{if(!(!i||i===m||i==="none"&&!m)){t(!0);try{const w=Object.keys(be).filter(p=>p!=="none");if(await g.from("lead_tags").update({is_active:!1,cleared_at:new Date().toISOString()}).eq("lead_id",s).eq("is_active",!0).in("tag_key",w),i!=="none"){const p=be[i],{error:j}=await g.rpc("anchor_apply_tag",{p_lead_id:s,p_tag_key:i,p_tag_label:p.label,p_tag_category:"ace",p_severity:p.severity,p_payload:{reason:"admin_manual_tag"},p_source:"admin"});if(j)throw j}v({title:i==="none"?"ACE blocker cleared":"ACE blocker applied",description:i==="none"?"Claim no longer flagged as ACE-stalled.":`Tag visible in partner, broker, and client portals: ${be[i].short}.`}),await _()}catch(w){v({title:"Failed to update ACE tag",description:(w==null?void 0:w.message)||String(w),variant:"destructive"})}finally{t(!1)}}};return n?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(_e,{value:i??"none",onValueChange:w=>c(w),disabled:E||d,children:[e.jsx(ve,{className:"h-8 text-xs w-[260px] max-w-full",children:e.jsx(ye,{placeholder:"Set ACE blocker…"})}),e.jsx(je,{children:Object.keys(be).map(w=>e.jsx(ie,{value:w,className:"text-xs",children:be[w].label},w))})]}),e.jsx(k,{size:"sm",variant:"outline",disabled:d||E||i===(m??"none"),onClick:A,children:d?e.jsx(Ie,{className:"h-3.5 w-3.5 animate-spin"}):"Save"})]}):e.jsxs("div",{className:"rounded-lg border border-border bg-card p-3 sm:p-4 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[m?e.jsx(He,{className:"h-4 w-4 text-destructive"}):e.jsx(ue,{className:"h-4 w-4 text-success"}),e.jsx("span",{className:"text-sm font-semibold",children:"ACE Blocker"}),m?e.jsx(R,{variant:"outline",className:"border-destructive/40 bg-destructive/10 text-destructive text-[10px]",children:be[m].short}):e.jsx(R,{variant:"outline",className:"border-success/30 bg-success/10 text-success text-[10px]",children:"None"})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Visible in partner, broker & client portals"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status stays at its current step — this overlay flag tells everyone the claim is waiting on ACE access."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsxs(_e,{value:i??"none",onValueChange:w=>c(w),disabled:E||d,children:[e.jsx(ve,{className:"h-9 text-xs w-full sm:w-[320px]",children:e.jsx(ye,{placeholder:"Set ACE blocker…"})}),e.jsx(je,{children:Object.keys(be).map(w=>e.jsx(ie,{value:w,className:"text-xs",children:be[w].label},w))})]}),e.jsxs(k,{size:"sm",disabled:d||E||i===(m??"none"),onClick:A,children:[d?e.jsx(Ie,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):null,i==="none"?"Clear blocker":"Apply blocker"]})]})]})}const Nn=F(()=>$(()=>import("./CrmCommsPanel-nS76Es73.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18])).then(s=>({default:s.CrmCommsPanel}))),wn=F(()=>$(()=>import("./AnchorProcessingTab-D0yUsLh6.js"),__vite__mapDeps([19,1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,14,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]))),Cn=F(()=>$(()=>import("./EntriesTab-pDlYBVhL.js"),__vite__mapDeps([61,1,2,3,4,6,7,8,9,10,11,12,13,5,35,15,16,17,62,14,41,34,63,64,65,25,22,66,67,24,68,23,69,70]))),An=F(()=>$(()=>import("./CapeReadiness-nFeSbDQt.js"),__vite__mapDeps([71,1,2,5,6,7,8,3,4,9,10,11,12,13,34]))),xs=F(()=>$(()=>import("./ScoringBreakdown-DJ6VDrav.js"),__vite__mapDeps([72,1,2,5,6,7,8,3,4,9,10,11,12,13,73,36,34]))),En=F(()=>$(()=>import("./LiquidationAnalysis-BtUOYMns.js"),__vite__mapDeps([74,1,2,5,6,7,8,3,4,9,10,11,12,13,34]))),Sn=F(()=>$(()=>import("./CommissionsTab-dcz8dxus.js"),__vite__mapDeps([75,1,2,5,6,7,8,3,4,9,10,11,12,13,62,35,15,16,17,14,76,69,77]))),Pn=F(()=>$(()=>import("./CommissionAuditLog-DYeQaLra.js"),__vite__mapDeps([78,1,2,5,6,7,8,3,4,9,10,11,12,13,25,22]))),kn=F(()=>$(()=>import("./BrokerInclusionPanel-DhqMmMen.js"),__vite__mapDeps([79,1,2,5,6,7,8,3,4,9,10,11,12,13,80]))),Tn=F(()=>$(()=>import("./BrokerOverrideCard-CkEaMU03.js"),__vite__mapDeps([81,1,2,5,6,7,8,3,4,9,10,11,12,13,35,14,80]))),In=F(()=>$(()=>import("./ClaimConversation-BhWEhiRg.js"),__vite__mapDeps([82,1,2,6,7,8,3,4,9,10,11,12,13,14,15,16,17,69,83,22,21]))),Rn=F(()=>$(()=>import("./DocumentAnalysis-CHm9BRR0.js"),__vite__mapDeps([84,1,2,3,4,6,7,8,9,10,11,12,13,5,73,27,28]))),Dn=F(()=>$(()=>import("./RefundReconciliation-DbgR2bMK.js"),__vite__mapDeps([85,1,2,5,6,7,8,3,4,9,10,11,12,13,62,35,63,64,65,25,22,66,67,24,68,23,69,70]))),gs=F(()=>$(()=>import("./DocumentVersionHistory-DXRYEjCr.js"),__vite__mapDeps([86,1,2,5,6,7,8,3,4,9,10,11,12,13,62,14,35,34]))),qn=F(()=>$(()=>import("./EntityEmailTimeline-CdMtIujJ.js"),__vite__mapDeps([87,1,2,5,6,7,8,3,4,9,10,11,12,13]))),$n=F(()=>$(()=>import("./CAPEBatchManager-Cqf9-fS-.js"),__vite__mapDeps([88,1,2,3,4,6,7,8,9,10,11,12,13,5,41,17,62]))),Bn=F(()=>$(()=>import("./ProtestManager-DEF-n4Ou.js"),__vite__mapDeps([89,1,2,3,4,6,7,8,9,10,11,12,13,5,35,14,41,17,40,63,64,65,25,22,66,67,24,68,23,69,70]))),Ln=F(()=>$(()=>import("./CITCaseManager-BQ9Gj4nT.js"),__vite__mapDeps([90,1,2,3,4,6,7,8,9,10,11,12,13,5,35,14,15,16,17,63,64,65,25,22,66,67,24,68,23,69,70]))),On=F(()=>$(()=>import("./ACEAccountManager-BxoAmsVL.js"),__vite__mapDeps([91,1,2,3,4,6,7,8,9,10,11,12,13,5,35,15,16,17,50,40,63,64,65,25,22,66,67,24,68,23,69,70]))),Fn=F(()=>$(()=>import("./CBPInteractions-B7l1ITYE.js"),__vite__mapDeps([92,1,2,3,4,5,6,7,8,9,10,11,12,13,62,26]))),Mn=F(()=>$(()=>import("./EligibilityMatrix-CmpXYGRK.js"),__vite__mapDeps([93,1,2,3,4,6,7,8,9,10,11,12,13,5,32,33,34,35,14,36,37,38,39,15,16,17,26,40,41,42,43,44,29,45,46,47,48,49,50,51,52,53,54,55,28,56,57,20,21,22,23,24,58,59]))),Vn=F(()=>$(()=>import("./ACECredentialManager-wXpU7d4y.js"),__vite__mapDeps([94,1,2,3,4,6,7,8,9,10,11,12,13,5,35,50,17]))),zn=F(()=>$(()=>import("./RPAJobManager-Djzyk0bw.js"),__vite__mapDeps([95,1,2,3,4,6,7,8,9,10,11,12,13,5,15,16,17,50,35,40]))),Un=F(()=>$(()=>import("./ACEReportETL-CR-0vrL7.js"),__vite__mapDeps([96,1,2,3,4,6,7,8,9,10,11,12,13,97,5,50,17,35]))),Wn=()=>{var Ht,Gt,Yt;const{id:s}=Ys(),[n,m]=Ks(),x=Qs(),{user:i,isCaseManager:c}=Gs(),{toast:d}=Bt(),[t,E]=b.useState(null),[f,v]=b.useState(null),[_,A]=b.useState([]),[w,p]=b.useState([]),[j,M]=b.useState([]),[V,Re]=b.useState([]),[T,Ce]=b.useState([]),[D,he]=b.useState([]),[P,at]=b.useState(null),[le,xt]=b.useState(null),[De,Ge]=b.useState(!1),[o,se]=b.useState([]),[oe,pe]=b.useState([]),[N,qe]=b.useState(null),[gt,Ye]=b.useState([]),[Q,z]=b.useState(null),[Ke,Qe]=b.useState(0),[Ze,$e]=b.useState([]),[ce,ft]=b.useState(!1),[bt,Ps]=b.useState(!0),[nt,_t]=b.useState(!1),[U,it]=b.useState({}),[q,xe]=b.useState({}),[Je,Ot]=b.useState(""),[Ft,Mt]=b.useState(!1),[ks,Vt]=b.useState(!1),[vt,Xe]=b.useState(!1),[Be,yt]=b.useState(null),[rt,jt]=b.useState(null),[Ts,zt]=b.useState(""),[Nt,Is]=b.useState([]),[Rs,lt]=b.useState(!1),[Ut,ot]=b.useState("overview"),{data:S}=Xa(s,{lead:t,claimDetails:f,entries:o}),C=async()=>{var Kt;if(!s)return;const[l,y,a,h,u,r,I,B,H,K,ge,de,G,et]=await Promise.all([g.from("leads").select("*").eq("id",s).single(),g.from("claim_details").select("*").eq("lead_id",s).maybeSingle(),g.from("claim_checklist").select("*").eq("lead_id",s).order("sort_order"),g.from("claim_timeline").select("*").eq("lead_id",s).order("created_at",{ascending:!1}).limit(50),g.from("lead_notes").select("*").eq("lead_id",s).order("created_at",{ascending:!1}),g.from("lead_documents").select("*").eq("lead_id",s).order("created_at",{ascending:!1}),g.from("claim_agreements").select("*").eq("lead_id",s).order("created_at",{ascending:!1}),g.from("agreement_templates").select("*").eq("is_active",!0),g.from("advance_funding").select("*").eq("lead_id",s).maybeSingle(),g.from("claim_entries").select("*").eq("lead_id",s).order("entry_date"),g.from("commission_ledger").select("*").eq("lead_id",s).order("created_at",{ascending:!1}),g.from("claim_messages").select("*").eq("lead_id",s).order("created_at",{ascending:!1}),g.from("ace_accounts").select("*").eq("lead_id",s).maybeSingle(),g.from("funding_applications").select("*").eq("lead_id",s).order("created_at",{ascending:!1}).limit(1).maybeSingle()]),ae=l.data;E(ae),it(ae||{}),v(y.data),xe(y.data||{}),A(a.data||[]),p(h.data||[]),M(u.data||[]),Re(r.data||[]),Ce(I.data||[]),he(B.data||[]),at(H.data),se(K.data||[]),pe(ge.data||[]),Ye(de.data||[]),z(G.data||null),xt(et.data||null);const{count:At}=await g.from("broker_clients").select("id",{count:"exact",head:!0}).eq("lead_id",s).eq("status","active");Qe(At||0);const{data:Oe}=await g.from("anchor_documents").select("*").eq("lead_id",s).is("removed_at",null).order("anchor_uploaded_at",{ascending:!1});$e(Oe||[]);const{count:ct}=await g.from("anchor_claim_snapshots").select("id",{count:"exact",head:!0}).eq("lead_id",s).eq("is_current",!0);ft((ct||0)>0),(Kt=y.data)!=null&&Kt.assigned_to&&zt(y.data.assigned_to);const{data:fe}=await g.from("user_roles").select("user_id").eq("role","admin");if(fe&&fe.length>0){const te=fe.map(Fe=>Fe.user_id),{data:re}=await g.from("profiles").select("user_id, full_name, email").in("user_id",te);Is(re||[])}if(ae!=null&&ae.affiliate_id){const{data:te}=await g.from("affiliates").select("id, full_name, email, phone, 
2company, slug, upline_affiliate_id, organization_id, comp_model, pool_pct, status, created_at").eq("id",ae.affiliate_id).maybeSingle();let re=null,Fe=null;if(te!=null&&te.upline_affiliate_id){const{data:Et}=await g.from("affiliates").select("id, full_name, email, company, slug").eq("id",te.upline_affiliate_id).maybeSingle();re=Et}if(te!=null&&te.organization_id){const{data:Et}=await g.from("organizations").select("id, company_short_name, slug").eq("id",te.organization_id).maybeSingle();Fe=Et}qe({...te,_upline:re,_organization:Fe})}else qe(null);if(ae&&!H.data){const te=K.data||[],re=_a(ae,te,y.data);if(re.estimatedRecovery>0){const{data:Fe}=await g.from("advance_funding").insert({lead_id:s,status:"pending_review",estimated_recovery:Math.round(re.estimatedRecovery*100)/100,advance_percentage:re.advancePct,advance_amount:Math.round(re.advanceAmount*100)/100,discount_rate:re.discountRate,net_to_client:Math.round(re.netToClient*100)/100}).select().single();at(Fe)}}Ps(!1)};b.useEffect(()=>{C()},[s]),b.useEffect(()=>{if(!s)return;const l=g.channel(`admin-lead-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"leads",filter:`id=eq.${s}`},()=>C()).on("postgres_changes",{event:"*",schema:"public",table:"claim_details",filter:`lead_id=eq.${s}`},()=>C()).on("postgres_changes",{event:"*",schema:"public",table:"claim_entries",filter:`lead_id=eq.${s}`},()=>C()).on("postgres_changes",{event:"*",schema:"public",table:"claim_timeline",filter:`lead_id=eq.${s}`},()=>C()).on("postgres_changes",{event:"*",schema:"public",table:"claim_agreements",filter:`lead_id=eq.${s}`},()=>C()).on("postgres_changes",{event:"*",schema:"public",table:"anchor_documents",filter:`lead_id=eq.${s}`},()=>C()).on("postgres_changes",{event:"*",schema:"public",table:"anchor_claim_snapshots",filter:`lead_id=eq.${s}`},()=>C()).on("postgres_changes",{event:"*",schema:"public",table:"anchor_processing_summaries",filter:`lead_id=eq.${s}`},()=>C()).subscribe();return()=>{g.removeChannel(l)}},[s]),b.useEffect(()=>{n.get("edit")==="1"&&_t(!0),n.get("action")==="1"&&lt(!0);const l=n.get("tab");l&&ot(l)},[n]);const Ds=async l=>{if(!t)return;const y=es(l,t,o,T,_);if(!y.allowed){d({title:"Cannot change status",description:y.blockers.join("; "),variant:"destructive"});return}await g.from("leads").update({status:l}).eq("id",t.id),await g.from("lead_activity_log").insert({lead_id:t.id,action:"status_change",old_status:t.status,new_status:l,user_id:(i==null?void 0:i.id)||null}),await g.from("claim_timeline").insert({lead_id:t.id,event_type:"status_change",title:`Status changed to ${Ee[l]||l}`,description:`From ${Ee[t.status]||t.status}`,user_id:(i==null?void 0:i.id)||null}),d({title:`Status updated to ${Ee[l]}`}),C()},qs=async()=>{t&&(Xe(!0),await g.from("leads").update({company_name:U.company_name,contact_name:U.contact_name,contact_email:U.contact_email,phone:U.phone,ein:U.ein,address:U.address,dba:U.dba,contact_title:U.contact_title,has_decision_maker:U.has_decision_maker,hts_concentration:U.hts_concentration,entry_complexity:U.entry_complexity,cooperation_level:U.cooperation_level,cash_urgency:U.cash_urgency,protest_days_remaining:U.protest_days_remaining?parseInt(U.protest_days_remaining):null}).eq("id",t.id),_t(!1),d({title:"Claim updated"}),C(),Xe(!1))},$s=async()=>{if(!t)return;const l=q.engagement_fee_pct_override;let y=null;if(l!==""&&l!=null){const r=Number(l);if(Number.isNaN(r)){d({title:"Invalid Override %",description:"Enter a number between 0 and 100.",variant:"destructive"});return}if(r<0){d({title:"Override cannot be negative",variant:"destructive"});return}if(r>100){d({title:"Override cannot exceed 100%",variant:"destructive"});return}if(f!=null&&f.engagement_fee_locked_at&&Number((f==null?void 0:f.engagement_fee_pct_override)??-1)!==r){d({title:"Override locked",description:`Contingency was locked on ${new Date(f.engagement_fee_locked_at).toLocaleDateString()}. It cannot be changed.`,variant:"destructive"});return}y=r}Xe(!0);const a=(()=>{const r=q.engagement_fee_pct??(f==null?void 0:f.engagement_fee_pct);if(r===""||r==null)return 20;const I=Number(r);return Number.isNaN(I)||I<=0?20:I})(),h={lead_id:t.id,priority:q.priority||"medium",estimated_recovery:q.estimated_recovery||0,actual_recovery:q.actual_recovery||0,engagement_fee_type:q.engagement_fee_type||"contingency",engagement_fee_pct:a,engagement_fee_pct_override:y,cbp_case_number:q.cbp_case_number||null,notes_internal:q.notes_internal||null};let u=null;if(f){const{error:r}=await g.from("claim_details").update(h).eq("id",f.id);u=r}else{const{error:r}=await g.from("claim_details").insert(h);u=r}if(u){d({title:"Save failed",description:u.message,variant:"destructive"}),Xe(!1);return}await Xt(g,t.id),d({title:"Claim details saved & score updated"}),C(),Xe(!1)},Bs=async()=>{!t||!Je.trim()||(Mt(!0),await g.from("lead_notes").insert({lead_id:t.id,user_id:(i==null?void 0:i.id)||null,user_email:(i==null?void 0:i.email)||null,
2note:Je.trim()}),await g.from("claim_timeline").insert({lead_id:t.id,event_type:"note_added",title:"Note added",description:Je.trim(),user_id:(i==null?void 0:i.id)||null}),Ot(""),C(),Mt(!1))},Ls=async()=>{if(!t)return;const l=_.map(a=>a.item_key),y=ca.filter(a=>!l.includes(a.key)).map(a=>({lead_id:t.id,item_key:a.key,label:a.label,description:a.description,required:a.required,sort_order:a.sort}));y.length>0?(await g.from("claim_checklist").insert(y),d({title:`${y.length} checklist items added`}),C()):d({title:"Checklist already complete"})},Os=async l=>{await g.from("claim_checklist").update({completed:!l.completed,completed_at:l.completed?null:new Date().toISOString(),completed_by:l.completed?null:i==null?void 0:i.id}).eq("id",l.id),C()},Le=async(l,y,a)=>{await g.from("lead_documents").update({status:y,reviewed_by:i==null?void 0:i.id,reviewed_at:new Date().toISOString(),rejection_reason:a||null}).eq("id",l),await g.from("claim_timeline").insert({lead_id:t.id,event_type:"document_reviewed",title:`Document ${y}`,description:a||void 0,user_id:(i==null?void 0:i.id)||null});try{const h=V.find(u=>u.id===l);if(h&&(t!=null&&t.contact_email)&&(y==="approved"||y==="accepted"||y==="rejected")){const{emailTriggers:u}=await $(async()=>{const{emailTriggers:r}=await import("./email-triggers-Bp6XbLok.js");return{emailTriggers:r}},__vite__mapDeps([98,3,4]));u.clientDocumentReviewed({leadId:t.id,documentId:l,status:y,fileName:h.file_name,rejectionReason:a,recipientEmail:t.contact_email,contactName:t.contact_name,organizationId:t.organization_id})}}catch{}d({title:`Document ${y}`}),C()},Fs=async(l,y)=>{await g.from("claim_agreements").update({status:"countersigned",countersigned_at:new Date().toISOString(),countersigned_by:i==null?void 0:i.id,countersign_data:y}).eq("id",l.id),await g.from("claim_timeline").insert({lead_id:t.id,event_type:"agreement_countersigned",title:`${l.title} countersigned`,user_id:(i==null?void 0:i.id)||null});try{const{emailTriggers:a}=await $(async()=>{const{emailTriggers:h}=await import("./email-triggers-Bp6XbLok.js");return{emailTriggers:h}},__vite__mapDeps([98,3,4]));a.adminAgreementSigned({leadId:t.id,agreementId:l.id,agreementTitle:l.title,signerName:l.signer_name,organizationId:t.organization_id})}catch{}d({title:"Agreement countersigned"}),jt(null),C()},wt=async l=>{if(!P)return;const y={status:l};l==="approved"&&(y.approved_by=i==null?void 0:i.id,y.approved_at=new Date().toISOString()),l==="funded"&&(y.funded_at=new Date().toISOString()),await g.from("advance_funding").update(y).eq("id",P.id),await g.from("claim_timeline").insert({lead_id:t.id,event_type:"funding_status",title:`Funding ${l}`,user_id:(i==null?void 0:i.id)||null}),d({title:`Funding ${l}`}),C()},Ms=async()=>{if(!t||De)return;Ge(!0);const l=String((f==null?void 0:f.estimated_recovery)||"").replace(/\D/g,""),{data:y,error:a}=await g.from("funding_applications").insert({lead_id:t.id,user_id:t.user_id||null,status:"draft",step1_answers:{estimated_refund:l||null,sell_interest:t.sell_interest||null,cash_urgency:t.cash_urgency||null},filed_claim:{},business_profile:{legal_name:t.company_name&&t.company_name!=="Funding Applicant"?t.company_name:""},signer_kyc:{full_name:t.contact_name||"",email:t.contact_email||"",mobile:t.phone||""},consents:{},tags:["converted_from_lead"]}).select().single(),h=y;if(Ge(!1),a||!(h!=null&&h.id)){d({title:"Could not create funding application",description:a==null?void 0:a.message,variant:"destructive"});return}await g.from("claim_timeline").insert({lead_id:t.id,event_type:"funding_application_created",title:"Funding application created from lead",user_id:(i==null?void 0:i.id)||null}),d({title:"Funding application created",description:"Draft opened — fill in business + signer details."}),C(),x(`/command/funding-applications/${h.id}`)};if(bt)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(St,{className:"h-8 w-64"}),e.jsx(St,{className:"h-[600px]"})]});if(!t)return e.jsx("div",{className:"text-center py-16 text-muted-foreground",children:"Claim not found"});const Vs=xa(t,o),Wt={};kt.forEach(l=>{const y=T.find(a=>a.agreement_type===l.key&&a.status!=="voided");y&&(Wt[l.key]=y)});const Ct={};
2V.forEach(l=>{const y=l.document_type||"other";Ct[y]||(Ct[y]=[]),Ct[y].push(l)});const zs={"Company Information":ns,"Import & Tariff Details":is,"Records & Access":ms,"Commercial & Scoring":rs,"Source & Tracking":pt},Us=[{section:"Company Information",fields:[["Company Name",t.company_name],["DBA",t.dba],["EIN",t.ein],["Address",t.address],["Contact Name",t.contact_name],["Contact Title",t.contact_title],["Email",t.contact_email],["Phone",t.phone],["Secondary Contact",t.secondary_contact]]},{section:"Import & Tariff Details",fields:[["Is IOR",t.is_ior],["IOR Numbers",t.ior_numbers],["ACE Accounts",t.ace_accounts],["Broker as IOR",t.broker_as_ior],["Broker Names",t.broker_names],["Form 4811",t.form_4811],["Countries",t.countries],["Import Value 2025",t.import_value_2025],["Import Value 2026",t.import_value_2026],["Entries per Year",t.entries_per_year],["Has IEEPA Lines",t.has_ieepa_lines],["IEEPA Duties 2025",t.ieepa_2025],["IEEPA Duties 2026",t.ieepa_2026]]},{section:"Records & Access",fields:[["ACE Access",t.ace_access],["Records Complete",t.records_complete],["Tracks Liquidation",t.tracks_liquidation],["Has Unliquidated",t.has_unliquidated],["Has Protest Window",t.has_protest_window],["Has Old Entries",t.has_old_entries],["Existing Protests",t.existing_protests],["ACH Enrolled",t.ach_enrolled],["Refund Broker",t.refund_broker]]},{section:"Commercial & Scoring",fields:[["Decision Maker",t.has_decision_maker],["HTS Concentration",t.hts_concentration],["Entry Complexity",t.entry_complexity],["Cooperation Level",t.cooperation_level],["Cash Urgency",t.cash_urgency],["Protest Days Remaining",t.protest_days_remaining?`${t.protest_days_remaining} days`:null],["Sell Interest",t.sell_interest],["Sell Questions",t.sell_questions],["Prior IEEPA Claim Filed",t.prior_recovery_firm]]},{section:"Source & Tracking",fields:[["Source",t.source],["Ref Slug",t.ref_slug],["Claim Type",t.claim_type],["UTM Source",t.utm_source],["UTM Medium",t.utm_medium],["UTM Campaign",t.utm_campaign],["UTM Content",t.utm_content],["Referral Partner",N?`${N.full_name}${N.slug?` (/ref/${N.slug})`:""}`:"—"],["Partner Email",(N==null?void 0:N.email)||"—"],["Partner Phone",(N==null?void 0:N.phone)||"—"],["Partner Company",(N==null?void 0:N.company)||"—"],["Partner Status",(N==null?void 0:N.status)||"—"],["Partner Comp Model",N?`${N.comp_model||"standard"}${N.pool_pct?` · ${N.pool_pct}%`:""}`:"—"],["Upline Partner",N!=null&&N._upline?`${N._upline.full_name}${N._upline.slug?` (/ref/${N._upline.slug})`:""}`:"—"],["Upline Email",((Ht=N==null?void 0:N._upline)==null?void 0:Ht.email)||"—"],["Upline Company",((Gt=N==null?void 0:N._upline)==null?void 0:Gt.company)||"—"],["Organization",((Yt=N==null?void 0:N._organization)==null?void 0:Yt.company_short_name)||"—"],["Broker Email",t.broker_email],["Broker Phone",t.broker_phone],["Created",new Date(t.created_at).toLocaleString()],["Updated",new Date(t.updated_at).toLocaleString()]]}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4 flex-wrap",children:[e.jsx(k,{variant:"ghost",size:"icon",className:"shrink-0",onClick:()=>{window.history.length>1?x(-1):x("/command/leads")},children:e.jsx(qa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[e.jsx("h1",{className:"font-display font-semibold text-lg sm:text-2xl text-foreground truncate max-w-[200px] sm:max-w-none",children:t.company_name}),e.jsxs(R,{variant:"outline",className:"font-mono text-xs shrink-0",children:["#",t.case_number]}),e.jsx(R,{variant:"secondary",className:"bg-primary/10 text-primary shrink-0",children:ra(t.claim_type)}),e.jsx(Zs,{isIor:t.is_ior,paidPartyNames:t.ior_numbers,size:"md",className:"shrink-0"}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(nn,{score:Vs,size:"md"}),e.jsx(k,{variant:"ghost",size:"icon",className:"h-5 w-5 text-muted-foreground hover:text-foreground",title:"Recompute score",onClick:async()=>{await Xt(g,t.id),d({title:"Score recomputed"}),C()},children:e.jsx(as,{className:"h-3 w-3"})})]}),e.jsxs(_e,{value:t.status,onValueChange:l=>yt(l),children:[e.jsx(ve,{className:`h-7 w-[160px] text-[11px] font-medium border ${la[t.status]||""}`,children:e.jsx(ye,{children:Ee[t.status]||t.status})}),e.jsxs(je,{children:[!Zt.includes(t.status)&&e.jsx(ie,{value:t.status,className:"text-xs",children:Ee[t.status]||t.status},t.status),Zt.filter(l=>
2!oa[l]).map(l=>e.jsx(ie,{value:l,className:"text-xs",children:Ee[l]},l))]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground truncate",children:[t.contact_name," · ",t.contact_email,t.phone?` · ${t.phone}`:""," · ",o.length," entries"]}),Nt.length>0&&e.jsxs(_e,{value:Ts||"unassigned",onValueChange:async l=>{var a;const y=l==="unassigned"?null:l;zt(y||""),f?await g.from("claim_details").update({assigned_to:y}).eq("id",f.id):await g.from("claim_details").insert({lead_id:t.id,assigned_to:y}),l&&await g.from("notifications").insert({user_id:l,title:"Claim assigned to you",message:`${t.company_name} (${t.case_number}) has been assigned to you.`,type:"info",link:`/command/leads/${t.id}`}),await g.from("claim_timeline").insert({lead_id:t.id,event_type:"assignment",title:`Claim assigned to ${((a=Nt.find(h=>h.user_id===l))==null?void 0:a.full_name)||"admin"}`,user_id:(i==null?void 0:i.id)||null}),d({title:"Claim assigned"})},children:[e.jsxs(ve,{className:"h-6 w-[140px] text-[10px] border-dashed",children:[e.jsx(Lt,{className:"h-3 w-3 mr-1"}),e.jsx(ye,{placeholder:"Assign to..."})]}),e.jsxs(je,{children:[e.jsx(ie,{value:"unassigned",className:"text-xs",children:"Unassigned"}),Nt.map(l=>e.jsx(ie,{value:l.user_id,className:"text-xs",children:l.full_name||l.email},l.user_id))]})]})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 items-center",children:[e.jsxs(k,{className:"gap-2 bg-gold/15 text-foreground border border-gold/30 hover:bg-gold hover:text-gold-foreground transition-all",onClick:()=>lt(!0),children:[e.jsx($t,{className:"h-4 w-4"}),"Action Center"]}),e.jsx(Js,{lead:t,onChanged:C})]})]}),(()=>{const l=ta(t,N);return l.flagged?e.jsxs(sa,{className:l.level==="strong"?"border-amber-500/60 bg-amber-500/10":"border-amber-500/30 bg-amber-500/5",children:[e.jsx(He,{className:"h-4 w-4 text-amber-600"}),e.jsxs(aa,{className:"flex items-center gap-2",children:[l.level==="strong"?"Likely test claim":"Possible test claim",e.jsx(ea,{result:l,size:"md"})]}),e.jsxs(na,{children:[e.jsxs("p",{className:"text-xs mt-1",children:["Signals matched (score ",l.score,"):"]}),e.jsx("ul",{className:"list-disc pl-5 text-xs mt-1 space-y-0.5",children:l.reasons.map((y,a)=>e.jsx("li",{children:y},a))}),e.jsx("p",{className:"text-xs mt-2 text-muted-foreground",children:"Use the Manage menu (top-right) to move this claim to Sandbox."})]})]}):null})(),e.jsx(an,{status:t.status,leadId:t.id}),e.jsx(jn,{leadId:t.id}),e.jsx(on,{lead:t,entries:o,agreements:T,checklist:_,funding:P,aceAccount:Q,isDialog:!0,open:Rs,onOpenChange:lt,onNavigateTab:l=>{ot(l),lt(!1)}}),e.jsx(Ka,{status:t.status}),e.jsx(Xs,{open:!!Be,onOpenChange:l=>{l||yt(null)},currentStatus:t.status,newStatus:Be||"",companyName:t.company_name,transitionCheck:Be?es(Be,t,o,T,_):void 0,onConfirm:()=>{Be&&Ds(Be),yt(null)}}),e.jsx(ja,{open:!!rt,onOpenChange:l=>{l||jt(null)},agreement:rt,isAdmin:!0,onSign:l=>{rt&&Fs(rt,l)}}),e.jsx(ln,{open:ks,onOpenChange:Vt,leadId:t.id,companyName:t.company_name,currentOverridePct:(f==null?void 0:f.engagement_fee_pct_override)!=null?Number(f.engagement_fee_pct_override):null,hasSignedEngagement:T.some(l=>l.agreement_type==="engagement"&&["signed","countersigned"].includes(l.status)&&!l.voided_at),onSuccess:C}),e.jsx(da,{value:Ut,onValueChange:ot,className:"space-y-0",children:e.jsx(b.Suspense,{fallback:e.jsx("div",{className:"p-6",children:e.jsx(St,{className:"h-64 w-full"})}),children:(()=>{var y;const l=[{heading:"Overview",items:[{v:"overview",l:"Overview",i:ns},...ce?[{v:"processing",l:"Processing",i:ht}]:[],{v:"timeline",l:"Timeline",i:Ne},{v:"scoring",l:"Scoring",i:$a},{v:"eligibility",l:"Eligibility",i:Ue},{v:"documents",l:`Documents (${V.length})`,i:Me},{v:"agreements",l:`Agreements (${T.length})`,i:tt}]},{heading:"Entries & Filing",items:[{v:"entries",l:`Entries (${o.length})`,i:Ba},{v:"cape",l:"CAPE Batches",i:is},{v:"liquidation",l:"Liquidation",i:st},{v:"reconciliation",l:"Reconciliation",i:La}]},{heading:"Legal & Disputes",items:[{v:"protests",l:"Protests",i:we}
2,{v:"cit",l:"CIT Cases",i:Oa},{v:"cbp_log",l:"CBP Log",i:$t}]},{heading:"Intelligence",items:[{v:"analysis",l:"AI Analysis",i:Fa}]},{heading:"Financial",items:[{v:"claim",l:"Claim Details",i:Ve},{v:"funding",l:"Funding",i:rs},{v:"commissions",l:`Commissions (${oe.length})`,i:Ma}]},{heading:"Automation & ACE",items:[{v:"ace_account",l:"ACE / ACH",i:Va},{v:"credentials",l:"ACE Credentials",i:za},{v:"rpa",l:"RPA Jobs",i:ut}]},{heading:"Communication",items:[{v:"messages",l:`Messages (${gt.length})`,i:ls},{v:"emails",l:"Emails",i:os},{v:"comms",l:"CRM Comms",i:ls},{v:"notes",l:"Notes",i:cs}]}];return e.jsxs("div",{className:"flex flex-col lg:flex-row gap-4",children:[e.jsxs("div",{className:"lg:w-56 shrink-0",children:[e.jsx(ma,{className:"lg:hidden w-full justify-start flex-wrap h-auto gap-1 bg-transparent p-0",children:l.flatMap(a=>a.items).map(a=>e.jsxs(ua,{value:a.v,className:"data-[state=active]:bg-primary/10 data-[state=active]:text-primary gap-1.5 text-xs",children:[e.jsx(a.i,{className:"h-3.5 w-3.5"}),a.l]},a.v))}),e.jsx("nav",{className:"hidden lg:block rounded-xl border border-border bg-card p-2 space-y-3 sticky top-4",children:l.map(a=>e.jsxs("div",{children:[e.jsx("p",{className:"px-2 pb-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60",children:a.heading}),e.jsx("div",{className:"space-y-0.5",children:a.items.map(h=>e.jsxs("button",{onClick:()=>ot(h.v),className:`w-full flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] font-medium transition-colors ${Ut===h.v?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,children:[e.jsx(h.i,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:h.l})]},h.v))})]},a.heading))})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(L,{value:"overview",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(rn,{lead:t,entries:o,agreements:T}),(()=>{const a=ga(t,f,o),h=Ss(o),u=T.filter(ae=>["signed","countersigned"].includes(ae.status)).length,r=S,I=!!(r!=null&&r.isAnchorBacked),B=!!r&&r.estimatedRefund>0,H=B?r.estimatedRefund:a.amount,K=B?(r==null?void 0:r.estimatedRefundSource)==="anchor_snapshot"?"Confirmed by Anchor":(r==null?void 0:r.estimatedRefundSource)==="anchor_summary"?`Summary Workbook v${r.summaryVersion??1}`:a.label:I?`${a.label} · Anchor: $0 eligible`:a.label,ge=I&&(r==null?void 0:r.phase1Eligible)!=null?r.phase1Eligible:h.totalFilableNow,de=I&&(r==null?void 0:r.phase1EntryCount)!=null?`Anchor P1: ${r.phase1EntryCount} entries`:`P1: ${h.byPhase.phase_1.count} · P3: ${h.byPhase.phase_3.count} entries`,G=I&&(r==null?void 0:r.totalEntriesImpacted)!=null?r.totalEntriesImpacted:o.length,et=I&&(r==null?void 0:r.remainingEligibleEntryCount)!=null?`${r.remainingEligibleEntryCount} eligible (Anchor)`:`${h.totalImpactedEntries} with IEEPA exposure`;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-end gap-2 -mt-2",children:[e.jsx(vn,{data:r}),e.jsx(yn,{leadId:t.id,enabled:!!(r!=null&&r.isAnchorBacked)})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs(W,{className:`p-4 border-primary/30 bg-gradient-to-br ${I?"from-success/5":"from-primary/5"} to-transparent`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold",children:"Est. IEEPA Recovery"}),e.jsx(Se,{children:e.jsxs(Pe,{children:[e.jsx(ke,{asChild:!0,children:e.jsx(We,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsx(Te,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:I?`Source: Anchor (${(r==null?void 0:r.estimatedRefundSource)==="anchor_snapshot"?"snapshot":`Summary Workbook v${(r==null?void 0:r.summaryVersion)??1}`}). TRA preliminary: ${fa(a,!0)}.`:`${a.method}. Confidence: ${ba(a.confidenceLabel)}.`})})]})})]}),e.jsx("p",{className:`text-xl font-bold tabular-nums leading-tight ${I?"text-success":"text-primary"}`,children:H>0?X(H):"—"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1 truncate",children:K})]}),e.jsxs(W,{className:"p-4 border-success/30 bg-gradient-to-br from-success/5 to-transparent",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold",children:"Filable Now"}),e.jsx(Se,{children:e.jsxs(Pe,{children:[e.jsx(ke,{asChild:!0,children:e.jsx(ue,{className:"h-3.5 w-3.5 text-success cursor-help"})}),e.jsx(Te,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:I?"Phase 1 (CAPE) eligible amount from Anchor Summary Workbook.":"Refunds we can file with CBP today — Phase 1 (CAPE bulk upload) plus Phase 3 (formal protest on deemed-liquidated entries). Excludes Phase 2 (awaiting liquidation) and CIT (litigation only)."})})]})})]}),e.jsx("p",{className:"text-xl font-bold text-success tabular-nums leading-tight",children:X(ge)}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:de})]}),e.jsxs(W,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold",children:"ACE Entries"}),e.jsx(st,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),e.jsx("p",{className:"text-xl font-bold text-foreground tabular-nums leading-tight",children:G}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:et})]}),e.jsxs(W,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-semibold",children:"Documents"}),e.jsx(tt,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),e.jsxs("p",{className:"text-xl font-bold text-foreground tabular-nums leading-tight",children:[u,e.jsxs("span",{className:"text-sm text-muted-foreground",children:["/",kt.length]})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:["agreements · ",V.length," files · ",P!=null&&P.status?P.status.replace(/_/g," "):"no funding"]})]})]})]})})(),e.jsx(cn,{status:t.status}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[o.length>0&&e.jsxs(e.Fragment,{children:[(S==null?void 0:S.isAnchorBacked)&&e.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2 rounded-lg border border-success/30 bg-success/5 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{className:"h-3.5 w-3.5 text-success"}),e.jsxs("span",{className:"font-medium text-success",children:["Source: Anchor — Summary Workbook v",S.summaryVersion??1]})]}),e.jsxs("div",{className:"flex items-center gap-3 font-mono text-foreground",children:[S.effectiveTotalRecoverable!=null&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Total Recoverable:"})," ",X(S.effectiveTotalRecoverable)]}),S.phase1Eligible!=null&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Filable Now (P1):"})," ",X(S.phase1Eligible)]})]})]}),e.jsx(bn,{entries:o,anchorClaim:S})]}),e.jsxs(W,{children:[e.jsxs(Z,{className:"flex flex-row items-center justify-between pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(tt,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(J,{className:"text-xl font-display",children:"Client-Submitted Data"}),e.jsx(me,{children:"All intake-form answers organized by category"})]})]}),e.jsxs(k,{variant:"ghost",size:"sm",onClick:()=>{nt?qs():_t(!0)},className:"gap-1.5",children:[nt?vt?e.jsx(Ie,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ds,{className:"h-3.5 w-3.5"}):e.jsx(cs,{className:"h-3.5 w-3.5"}),nt?"Save":"Edit"]})]}),e.jsx(Y,{children:nt?e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[[["Company","company_name"],["DBA","dba"],["Contact","contact_name"],["Title","contact_title"],["Email","contact_email"],["Phone","phone"],["EIN","ein"],["Address","address"]].map(([a,h])=>e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:a}),e.jsx(Ae,{value:U[h]||"",onChange:u=>it({...U,[h]:u.target.value})})]},h)),e.jsx(Tt,{className:"col-span-2 my-2"}),e.jsx("p",{className:"col-span-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Scoring Fields"}),[["Decision Maker","has_decision_maker",["yes","no"]],["HTS Concentration","hts_concentration",["high","medium","low"]],["Entry Complexity","entry_complexity",["low","medium","high"]],["Cooperation Level","cooperation_level",["high","medium","low"]],["Cash Urgency","cash_urgency",["high","medium","low","none"]]].map(([a,h,u])=>e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:a}),e.jsxs(_e,{value:U[h]||"",onValueChange:r=>it({...U,[h]:r}),children:[e.jsx(ve,{className:"mt-1",children:e.jsx(ye,{placeholder:"Select..."})}),e.jsx(je,{children:u.map(r=>e.jsx(ie,{value:r,children:r.charAt(0).toUpperCase()+r.slice(1)},r))})]})]},h)),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Protest Days Remaining"}),e.jsx(Ae,{type:"number",value:U.protest_days_remaining||"",onChange:a=>it({...U,protest_days_remaining:a.target.value}),className:"mt-1",placeholder:"e.g. 120"})]})]}):e.jsx("div",{className:"space-y-4",children:Us.map(a=>{const h=zs[a.section]||Me,u={};if(S!=null&&S.isAnchorBacked&&a.section==="Import & Tariff Details"){const B=tn(t,S.summary);
2Object.entries(B).forEach(([H,K])=>{if(!(K!=null&&K.fromAnchor))return;const de={importerBusinessName:"Company Name",countries:"Countries",iorNumbers:"IOR Numbers",aceAccounts:"ACE Accounts",importValue2025:"Import Value 2025",importValue2026:"Import Value 2026",ieepaDuties2025:"IEEPA Duties 2025",ieepaDuties2026:"IEEPA Duties 2026",entriesPerYear:"Entries per Year"}[H];de&&(u[de]={value:K.value,preliminary:K.preliminary})})}const r=a.fields.map(([B,H])=>{const K=u[B];return K?[B,K.value,!0,K.preliminary]:[B,H,!1,null]}),I=r.filter(([,B])=>B!=null&&B!==""&&B!=="—").length;return e.jsxs(W,{className:"border border-border/60 shadow-none bg-muted/30",children:[e.jsx(Z,{className:"py-3 px-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(h,{className:"h-4 w-4 text-primary"}),e.jsx(J,{className:"text-sm font-semibold font-display",children:a.section})]}),e.jsxs(R,{variant:"outline",className:"text-[10px] font-mono",children:[I,"/",r.length," filled"]})]})}),e.jsx(Y,{className:"px-4 pb-4 pt-0",children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-3 text-sm",children:r.map(([B,H,K,ge])=>{const de=B,G=H,et=/value|duties|ieepa|refund/i.test(de)&&G&&!isNaN(Number(String(G).replace(/[^0-9.\-]/g,""))),ae=G==="yes"||G==="no"||G===!0||G===!1,At=G==null||G===""||G==="—";let Oe=G,ct="font-medium text-foreground";if(At)Oe=e.jsx("span",{className:"text-muted-foreground/50",children:"—"});else if(et){const fe=Number(String(G).replace(/[^0-9.\-]/g,""));Oe=X(fe),ct="font-bold text-success tabular-nums"}else if(ae){const fe=G==="yes"||G===!0;Oe=e.jsx(R,{variant:"outline",className:fe?"bg-success/10 text-success border-success/30 text-[10px] px-1.5 py-0":"bg-muted text-muted-foreground border-border text-[10px] px-1.5 py-0",children:fe?"Yes":"No"})}return e.jsxs("div",{children:[e.jsxs("span",{className:"text-muted-foreground block text-[11px] uppercase tracking-wide flex items-center gap-1",children:[de,K&&e.jsx(Se,{children:e.jsxs(Pe,{children:[e.jsx(ke,{asChild:!0,children:e.jsx(R,{variant:"outline",className:"bg-success/10 text-success border-success/30 text-[8px] px-1 py-0 font-semibold cursor-help",children:"ANCHOR"})}),e.jsx(Te,{children:e.jsxs("p",{className:"text-xs",children:["Sourced from Anchor Summary Workbook.",ge!=null&&ge!==""&&e.jsxs(e.Fragment,{children:[" TRA preliminary: ",e.jsx("span",{className:"font-mono",children:String(ge)})]})]})})]})})]}),e.jsx("span",{className:ct,children:Oe})]},de)})})})]},a.section)})})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(xs,{lead:t,entries:o,compact:!0}),e.jsx(An,{lead:t,entries:o,checklist:_,agreements:T})]})]})]})}),e.jsxs(L,{value:"entries",children:[e.jsx(ne,{tab:"entries",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),(S==null?void 0:S.isAnchorBacked)&&(S.totalEntriesImpacted!=null||S.phase1EntryCount!=null)&&e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-gold/30 bg-gold/[0.04] px-3 py-2 text-xs",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(R,{variant:"outline",className:"border-gold/40 text-gold text-[10px]",children:"Source: Anchor"}),S.totalEntriesImpacted!=null&&e.jsxs("span",{children:[e.jsx("strong",{children:S.totalEntriesImpacted})," total entries impacted"]}),S.phase1EntryCount!=null&&e.jsxs("span",{children:[e.jsx("strong",{children:S.phase1EntryCount})," Phase 1 eligible"]}),S.remainingEligibleEntryCount!=null&&e.jsxs("span",{children:[e.jsx("strong",{children:S.remainingEligibleEntryCount})," remaining eligible"]})]}),e.jsx("span",{className:"text-muted-foreground",children:"Anchor totals take precedence over TRA preliminary entries."})]}),e.jsx(Cn,{leadId:t.id,entries:o,lead:t,onRefresh:C})]}),e.jsxs(L,{value:"cape",children:[e.jsx(ne,{tab:"cape",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsx($n,{leadId:t.id,entries:o,onRefresh:C})]}),e.jsxs(L,{value:"protests",children:[e.jsx(ne,{tab:"protests",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsx(Bn,{leadId:t.id,entries:o,onRefresh:C})]}),e.jsxs(L,{value:"cit",children:[e.jsx(ne,{tab:"cit",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsx(Ln,{leadId:t.id,onRefresh:C})]}),e.jsxs(L,{value:"ace_account",children:[e.jsx(ne,{tab:"ace_account",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsx(On,{leadId:t.id,onRefresh:C})]}),e.jsx(L,{value:"eligibility",children:e.jsx(Mn,{entries:o,leadId:t.id})}),e.jsx(L,{value:"cbp_log",children:e.jsx(Fn,{leadId:t.id})}),e.jsxs(L,{value:"liquidation",children:[e.jsx(ne,{tab:"liquidation",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsx(En,{entries:o})]}),e.jsxs(L,{value:"claim",children:[e.jsxs(W,{children:[e.jsx(Z,{children:e.jsx(J,{className:"text-lg",children:"Claim Details & Recovery"})}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Claim Type"}),e.jsxs(_e,{value:t.claim_type||"ieepa",onValueChange:async a=>{var h;await g.from("leads").update({claim_type:a}).eq("id",t.id),E({...t,claim_type:a}),d({title:`Claim type set to ${((h=Jt[a])==null?void 0:h.shortL
2abel)||a}`})},children:[e.jsx(ve,{className:"mt-1",children:e.jsx(ye,{})}),e.jsx(je,{children:Object.entries(Jt).map(([a,h])=>e.jsx(ie,{value:a,children:h.label},a))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Priority"}),e.jsxs(_e,{value:q.priority||"medium",onValueChange:a=>xe({...q,priority:a}),children:[e.jsx(ve,{className:"mt-1",children:e.jsx(ye,{})}),e.jsx(je,{children:["low","medium","high","urgent"].map(a=>e.jsx(ie,{value:a,children:a.charAt(0).toUpperCase()+a.slice(1)},a))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Estimated Recovery ($)"}),e.jsx(Ae,{type:"number",value:q.estimated_recovery||"",onChange:a=>xe({...q,estimated_recovery:a.target.value}),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Actual Recovery ($)"}),e.jsx(Ae,{type:"number",value:q.actual_recovery||"",onChange:a=>xe({...q,actual_recovery:a.target.value}),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Fee Type"}),e.jsxs(_e,{value:q.engagement_fee_type||"contingency",onValueChange:a=>xe({...q,engagement_fee_type:a}),children:[e.jsx(ve,{className:"mt-1",children:e.jsx(ye,{})}),e.jsxs(je,{children:[e.jsx(ie,{value:"contingency",children:"Contingency"}),e.jsx(ie,{value:"flat",children:"Flat Fee"}),e.jsx(ie,{value:"hybrid",children:"Hybrid"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Fee %"}),e.jsx(Ae,{type:"number",value:q.engagement_fee_pct||"",onChange:a=>xe({...q,engagement_fee_pct:a.target.value}),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Contingency Override %"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 px-3 py-2 rounded-md border border-border bg-muted/30 text-sm font-mono",children:(f==null?void 0:f.engagement_fee_pct_override)!=null?`${f.engagement_fee_pct_override}%`:e.jsx("span",{className:"text-muted-foreground",children:"Using default"})}),e.jsxs(k,{type:"button",variant:"outline",size:"sm",onClick:()=>Vt(!0),className:"gap-1.5 shrink-0",children:[e.jsx(js,{className:"h-3.5 w-3.5 text-gold"})," Override"]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Sets the contingency % in the Consulting Agreement (Section C.2) and waterfall. Voids any existing agreement and forces re-signature."})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"CBP Case #"}),e.jsx(Ae,{value:q.cbp_case_number||"",onChange:a=>xe({...q,cbp_case_number:a.target.value}),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Internal Notes"}),e.jsx(Dt,{value:q.notes_internal||"",onChange:a=>xe({...q,notes_internal:a.target.value}),className:"mt-1",rows:3})]}),e.jsxs(k,{onClick:$s,disabled:vt,className:"bg-primary text-primary-foreground gap-1",children:[vt?e.jsx(Ie,{className:"h-4 w-4 animate-spin"}):e.jsx(ds,{className:"h-4 w-4"})," Save Details"]})]})]}),e.jsx(Ua,{initialRefund:Number(q.actual_recovery)||Number(q.estimated_recovery)||1e5,contingencyPctOverride:q.engagement_fee_pct_override?Number(q.engagement_fee_pct_override):void 0,hasBroker:Ke>0,editable:!0}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(k,{variant:"outline",size:"sm",onClick:async()=>{var r;if(!confirm("Recalculate the commission waterfall? This replaces pending ledger rows. Paid rows are protected."))return;const{data:a,error:h}=await g.rpc("recalculate_claim_waterfall",{_lead_id:t.id}),u=a;if(h){d({title:"Recalculate failed",description:h.message,variant:"destructive"});return}if(!(u!=null&&u.ok)){d({title:"Recalculate blocked",description:(u==null?void 0:u.reason)==="paid_rows_exist"?`${((r=u.rows)==null?void 0:r.length)||0} paid row(s) prevent recalculation. Void them first.`:`Reason: ${(u==null?void 0:u.reason)||"unknown"}`,variant:"destructive"});return}d({title:"Waterfall recalculated",description:"Pending ledger rows replaced. Audit log updated."}),C()},children:[e.jsx(as,{className:"h-3 w-3 mr-2"})," Recalculate Waterfall"]})}),e.jsx(kn,{leadId:t.id}),e.jsx(Tn,{leadId:t.id}),e.jsx(Pn,{leadId:t.id})]}),e.jsxs(L,{value:"documents",children:[e.jsx(ne,{tab:"documents",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsxs("div",{className:"space-y-4",children:[Ze.length>0&&e.jsxs(W,{className:"border-gold/30 bg-gold/[0.03]",children:[e.jsx(Z,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-gold/15 flex items-center justify-center",children:e.jsx(tt,{className:"h-4 w-4 text-gold"})}),e.jsxs("div",{children:[e.jsxs(J,{className:"text-base",children:["Anchor Documents (",Ze.length,")"]}),e.jsx(me,{className:"text-xs",children:"Mirrored from Anchor (AAS). These reflect the processor's record."})]})]}),e.jsx(R,{variant:"outline",className:"border-gold/40 text-gold text-[10px]",children:"Source: Anchor"})]})}),e.jsx(Y,{className:"space-y-2",children:Ze.map(a=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-background rounded-lg border",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Me,{className:"h-4 w-4 text-gold shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:a.file_name||a.anch
2or_document_id}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.category_display||a.category||"uncategorized",a.anchor_uploaded_at&&e.jsxs(e.Fragment,{children:[" · ",new Date(a.anchor_uploaded_at).toLocaleDateString()]}),a.file_size&&e.jsxs(e.Fragment,{children:[" · ",(a.file_size/1024).toFixed(0)," KB"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx(R,{variant:"outline",className:`text-[10px] ${a.mirror_status==="mirrored"?"border-success/30 text-success":a.mirror_status==="failed"?"border-destructive/30 text-destructive":"border-muted-foreground/30 text-muted-foreground"}`,children:a.mirror_status}),a.is_locked&&e.jsx(R,{variant:"outline",className:"text-[10px] border-gold/30 text-gold",children:"Locked"}),a.latest_download_url&&e.jsx(k,{size:"sm",variant:"outline",asChild:!0,className:"gap-1.5 h-7 text-xs",children:e.jsxs("a",{href:a.latest_download_url,target:"_blank",rel:"noreferrer",children:[e.jsx(dt,{className:"h-3 w-3"})," Open"]})})]})]},a.id))})]}),(()=>{const a=V.filter(u=>u.file_path);if(a.length===0)return null;const h=async u=>{try{const{data:r,error:I}=await g.storage.from("lead-documents").download(u.file_path);if(I||!r){d({title:"Download failed",description:(I==null?void 0:I.message)||"Could not download file",variant:"destructive"});return}const B=URL.createObjectURL(r),H=document.createElement("a");H.href=B,H.download=u.file_name||"document",document.body.appendChild(H),H.click(),H.remove(),URL.revokeObjectURL(B)}catch{d({title:"Download failed",variant:"destructive"})}};return e.jsxs(W,{className:"border-primary/20 bg-primary/[0.02]",children:[e.jsx(Z,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(ms,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs(J,{className:"text-base",children:["Available Documents (",a.length,")"]}),e.jsx(me,{className:"text-xs",children:"Generated and uploaded files ready for download"})]})]})}),e.jsx(Y,{className:"space-y-2",children:a.map(u=>{var r;return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-background rounded-lg border",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/8 border border-primary/12 flex items-center justify-center shrink-0",children:e.jsx(tt,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:u.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[((r=u.document_type)==null?void 0:r.replace(/_/g," "))||"document"," · ",new Date(u.created_at).toLocaleDateString(),u.file_size&&e.jsxs("span",{children:[" · ",(u.file_size/1024).toFixed(0)," KB"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(R,{variant:"outline",className:`text-[10px] ${u.status==="accepted"?"border-success/30 text-success":u.status==="rejected"?"border-destructive/30 text-destructive":"border-gold/30 text-gold"}`,children:u.status||"pending"}),e.jsxs(k,{size:"sm",variant:"outline",onClick:()=>h(u),className:"gap-1.5 h-7 text-xs",children:[e.jsx(dt,{className:"h-3 w-3"})," Download"]}),e.jsx(k,{size:"sm",variant:"ghost",onClick:()=>Le(u.id,"accepted"),className:"text-success h-7 px-2",children:e.jsx(ue,{className:"h-3.5 w-3.5"})}),e.jsx(k,{size:"sm",variant:"ghost",onClick:()=>Le(u.id,"rejected","Does not meet requirements"),className:"text-destructive h-7 px-2",children:e.jsx(It,{className:"h-3.5 w-3.5"})})]})]},u.id)})})]})})(),e.jsxs(W,{children:[e.jsxs(Z,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(J,{className:"text-lg",children:"Document Requirements"}),e.jsxs(me,{children:["Each document is tied to a required document type. ",_.filter(a=>a.completed).length,"/",_.length," completed."]})]}),e.jsxs(k,{size:"sm",onClick:Ls,className:"gap-1",children:[e.jsx(Me,{className:"h-3.5 w-3.5"})," Sync Checklist"]})]}),e.jsx(Y,{className:"space-y-3",children:_.map(a=>{const h=V.filter(u=>u.document_type===a.item_key||u.checklist_item_id===a.id);return e.jsx("div",{className:`p-4 rounded-lg border ${a.completed?"bg-success/5 border-success/20":h.length>0?"bg-gold/5 border-gold/20":"bg-muted/30 border-border"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ha,{checked:a.completed,onCheckedChange:()=>Os(a),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:a.label}),a.required&&e.jsx(R,{variant:"outline",className:"text-[10px]",children:"Required"}),a.completed&&e.jsx(ue,{className:"h-4 w-4 text-success"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:a.description}),h.length>0&&e.jsx("div",{className:"mt-2 space-y-1.5",children:h.map(u=>e.jsxs("div",{className:"flex items-center justify-between bg-background/80 rounded p-2 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"font-medium",children:u.file_name}),e.jsx(R,{variant:"outline",className:`text-[10px] ${u.status==="accepted"?"border-success/30 text-success":u.status==="rejected"?"border-destructive/30 text-destructive":"border-gold/30 text-gold"}`,children:u.status||"pending"}),e.jsx(gs,{document:u,leadId:t.id,onRefresh:C,isAdmin:!0}),e.jsx("span",{className:"text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()})]}),e.jsxs("div",{className:"flex gap-1",children:[u.file_path&&e.jsx(k,{size:"sm",variant:"ghost",onClick:async()=>{const{data:r}=await g.storage.from("lead-documents").download(u.file_path);if(r){const I=URL.createObjectURL(r),B=document.createElement("a");B.href=I,B.download=u.file_name||"document",document.body.appendChild(B),B.click(),B.remove(),URL.revokeObjectURL(I)}},className:"h-6 px-2",children:e.jsx(dt,{className:"h-3 w-3"})}),e.jsx(k,{size:"sm",variant:"ghost",onClick:()=>
2Le(u.id,"accepted"),className:"text-success h-6 px-2",children:e.jsx(ue,{className:"h-3 w-3"})}),e.jsx(k,{size:"sm",variant:"ghost",onClick:()=>Le(u.id,"rejected","Does not meet requirements"),className:"text-destructive h-6 px-2",children:e.jsx(It,{className:"h-3 w-3"})})]})]},u.id))}),h.length===0&&!a.completed&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1 italic",children:"No documents uploaded for this requirement"})]})]})},a.id)})})]}),(()=>{const a=new Set;_.forEach(r=>{V.forEach(I=>{(I.document_type===r.item_key||I.checklist_item_id===r.id)&&a.add(I.id)})});const h=new Set(V.filter(r=>r.file_path).map(r=>r.id)),u=V.filter(r=>!a.has(r.id)&&!h.has(r.id));return u.length===0?null:e.jsxs(W,{children:[e.jsxs(Z,{children:[e.jsxs(J,{className:"text-sm",children:["Other Documents (",u.length,")"]}),e.jsx(me,{className:"text-xs",children:"Documents not yet linked to a specific requirement"})]}),e.jsx(Y,{className:"space-y-2",children:u.map(r=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Me,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:r.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.document_type||"unclassified"," · ",new Date(r.created_at).toLocaleDateString(),e.jsx(R,{variant:"outline",className:"ml-2 text-[10px]",children:r.status||"pending"})]}),e.jsx(gs,{document:r,leadId:t.id,onRefresh:C,isAdmin:!0})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(k,{size:"sm",variant:"ghost",onClick:()=>Le(r.id,"accepted"),className:"text-success h-7 px-2",children:e.jsx(ue,{className:"h-3.5 w-3.5"})}),e.jsx(k,{size:"sm",variant:"ghost",onClick:()=>Le(r.id,"rejected","Does not meet requirements"),className:"text-destructive h-7 px-2",children:e.jsx(It,{className:"h-3.5 w-3.5"})})]})]},r.id))})]})})()]})]}),e.jsxs(L,{value:"agreements",children:[e.jsx(ne,{tab:"agreements",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ya,{leadId:t.id,initialEnabled:!!t.identity_verification_waived,inheritedFromBroker:t.identity_waived_reason==="broker_policy",onChanged:()=>C()}),e.jsxs(W,{children:[e.jsxs(Z,{children:[e.jsx(J,{className:"text-lg",children:"Engagement Agreements"}),e.jsx(me,{children:"Agreements are auto-generated when the client reaches the agreements step. Click any card to view the full agreement."})]}),e.jsxs(Y,{children:[(S==null?void 0:S.isAnchorBacked)&&e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-gold/30 bg-gold/[0.04] px-3 py-2 text-xs",children:[e.jsxs("span",{className:"text-foreground/90",children:[e.jsx("strong",{className:"text-gold",children:"Anchor-confirmed:"})," Anchor has acknowledged this claim's executed agreements as part of their workbook."]}),S.lastSyncedAt&&e.jsxs("span",{className:"text-muted-foreground",children:["Synced ",new Date(S.lastSyncedAt).toLocaleDateString()]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:kt.map(a=>{const h=Wt[a.key],u=(h==null?void 0:h.status)&&["signed","countersigned"].includes(h.status);return e.jsxs("div",{className:"relative",children:[e.jsx(va,{title:a.label,description:ya[a.key]||"",status:(h==null?void 0:h.status)||"draft",signedAt:h==null?void 0:h.signed_at,onClick:()=>{h&&jt(h)}}),(S==null?void 0:S.isAnchorBacked)&&u&&e.jsx(R,{variant:"outline",className:"absolute top-2 right-2 border-gold/40 text-gold text-[9px] bg-background/80",children:"Anchor ✓"})]},a.key)})})]})]})]})]}),e.jsxs(L,{value:"scoring",children:[e.jsx(ne,{tab:"scoring",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsx(xs,{lead:t,entries:o})]}),e.jsx(L,{value:"processing",children:e.jsx(wn,{leadId:t.id})}),e.jsx(L,{value:"timeline",children:e.jsxs(W,{children:[e.jsx(Z,{children:e.jsx(J,{className:"text-lg",children:"Activity Timeline"})}),e.jsx(Y,{children:w.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No activity yet"}):e.jsx("div",{className:"space-y-4",children:w.map(a=>e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-gold mt-2 shrink-0"}),e.jsx("div",{className:"w-0.5 flex-1 bg-border"})]}),e.jsxs("div",{className:"pb-4",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:a.title}),a.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.description}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:new Date(a.created_at).toLocaleStr
2ing()})]})]},a.id))})})]})}),e.jsx(L,{value:"emails",children:e.jsx(qn,{leadId:t.id,recipientEmail:t.contact_email,title:`Emails for ${t.company_name||t.contact_name||"this lead"}`,limit:50})}),e.jsx(L,{value:"notes",children:e.jsxs(W,{children:[e.jsx(Z,{children:e.jsx(J,{className:"text-lg",children:"Internal Notes"})}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Dt,{value:Je,onChange:a=>Ot(a.target.value),placeholder:"Add a note...",className:"flex-1",rows:2}),e.jsx(k,{onClick:Bs,disabled:Ft||!Je.trim(),className:"bg-primary text-primary-foreground gap-1 self-end",children:Ft?e.jsx(Ie,{className:"h-4 w-4 animate-spin"}):e.jsx(os,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3",children:j.map(a=>e.jsxs("div",{className:"p-3 bg-muted/30 rounded-lg",children:[e.jsx("p",{className:"text-sm text-foreground",children:a.note}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:[a.user_email||"System"," · ",new Date(a.created_at).toLocaleString()]})]},a.id))})]})]})}),e.jsx(L,{value:"comms",children:e.jsx(Nn,{leadId:t.id})}),e.jsxs(L,{value:"funding",className:"space-y-4",children:[e.jsxs(W,{children:[e.jsxs(Z,{children:[e.jsxs(J,{className:"text-lg flex items-center gap-2",children:[e.jsx(Ve,{className:"h-5 w-5 text-gold"})," Funding Application"]}),e.jsx(me,{children:"Standalone underwriting packet routed to advance funders. Separate from the auto-generated assessment below."})]}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block text-xs",children:"Intake: Wants funding"}),e.jsx("span",{className:"font-medium capitalize",children:t.sell_interest||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block text-xs",children:"Intake: Urgency"}),e.jsx("span",{className:"font-medium capitalize",children:t.cash_urgency||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block text-xs",children:"Funding intent (derived)"}),e.jsx("span",{className:"font-medium capitalize",children:(t.funding_intent||"standard").replace(/_/g," ")})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block text-xs",children:"Application"}),e.jsx("span",{className:"font-medium capitalize",children:le?String(le.status).replace(/_/g," "):"Not started"})]})]}),e.jsx(Tt,{}),le?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(R,{variant:"outline",className:"capitalize",children:String(le.status).replace(/_/g," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Created ",new Date(le.created_at).toLocaleDateString(),le.submitted_at&&e.jsxs(e.Fragment,{children:[" · Submitted ",new Date(le.submitted_at).toLocaleDateString()]})]}),e.jsx(k,{size:"sm",variant:"outline",onClick:()=>x(`/command/funding-applications/${le.id}`),children:"Open application"})]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground flex-1 min-w-[200px]",children:String(t.sell_interest||"").toLowerCase().startsWith("yes")?"Client indicated interest in advance funding during intake. Convert this lead into a funding application to begin underwriting.":"No funding application yet. Create one to begin underwriting."}),e.jsxs(k,{size:"sm",onClick:Ms,disabled:De,className:"gap-1",children:[e.jsx(Ve,{className:"h-3.5 w-3.5"}),De?"Creating…":"Convert to funding application"]})]})]})]}),e.jsxs(W,{children:[e.jsxs(Z,{children:[e.jsxs(J,{className:"text-lg flex items-center gap-2",children:[e.jsx(Ve,{className:"h-5 w-5 text-gold"})," Advance Funding Assessment"]}),e.jsx(me,{children:"Auto-generated funding assessment. Manage approval and disbursement."})]}),e.jsx(Y,{className:"space-y-4",children:P?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[["Status",e.jsx(R,{variant:"outline",className:`capitalize ${P.status==="funded"?"border-success/30 text-success":P.status==="approved"?"border-primary/30 text-primary":P.status==="declined"?"border-destructive/30 text-destructive":"border-gold/30 text-gold"}`,children:(y=P.status)==null?void 0:y.replace(/_/g," ")},"s")],["Est. Recovery",X(P.estimated_recovery)],["Advance %",`${P.advance_percentage}%`],["Advance Amount",X(P.advance_amount)],["Discount Rate",`${P.discount_rate}%`],["Net to Client",X(P.net_to_client)],["Approved At",P.approved_at?new Date(P.approved_at).toLocaleDateString():"—"],["Funded At",P.funded_at?new Date(P.funded_at).toLocaleDateString():"—"]].map(([a,h])=>e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground block text-xs",children:a}),e.jsx("span",{className:"text-sm font-medium",children:h})]},a))}),P.notes&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Notes:"}),e.jsx("p",{className:"text-sm",children:P.notes})]}),e.jsx(Tt,{}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[P.status==="pending_review"&&e.jsxs(e.Fragment,{children:[e.jsxs(k,{size:"sm",onClick:()=>wt("approved"),className:"bg-success text-success-foreground gap-1",children:[e.jsx(ue,{className:"h-3.5 w-3.5"})," Approve"]}),e.jsxs(k,{size:"sm",variant:"destructive",onClick:()=>wt("declined"),className:"gap-1",children:[e.jsx(As,{className:"h-3.5 w-3.5"})," Decline"]})]}),P.status==="approved"&&e.jsxs(k,{size:"sm",onClick:()=>wt("funded"),className:"bg-gold text-gold-foreground gap-1",children:[e.jsx(Ve,{className:"h-3.5 w-3.5"})," Mark as Funded"]})]})]}):e.jsx("div",{className:"text-center py-8 space-y-3",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No funding assessment yet. Will auto-generate when estimated recovery is available."})})})]})]}),e.jsxs(L,{value:"reconciliation",children:[e.jsx(ne,{tab:"reconciliation",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsx(Dn,{lead:t,entries:o,claimDetails:f,affiliateInfo:N,commissions:oe,onRefresh:C})]}),e.jsx(L,{value:"commissions",children:e.jsx(Sn,{lead:t,commissions:oe,affiliateInfo:N,claimDetails:f,onRefresh:C})}),e.jsx(L,{value:"messages",children:e.jsx(In,{leadId:t.id,viewerRole:c?"case_manager":"admin",maxHeight:"520px"})}),e.jsx(L,{value:"analysis",children:e.jsx(Rn,{leadId:t.id,onRefresh:C})}),e.jsxs(L,{value:"credentials",children:[e.jsx(ne,{tab:"credentials",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsx(Vn,{leadId:t.id,onRefresh:C})]}),e.jsxs(L,{value:"rpa",className:"space-y-6",children:[e.jsx(ne,{tab:"rpa",status:t.status,entries:o,agreements:T,checklist:_,aceAccount:Q}),e.jsx(Un,{leadId:t.id,onRefresh:C}),e.jsx(zn,{leadId:t.id,onRefresh:C})]})]})]})})()})})]})},Ci=Object.freeze(Object.defineProperty({__proto__:null,default:Wn},Symbol.toStringTag,{value:"Module"}));
2export{yn as A,Ci as L,wi as P};

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.