1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PaymentElementModal-CAUG_seD.js","assets/ui-vendor-CEfr44HH.js","assets/react-vendor-DSC_Ttnc.js","assets/index-BMQoS61I.js","assets/charts-2EW6PHWP.js","assets/supabase-vxdGgALD.js","assets/forms-CydccyH2.js","assets/index-CvId7u0R.css","assets/index-D4donCUO.js"])))=>i.map(i=>d[i]); 2import{j as e}from"./ui-vendor-CEfr44HH.js";import{r as o,i as $s,u as zs}from"./react-vendor-DSC_Ttnc.js";import{u as Y}from"./useQuery-rQDY3OdA.js";import{k as Ls,v as he,aJ as Fe,B as b,L as U,G as c,aE as Os,C as W,q as re,r as ne,p as R,a as X,a4 as Bs,_ as bs,j as te,I as ue,a2 as us,e as Ee,s as xs,M as hs,ao as qe,a5 as pe,ap as Pe,aq as $e}from"./index-BMQoS61I.js";import{S as ze,A as Le,a as Us}from"./AdminSidebar-CZrCfeC8.js";import{T as Ks,a as Rs,b as fe,c as je}from"./tabs-D4n5kecG.js";import{S as Is}from"./skeleton-CDpAxDmT.js";import{T as we,a as Ne,b as le,c as D,d as _e,e as F}from"./table-CcsaRpf3.js";import{S as Ze,a as Ge,b as We,c as Xe,d as I}from"./select-DXzI1Al_.js";import{g as Hs}from"./tollAuthorities-BPD7RpLc.js";import{C as Qs}from"./CustomerFormDialog-BqMB64ZH.js";import{C as Vs}from"./CustomerStatementsPanel-CDs_pBHN.js";import{C as Zs,R as Gs}from"./RecordExternalPaymentDialog-Bn2KaJnG.js";import{f as Se}from"./dateOnly-Z7WnstJ9.js";import{loadStripe as Ws}from"./index-D4donCUO.js";import{D as Je,f as Xs,a as es,b as ss,c as ts,d as Ys,e as ws}from"./dialog-Blz-XO4j.js";import{R as Js,a as ps}from"./radio-group-BbhYrUZ8.js";import{C as me}from"./credit-card-BjEfH9qN.js";import{B as ke}from"./building-2-B_xFG9XL.js";import{L as z}from"./loader-circle-BeUjl6Sg.js";import{P as et}from"./PaymentMethodPicker-BWFsMdkQ.js";import{S as st}from"./switch-D5xeTu1l.js";import{T as De}from"./textarea-BuY3m1hq.js";import{A as Oe,a as Be,b as Ue,c as Ke,d as Re,e as Ie,f as He,g as Qe}from"./alert-dialog-DPnpTKSP.js";import{F as Ns}from"./flask-conical-BmIAOnNR.js";import{C as tt}from"./copy-Bp8U-OIN.js";import{E as at}from"./external-link-C8ItMaDb.js";import{C as rt}from"./checkbox-CsXAE6wd.js";import{D as xe}from"./download-nFacK3tY.js";import{U as as}from"./upload-T0UYn8F4.js";import{P as ge}from"./plus-BSttj8na.js";import{T as fs}from"./trash-2-CRZemTp-.js";import{f as ee}from"./dates-CKTmhkQL.js";import{A as js}from"./arrow-left-mBl8vcHL.js";import{P as gs}from"./pencil-B7Kpz8Dz.js";import{U as Ve}from"./user-Cwj0QMIV.js";import{M as nt}from"./mail-BK5WKYzG.js";import{C as it}from"./calendar-ego-vvFg.js";import{C as Ce}from"./circle-check-3Jxsitye.js";import{C as ys}from"./clock-D3dfzIig.js";import"./charts-2EW6PHWP.js";import"./supabase-vxdGgALD.js";import"./forms-CydccyH2.js";import"./separator-D8WSue9g.js";import"./clipboard-check-C9yBNx5r.js";import"./receipt-QJVPzAuB.js";import"./shield-check-CchJZvLE.js";import"./wrench-CWPxbNoD.js";import"./message-square-zR5Wtb_O.js";import"./target-p1lmjj-k.js";import"./chart-column-DPubTCzp.js";import"./zap-DfRBv8iJ.js";import"./search-9gdqXau6.js";import"./chevron-right-CY-bQ_Bh.js";import"./log-out-tH6E1Rfl.js";import"./form-Bwol1-mc.js";import"./useMutation-Bo-wIhL-.js";import"./eventLogger-32bxteZ2.js";import"./calendar-Qn5oSuqG.js";import"./chevron-left-B57GWFxu.js";import"./popover-BX5ZWNwb.js";import"./user-check-D_DMt3eX.js";import"./hash-B0wIZZDK.js";import"./save-D4s5Y4zF.js";import"./triangle-alert-C4_n-ePO.js";import"./circle-MLbpcf5G.js";/** 3 * @license lucide-react v0.462.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const _s=Ls("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);function lt({targetUserId:a,customerId:C,customerEmail:x,customerName:E}
7){const[f,p]=o.useState(!1),[g,k]=o.useState(!1),[$,N]=o.useState("idle"),[T,L]=o.useState("ach"),{toast:O}=he(),H=Fe(),K=async()=>{k(!0),N("connecting");try{const{data:d,error:_}=await c.auth.getSession();if(_||!d.session)throw new Error("Not authenticated");const{data:S,error:y}=await c.functions.invoke("create-ach-setup",{body:{targetUserId:a,customerId:C,customerEmail:x,paymentMethodType:T}});if(y)throw new Error(y.message||"Failed to create setup");if(S!=null&&S.error)throw new Error(S.error);const{clientSecret:M,setupIntentId:P,publishableKey:j}=S;if(!M||!j)throw new Error("Missing setup data from server");const q=await Ws(j);if(!q)throw new Error("Failed to load Stripe");T==="card"?(p(!1),await new Promise(t=>setTimeout(t,50)),await Q(q,M,P,j)):await A(q,M,P)}catch(d){console.error("[AdminPaymentSetup] Error:",d),O({title:"Setup Failed",description:d.message,variant:"destructive"})}finally{k(!1),N("idle")}},B=async(d,_)=>{try{await c.functions.invoke("log-payment-setup-failure",{body:{targetUserId:a,customerId:C,paymentMethodType:"card",stripeErrorCode:d.code,stripeDeclineCode:d.decline_code,stripeErrorMessage:d.message,setupIntentId:_}})}catch(S){console.error("Failed to log card failure:",S)}},Q=async(d,_,S,y)=>{const{openPaymentElementModal:M}=await Os(async()=>{const{openPaymentElementModal:t}=await import("./PaymentElementModal-CAUG_seD.js");return{openPaymentElementModal:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])),P=await M({clientSecret:_,publishableKey:y,title:`Add a payment method for ${E}`,onError:(t,h)=>{B({code:h||"confirm_error",message:t},S)}});if(!P)return;N("confirming");const{data:j,error:q}=await c.functions.invoke("confirm-ach-setup",{body:{setupIntentId:P.setupIntentId,paymentMethodId:P.paymentMethodId,targetUserId:a,customerId:C,paymentMethodType:"card"}});if(q)throw new Error(q.message||"Failed to save payment method to profile");if(j!=null&&j.error)throw new Error(j.error);O({title:"Payment method linked",description:`Saved for ${E}`}),H.invalidateQueries({queryKey:["admin-customer-application"]}),p(!1)},A=async(d,_,S)=>{const{setupIntent:y,error:M}=await d.collectBankAccountForSetup({clientSecret:_,params:{payment_method_type:"us_bank_account",payment_method_data:{billing_details:{name:E}}}});if(M)throw new Error(M.message);if(!y)throw new Error("No setup intent returned");if(y.status==="requires_payment_method")return;if(N("confirming"),y.status==="requires_confirmation"){const{setupIntent:q,error:t}=await d.confirmUsBankAccountSetup(_);if(t)throw new Error(t.message);if(!q||q.status!=="succeeded")throw new Error("Bank account verification did not succeed")}const{data:P,error:j}=await c.functions.invoke("confirm-ach-setup",{body:{setupIntentId:S,targetUserId:a,customerId:C,paymentMethodType:"ach"}});if(j)throw new Error(j.message||"Failed to confirm setup");if(P!=null&&P.error)throw new Error(P.error);O({title:"ACH Linked",description:`Bank account linked for ${E}`}),H.invalidateQueries({queryKey:["admin-customer-application"]}),p(!1)};return e.jsxs(Je,{open:f,onOpenChange:p,children:[e.jsx(Xs,{asChild:!0,children:e.jsxs(b,{variant:"outline",size:"sm",children:[e.jsx(me,{className:"h-3 w-3 mr-1"}),"Set Up Payment"]})}),e.jsxs(es,{children:[e.jsxs(ss,{children:[e.jsxs(ts,{children:["Set Up Payment for ",E]}),e.jsx(Ys,{children:"Choose a payment method to link for this customer's billing."})]}),e.jsxs("div",{className:"flex flex-col gap-4 pt-2",children:[e.jsxs(Js,{value:T,onValueChange:d=>L(d),className:"grid gap-2",children:[e.jsxs("div",{className:"flex items-center space-x-3 rounded-md border p-3",children:[e.jsx(ps,{value:"ach",id:"admin-pm-ach"}),e.jsxs(U,{htmlFor:"admin-pm-ach",className:"flex items-center gap-2 cursor-pointer flex-1",children:[e.jsx(ke,{className:"h-4 w-4"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"ACH Bank Transfer"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No processing fees"})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-3 rounded-md border p-3",children:[e.jsx(ps,{value:"card",id:"admin-pm-card"}),e.jsxs(U,{htmlFor:"admin-pm-card",className:"flex items-center gap-2 cursor-pointer flex-1",children:[e.jsx(me,{className:"h-4 w-4"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Credit Card"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"2.9% + $0.30 fee per transaction"})]})]})]})]}),$==="connecting"&&e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(z,{className:"h-4 w-4 animate-spin"}),"Opening ",T==="card"?"card entry":"bank connection","â¦"]}),$==="confirming"&&e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(z,{className:"h-4 w-4 animate-spin"}),"Confirming payment methodâ¦"]}),e.jsx(b,{onClick:K,disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(z,{className:"h-4 w-4 mr-2 animate-spin"}),"Processingâ¦"]}):e.jsxs(e.Fragment,{children:[T==="card"?e.jsx(me,{className:"h-4 w-4 mr-2"}):e.jsx(ke,{className:"h-4 w-4 mr-2"}),"Link ",T==="card"?"Credit Card":"Bank Account"]})})]})]})]})}function ct({applicationId:a,sandbox:C,sandboxStripeCustomerId:x,paymentSetupStatus:E}){const{toast:f}=he(),p=Fe(),[g,k]=o.useState(!1),[$,N]=o.useState(!1),[T,L]=o.useState(!1),[O,H]=o.use
7State(!1),[K,B]=o.useState(""),[Q,A]=o.useState(""),[d,_]=o.useState(""),[S,y]=o.useState(!1),M=()=>{p.invalidateQueries({queryKey:["admin-customer-application"]}),p.invalidateQueries({queryKey:["sandbox-audit-recent"]}),p.invalidateQueries({queryKey:["applications"]})},P=async(m,w,V=!1)=>{const{data:n,error:Z}=await c.functions.invoke("toggle-application-sandbox",{body:{applicationId:a,enable:m,reason:w||void 0,force:V}});if(Z){const l=Z==null?void 0:Z.context;try{const i=l!=null&&l.body?JSON.parse(l.body):null;return i!=null&&i.requiresForce?{ok:!1,needsForce:!0,message:i.error}:{ok:!1,message:(i==null?void 0:i.error)||Z.message}}catch{return{ok:!1,message:Z.message}}}return n!=null&&n.requiresForce?{ok:!1,needsForce:!0,message:n.error}:{ok:!0}},j=async()=>{const m=K.trim();N(!1),k(!0);try{const w=await P(!0,m);if(!w.ok)throw new Error(w.message||"Failed to enable sandbox");f({title:"Sandbox enabled",description:"Payment setup will now run against Stripe test mode. No real bank or card will be charged."}),M()}catch(w){f({title:"Failed to enable sandbox",description:w.message,variant:"destructive"})}finally{k(!1),B("")}},q=async()=>{const m=Q.trim();L(!1),k(!0);try{const w=await P(!1,m);if(w.needsForce){_(m),H(!0);return}if(!w.ok)throw new Error(w.message||"Failed to switch to live");f({title:"Switched to live mode"}),M()}catch(w){f({title:"Failed to switch to live",description:w.message,variant:"destructive"})}finally{k(!1),A("")}},t=async()=>{H(!1),k(!0);try{const m=await P(!1,d,!0);if(!m.ok)throw new Error(m.message||"Failed to force-switch to live");f({title:"Switched to live â payment cleared",description:"The customer's stored payment method has been cleared. They'll be re-prompted to set up payment in live mode."}),M()}catch(m){f({title:"Failed to switch to live",description:m.message,variant:"destructive"})}finally{k(!1),_("")}},h=async()=>{x&&(await navigator.clipboard.writeText(x),y(!0),setTimeout(()=>y(!1),1500))};return e.jsxs(e.Fragment,{children:[e.jsxs(W,{children:[e.jsx(re,{className:"pb-3",children:e.jsxs(ne,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ns,{className:"h-4 w-4"}),"Sandbox Application",C?e.jsx(R,{className:"bg-amber-500/15 text-amber-700 dark:text-amber-400 border-amber-500/30 hover:bg-amber-500/20",children:"Sandbox"}):e.jsx(R,{className:"bg-emerald-500/15 text-emerald-700 dark:text-emerald-400 border-emerald-500/30 hover:bg-emerald-500/20",children:"Live"})]})}),e.jsxs(X,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(U,{className:"text-sm",children:"Use Stripe test mode for payment setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When on, this application's ACH/card linking runs against Stripe test mode. The downstream subscription auto-inherits sandbox."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g&&e.jsx(z,{className:"h-4 w-4 animate-spin text-muted-foreground"}),e.jsx(st,{checked:C,disabled:g,onCheckedChange:m=>{m?N(!0):L(!0)}})]})]}),C&&x&&e.jsxs("div",{className:"space-y-3 rounded-lg border border-amber-500/30 bg-amber-500/5 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(U,{className:"text-xs text-muted-foreground",children:"Test Stripe customer"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 text-xs font-mono bg-background border border-border rounded px-2 py-1.5 truncate",children:x}),e.jsx(b,{type:"button",variant:"outline",size:"sm",onClick:h,className:"h-8",children:S?e.jsx(Bs,{className:"h-3.5 w-3.5"}):e.jsx(tt,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("a",{href:`https://dashboard.stripe.com/test/customers/${x}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:[e.jsx(at,{className:"h-3.5 w-3.5"}),"Open in Stripe test dashboard"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["â¹ Test ACH:"," ",e.jsx("code",{className:"font-mono",children:"routing 110000000"})," /"," ",e.jsx("code",{className:"font-mono",children:"account 000123456789"})," · Test card ",e.jsx("code",{className:"font-mono",children:"4242 4242 4242 4242"})]})]})]})]}),e.jsx(Oe,{open:$,onOpenChange:m=>{N(m),m||B("")},children:e.jsxs(Be,{children:[e.jsxs(Ue,{children:[e.jsx(Ke,{children:"Enable sandbox mode for this application?"}),e.jsx(Re,{asChild:!0,children:e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx("p",{children:"⢠Payment setup runs against Stripe test mode â no real bank or card will be linked or charged."}),e.jsx("p",{children:"⢠A test-mode Stripe customer will be created the first time the customer hits payment setup."}),e.jsx("p",{children:"⢠The resulting subscription will automatically inherit sandbox mode on activation."})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{htmlFor:"enable-app-sandbox-reason",className:"text-sm",children:["Reason"," ",e.jsx("span",{className:"text-muted-foreground font-normal",children:"(optional)"})]}),e.jsx(De,{id:"enable-app-sandbox-reason",rows:2,maxLength:500,placeholder:"e.g. Internal QA account",value:K,onChange:m=>B(m.target.value)})]}),e.jsxs(Ie,{children:[e.jsx(He,{children:"Cancel"}),e.jsx(Qe,{onClick:j,children:"Enable sandbox"})]})]})}),e.jsx(Oe,{open:T,onOpenChange:m=>{L(m),m||A("")},children:e.jsxs(Be,{children:[e.jsxs(Ue,{children:[e.jsx(Ke,{children:"Switch application back to live mode?"}),e.jsx(Re,{children:E==="completed"?"Payment setup is already completed in sandbox mode â you may be asked to confirm clearing the stored test payment method.":"Future payment setup attempts will route through your live Stripe account."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{htmlFor:"disable-app-sandbox-reason",className:"text-sm",children:["Reason"," ",e.jsx("span",{className:"text-muted-foreground font-normal",children:"(optional)"})]}),e.jsx(De,{id:"disable-app-sandbox-reason",rows:2,maxLength:500,placeholder:"e.g. Done testing â switching to production",value:Q,onChange:m=>A(m.target.value)})]}),e.jsxs(Ie,{children:[e.jsx(He,{children:"Cancel"}),e.jsx(Qe,{onClick:q,children:"Switch to live"})]})]})}),e.jsx(Oe,{open:O,onOpenChange:m=>{H(m),m||_("")},children:e.jsxs(Be,{children:[e.jsxs(Ue,{children:[e.jsx(Ke,{children:"Clear test payment method and switch to live?"}),e.jsx(Re,{asChild:!0,children:e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("p",{children:["This application has a completed payment setup in sandbox mode. Switching to live will ",e.jsx("strong",{children:"clear the stored test payment method"})," so it doesn't orphan in your live Stripe account."]}),e.jsx("p",{children:"The customer will be re-prompted to set up a real bank account or card in live mode the next time they visit payment setup."})]})})]}),e.jsxs(Ie,{children:[e.jsx(He,{children:"Cancel"}),e.jsx(Qe,{onClick:t,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Clear & switch to live"})]})]})})]})}const Ye="image/jpeg,image/jpg,image/png,image/heic,image/webp,application/pdf",Ss=10*1024*1024,ot=25*1024*1024,dt=[{key:"drivers_license_url",label:"Driver's License (Front)",folder:"drivers-license-front"},{key:"drivers_license_back_url",label:"Driver's License (Back)",folder:"drivers-license-back"},{key:"insurance_docs_url",label:"Insurance Documents",folder:"insurance"},{key:"dot_number_url",label:"DOT Number / Authority",folder:"dot"}];function rs(a){return a.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120)}function mt({customerId:a,customerEmail:C,application:x,profileId:E}){const{toast:f}=he(),{user:p}=bs(),g=Fe(),[k,$]=o.useState(null),[N,T]=o.useState(null),[L,O]=o.useState(!1),[H,K]=o.useState(!1),B=o.useRef({}),{data:Q}=Y({queryKey:["admin-customer-application-docs",E,a],queryFn:async()=>
7{if(E){const{data:t}=await c.from("customer_applications").select("*").eq("user_id",E).maybeSingle();if(t)return t}if(a){const{data:t}=await c.from("customer_applications").select("*").eq("customer_id",a).maybeSingle();if(t)return t}return null},enabled:!!E||!!a}),A=Q??x??null,{data:d=[]}=Y({queryKey:["customer-documents",a],queryFn:async()=>{const{data:t,error:h}=await c.from("customer_documents").select("*").eq("customer_id",a).order("created_at",{ascending:!1});if(h)throw h;return t||[]},enabled:!!a}),{data:_=[]}=Y({queryKey:["customer-contracts",a],queryFn:async()=>{const{data:t,error:h}=await c.from("customer_contracts").select("*").eq("customer_id",a).neq("status","voided").order("signed_at",{ascending:!1,nullsFirst:!1});if(h)throw h;return t||[]},enabled:!!a}),S=()=>{g.invalidateQueries({queryKey:["customer-documents",a]}),g.invalidateQueries({queryKey:["customer-contracts",a]}),g.invalidateQueries({queryKey:["admin-customer-application"]})},y=t=>t.size>Ss?"File exceeds 10MB limit":Ye.split(",").includes(t.type)?null:"Only PDF and image files allowed",M=async(t,h)=>{T(h);try{const{data:m,error:w}=await c.storage.from("customer-documents").createSignedUrl(t,3600);if(w)throw w;window.open(m.signedUrl,"_blank")}catch(m){f({title:"Download failed",description:m.message,variant:"destructive"})}finally{T(null)}},P=async(t,h)=>{const m=y(h);if(m){f({title:"Invalid file",description:m,variant:"destructive"});return}$(t.key);try{const V=`${E||a}/${t.folder}/${Date.now()}-${rs(h.name)}`,{error:n}=await c.storage.from("customer-documents").upload(V,h,{upsert:!1,contentType:h.type});if(n)throw n;if(A!=null&&A.id){const{error:Z}=await c.from("customer_applications").update({[t.key]:V}).eq("id",A.id);if(Z)throw Z}else if(E){const{error:Z}=await c.from("customer_applications").insert({user_id:E,customer_id:a,email:C,[t.key]:V});if(Z)throw Z}else await c.from("customer_documents").insert({customer_id:a,label:t.label,category:t.key.includes("insurance")?"insurance":t.key.includes("dot")?"authority":"identity",file_path:V,mime_type:h.type,file_size_bytes:h.size,source:"admin_upload",uploaded_by:(p==null?void 0:p.id)??null});f({title:`${t.label} uploaded`}),S()}catch(w){f({title:"Upload failed",description:w.message,variant:"destructive"})}
7finally{$(null),B.current[t.key]&&(B.current[t.key].value="")}},j=async t=>{if(confirm(`Delete "${t.label}"? This cannot be undone.`))try{await c.storage.from("customer-documents").remove([t.file_path]);const{error:h}=await c.from("customer_documents").delete().eq("id",t.id);if(h)throw h;f({title:"Document deleted"}),S()}catch(h){f({title:"Delete failed",description:h.message,variant:"destructive"})}},q=async t=>{if(confirm(`Delete contract "${t.envelope_name||t.subject||"Untitled"}"? This cannot be undone.`))try{t.pdf_path&&await c.storage.from("customer-documents").remove([t.pdf_path]);const{error:h}=await c.from("customer_contracts").delete().eq("id",t.id);if(h)throw h;f({title:"Contract deleted"}),S()}catch(h){f({title:"Delete failed",description:h.message,variant:"destructive"})}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Application Documents"}),e.jsx("div",{className:"space-y-2",children:dt.map(t=>{const h=A==null?void 0:A[t.key],m=k===t.key;return e.jsxs("div",{className:"rounded-lg border border-border bg-card overflow-hidden",children:[h&&e.jsx(vs,{path:h,label:t.label}),e.jsxs("div",{className:"flex items-center justify-between gap-3 py-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(te,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:t.label}),e.jsx("p",{className:"text-xs text-muted-foreground font-mono truncate",children:h?h.split("/").pop():"Not uploaded"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[h&&e.jsx(b,{variant:"outline",size:"sm",onClick:()=>M(h,`slot-${t.key}`),disabled:N===`slot-${t.key}`,children:N===`slot-${t.key}`?e.jsx(z,{className:"h-4 w-4 animate-spin"}):e.jsx(xe,{className:"h-4 w-4"})}),e.jsx("input",{ref:w=>
7B.current[t.key]=w,type:"file",accept:Ye,className:"hidden",onChange:w=>{var n;const V=(n=w.target.files)==null?void 0:n[0];V&&P(t,V)}}),e.jsx(b,{size:"sm",onClick:()=>{var w;return(w=B.current[t.key])==null?void 0:w.click()},disabled:m,children:m?e.jsx(z,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(as,{className:"h-4 w-4 mr-1.5"}),h?"Replace":"Upload"]})})]})]})]},t.key)})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Contracts"}),e.jsxs(b,{size:"sm",onClick:()=>K(!0),children:[e.jsx(ge,{className:"h-4 w-4 mr-1.5"}),"Upload Contract"]})]}),_.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-2 border border-dashed rounded-lg",children:[e.jsx(te,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No contracts yet. Upload a signed PDF to make it visible to the customer."})]}):e.jsx("div",{className:"space-y-2",children:_.map(t=>e.jsxs("div",{className:"flex items-center justify-between gap-3 py-3 px-4 rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(te,{className:"h-5 w-5 text-primary shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:t.envelope_name||t.subject||"Contract"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.signed_at?`Signed ${ee(new Date(t.signed_at),"MMM d, yyyy")}`:`Uploaded ${ee(new Date(t.created_at),"MMM d, yyyy")}`," · ",e.jsx(R,{variant:"outline",className:"text-[10px] ml-1",children:t.status})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.pdf_path&&e.jsx(b,{variant:"outline",size:"sm",onClick:()=>M(t.pdf_path,`contract-${t.id}`),disabled:N===`contract-${t.id}`,children:N===`contract-${t.id}`?e.jsx(z,{className:"h-4 w-4 animate-spin"}):e.jsx(xe,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>q(t),children:e.jsx(fs,{className:"h-4 w-4 text-destructive"})})]})]},t.id))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Additional Documents"}),e.jsxs(b,{size:"sm",onClick:()=>O(!0),children:[e.jsx(ge,{className:"h-4 w-4 mr-1.5"}),"Upload Document"]})]}),d.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-2 border border-dashed rounded-lg",children:[e.jsx(_s,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No extra documents beyond the application files above. Click Upload to add files received via email or text."})]}):e.jsx("div",{className:"space-y-2",children:d.map(t=>e.jsxs("div",{className:"rounded-lg border border-border bg-card overflow-hidden",children:[t.file_path&&e.jsx(vs,{path:t.file_path,label:t.label}),e.jsxs("div",{className:"flex items-center justify-between gap-3 py-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(te,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:t.label}),e.jsx(R,{variant:"secondary",className:"text-[10px]",children:t.category}),t.is_internal&&e.jsx(R,{variant:"destructive",className:"text-[10px]",children:"Internal â staff only"}),e.jsxs(R,{variant:"outline",className:"text-[10px]",children:["via ",t.source.replace("_"," ")]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ee(new Date(t.created_at),"MMM d, yyyy h:mm a"),t.notes&&e.jsxs(e.Fragment,{children:[" · ",t.notes]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(b,{variant:"outline",size:"sm",onClick:()=>M(t.file_path,`extra-${t.id}`),disabled:N===`extra-${t.id}`,children:N===`extra-${t.id}`?e.jsx(z,{className:"h-4 w-4 animate-spin"}):e.jsx(xe,{className:"h-4 w-4"})}),e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>j(t),children:e.jsx(fs,{className:"h-4 w-4 text-destructive"})})]})]})]},t.id))})]}),e.jsx(ut,{open:L,onOpenChange:O,customerId:a,applicationId:(A==null?void 0:A.id)??null,uploadedBy:(p==null?void 0:p.id)??null,onUploaded:S}),e.jsx(xt,{open:H,onOpenChange:K,customerId:a,customerEmail:C,onUploaded:S})]})}function ut({open:a,onOpenChange:C,customerId:x,applicationId:E,uploadedBy:f,onUploaded:p}){const{toast:g}=he(),[k,$]=o.useState([]),[N,T]=o.useState(""),[L,O]=o.useState("other"),[H,K]=o.useState("email"),[B,Q]=o.use
7State(""),[A,d]=o.useState(!1),[_,S]=o.useState(!1),y=L==="collections",M=()=>{$([]),T(""),O("other"),K("email"),Q(""),d(!1)},P=async()=>{if(k.length===0){g({title:"Select a file",variant:"destructive"});return}if(!N.trim()){g({title:"Label is required",variant:"destructive"});return}if(k.some(t=>t.size>Ss)){g({title:"File exceeds 10MB",variant:"destructive"});return}const j=y||A;S(!0);let q=0;try{for(const t of k){const m=`${x}/${j?"internal":"admin-uploads"}/${Date.now()}-${rs(t.name)}`,{error:w}=await c.storage.from("customer-documents").upload(m,t,{upsert:!1,contentType:t.type});if(w)throw w;const{error:V}=await c.from("customer_documents").insert({customer_id:x,application_id:E,label:k.length>1?`${N.trim()} (${q+1}/${k.length})`:N.trim(),category:L,file_path:m,mime_type:t.type,file_size_bytes:t.size,source:H,notes:B.trim()||null,uploaded_by:f,is_internal:j});if(V)throw await c.storage.from("customer-documents").remove([m]),V;q++}g({title:k.length>1?`${q} documents uploaded`:"Document uploaded"}),M(),C(!1),p()}catch(t){g({title:"Upload failed",description:q>0?`${q} of ${k.length} uploaded. ${t.message}`:t.message,variant:"destructive"}),q>0&&p()}finally{S(!1)}};return e.jsx(Je,{open:a,onOpenChange:j=>{_||(C(j),j||M())},children:e.jsxs(es,{children:[e.jsx(ss,{children:e.jsx(ts,{children:"Upload Customer Document"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(U,{htmlFor:"file",children:"Files (PDF or image, max 10MB each)"}),e.jsx(ue,{id:"file",type:"file",multiple:!0,accept:Ye,onChange:j=>$(Array.from(j.target.files??[]))})]}),e.jsxs("div",{children:[e.jsx(U,{htmlFor:"label",children:"Label"}),e.jsx(ue,{id:"label",placeholder:"e.g. W-9, Voided Check, MC Authority, Signed Form",value:N,onChange:j=>T(j.target.value),maxLength:120})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(U,{children:"Category"}),e.jsxs(Ze,{value:L,onValueChange:j=>{O(j),j==="collections"&&d(!0)},children:[e.jsx(Ge,{children:e.jsx(We,{})}),e.jsxs(Xe,{children:[e.jsx(I,{value:"identity",children:"Identity"}),e.jsx(I,{value:"insurance",children:"Insurance"}),e.jsx(I,{value:"tax",children:"Tax"}),e.jsx(I,{value:"authority",children:"Authority / DOT"}),e.jsx(I,{value:"agreement",children:"Agreement"}),e.jsx(I,{value:"collections",children:"Collections (staff only)"}),e.jsx(I,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(U,{children:"Received via"}),e.jsxs(Ze,{value:H,onValueChange:K,children:[e.jsx(Ge,{children:e.jsx(We,{})}),e.jsxs(Xe,{children:[e.jsx(I,{value:"email",children:"Email"}),e.jsx(I,{value:"text",children:"Text / SMS"}),e.jsx(I,{value:"in_person",children:"In person"}),e.jsx(I,{value:"admin_upload",children:"Admin upload"}),e.jsx(I,{value:"other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{id:"is-internal",checked:y||A,disabled:y,onCheckedChange:j=>d(j===!0)}),e.jsx(U,{htmlFor:"is-internal",className:"cursor-pointer",children:"Staff only â hidden from customer"})]}),e.jsxs("div",{children:[e.jsx(U,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(De,{id:"notes",placeholder:"Any context â sender, date received, etc.",value:B,onChange:j=>Q(j.target.value),maxLength:500,rows:3})]})]}),e.jsxs(ws,{children:[e.jsx(b,{variant:"outline",onClick:()=>C(!1),disabled:_,children:"Cancel"}),e.jsxs(b,{onClick:P,disabled:_,children:[_?e.jsx(z,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(as,{className:"h-4 w-4 mr-2"}),"Upload"]})]})]})})}function xt({open:a,onOpenChange:C,customerId:x,customerEmail:E,onUploaded:f}){const{toast:p}=he(),[g,k]=o.useState(null),[$,N]=o.useState(""),[T,L]=o.useState(""),[O,H]=o.use
7State(""),[K,B]=o.useState(!1),Q=()=>{k(null),N(""),L(""),H("")},A=async()=>{if(!g){p({title:"Select a PDF",variant:"destructive"});return}if(g.type!=="application/pdf"){p({title:"Only PDF files are allowed for contracts",variant:"destructive"});return}if(g.size>ot){p({title:"File exceeds 25MB",variant:"destructive"});return}if(!$.trim()){p({title:"Contract name is required",variant:"destructive"});return}B(!0);try{const d=`contracts/${x}/${Date.now()}-${rs(g.name)}`,{error:_}=await c.storage.from("customer-documents").upload(d,g,{upsert:!1,contentType:"application/pdf"});if(_)throw _;const{data:S}=await c.from("customers").select("full_name").eq("id",x).maybeSingle(),{error:y}=await c.from("customer_contracts").insert({customer_id:x,envelope_id:`manual-${crypto.randomUUID()}`,envelope_name:$.trim(),subject:O.trim()||null,pdf_path:d,status:"completed",signer_email:E,signer_name:(S==null?void 0:S.full_name)??null,signed_at:T?new Date(T).toISOString():new Date().toISOString()});if(y)throw y;p({title:"Contract uploaded",description:"The customer can now view this contract."}),Q(),C(!1),f()}catch(d){p({title:"Upload failed",description:d.message,variant:"destructive"})}finally{B(!1)}};return e.jsx(Je,{open:a,onOpenChange:d=>{K||(C(d),d||Q())},children:e.jsxs(es,{children:[e.jsx(ss,{children:e.jsx(ts,{children:"Upload Contract PDF"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(U,{htmlFor:"contract-file",children:"PDF (max 25MB)"}),e.jsx(ue,{id:"contract-file",type:"file",accept:"application/pdf",onChange:d=>{var _;return k(((_=d.target.files)==null?void 0:_[0])??null)}})]}),e.jsxs("div",{children:[e.jsx(U,{htmlFor:"contract-name",children:"Contract Name"}),e.jsx(ue,{id:"contract-name",placeholder:"e.g. 2026 Trailer Lease Agreement",value:$,onChange:d=>N(d.target.value),maxLength:200})]}),e.jsxs("div",{children:[e.jsx(U,{htmlFor:"contract-date",children:"Signed Date (optional)"}),e.jsx(ue,{id:"contract-date",type:"date",value:T,onChange:d=>L(d.target.value)})]}),e.jsxs("div",{children:[e.jsx(U,{htmlFor:"contract-notes",children:"Notes (optional)"}),e.jsx(De,{id:"contract-notes",placeholder:"Any context â version, addendum, etc.",value:O,onChange:d=>H(d.target.value),maxLength:500,rows:3})]})]}),e.jsxs(ws,{children:[e.jsx(b,{variant:"outline",onClick:()=>C(!1),disabled:K,children:"Cancel"}),e.jsxs(b,{onClick:A,disabled:K,children:[K?e.jsx(z,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(as,{className:"h-4 w-4 mr-2"}),"Upload Contract"]})]})]})})}function vs({path:a,label:C}
7){const[x,E]=o.useState(null),[f,p]=o.useState(!1),g=a.toLowerCase().endsWith(".pdf");o.useEffect(()=>{let $=!1;return(async()=>{const{data:N,error:T}=await c.storage.from("customer-documents").createSignedUrl(a,3600);$||(T||!(N!=null&&N.signedUrl)?p(!0):E(N.signedUrl))})(),()=>{$=!0}},[a]);const k=()=>x&&window.open(x,"_blank");return f?e.jsx("div",{className:"flex items-center justify-center bg-muted/40 h-24 text-xs text-muted-foreground border-b border-border",children:"Preview unavailable"}):x?g?e.jsxs("button",{type:"button",onClick:k,className:"w-full flex items-center justify-center gap-2 bg-muted/40 hover:bg-muted h-24 text-sm text-muted-foreground border-b border-border transition-colors",children:[e.jsx(te,{className:"h-5 w-5"}),"PDF â click to open"]}):e.jsx("button",{type:"button",onClick:k,className:"w-full block bg-muted/20 hover:bg-muted/40 border-b border-border transition-colors",title:`Open ${C}`,children:e.jsx("img",{src:x,alt:C,loading:"lazy",onError:()=>p(!0),className:"max-h-40 w-full object-contain mx-auto"})}):e.jsxs("div",{className:"flex items-center justify-center bg-muted/40 h-24 text-xs text-muted-foreground border-b border-border",children:[e.jsx(z,{className:"h-4 w-4 animate-spin mr-2"})," Loading previewâ¦"]})}const de=a=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(a),ht={succeeded:"text-green-600",paid:"text-green-600",pending:"text-yellow-600",processing:"text-yellow-600",failed:"text-destructive",refunded:"text-muted-foreground",voided:"text-muted-foreground",active:"text-green-600",cancelled:"text-muted-foreground",archived:"text-muted-foreground"};function ka(){var os,ds;const{customerId:a}=$s(),C=zs(),{toast:x}=he(),{startImpersonation:E,user:f,userRole:p}=bs(),g=Fe(),[k,$]=o.useState(!1),[N,T]=o.useState(!1),[L,O]=o.useState(null),[H,K]=o.useState(null),[B,Q]=o.useState(!1),[A,d]=o.useState(!1),[_,S]=o.useState(!1),[y,M]=o.useState({provider:"",account_number:"",tag_number:""}),[P,j]=o.useState(!1),[q,t]=o.useState(!1),[h,m]=o.useState(null),[w,V]=o.useState(!1),{data:n,isLoading:Z}=Y({queryKey:["admin-customer-detail",a],queryFn:async()=>{const{data:s,error:r}=await c.from("customers").select("*").eq("id",a).single();if(r)throw r;return s},enabled:!!a}),{data:l}=Y({queryKey:["admin-customer-profile",n==null?void 0:n.email],queryFn:async()=>{if(!(n!=null&&n.email))return null;const{data:s,error:r}=await c.from("profiles").select("*").ilike("email",n.email).maybeSingle();return r?null:s},enabled:!!(n!=null&&n.email)}),{data:i,error:ye}=Y({queryKey:["admin-customer-application",l==null?void 0:l.id,a],queryFn:async()=>{let s=null;if(l!=null&&l.id){const{data:r,error:u}=await c.from("customer_applications").select("*").eq("user_id",l.id).order("updated_at",{ascending:!1}).limit(1).maybeSingle();if(r)return r;u&&(s=u)}if(a){const{data:r,error:u}=await c.from("customer_applications").select("*").eq("customer_id",a).order("updated_at",{ascending:!1}).limit(1).maybeSingle();if(r)return r;u&&(s=u)}if(s){try{await c.from("app_event_logs").insert({user_id:(f==null?void 0:f.id)??null,user_email:(f==null?void 0:f.email)??null,event_category:"billing",event_type:"admin_customer_detail_application_read_error",description:`Admin Customer Detail: application query failed for customer ${a}: ${s.message||s}`,metadata:{customer_id:a,profile_id:(l==null?void 0:l.id)??null,role:p??null,error_code:s.code??null,error_message:s.message??String(s),error_details:s.details??null},page_url:typeof window<"u"?window.location.pathname:null})}catch{}throw new Error(s.message||"Failed to load application")}return null},enabled:!!(l!=null&&l.id)||!!a,retry:!1}),{data:se,error:Te,refetch:ve}=Y({queryKey:["admin-customer-payment-status",l==null?void 0:l.id,a],queryFn:async()=>{if(!(l!=null&&l.id)&&!a)return null;const{data:s,error:r}=await c.functions.invoke("check-payment-status",{body:{...l!=null&&l.id?{targetUserId:l.id}:{},...a?{customerId:a}:{}}});if(r){try{await c.from("app_event_logs").insert({user_id:(f==null?void 0:f.id)??null,user_email:(f==null?void 0:f.email)??null,event_category:"billing",event_type:"admin_customer_detail_check_payment_status_error",description:`check-payment-status failed for customer ${a}: ${r.message||r}`,metadata:{customer_id:a,profile_id:(l==null?void 0:l.id)??null,role:p??null,error_message:r.message??String(r)},page_url:typeof window<"u"?window.location.pathname:null})}catch{}throw r}return s},enabled:!!(l!=null&&l.id)||!!a,retry:!1}),{data:ce=[]}=Y({queryKey:["admin-customer-subscriptions",a],queryFn:async()=>{const{data:s,error:r}=await c.from("customer_subscriptions").select("*").eq("customer_id",a).order("created_at",{ascending:!0});return r?[]:s||[]},enabled:!!a}),oe=ce.map(s=>s.id),{data:ns=[]}=Y({queryKey:["admin-customer-sub-items",oe],queryFn:async()=>
7{if(oe.length===0)return[];const{data:s,error:r}=await c.from("subscription_items").select("*, trailers:trailer_id (trailer_number, type, vin, status)").in("subscription_id",oe);if(r)throw r;return s||[]},enabled:oe.length>0}),{data:be=[]}=Y({queryKey:["admin-customer-assigned-trailers",a],queryFn:async()=>{const{data:s,error:r}=await c.from("trailers").select("id, trailer_number, type, vin, status, make, model, year").eq("customer_id",a).neq("status","archived").order("trailer_number",{ascending:!0});if(r)throw r;return s||[]},enabled:!!a}),{data:Ae=[]}=Y({queryKey:["admin-customer-billing",a,oe],queryFn:async()=>{const s=[`customer_id.eq.${a}`];oe.length>0&&s.push(`subscription_id.in.(${oe.join(",")})`);const{data:r,error:u}=await c.from("billing_history").select("*").or(s.join(",")).order("created_at",{ascending:!1});if(u)throw u;return r||[]},enabled:!!a}),{data:is=[],isLoading:Cs}=Y({queryKey:["customer-statements",a],queryFn:async()=>{const{data:s,error:r}=await c.from("customer_statements").select("*").eq("customer_id",a).order("statement_date",{ascending:!1});if(r)throw r;return s||[]},enabled:!!a}),{data:ks=[]}=Y({queryKey:["admin-customer-tolls",a],queryFn:async()=>{const{data:s,error:r}=await c.from("tolls").select("*").eq("customer_id",a).order("toll_date",{ascending:!1});if(r)throw r;return s||[]},enabled:!!a}),{data:ls=[]}=Y({queryKey:["admin-customer-contracts",a],queryFn:async()=>{const{data:s,error:r}=await c.from("customer_contracts").select("*").eq("customer_id",a).order("signed_at",{ascending:!1});if(r)throw r;return s||[]},enabled:!!a});i&&[{label:"Driver's License (Front)",path:i.drivers_license_url},{label:"Driver's License (Back)",path:i.drivers_license_back_url},{label:"Insurance Documents",path:i.insurance_docs_url},{label:"DOT Number",path:i.dot_number_url}].filter(s=>s.path);const Ds=async(s,r)=>{O(s);try{const{data:u,error:v}=await c.storage.from("customer-documents").createSignedUrl(s,3600);if(v)throw v;window.open(u.signedUrl,"_blank")}catch(u){x({title:"Error generating download link",description:u.message,variant:"destructive"})}finally{O(null)}},Fs=async(s,r)=>{K(r);try{const{data:u,error:v}=await c.storage.from("customer-documents").createSignedUrl(s,3600);if(v)throw v;window.open(u.signedUrl,"_blank")}catch(u){x({title:"Error generating download link",description:u.message,variant:"destructive"})}finally{K(null)}},Ts=async()=>{if(i!=null&&i.id){Q(!0);try{const{data:{session:s}}=await c.auth.getSession(),r=await c.functions.invoke("reset-payment-setup",{body:{applicationId:i.id}});if(r.error)throw new Error(r.error.message);const u=r.data;if(u!=null&&u.error)throw new Error(u.error);x({title:"Payment setup reset",description:`Detached ${u.detachedCount||0} payment method(s). Customer can now re-link.`}),await Promise.all([g.invalidateQueries({queryKey:["admin-customer-application"]}),ve()])}catch(s){x({title:"Reset failed",description:s.message,variant:"destructive"})}finally{Q(!1)}}},As=async()=>{if(a){j(!0);try{const s=await c.functions.invoke("sync-payment-method-from-stripe",{body:{customerId:a,targetUserId:l==null?void 0:l.id}});if(s.error)throw new Error(s.error.message);const r=s.data;if(r!=null&&r.error)throw new Error(r.error);x({title:"Payment method synced",description:`Saved ${(r==null?void 0:r.paymentMethodLabel)||((r==null?void 0:r.paymentMethodType)==="card"?"card":"ACH")} to this customer.`}),await Promise.all([g.invalidateQueries({queryKey:["admin-customer-application"]}),ve()])}catch(s){x({title:"Sync failed",description:s.message,variant:"destructive"})}finally{j(!1)}}},Ms=async()=>{var u;if(!a)return;const s=window.prompt("Enter the last 4 digits of the card on file to set as default (this will void any open ACH invoices and detach the bank account):");if(!s)return;const r=s.trim();if(!/^\d{4}$/.test(r)){x({title:"Invalid input",description:"Enter exactly 4 digits.",variant:"destructive"});return}if(window.confirm(`Detach the bank account and set the card ending ${r} as default? Any open ACH invoices will be voided.`)){t(!0);try{const v=await c.functions.invoke("switch-customer-to-card",{body:{customer_id:a,card_last4:r}});if(v.error)throw new Error(v.error.message);const G=v.data;if(G!=null&&G.error)throw new Error(G.error);x({title:"Switched to card",description:`Default set to ${G.defaultCardBrand||"card"} â¢â¢â¢â¢ ${G.defaultCardLast4}. Detached ${G.detachedAch||0} ACH, voided ${((u=G.voidedInvoices)==null?void 0:u.length)||0} open invoice(s).`}),g.invalidateQueries({queryKey:["admin-customer-application"]}),await ve(),g.invalidateQueries({queryKey:["admin-customer-billing"]})}catch(v){x({title:"Switch failed",description:v.message,variant:"destructive"})}finally{t(!1)}}},Es=async()=>{var s,r,u,v,G;if(i!=null&&i.id){V(!0);try{const{data:{session:ie}}=await c.auth.getSession(),ae=await c.functions.invoke("ssn-crypto",{body:{action:"decrypt",applicationId:i.id},headers:{Authorization:`Bearer ${ie==null?void 0:ie.access_token}`}});if(ae.error){const Ps=(r=(s=ae.error)==null?void 0:s.context)==null?void 0:r.status,Me=((u=ae.error)==null?void 0:u.error)??((v=ae.error)==null?void 0:v.message)??String(ae.error);if(Ps===403||typeof Me=="string"&&Me.includes("Admin or sales role required")){x({title:"Admin or sales role required",variant:"destructive"});return}throw new Error(Me)}const ms=(G=ae.data)==null?void 0:G.decrypted;typeof ms=="string"&&m(ms)}catch(ie){x({title:"SSN reveal failed",description:ie.message,variant:"destructive"})}finally{V(!1)}}},qs=async()=>
7{if(!(n!=null&&n.email)||!l){x({title:"No account linked to this customer.",variant:"destructive"});return}const s=l.first_name||l.last_name?`${l.first_name||""} ${l.last_name||""}`.trim():n.full_name;E({id:l.id,email:n.email,role:"customer",displayName:s})};if(Z)return e.jsx(ze,{children:e.jsxs("div",{className:"min-h-screen flex w-full bg-background",children:[e.jsx(Le,{}),e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(z,{className:"h-8 w-8 animate-spin text-muted-foreground"})})]})});if(!n)return e.jsx(ze,{children:e.jsxs("div",{className:"min-h-screen flex w-full bg-background",children:[e.jsx(Le,{}),e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Customer not found."}),e.jsxs(b,{variant:"outline",onClick:()=>C("/dashboard/admin/customers"),children:[e.jsx(js,{className:"h-4 w-4 mr-2"}),"Back to Customers"]})]})]})});const cs=ks.filter(s=>s.status==="pending").reduce((s,r)=>s+Number(r.amount),0);return e.jsxs(ze,{children:[e.jsxs("div",{className:"min-h-screen flex w-full bg-background",children:[e.jsx(Le,{}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("header",{className:"h-14 sm:h-16 border-b border-border flex items-center px-3 sm:px-6 bg-card gap-4",children:[e.jsx(Us,{}),e.jsxs(b,{variant:"ghost",size:"sm",onClick:()=>C("/dashboard/admin/customers"),className:"text-muted-foreground",children:[e.jsx(js,{className:"h-4 w-4 mr-1"}),"Customers"]}),e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx("h1",{className:"text-lg font-semibold text-foreground truncate flex-1",children:n.full_name}),e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsxs(b,{variant:"outline",size:"sm",onClick:qs,children:[e.jsx(us,{className:"h-4 w-4 mr-2"}),"View As Customer"]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>$(!0),children:[e.jsx(gs,{className:"h-4 w-4 mr-2"}),"Edit"]}),ce.some(s=>s.stripe_customer_id)&&e.jsx(Zs,{customerId:a,customerName:n.full_name,onSuccess:()=>g.invalidateQueries({queryKey:["admin-customer-billing"]})}),e.jsx(Gs,{customerId:a,customerName:n.full_name,onSuccess:()=>{g.invalidateQueries({queryKey:["admin-customer-billing"]}),g.invalidateQueries({queryKey:["admin-customer",a]})}}),e.jsxs(b,{size:"sm",onClick:()=>T(!0),children:[e.jsx(ge,{className:"h-4 w-4 mr-2"}),"Add Statement"]})]})]}),e.jsxs("main",{className:"flex-1 p-3 sm:p-6 overflow-x-hidden",children:[(i==null?void 0:i.sandbox)&&e.jsxs("div",{className:"mb-6 flex items-start gap-3 rounded-lg border border-amber-500/30 bg-amber-500/10 p-4 text-amber-900 dark:text-amber-200",children:[e.jsx(Ns,{className:"h-5 w-5 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold",children:"This customer's application is in SANDBOX mode"}),e.jsx("p",{className:"text-amber-800/90 dark:text-amber-200/90",children:"Payment setup runs against Stripe test mode. No real bank or card will be linked or charged. The activated subscription will inherit sandbox mode automatically."})]})]}),e.jsxs("div",{className:"grid gap-4 grid-cols-2 md:grid-cols-4 mb-6",children:[e.jsx(W,{children:e.jsxs(X,{className:"pt-5 pb-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Account #"}),e.jsx("p",{className:"font-mono font-semibold",children:n.account_number})]})}),e.jsx(W,{children:e.jsxs(X,{className:"pt-5 pb-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx(R,{variant:n.status==="active"?"default":"secondary",className:"capitalize",children:n.status}),n.payment_channel==="zelle"&&e.jsx(R,{variant:"outline",className:"bg-purple-50 text-purple-800 border-purple-300 dark:bg-purple-950/40 dark:text-purple-300 dark:border-purple-800",children:"Zelle"})]})]})}),e.jsx(W,{children:e.jsxs(X,{className:"pt-5 pb-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Trailers"}),e.jsx("p",{className:"font-semibold",children:be.length||ns.length})]})}),e.jsx(W,{children:e.jsxs(X,{className:"pt-5 pb-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Outstanding Tolls"}),e.jsx("p",{className:`font-semibold ${cs>0?"text-destructive":""}`,children:de(cs)})]})})]}),e.jsxs(Ks,{defaultValue:"profile",children:[e.jsxs(Rs,{className:"mb-6",children:[e.jsxs(fe,{value:"profile",children:[e.jsx(Ve,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(fe,{value:"subscription",children:[e.jsx(Ee,{className:"h-4 w-4 mr-2"}),"Subscription"]}),e.jsxs(fe,{value:"billing",children:[e.jsx(me,{className:"h-4 w-4 mr-2"}),"Billing History"]}),e.jsxs(fe,{value:"statements",children:[e.jsx(te,{className:"h-4 w-4 mr-2"}),"Statements"]}),e.jsxs(fe,{value:"documents",children:[e.jsx(_s,{className:"h-4 w-4 mr-2"}),"Documents"]})]}),e.jsx(je,{value:"profile",children:e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(W,{children:[e.jsx(re,{children:e.jsx(ne,{className:"text-base",children:"Customer Info"})}),e.jsxs(X,{className:"space-y-3 text-sm",children:[e.jsx(J,{icon:e.jsx(Ve,{className:"h-4 w-4"}),label:"Full Name",value:n.full_name}),n.company_name&&e.jsx(J,{icon:e.jsx(ke,{className:"h-4 w-4"}),label:"Company",value:n.company_name}),n.email&&e.jsx(J,{icon:e.jsx(nt,{className:"h-4 w-4"}),label:"Email",value:n.email}),n.phone&&e.jsx(J,{icon:e.jsx(xs,{className:"h-4 w-4"}),label:"Phone",value:n.phone}),(n.city||n.state||n.zip)&&e.jsx(J,{icon:e.jsx(hs,{className:"h-4 w-4"}
7),label:"Location",value:[n.city,n.state,n.zip].filter(Boolean).join(", ")}),n.birthday&&e.jsx(J,{icon:e.jsx(it,{className:"h-4 w-4"}),label:"Birthday",value:ee(new Date(n.birthday),"MMMM d, yyyy")}),n.payment_type&&e.jsx(J,{icon:e.jsx(me,{className:"h-4 w-4"}),label:"Payment Type",value:n.payment_type}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx("span",{className:"text-muted-foreground w-28",children:"Payment Method"}),i!=null&&i.stripe_payment_method_id?e.jsxs(R,{variant:"default",className:"text-xs",children:[e.jsx(Ce,{className:"h-3 w-3 mr-1"}),(i==null?void 0:i.payment_method_type)==="card"?"Card Linked":"ACH Linked"]}):e.jsx(R,{variant:"outline",className:"text-xs text-muted-foreground",children:"Not Linked"}),e.jsx(lt,{targetUserId:l==null?void 0:l.id,customerId:a,customerEmail:n.email||void 0,customerName:n.full_name}),e.jsxs(e.Fragment,{children:[e.jsxs(b,{variant:"outline",size:"sm",className:"h-7 text-xs",disabled:P,onClick:As,title:"Pull the customer's current default payment method from Stripe and update this profile",children:[P?e.jsx(z,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(Ce,{className:"h-3 w-3 mr-1"}),"Sync from Stripe"]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs(b,{variant:"outline",size:"sm",className:"h-7 text-xs",disabled:B,onClick:Ts,children:[B?e.jsx(z,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(me,{className:"h-3 w-3 mr-1"}),"Reset Payment"]}),e.jsxs(b,{variant:"outline",size:"sm",className:"h-7 text-xs",disabled:q,onClick:Ms,title:"Detach bank account, void open ACH invoices, and set a card on file as default",children:[q?e.jsx(z,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(me,{className:"h-3 w-3 mr-1"}),"Switch to Card"]})]})]})]}),ye&&e.jsxs(qe,{variant:"destructive",className:"mt-2",children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsx(Pe,{children:"Couldn't load application data"}),e.jsxs($e,{className:"text-xs",children:[ye.message||String(ye),p&&p!=="admin"&&e.jsxs("div",{className:"mt-1 opacity-80",children:["Signed in as ",p,". This has been logged â send this screenshot to engineering."]})]})]}),Te&&e.jsxs(qe,{variant:"destructive",className:"mt-2",children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsx(Pe,{children:"Live Stripe check failed"}),e.jsxs($e,{className:"text-xs",children:[Te.message||String(Te)," â click ",e.jsx("span",{className:"font-medium",children:"Sync from Stripe"})," to retry."]})]}),p==="sales"&&!ye&&e.jsx("p",{className:"text-[11px] text-muted-foreground italic mt-1",children:"Signed in as sales â payment sync/reset uses your session."}),(((os=se==null?void 0:se.savedMethods)==null?void 0:os.length)??0)>0&&e.jsx(et,{methods:se.savedMethods,targetUserId:l==null?void 0:l.id,customerId:a,onChanged:async()=>{await ve(),g.invalidateQueries({queryKey:["admin-customer-application"]})},className:"mt-2"}),(se==null?void 0:se.paymentSetupUnsynced)&&e.jsxs(qe,{className:"mt-3 border-yellow-500/50 bg-yellow-50 dark:bg-yellow-950/20",children:[e.jsx(pe,{className:"h-4 w-4 text-yellow-700 dark:text-yellow-400"}),e.jsx(Pe,{className:"text-yellow-800 dark:text-yellow-300",children:"Payment method found but not saved"}),e.jsxs($e,{className:"text-yellow-800 dark:text-yellow-300",children:["Stripe shows an attached ",se.paymentMethodType==="card"?"card":"ACH bank account",(ds=se.unsyncedPaymentMethod)!=null&&ds.last4?` ending ${se.unsyncedPaymentMethod.last4}`:"",", but CRUMS still has this customer marked pending. Click ",e.jsx("span",{className:"font-medium",children:"Sync from Stripe"})," to save it here."]})]}),(i==null?void 0:i.payment_setup_status)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-28",children:"Setup Status"}),e.jsxs(R,{variant:i.payment_setup_status==="completed"?"default":"secondary",className:"text-xs capitalize",children:[i.payment_setup_status==="completed"?e.jsx(Ce,{className:"h-3 w-3 mr-1"}):i.payment_setup_status==="pending"?e.jsx(ys,{className:"h-3 w-3 mr-1"}):e.jsx(pe,{className:"h-3 w-3 mr-1"}),i.payment_setup_status]})]}),(p==="admin"||p==="sales")&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-28",children:"SSN"}),i!=null&&i.has_ssn?h?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono text-sm",children:h}),e.jsx(b,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>m(null),children:"Hide"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-mono text-sm",children:"â¢â¢â¢-â¢â¢-â¢â¢â¢â¢"}),e.jsxs(b,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:w,onClick:Es,children:[w?e.jsx(z,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(us,{className:"h-3 w-3 mr-1"}),"Reveal"]})]}):e.jsx(R,{variant:"outline",className:"text-[10px] h-5 border-yellow-500/50 bg-yellow-50 text-yellow-700 dark:bg-yellow-950/20 dark:text-yellow-400",children:"Missing"})]}),n.notes&&e.jsxs("div",{className:"pt-2 border-t border-border",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Notes"}),e.jsx("p",{className:"text-sm",children:n.notes})]}),e.jsxs("div",{className:"pt-2 border-t border-border",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Toll Pass on File"}),e.jsxs("div",{className:"flex items-center gap-2",children:[!n.toll_pass_provider&&!A&&e.jsx(R,{variant:"outline",className:"text-[10px] h-5",children:"Missing"}),!A&&e.jsxs(b,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>{M({provider:n.toll_pass_provider||"",account_number:n.toll_pass_account_number||"",tag_number:n.toll_pass_tag_number||""}),d(!0)},children:[e.jsx(gs,{className:"h-3 w-3 mr-1"}),n.toll_pass_provider?"Edit":"Add"]})]})]}),A?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(U,{className:"text-xs",children:"Provider"}),e.jsxs(Ze,{value:y.provider,onValueChange:s=>M({...y,provider:s}),children:[e.jsx(Ge,{className:"h-8 text-xs",children:e.jsx(We,{placeholder:"Select a provider"})}),e.jsxs(Xe,{children:[e.jsx(I,{value:"None",children:"None / Doesn't use toll roads"}),Hs().map(s=>e.jsx(I,{value:s.value,children:s.label},s.value)),e.jsx(I,{value:"EZ Pass",children:"EZ Pass (generic)"}),e.jsx(I,{value:"PrePass",children:"PrePass"}),e.jsx(I,{value:"Bestpass",children:"Bestpass"}),e.jsx(I,{value:"Other",children:"Other"})]})]})]}),y.provider&&y.provider!=="None"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(U,{className:"text-xs",children:"Account #"}),e.jsx(ue,{className:"h-8 text-xs",value:y.account_number,onChange:s=>M({...y,account_number:s.target.value})})]}),e.jsxs("div",{children:[e.jsx(U,{className:"text-xs",children:"Tag / Transponder #"}),e.jsx(ue,{className:"h-8 text-xs",value:y.tag_number,onChange:s=>M({...y,tag_number:s.target.value})})]})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(b,{size:"sm",className:"h-7 text-xs",disabled:_||!y.provider,onClick:async()=>{var s,r;if(n!=null&&n.id){S(!0);try{const u=y.provider==="None",{error:v}=await c.from("customers").update({toll_pass_provider:y.provider||null,toll_pass_account_number:u?null:((s=y.account_number)==null?void 0:s.trim())||null,toll_pass_tag_number:u?null:((r=y.tag_number)==null?void 0:r.trim())||null,toll_pass_updated_at:new Date().toISOString()}).eq("id",n.id);if(v)throw v;x({title:"Toll pass saved"}),d(!1),g.invalidateQueries({queryKey:["admin-customer-detail",a]})}catch(u){x({title:"Save failed",description:u.message,variant:"destructive"})}finally{S(!1)}}},children:_?e.jsx(z,{className:"h-3 w-3 animate-spin"}):"Save"}),e.jsx(b,{size:"sm",variant:"ghost",className:"h-7 text-xs",onClick:()=>d(!1),disabled:_,children:"Cancel"})]})]}):n.toll_pass_provider?e.jsxs("div",{className:"text-sm space-y-0.5",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Provider:"})," ",n.toll_pass_provider]}),n.toll_pass_account_number&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Account #:"})," ",e.jsx("span",{className:"font-mono",children:n.toll_pass_account_number})]}),n.toll_pass_tag_number&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Tag #:"})," ",e.jsx("span",{className:"font-mono",children:n.toll_pass_tag_number})]}),n.toll_pass_updated_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Updated ",ee(new Date(n.toll_pass_updated_at),"MMM d, yyyy")]})]}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Not provided yet"})]})]})]}),e.jsxs(W,{children:[e.jsx(re,{children:e.jsx(ne,{className:"text-base",children:"Application Info"})}),e.jsx(X,{className:"space-y-3 text-sm",children:i?e.jsxs(e.Fragment,{children:[i.business_type&&e.jsx(J,{icon:e.jsx(ke,{className:"h-4 w-4"}),label:"Business Type",value:i.business_type}),i.company_address&&e.jsx(J,{icon:e.jsx(hs,{className:"h-4 w-4"}),label:"Company Address",value:i.company_address}),i.truck_vin&&e.jsx(J,{icon:e.jsx(Ee,{className:"h-4 w-4"}),label:"Truck VIN",value:i.truck_vin}),i.insurance_company&&e.jsx(J,{icon:e.jsx(te,{className:"h-4 w-4"}),label:"Insurance Co.",value:i.insurance_company}),i.insurance_company_phone&&e.jsx(J,{icon:e.jsx(xs,{className:"h-4 w-4"}),label:"Insurance Phone",value:i.insurance_company_phone}),i.secondary_contact_name&&e.jsx(J,{icon:e.jsx(Ve,{className:"h-4 w-4"}),label:"Secondary Contact",value:`${i.secondary_contact_name} (${i.secondary_contact_relationship||"â"}) ${i.secondary_contact_phone||""}`}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-28",children:"App Status"}),e.jsx(R,{variant:"secondary",className:"text-xs capitalize",children:i.status})]})]}):e.jsx("p",{className:"text-muted-foreground text-sm",children:"No application on file."})})]}),i&&e.jsx("div",{className:"md:col-span-2",children:e.jsx(ct,{applicationId:i.id,sandbox:!!i.sandbox,sandboxStripeCustomerId:i.sandbox_stripe_customer_id??null,paymentSetupStatus:i.payment_setup_status??null})})]})}),e.jsx(je,{value:"subscription",children:ce.length===0?e.jsx(W,{children:e.jsxs(X,{className:"flex flex-col items-center justify-center py-12 gap-3",children:[e.jsx(Ee,{className:"h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"No subscription on file."})]})}):e.jsxs("div",{className:"space-y-8",children:[ce.map(s=>{const r=ns.filter(v=>v.subscription_id===s.id),u=r.length>0?r[0].billing_anchor_day:null;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(W,{children:[e.jsx(re,{children:e.jsxs(ne,{className:"text-base flex items-center justify-between",children:[e.jsxs("span",{children:["Subscription Overview",u&&e.jsxs("span",{className:"ml-2 text-sm font-normal text-muted-foreground",children:["â Bills on the ",u,u===1?"st":u===2?"nd":u===3?"rd":"th"]})]}),e.jsx(R,{variant:s.status==="active"?"default":"secondary",className:"capitalize",children:s.status})]})}),e.jsxs(X,{className:"grid gap-4 sm:grid-cols-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Type"}),e.jsx("p",{className:"capitalize",children:(s.subscription_type||"â").replace(/_/g," ")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Billing Cycle"}),e.jsx("p",{className:"capitalize",children:s.billing_cycle})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Next Billing"}),e.jsx("p",{children:Se(s.next_billing_date)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Contract Start"}),e.jsx("p",{children:Se(s.contract_start_date)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"End Date"}),e.jsx("p",{children:s.end_date?ee(new Date(s.end_date),"MMM d, yyyy"):"â"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Deposit"}),e.jsxs("p",{children:[s.deposit_amount?de(Number(s.deposit_amount)):"â",s.deposit_paid&&e.jsx("span",{className:"ml-2 text-xs text-green-600",children:"â Paid"})]})]})]})]}),e.jsxs(W,{children:[e.jsx(re,{children:e.jsxs(ne,{className:"text-base",children:["Trailers (",r.length,")"]})}),e.jsx(X,{children:r.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No trailers assigned."}):e.jsxs(we,{children:[e.jsx(Ne,{children:e.jsxs(le,{children:[e.jsx(D,{children:"Trailer #"}),e.jsx(D,{children:"Type"}),e.jsx(D,{children:"VIN"}),e.jsx(D,{children:"Billing Cycle"}),e.jsx(D,{children:"Anchor Day"}),e.jsx(D,{className:"text-right",children:"Rate"}),e.jsx(D,{children:"Status"})]})}),e.jsx(_e,{children:r.map(v=>{var G,ie,ae;return e.jsxs(le,{children:[e.jsx(F,{className:"font-medium",children:((G=v.trailers)==null?void 0:G.trailer_number)||"â"}),e.jsx(F,{className:"text-muted-foreground capitalize",children:((ie=v.trailers)==null?void 0:ie.type)||"â"}),e.jsx(F,{className:"font-mono text-xs text-muted-foreground",children:((ae=v.trailers)==null?void 0:ae.vin)||"â"}),e.jsx(F,{className:"capitalize",children:v.billing_cycle||s.billing_cycle}),e.jsx(F,{children:v.billing_anchor_day?`${v.billing_anchor_day}${v.billing_anchor_day===1?"st":v.billing_anchor_day===2?"nd":v.billing_anchor_day===3?"rd":"th"}
7`:"â"}),e.jsx(F,{className:"text-right font-medium",children:v.monthly_rate?de(Number(v.monthly_rate)):"â"}),e.jsx(F,{children:e.jsx(R,{variant:v.status==="active"?"default":"secondary",className:"text-xs capitalize",children:v.status})})]},v.id)})})]})})]})]},s.id)}),be.length>0&&e.jsxs(W,{children:[e.jsx(re,{children:e.jsxs(ne,{className:"text-base",children:["All Assigned Trailers (",be.length,")"]})}),e.jsx(X,{children:e.jsxs(we,{children:[e.jsx(Ne,{children:e.jsxs(le,{children:[e.jsx(D,{children:"Trailer #"}),e.jsx(D,{children:"Type"}),e.jsx(D,{children:"Make / Model"}),e.jsx(D,{children:"Year"}),e.jsx(D,{children:"VIN"}),e.jsx(D,{children:"Status"})]})}),e.jsx(_e,{children:be.map(s=>e.jsxs(le,{className:"cursor-pointer",onClick:()=>C(`/dashboard/admin/fleet/${s.id}`),children:[e.jsx(F,{className:"font-medium",children:s.trailer_number}),e.jsx(F,{className:"text-muted-foreground capitalize",children:s.type}),e.jsx(F,{className:"text-muted-foreground",children:[s.make,s.model].filter(Boolean).join(" ")||"â"}),e.jsx(F,{className:"text-muted-foreground",children:s.year||"â"}),e.jsx(F,{className:"font-mono text-xs text-muted-foreground",children:s.vin||"â"}),e.jsx(F,{children:e.jsx(R,{variant:s.status==="leased"?"default":"secondary",className:"text-xs capitalize",children:s.status})})]},s.id))})]})})]})]})}),e.jsx(je,{value:"billing",children:e.jsxs(W,{children:[e.jsx(re,{children:e.jsx(ne,{className:"text-base",children:"Billing History"})}),e.jsx(X,{children:Ae.length===0&&ce.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No billing records for this customer yet."}):Ae.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No billing records yet."}):e.jsxs(we,{children:[e.jsx(Ne,{children:e.jsxs(le,{children:[e.jsx(D,{children:"Date"}),e.jsx(D,{children:"Period"}),e.jsx(D,{children:"Method"}),e.jsx(D,{className:"text-right",children:"Amount"}),e.jsx(D,{className:"text-right",children:"Discount"}),e.jsx(D,{className:"text-right",children:"Net"}),e.jsx(D,{children:"Status"})]})}),e.jsx(_e,{children:Ae.map(s=>e.jsxs(le,{children:[e.jsx(F,{className:"text-sm whitespace-nowrap",children:s.paid_at?ee(new Date(s.paid_at),"MMM d, yyyy"):ee(new Date(s.created_at),"MMM d, yyyy")}),e.jsx(F,{className:"text-sm text-muted-foreground whitespace-nowrap",children:s.billing_period_start&&s.billing_period_end?`${Se(s.billing_period_start,"MMM d")} â ${Se(s.billing_period_end,"MMM d, yyyy")}`:"â"}),e.jsx(F,{className:"text-sm capitalize text-muted-foreground",children:s.payment_method||"â"}),e.jsx(F,{className:"text-right font-medium",children:de(Number(s.amount))}),e.jsx(F,{className:"text-right text-muted-foreground",children:s.discount_amount&&Number(s.discount_amount)>0?`-${de(Number(s.discount_amount))}`:"â"}),e.jsx(F,{className:"text-right font-semibold",children:de(Number(s.net_amount))}),e.jsx(F,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[(s.status==="succeeded"||s.status==="paid")&&e.jsx(Ce,{className:"h-3.5 w-3.5 text-green-600"}),(s.status==="pending"||s.status==="processing")&&e.jsx(ys,{className:"h-3.5 w-3.5 text-yellow-500"}),s.status==="failed"&&e.jsx(pe,{className:"h-3.5 w-3.5 text-destructive"}),e.jsx("span",{className:`text-xs capitalize ${ht[s.status]||""}`,children:s.status})]})})]},s.id))})]})})]})}),e.jsx(je,{value:"statements",children:e.jsxs(W,{children:[e.jsx(re,{children:e.jsxs(ne,{className:"text-base flex items-center justify-between",children:["Statements & Tax Records",e.jsxs(b,{size:"sm",onClick:()=>T(!0),children:[e.jsx(ge,{className:"h-4 w-4 mr-2"}),"Add Statement"]})]})}),e.jsx(X,{children:Cs?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((s,r)=>e.jsx(Is,{className:"h-10 w-full"},r))}):is.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e.jsx(te,{className:"h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"No statements on file."}),e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>T(!0),children:[e.jsx(ge,{className:"h-4 w-4 mr-2"}),"Add First Statement"]})]}):e.jsxs(we,{children:[e.jsx(Ne,{children:e.jsxs(le,{children:[e.jsx(D,{children:"Date"}),e.jsx(D,{children:"Description"}),e.jsx(D,{children:"Period"}),e.jsx(D,{className:"text-right",children:"Amount"}),e.jsx(D,{children:"Source"}),e.jsx(D,{className:"text-right",children:"PDF"})]})}),e.jsx(_e,{children:is.map(s=>e.jsxs(le,{children:[e.jsx(F,{className:"whitespace-nowrap text-sm",children:ee(new Date(s.statement_date),"MMM d, yyyy")}),e.jsxs(F,{className:"text-sm",children:[e.jsx("div",{children:s.description}),s.notes&&e.jsx("div",{className:"text-xs text-muted-foreground",children:s.notes})]}),e.jsx(F,{className:"text-sm text-muted-foreground whitespace-nowrap",children:s.period_start&&s.period_end?`${ee(new Date(s.period_start),"MMM d")} â ${ee(new Date(s.period_end),"MMM d, yyyy")}`:"â"}),e.jsx(F,{className:"text-right font-medium",children:de(Number(s.amount))}),e.jsx(F,{children:e.jsx(R,{variant:s.source==="stripe"?"default":"secondary",className:"text-xs capitalize",children:s.source})}),e.jsx(F,{className:"text-right",children:s.file_url?e.jsx(b,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Fs(s.file_url,s.id),disabled:H===s.id,children:H===s.id?e.jsx(z,{className:"h-4 w-4 animate-spin"}):e.jsx(xe,{className:"h-4 w-4"})}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"â"})})]},s.id))})]})})]})}),e.jsx(je,{value:"documents",children:e.jsxs(W,{children:[e.jsx(re,{children:e.jsx(ne,{className:"text-base",children:"Application Documents"})}),e.jsxs(X,{children:[e.jsx(mt,{customerId:a,customerEmail:(n==null?void 0:n.email)||"",application:i,profileId:(l==null?void 0:l.id)??null}),ce.some(s=>s.lease_agreement_url)&&e.jsxs("div",{className:"mt-6",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Lease Agreement"}),ce.filter(s=>s.lease_agreement_url).map(s=>e.jsxs("div",{className:"flex items-center justify-between py-3 px-4 roun
7ded-lg border border-border bg-card mb-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(te,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Lease Agreement"}),s.docusign_completed_at&&e.jsxs("p",{className:"text-xs text-green-600",children:["Signed ",ee(new Date(s.docusign_completed_at),"MMM d, yyyy")]})]})]}),e.jsx(b,{variant:"outline",size:"sm",onClick:async()=>{O("lease-"+s.id);try{const{data:r,error:u}=await c.storage.from("customer-documents").createSignedUrl(s.lease_agreement_url,3600);if(u)throw u;window.open(r.signedUrl,"_blank")}catch(r){x({title:"Error",description:r.message,variant:"destructive"})}finally{O(null)}},disabled:L==="lease-"+s.id,children:L==="lease-"+s.id?e.jsx(z,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{className:"h-4 w-4 mr-2"}),"View"]})})]},s.id))]}),ls.length>0&&e.jsxs("div",{className:"mt-6",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Signed Contracts"}),ls.map(s=>e.jsxs("div",{className:"flex items-center justify-between py-3 px-4 rounded-lg border border-border bg-card mb-2",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(te,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.envelope_name||s.subject||"Signed Contract"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.signer_name||s.signer_email,s.signed_at&&` ⢠Signed ${ee(new Date(s.signed_at),"MMM d, yyyy")}`,s.status==="voided"&&" ⢠Voided"]})]})]}),s.pdf_path&&e.jsx(b,{variant:"outline",size:"sm",onClick:()=>Ds(s.pdf_path,s.envelope_name||"contract"),disabled:L===s.pdf_path,children:L===s.pdf_path?e.jsx(z,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(xe,{className:"h-4 w-4 mr-2"}),"View"]})})]},s.id))]})]})]})})]})]})]})]}),e.jsx(Qs,{open:k,onOpenChange:s=>{$(s),s||g.invalidateQueries({queryKey:["admin-customer-detail",a]})},customer:n}),e.jsx(Vs,{open:N,onOpenChange:T,customerId:a,customerName:n.full_name})]})}function J({icon:a,label:C,value:x}){return x?e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 text-muted-foreground shrink-0",children:a}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:C}),e.jsx("p",{className:"text-sm break-words",children:x})]})]}):null}export{ka as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.