1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/OutreachPreviewDialog-FSTchJK2.js","assets/index-CiYeuz0N.js","assets/index-B0tBmIOJ.css","assets/videoFollowup-NFtbMcQI.js","assets/videoLibrary-CIaNtXUK.js","assets/industry-videos-BPgxuer2.js","assets/fundingStrategyTranscript-CN6fI3ti.js","assets/workingCapitalVideo-CLQvgXx8.js","assets/circle-play-BoWAK_mr.js","assets/loader-circle-CojJEhe1.js","assets/dialog-B5tpbFY2.js","assets/index-pJfIofiV.js","assets/Combination-B4zPcfIW.js","assets/x-Dbso6HhZ.js","assets/input-D314iH3y.js","assets/label-Dm2MMzuh.js","assets/textarea-CHfYhtY8.js","assets/badge-vdvaIFAH.js","assets/sms-_wvs-AYW.js","assets/mailMergeTemplates-DqwTYFNN.js","assets/vcardSlug-BEXp96Em.js","assets/message-square-DFNmF4KT.js","assets/mail-Doxwvgpo.js","assets/send-DIp21oOB.js","assets/jszip.min-DDPennXk.js","assets/AgentLinkActivity-DeSoEC9x.js","assets/useQuery-DDBuj9h-.js","assets/dashboardStore-CFqjqKhF.js","assets/contactCardInsights-Ir9TAsJd.js","assets/link-2-BjS6h1f3.js","assets/download-BISozIfD.js","assets/documentRequests--GtjDSrL.js","assets/workspaceNavigation-BKDJuyWx.js","assets/file-text-BP4KmZmz.js","assets/usePerformanceTabVisibility-l1WoI7zQ.js","assets/clipboard-list-BjmQZ0pE.js","assets/sparkles-DRJhCLLh.js","assets/trophy-wCsMVfk1.js","assets/id-card-BzBv8jkE.js","assets/layout-dashboard-DpKPOT_e.js","assets/zap-BmZUj943.js","assets/calculator-CU_yJGls.js","assets/skeleton-uEYaQCK0.js","assets/use-mobile-DRm0Xkbv.js","assets/LoadingSkeletons-1Vf6XJyS.js","assets/PageTransition-CCwfXGLx.js","assets/chevron-left-CAY-ud8x.js","assets/chevron-right-L0SEErDU.js","assets/DebtScheduleForm-Bg8yRX97.js","assets/trash-2-BGx4f58m.js","assets/plus-nGcDYAPD.js","assets/client-acceptance-GXYpvK2G.js","assets/slugService-BRoC1GD8.js","assets/formatters-DOoK6GbP.js","assets/proposalSubmitService-3Lb8t9rP.js","assets/viewerLabel-DZtKMLCT.js","assets/postgrest-DAqLjrwt.js","assets/queryKeys-gD335jnI.js","assets/useMutation-BIVTJNYP.js","assets/errorHandler-CuCRfYcc.js","assets/popover-tDTYgAuR.js","assets/checkbox-DAsAX-fv.js","assets/index-l_Lcklqs.js","assets/switch-DX29oGYf.js","assets/salesforceUrl-Buq4irYQ.js","assets/stateUccSearch-BpyKllIP.js","assets/CurrentClientContext-g0sPScp2.js","assets/useMyDealOptions-B2Y9hiZG.js","assets/building-2-9zyhMRHV.js","assets/clipboard-DMs05LM0.js","assets/copy-C8-qfnKa.js","assets/external-link-CU3c0KFt.js","assets/scroll-area-JBQ52yJx.js","assets/index-DJmaWTSb.js","assets/index-BdQq_4o_.js","assets/tabs-DSQ8QzzU.js","assets/index-GcNEUHS_.js","assets/pencil-CfXL2ajK.js","assets/save-7UntdLi4.js","assets/EmailPreviewDialog-De2sQIz0.js","assets/calendar-C5f48h1x.js","assets/monitor-gJPIWMmo.js","assets/smartphone-DHJYhyGV.js","assets/circle-check-5M5KvzHg.js","assets/format-UAvZmgjS.js","assets/defaultOptions-w8f6iY6A.js","assets/en-US-3YMWytgS.js","assets/startOfDay-DMlJ_ut9.js","assets/startOfYear-Ov-gL0eb.js","assets/addWeeks-DKAzaxdp.js","assets/isBefore-BKK2juqp.js","assets/circle-alert-s7kD66zS.js","assets/eye-CysgaSrb.js","assets/clock-BlMM4srd.js","assets/dateOnly-DJLeK1H3.js","assets/menu-C6r1e_Cc.js","assets/useLeaderboard-BayvR5Xl.js","assets/ceoRanges-BMIa3XnC.js","assets/startOfMonth-Fq_ht1tL.js","assets/addMonths-BmX0UQe5.js","assets/trending-down-KwE5ZPrN.js","assets/chevron-up-CYwhGDi8.js","assets/chevron-down-Bh-duVQA.js","assets/activity-C1p7gS4S.js","assets/mail-check-D38rCsQH.js","assets/cloud-BeCNr4RT.js","assets/settings-BAIpSAJO.js","assets/scale-rop2jgxa.js","assets/party-popper-By8rLBZA.js","assets/circle-x-3q5v4dS9.js","assets/user-plus-DjUHGZY8.js","assets/map-pin-Dy1vQ9V-.js","assets/flame-B4j6wdSg.js","assets/phone-call-duNcwMv3.js","assets/dropdown-menu-_DzAUmh3.js","assets/circle-Chm9rIMJ.js","assets/sheet-H9IjI4k8.js","assets/proposalRoutes-C6AP2Pc3.js","assets/progress-DPLuadZw.js","assets/brain-sGrg3XRG.js","assets/dollar-sign-CJhoZxCc.js","assets/arrow-down-to-line-BVIuE0Sa.js","assets/radio-group-Bm9zxjRx.js","assets/select-BvtbyBgq.js","assets/emailPreviewService-CQ9yvxbp.js","assets/filter-By8eUcWP.js","assets/search-CKERWwVe.js","assets/upload-9EcgXRS3.js","assets/number-input-Bz7S_FIE.js","assets/financingFit-CQ1LRZ9Z.js","assets/locCalculator-Bg7fpCe-.js","assets/whatsNew-IiGaB7uu.js","assets/target-di2ibI-t.js","assets/accordion-phqrPUWr.js","assets/index-Dtr4EgwU.js","assets/aprMath-DSUvhvcs.js","assets/arrow-up-CEligF94.js","assets/arrow-down-B_b9wO9S.js","assets/table-IgKfYi-z.js","assets/tablet-C_R8bykB.js","assets/activityEvents-C6a3ozhm.js","assets/globe-BOtHpRMY.js","assets/mouse-pointer-click-CctoANfI.js","assets/mail-open-HNwRX8Y8.js","assets/shield-alert-CsMAk9Lo.js","assets/proposal-sequence-policy-7Gw7yLfd.js","assets/loanMath-CS9851mb.js","assets/financingTax-yl5ITXgU.js","assets/shield-check-WHTVc8Oo.js","assets/arrow-up-right-DVydq4aH.js","assets/formatDistanceToNow-D-BAksUH.js","assets/endOfMonth-n48n9qTe.js","assets/core.esm-DSIFM7mX.js","assets/useGlobalActivity-DSS1HkKG.js","assets/useCompanyPerformance-BpleUoep.js","assets/useHiddenReps-DPAqKpAM.js","assets/companyPerformance-CzxNH-KV.js","assets/file-pen-line-eFgFVG6e.js","assets/calendar-clock-BuNDRX9B.js","assets/agentActivity-B1FRrkMG.js","assets/alert-Ch2-_zj3.js","assets/info-B-2_CKCQ.js","assets/chart-column-DUn-HU2o.js","assets/trending-up-BrgtklH_.js","assets/sms-templates-Fk18nV8b.js","assets/SubmittedApplicationsSection-CiB-PKBD.js","assets/visibleInterval-wrqtxvKC.js","assets/alert-dialog-Ba5hDpgv.js","assets/rotate-ccw-Bi9YD835.js","assets/eye-off-USLrUbnG.js","assets/TodayOutreachDialog-BimlXG5m.js","assets/TodayCallOutcomeDialog-K_4Qxd7s.js","assets/TodayDraftReviewDialog-Cf8GDtb8.js","assets/validation-Cw4nmJQ3.js","assets/types-DwDs1
1FXA.js","assets/circle-help-uF3gCHHG.js","assets/KanbanBoard-BhlBQRYy.js","assets/index-D-Gxonvv.js","assets/proxy-B3uMvdkW.js","assets/dealIntelligence-RfLYrPah.js","assets/gauge-O9SCDIgF.js","assets/WarRoomTab-BW7KmJVN.js","assets/model-DXia0uBN.js","assets/ranking-CNdzgD1E.js","assets/arrow-left-DDculkbl.js","assets/settings-2-DmkQ4pBk.js","assets/ContactCardInsightsDashboard-2n7jvzuf.js","assets/AgentAvatar-DFKU9Yir.js","assets/medal-BLRGMW2b.js","assets/DocumentUploaderTab-Br1xp8G2.js","assets/UnsavedChangesGuard-3VOa4iZU.js","assets/pdfWorker-BPkRCQuu.js","assets/DealBlitzPanel-BB62rrfn.js","assets/MailMergePanel-NOVW8tK5.js","assets/xlsx-CyIgH-Tr.js","assets/mailMergeApprovals-CkSHzXxQ.js","assets/mailMergeParse-CAJx03yK.js","assets/RecipientTimelineDialog-BhQArRrj.js","assets/shield-off-D8WlBOEs.js","assets/sliders-horizontal-DLpZFG1c.js","assets/RenewalsTab-DSYD0tvZ.js","assets/banknote-DDK9JOKr.js","assets/minus-CU45YsEq.js","assets/CommissionsTab-C2hhx7wS.js","assets/calendar-days-BEU8DseJ.js","assets/CalculatorsTab-q9-GDsOI.js","assets/kapitusMath-CUSt5CYa.js","assets/parseISO-CSAVsl0c.js","assets/AgentPerformanceDashboard-m7IDMie2.js","assets/tvApi-p9Y2YlK8.js","assets/CelebrationPreferences-BJmSJUcb.js","assets/FundingCelebrationCard-DYOmgOHz.js","assets/volume-x-Br7qULZA.js"])))=>i.map(i=>d[i]); 2import{c as $e,j as e,y as dt,r as h,z as yc,B as R,R as Ct,s as F,g as Pt,f as Nt,D as wc,u as Qt,a as U,T as We,p as Se,q as Ce,P as qt,t as De,_ as Ze,E as vc,F as X,k as At,C as nt,h as Gn,n as Zs,G as Xn,H as jc,I as _c,J as Nc,K as kc,M as Kt,N as Qi,Q as Sc,S as Cc,U as Dc,V as Tc,W as Ec,X as $c,Y as es,e as Ke,Z as Gi,b as Jn,L as Ac,$ as La,a0 as Pc,a1 as Xi,a2 as Rc,i as Ji,m as Fc,o as Lc,a3 as Zi}from"./index-CiYeuz0N.js";import{r as le,a as el,b as jt}from"./documentRequests--GtjDSrL.js";import{S as tl,G as Mc,F as sl,u as qc,e as Oc,W as Ic,t as Uc,D as zc}from"./workspaceNavigation-BKDJuyWx.js";import{s as Ts,d as ea}from"./sms-_wvs-AYW.js";import{B as J}from"./badge-vdvaIFAH.js";import{S as je}from"./skeleton-uEYaQCK0.js";import{u as al}from"./use-mobile-DRm0Xkbv.js";import{D as Na}from"./LoadingSkeletons-1Vf6XJyS.js";import{F as Bc}from"./PageTransition-CCwfXGLx.js";import{C as Zn}from"./chevron-left-CAY-ud8x.js";import{C as oa}from"./chevron-right-L0SEErDU.js";import{u as ve}from"./useQuery-DDBuj9h-.js";import{p as Mn,d as Hc,D as Vc}from"./DebtScheduleForm-Bg8yRX97.js";import{s as Wc,r as nl,a as Kc}from"./client-acceptance-GXYpvK2G.js";import{g as rl}from"./slugService-BRoC1GD8.js";import{p as Yc}from"./proposalSubmitService-3Lb8t9rP.js";import{i as Qc,d as ca,a as Gc}from"./viewerLabel-DZtKMLCT.js";import{o as er}from"./postgrest-DAqLjrwt.js";import{q as Me}from"./queryKeys-gD335jnI.js";import{u as Le}from"./useMutation-BIVTJNYP.js";import{h as it}from"./errorHandler-CuCRfYcc.js";import{M as ts}from"./message-square-DFNmF4KT.js";import{M as Be}from"./mail-Doxwvgpo.js";import{I as he}from"./input-D314iH3y.js";import{P as tr,a as sr,b as ar}from"./popover-tDTYgAuR.js";import{C as ct}from"./checkbox-DAsAX-fv.js";import{S as ta}from"./switch-DX29oGYf.js";import{s as Ja}from"./salesforceUrl-Buq4irYQ.js";import{D as ut,a as mt,b as ht,c as xt,d as kt,f as il,e as da}from"./dialog-B5tpbFY2.js";import{L as de}from"./label-Dm2MMzuh.js";import{S as ll,C as Xc}from"./stateUccSearch-BpyKllIP.js";import{c as Ma}from"./clipboard-DMs05LM0.js";import{L as Ot}from"./loader-circle-CojJEhe1.js";import{C as _t}from"./copy-C8-qfnKa.js";import{E as It}from"./external-link-CU3c0KFt.js";import{T as Jc,a as Zc,R as ed,P as td,C as sd,O as ad,D as nd}from"./index-pJfIofiV.js";import{S as ua}from"./scroll-area-JBQ52yJx.js";import{T as Rt}from"./textarea-CHfYhtY8.js";import{T as qn,a as On,b as $t,c as Ie}from"./tabs-DSQ8QzzU.js";import{P as rd}from"./pencil-CfXL2ajK.js";import{S as id}from"./save-7UntdLi4.js";import{E as ld,U as od}from"./EmailPreviewDialog-De2sQIz0.js";import{a as ka}from"./addWeeks-DKAzaxdp.js";import{i as Sa}from"./isBefore-BKK2juqp.js";import{d as cd,f as qa}from"./format-UAvZmgjS.js";import{t as Xr}from"./defaultOptions-w8f6iY6A.js";import{C as Oa}from"./calendar-C5f48h1x.js";import{C as ds}from"./circle-alert-s7kD66zS.js";import{E as bt}from"./eye-CysgaSrb.js";import{C as hs}from"./clock-BlMM4srd.js";import{X as Yt}from"./x-Dbso6HhZ.js";
2import{f as ma,i as ol,d as nr}from"./dateOnly-DJLeK1H3.js";import{M as cl}from"./menu-C6r1e_Cc.js";import{F as Ft}from"./file-text-BP4KmZmz.js";import{A as Es,u as dl,S as Jt,b as Jr,a as Zr,c as dd,r as ud}from"./useLeaderboard-BayvR5Xl.js";import{T as ul}from"./trending-down-KwE5ZPrN.js";import{C as rr}from"./chevron-up-CYwhGDi8.js";import{C as ms}from"./chevron-down-Bh-duVQA.js";import{A as $s}from"./activity-C1p7gS4S.js";import{Z as Ia}from"./zap-BmZUj943.js";import{M as ir}from"./mail-check-D38rCsQH.js";import{C as lr}from"./cloud-BeCNr4RT.js";import{S as or}from"./settings-BAIpSAJO.js";import{S as ha}from"./scale-rop2jgxa.js";import{P as xa}from"./party-popper-By8rLBZA.js";import{C as Za}from"./circle-x-3q5v4dS9.js";import{U as cr}from"./user-plus-DjUHGZY8.js";import{T as Is}from"./trash-2-BGx4f58m.js";import{M as en}from"./map-pin-Dy1vQ9V-.js";import{F as ml}from"./flame-B4j6wdSg.js";import{P as hl}from"./phone-call-duNcwMv3.js";import{f as ei,a as Gs,b as In}from"./formatters-DOoK6GbP.js";import{D as Ua,a as za,b as Ba,c as md,d as Cs,e as pe}from"./dropdown-menu-_DzAUmh3.js";import{S as as,a as xs,b as ps,c as fs,d as tn,e as xl}from"./sheet-H9IjI4k8.js";import{g as Lt,F as hd}from"./proposalRoutes-C6AP2Pc3.js";import{P as xd}from"./progress-DPLuadZw.js";import{B as sa}from"./brain-sGrg3XRG.js";import{C as St}from"./circle-check-5M5KvzHg.js";import{D as pl}from"./dollar-sign-CJhoZxCc.js";import{A as pd}from"./arrow-down-to-line-BVIuE0Sa.js";import{P as aa}from"./plus-nGcDYAPD.js";import{R as fd,a as gd,L as fl}from"./radio-group-Bm9zxjRx.js";import{S as ss}from"./sparkles-DRJhCLLh.js";import{S as As,a as Ps,b as Rs,c as Fs,d as Je}from"./select-BvtbyBgq.js";import{S as dr}from"./send-DIp21oOB.js";import{C as bd}from"./clipboard-list-BjmQZ0pE.js";import{c as yd}from"./CurrentClientContext-g0sPScp2.js";import{i as Un,r as gl}from"./emailPreviewService-CQ9yvxbp.js";import{F as bl}from"./filter-By8eUcWP.js";import{S as na}from"./search-CKERWwVe.js";import{A as ra,e as ur,p as Ls,c as yl,i as wd}from"./vcardSlug-BEXp96Em.js";import{U as vd}from"./upload-9EcgXRS3.js";import{C as jd}from"./calculator-CU_yJGls.js";import{s as _d,a as Nd,V as mr,b as ti}from"./videoLibrary-CIaNtXUK.js";import{C as hr}from"./circle-play-BoWAK_mr.js";import{N as si}from"./number-input-Bz7S_FIE.js";import{b as kd,m as Sd,A as Cd,a as ai,c as Dd,d as ni,f as wl}from"./financingFit-CQ1LRZ9Z.js";import{s as Td,b as ri,W as Ed,U as $d,N as Ad,m as Pd}from"./whatsNew-IiGaB7uu.js";import{A as Rd,a as Fd,b as Ld,c as Md}from"./accordion-phqrPUWr.js";import{u as ia}from"./dashboardStore-CFqjqKhF.js";import{a as qd}from"./aprMath-DSUvhvcs.js";import{A as Od}from"./arrow-up-CEligF94.js";import{A as Id}from"./arrow-down-B_b9wO9S.js";import{T as vl,a as jl,b as Ha,c as lt,d as _l,e as ot}from"./table-IgKfYi-z.js";import{M as Va}from"./monitor-gJPIWMmo.js";import{T as xr}from"./tablet-C_R8bykB.js";import{S as pr}from"./smartphone-DHJYhyGV.js";import{C as Nl}from"./circle-Chm9rIMJ.js";import{T as fr}from"./trophy-wCsMVfk1.js";import{a as Ud,l as zd,b as Ws,c as Mt}from"./activityEvents-C6a3ozhm.js";import{G as gr}from"./globe-BOtHpRMY.js";import{M as Xs}from"./mouse-pointer-click-CctoANfI.js";import{M as Wa}from"./mail-open-HNwRX8Y8.js";import{S as Bd}from"./shield-alert-CsMAk9Lo.js";import{s as Hd,c as Vd}from"./proposal-sequence-policy-7Gw7yLfd.js";import{v as Wd,a as Kd}from"./videoFollowup-NFtbMcQI.js";import{P as Yd}from"./loanMath-CS9851mb.js";import{S as kl}from"./shield-check-WHTVc8Oo.js";import{A as zn}from"./arrow-up-right-DVydq4aH.js";import{f as Ka}from"./formatDistanceToNow-D-BAksUH.js";import{L as Qd}from"./link-2-BjS6h1f3.js";import"./core.esm-DSIFM7mX.js";import{u as Gd}from"./useGlobalActivity-DSS1HkKG.js";import{D as Xd}from"./download-BISozIfD.js";import{B as Jd}from"./building-2-9zyhMRHV.js";import{a as Zd}from"./useCompanyPerformance-BpleUoep.js";import{u as eu,h as tu}from"./useHiddenReps-DPAqKpAM.js";import{r as su,v as au}from"./companyPerformance-CzxNH-KV.js";import{F as nu}from"./file-pen-line-eFgFVG6e.js";import{C as vn}from"./calendar-clock-BuNDRX9B.js";import{r as ru}from"./agentActivity-B1FRrkMG.js";import{A as ii,a as li}from"./alert-Ch2-_zj3.js";import{I as iu}from"./info-B-2_CKCQ.js";import{C as lu}from"./chart-column-DUn-HU2o.js";import{T as ou}from"./trending-up-BrgtklH_.js";import{u as cu,R as du}from"./usePerformanceTabVisibility-l1WoI7zQ.js";import{S as uu}from"./sms-templates-Fk18nV8b.js";import{S as mu}from"./SubmittedApplicationsSection-CiB-PKBD.js";import{A as hu,a as xu,b as pu,c as fu,d as gu,e as bu,f as yu,g as wu}from"./alert-dialog-Ba5hDpgv.js";import{s as vu}from"./visibleInterval-wrqtxvKC.js";import{R as ju}from"./rotate-ccw-Bi9YD835.js";import{E as _u}from"./eye-off-USLrUbnG.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 Sl=$e("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);/** 8 * @license lucide-react v0.462.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const Nu=$e("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** 13 * @license lucide-react v0.462.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const Cl=$e("CircleArrowRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/** 18 * @license lucide-react v0.462.0 - ISC 19 * 20 * This source code is licensed under the ISC license. 21 * See the LICENSE file in the root directory of this source tree.
22 */const ku=$e("Clipboard",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]]);/** 23 * @license lucide-react v0.462.0 - ISC 24 * 25 * This source code is licensed under the ISC license. 26 * See the LICENSE file in the root directory of this source tree. 27 */const Su=$e("CloudOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5.782 5.782A7 7 0 0 0 9 19h8.5a4.5 4.5 0 0 0 1.307-.193",key:"yfwify"}],["path",{d:"M21.532 16.5A4.5 4.5 0 0 0 17.5 10h-1.79A7.008 7.008 0 0 0 10 5.07",key:"jlfiyv"}]]);/** 28 * @license lucide-react v0.462.0 - ISC 29 * 30 * This source code is licensed under the ISC license. 31 * See the LICENSE file in the root directory of this source tree. 32 */const Cu=$e("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);/** 33 * @license lucide-react v0.462.0 - ISC 34 * 35 * This source code is licensed under the ISC license. 36 * See the LICENSE file in the root directory of this source tree. 37 */const Du=$e("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** 38 * @license lucide-react v0.462.0 - ISC 39 * 40 * This source code is licensed under the ISC license. 41 * See the LICENSE file in the root directory of this source tree. 42 */const Ya=$e("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** 43 * @license lucide-react v0.462.0 - ISC 44 * 45 * This source code is licensed under the ISC license. 46 * See the LICENSE file in the root directory of this source tree. 47 */const Dl=$e("FileSearch",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"ms7g94"}],["path",{d:"m9 18-1.5-1.5",key:"1j6qii"}],["circle",{cx:"5",cy:"14",r:"3",key:"ufru5t"}]]);/** 48 * @license lucide-react v0.462.0 - ISC 49 * 50 * This source code is licensed under the ISC license. 51 * See the LICENSE file in the root directory of this source tree. 52 */const oi=$e("Files",[["path",{d:"M20 7h-3a2 2 0 0 1-2-2V2",key:"x099mo"}],["path",{d:"M9 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7l4 4v10a2 2 0 0 1-2 2Z",key:"18t6ie"}],["path",{d:"M3 7.6v12.8A1.6 1.6 0 0 0 4.6 22h9.8",key:"1nja0z"}]]);/** 53 * @license lucide-react v0.462.0 - ISC 54 * 55 * This source code is licensed under the ISC license. 56 * See the LICENSE file in the root directory of this source tree. 57 */const Tu=$e("Handshake",[["path",{d:"m11 17 2 2a1 1 0 1 0 3-3",key:"efffak"}],["path",{d:"m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4",key:"9pr0kb"}],["path",{d:"m21 3 1 11h-2",key:"1tisrp"}],["path",{d:"M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3",key:"1uvwmv"}],["path",{d:"M3 4h8",key:"1ep09j"}]]);/** 58 * @license lucide-react v0.462.0 - ISC 59 * 60 * This source code is licensed under the ISC license. 61 * See the LICENSE file in the root directory of this source tree. 62 */const Eu=$e("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/** 63 * @license lucide-react v0.462.0 - ISC 64 * 65 * This source code is licensed under the ISC license. 66 * See the LICENSE file in the root directory of this source tree. 67 */const $u=$e("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/** 68 * @license lucide-react v0.462.0 - ISC 69 * 70 * This source code is licensed under the ISC license. 71 * See the LICENSE file in the root directory of this source tree. 72 */const Au=$e("MessageSquareText",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M13 8H7",key:"14i4kc"}],["path",{d:"M17 12H7",key:"16if0g"}]]);/** 73 * @license lucide-react v0.462.0 - ISC 74 * 75 * This source code is licensed under the ISC license. 76 * See the LICENSE file in the root directory of this source tree. 77 */const Pu=$e("NotebookPen",[["path",{d:"M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4",key:"re6nr2"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}
77],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"pqwjuv"}]]);/** 78 * @license lucide-react v0.462.0 - ISC 79 * 80 * This source code is licensed under the ISC license. 81 * See the LICENSE file in the root directory of this source tree. 82 */const Ru=$e("PhoneOff",[["path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91",key:"z86iuo"}],["line",{x1:"22",x2:"2",y1:"2",y2:"22",key:"11kh81"}]]);/** 83 * @license lucide-react v0.462.0 - ISC 84 * 85 * This source code is licensed under the ISC license. 86 * See the LICENSE file in the root directory of this source tree. 87 */const ci=$e("PinOff",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]]);/** 88 * @license lucide-react v0.462.0 - ISC 89 * 90 * This source code is licensed under the ISC license. 91 * See the LICENSE file in the root directory of this source tree. 92 */const Fu=$e("Pin",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]]);/** 93 * @license lucide-react v0.462.0 - ISC 94 * 95 * This source code is licensed under the ISC license. 96 * See the LICENSE file in the root directory of this source tree. 97 */const Lu=$e("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/** 98 * @license lucide-react v0.462.0 - ISC 99 * 100 * This source code is licensed under the ISC license. 101 * See the LICENSE file in the root directory of this source tree. 102 */const pa=$e("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/** 103 * @license lucide-react v0.462.0 - ISC 104 * 105 * This source code is licensed under the ISC license. 106 * See the LICENSE file in the root directory of this source tree. 107 */const Tl=$e("Snowflake",[["line",{x1:"2",x2:"22",y1:"12",y2:"12",key:"1dnqot"}],["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"m20 16-4-4 4-4",key:"rquw4f"}],["path",{d:"m4 8 4 4-4 4",key:"12s3z9"}],["path",{d:"m16 4-4 4-4-4",key:"1tumq1"}],["path",{d:"m8 20 4-4 4 4",key:"9p200w"}]]);/** 108 * @license lucide-react v0.462.0 - ISC 109 * 110 * This source code is licensed under the ISC license. 111 * See the LICENSE file in the root directory of this source tree. 112 */const Mu=$e("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** 113 * @license lucide-react v0.462.0 - ISC 114 * 115 * This source code is licensed under the ISC license. 116 * See the LICENSE file in the root directory of this source tree. 117 */const qu=$e("Unlink",[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]]);/** 118 * @license lucide-react v0.462.0 - ISC 119 * 120 * This source code is licensed under the ISC license. 121 * See the LICENSE file in the root directory of this source tree. 122 */const di=$e("UserRound",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}
122],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);function Ou(t,s){const a=Xr(t),n=Xr(s),r=ui(a,n),i=Math.abs(cd(a,n));a.setDate(a.getDate()-r*i);const l=+(ui(a,n)===-r),o=r*(i-l);return o===0?0:o}function ui(t,s){const a=t.getFullYear()-s.getFullYear()||t.getMonth()-s.getMonth()||t.getDate()-s.getDate()||t.getHours()-s.getHours()||t.getMinutes()-s.getMinutes()||t.getSeconds()-s.getSeconds()||t.getMilliseconds()-s.getMilliseconds();return a<0?-1:a>0?1:a}const El=({className:t,...s})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:dt("mx-auto flex w-full justify-center",t),...s});El.displayName="Pagination";const $l=h.forwardRef(({className:t,...s},a)=>e.jsx("ul",{ref:a,className:dt("flex flex-row items-center gap-1",t),...s}));$l.displayName="PaginationContent";const Qs=h.forwardRef(({className:t,...s},a)=>e.jsx("li",{ref:a,className:dt("",t),...s}));Qs.displayName="PaginationItem";const sn=({className:t,isActive:s,size:a="icon",...n})=>e.jsx("a",{"aria-current":s?"page":void 0,className:dt(yc({variant:s?"outline":"ghost",size:a}),t),...n});sn.displayName="PaginationLink";const Al=({className:t,...s})=>e.jsxs(sn,{"aria-label":"Go to previous page",size:"default",className:dt("gap-1 pl-2.5",t),...s,children:[e.jsx(Zn,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});Al.displayName="PaginationPrevious";const Pl=({className:t,...s})=>e.jsxs(sn,{"aria-label":"Go to next page",size:"default",className:dt("gap-1 pr-2.5",t),...s,children:[e.jsx("span",{children:"Next"}),e.jsx(oa,{className:"h-4 w-4"})]});Pl.displayName="PaginationNext";const Rl=({className:t,...s})=>e.jsxs("span",{"aria-hidden":!0,className:dt("flex h-9 w-9 items-center justify-center",t),...s,children:[e.jsx(Ya,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});Rl.displayName="PaginationEllipsis";function Iu({currentPage:t,totalPages:s,totalCount:a,pageSize:n,onPageChange:r}){if(s<=1)return null;const i=(t-1)*n+1,l=Math.min(t*n,a),c=(()=>{const m=[];if(s<=5)for(let d=1;d<=s;d++)m.push(d);else{m.push(1),t>3&&m.push("ellipsis");const d=Math.max(2,t-1),u=Math.min(s-1,t+1);for(let g=d;g<=u;g++)m.includes(g)||m.push(g);t<s-2&&m.push("ellipsis"),m.includes(s)||m.push(s)}return m})();return e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-4 pt-4 border-t",children:[e.jsxs("p",{className:"text-sm text-muted-foreground order-2 sm:order-1",children:["Showing ",i,"-",l," of ",a," proposals"]}),e.jsxs("div",{className:"flex items-center gap-2 order-1 sm:order-2",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:hidden",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>r(t-1),disabled:t===1,children:[e.jsx(Zn,{className:"h-4 w-4"}),"Prev"]}),e.jsxs("span",{className:"px-3 text-sm text-muted-foreground",children:[t," / ",s]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>r(t+1),disabled:t===s,children:["Next",e.jsx(oa,{className:"h-4 w-4"})]})]}),e.jsx(El,{className:"hidden sm:flex",children:e.jsxs($l,{children:[e.jsx(Qs,{children:e.jsx(Al,{onClick:()=>r(t-1),className:t===1?"pointer-events-none opacity-50":"cursor-pointer"})}),c.map((m,f)=>m==="ellipsis"?e.jsx(Qs,{children:e.jsx(Rl,{})},`ellipsis-${f}`):e.jsx(Qs,{children:e.jsx(sn,{onClick:()=>r(m),isActive:t===m,className:"cursor-pointer",children:m})},m)),e.jsx(Qs,{children:e.jsx(Pl,{onClick:()=>r(t+1),className:t===s?"pointer-events-none opacity-50":"cursor-pointer"})})]})})]})]})}const jn=80,mi=120;function Uu({children:t,onRefresh:s,disabled:a=!1}){const[n,r]=h.useState(!1),i=h.useRef(null),l=h.useRef(null),o=h.useRef(null),c=h.useRef(null),m=h.useRef(null),f=h.useRef(0),d=h.useRef(!1),u=h.useRef(0),g=h.useCallback((x,$=!1)=>{u.current=x;const T=Math.min(x/jn,1),S=$?"transform 200ms ease-out, height 200ms ease-out, opacity 200ms ease-out":"none";l.current&&(l.current.style.height=`${x}px`,l.current.style.opacity=String(T),l.current.style.transition=S),o.current&&(o.current.style.transform=`scale(${.5+.5*T})`),c.current&&(c.current.style.transform=`rotate(${x/mi*360}deg)`),m.current&&(m.current.style.transform=x?`translateY(${x}px)`:"",m.current.style.transition=S)},[]),D=h.useCallback(x=>{if(a||n)return;const $=i.current;$&&$.scrollTop<=0&&(f.current=x.touches[0].clientY,d.current=!0)},[a,n]),E=h.useCallback(x=>{if(!d.current||a||n)return;const $=i.current;if(!$||$.scrollTop>0){d.current=!1,g(0);return}const T=x.touches[0].clientY-f.current;T>0&&(x.preventDefault(),g(Math.min(T*.4,mi)))},[a,n,g]),v=h.useCallback(async()=>
122{if(d.current){if(d.current=!1,u.current>=jn&&!n){r(!0),g(jn,!0);try{await s()}finally{r(!1)}}g(0,!0)}},[n,s,g]);return h.useEffect(()=>{const x=i.current;if(x)return x.addEventListener("touchstart",D,{passive:!0}),x.addEventListener("touchmove",E,{passive:!1}),x.addEventListener("touchend",v),()=>{x.removeEventListener("touchstart",D),x.removeEventListener("touchmove",E),x.removeEventListener("touchend",v)}},[D,E,v]),e.jsxs("div",{ref:i,className:"relative h-full overflow-auto",children:[e.jsx("div",{ref:l,className:"absolute top-0 left-0 right-0 flex items-center justify-center pointer-events-none z-50 overflow-hidden",style:{height:0,opacity:0},children:e.jsx("div",{ref:o,className:"flex items-center justify-center w-10 h-10 rounded-full bg-primary text-primary-foreground shadow-lg",style:{transform:"scale(0.5)"},children:e.jsx("div",{ref:c,children:e.jsx(Ct,{className:`h-5 w-5 ${n?"animate-spin":""}`})})})}),e.jsx("div",{ref:m,children:t})]})}async function vt(t,s){const a=[];for(let r=0;r<200;r++){const{data:i,error:l}=await t(r*500,(r+1)*500-1);if(l||!i)throw new Error(`${s} could not be loaded. Please retry.`);if(a.push(...i),i.length<500)return{data:a}}throw new Error(`${s} exceeds the history limit. No partial results were shown.`)}const Fl=50;function zu(t,s){let a=0;const n=new Date(t);n.setHours(0,0,0,0);const r=new Date(s);for(r.setHours(0,0,0,0);n<=r;){const i=n.getDay();i!==0&&i!==6&&a++,n.setDate(n.getDate()+1)}return a}function Bu(t,s,a=new Date){const n=(s||"").toLowerCase();if(n.startsWith("daily")){const i=new Date(t);return i.setDate(i.getDate()+1),i>a?0:zu(i,a)}const r=(a.getTime()-t.getTime())/(1e3*60*60*24);return r<=0?0:n.includes("bi")&&n.includes("week")?Math.floor(r/14):n.startsWith("week")?Math.floor(r/7):n.startsWith("month")?Math.floor(r/30.44):Math.floor(r/7)}function br(t){if(t.status!=="funded"||!t.funded_at||!t.accepted_option)return null;const{accepted_option:s,funded_at:a}=t,{payment_amount:n,payment_frequency:r,total_repayment:i,term_length_months:l}=s;if(!n||!r||!i||!l)return null;const o=new Date(a),c=new Date,m=Math.floor((c.getTime()-o.getTime())/(1e3*60*60*24)),f=s.original_amount??null,d=t.funded_amount??s.adjusted_amount??f,u=f&&d&&f>0?d/f:1,g=i*u,D=n*u,v=Bu(o,r,c)*D,x=Math.min(100,Math.round(v/g*100)),$=Math.max(0,g-v),T=Math.ceil($/D),S=r.toLowerCase();let p;S.startsWith("daily")?p=1.4:S.includes("bi")&&S.includes("week")?p=14:S.startsWith("week")?p=7:S.startsWith("month")?p=30.44:p=7;const _=Math.max(0,Math.ceil(T*p)),y=new Date(c.getTime()+_*24*60*60*1e3);return{percentPaidOff:x,estimatedPayoffDate:_>0?y:null,daysRemaining:_,daysElapsed:m,estimatedRemainingBalance:$,totalRepayment:g,isRenewalEligible:x>=Fl,isFunded:!0}}function Hu(t){const s=br(t);return s?s.percentPaidOff>=Fl?{label:`${s.percentPaidOff}% paid - Renewal ready`,color:"text-emerald-700 dark:text-emerald-400",bgClass:"bg-emerald-100 dark:bg-emerald-950/30 border-emerald-200"}:s.percentPaidOff>=40?{label:`${s.percentPaidOff}% paid - ${s.daysRemaining}d to renewal`,color:"text-amber-700 dark:text-amber-400",bgClass:"bg-amber-100 dark:bg-amber-950/30 border-amber-200"}:{label:`${s.percentPaidOff}% paid off`,color:"text-blue-700 dark:text-blue-400",bgClass:"bg-blue-100 dark:bg-blue-950/30 border-blue-200"}:null}const Vu=new Set(["rejected","expired","funded","funding_lost"]),Wu=`(${Array.from(Vu).join(",")})`;function Ku(){return new Date().toISOString().split("T")[0]}function an(t){return(t.view_count||0)>=4}function nn(t){return t.status!=="pending"||(t.view_count||0)>0||!t.initial_email_sent?!1:Date.now()-new Date(t.created_at).getTime()>=2*60*60*1e3}function rn(t){return(t.view_states||[]).length>=2}function ln(t){return(t.view_count||0)===0?!1:t.max_view_duration!=null&&t.max_view_duration<=30}function Ll(t){return rn(t)?"border-l-4 border-l-purple-500":an(t)?"border-l-4 border-l-orange-500":ln(t)?"border-l-4 border-l-amber-500":nn(t)?"border-l-4 border-l-slate-400":""}async function Yu(t){const{data:s,error:a}=await F.rpc("pipeline_proposal_counts",{p_types:t!=null&&t.length?t:void 0});if((a==null?void 0:a.code)==="PGRST202"||(a==null?void 0:a.code)==="42883")return Qu(t);if(a)throw a;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("Pipeline counts are unavailable");const n=["active","archived","funded","fundingLost","total"];for(const r of n)if(typeof s[r]!="number"||!Number.isSafeInteger(s[r])||s[r]<0)throw new Error("Pipeline counts are incomplete");return s}async function Qu(t){const s=c=>t&&t.length>0?c.in("type",t):c.neq("type","document_request"),[a,n,r,i,l]=await Promise.all([s(F.from("proposals").select("id",{count:"exact",head:!0}).eq("is_archived",!1).not("status","in","(funded,funding_lost)").or("status.neq.draft,auto_created_from_sf.is.null,auto_created_from_sf.eq.fal
122se")),s(F.from("proposals").select("id",{count:"exact",head:!0}).eq("is_archived",!0)),s(F.from("proposals").select("id",{count:"exact",head:!0}).eq("status","funded").eq("is_archived",!1)),s(F.from("proposals").select("id",{count:"exact",head:!0}).eq("status","funding_lost").eq("is_archived",!1)),s(F.from("proposals").select("id",{count:"exact",head:!0}))]),o=[a,n,r,i,l].find(c=>c.error);if(o!=null&&o.error)throw o.error;return{active:a.count??0,archived:n.count??0,funded:r.count??0,fundingLost:i.count??0,total:l.count??0}}async function Js(t,s=!1){const a=t.map(N=>N.id);if(a.length===0)return[];const[{data:n},{data:r},{data:i},{data:l},{data:o},{data:c}]=await Promise.all([s?Promise.resolve({data:[]}):vt((N,C)=>F.from("uploaded_documents").select("*").in("proposal_id",a).order("uploaded_at",{ascending:!1}).order("id").range(N,C),"Documents"),s?Promise.resolve({data:[]}):vt((N,C)=>F.from("proposal_view_logs").select("id, proposal_id, state, session_duration, viewed_at, viewer_ip, viewer_class").in("proposal_id",a).order("id").range(N,C),"Visits"),s?Promise.resolve({data:[]}):vt((N,C)=>F.from("allowed_ips").select("id, ip_address").eq("is_active",!0).order("id").range(N,C),"Internal IP list"),vt((N,C)=>F.from("loan_options").select("id, name, bank_name, term_length_months, approved_amount, min_amount, max_amount, total_repayment, payment_amount, payment_frequency, proposal_id").in("proposal_id",a).order("id").range(N,C),"Loan options"),s?Promise.resolve({data:[]}):vt((N,C)=>F.from("custom_documents").select("id, document_title, document_description, request_key, proposal_id").in("proposal_id",a).order("id").range(N,C).returns(),"Document requests"),s?Promise.resolve({data:[]}):vt((N,C)=>F.from("email_logs").select("id, proposal_id, recipient_email, sent_at").in("proposal_id",a).eq("status","sent").order("id").range(N,C),"Sent emails")]),m=new Map(t.map(N=>[N.id,String(N.email||"").toLowerCase()])),f=new Map;(c||[]).forEach(N=>{if(!N.proposal_id||!N.sent_at)return;const C=m.get(N.proposal_id);if(!C||String(N.recipient_email||"").toLowerCase()!==C)return;const I=f.get(N.proposal_id);(!I||new Date(N.sent_at)>new Date(I))&&f.set(N.proposal_id,N.sent_at)});const d=new Set((i||[]).map(N=>N.ip_address)),u=t.filter(N=>N.status==="accepted"||N.status==="in_final_review"||N.status==="funded").map(N=>N.id),{data:g}=u.length>0?await vt((N,C)=>F.from("client_responses").select("*").in("proposal_id",u).order("id").range(N,C),"Accepted responses"):{data:[]},D=(g||[]).map(N=>N.selected_option_id).filter(Boolean),{data:E}=D.length>0?await vt((N,C)=>F.from("line_of_credit_options").select("id, name, draw_amount, total_payback, payment_amount, payment_frequency, term_length_months").in("id",D).order("id").range(N,C),"Credit line options"):{data:[]},v=new Map;(n||[]).forEach(N=>{v.has(N.proposal_id)||v.set(N.proposal_id,[]),v.get(N.proposal_id).push(N)});const x=new Map;(o||[]).forEach(N=>{x.has(N.proposal_id)||x.set(N.proposal_id,[]),x.get(N.proposal_id).push(N)});const $=new Map,T=new Map,S=new Map,p=new Map;(r||[]).forEach(N=>{if(!(N.viewer_class==="internal"||N.viewer_class==="scanner"||N.viewer_class!=="client"&&(Qc(N.viewer_ip)||N.viewer_ip&&d.has(N.viewer_ip)))){if($.set(N.proposal_id,($.get(N.proposal_id)||0)+1),N.state&&(T.has(N.proposal_id)||T.set(N.proposal_id,new Set),T.get(N.proposal_id).add(N.state)),N.session_duration!=null){const C=S.get(N.proposal_id)??0;N.session_duration>C&&S.set(N.proposal_id,N.session_duration)}if(N.viewed_at){const C=p.get(N.proposal_id);(!C||new Date(N.viewed_at)>new Date(C))&&p.set(N.proposal_id,N.viewed_at)}}});const _=new Map;(l||[]).forEach(N=>{_.has(N.proposal_id)||_.set(N.proposal_id,[]),_.get(N.proposal_id).push(N)});const y=new Map;[...g||[]].sort((N,C)=>new Date(N.accepted_at).getTime()-new Date(C.accepted_at).getTime()).forEach(N=>{y.set(N.proposal_id,N)});const q=new Map;return(E||[]).forEach(N=>{q.set(N.id,N)}),t.map(N=>{const C=v.get(N.id)||[],I=$.get(N.id)||0,H=T.has(N.id)?[...T.get(N.id)]:[],P=_.get(N.id)||[];let z=null;if(N.status==="accepted"||N.status==="in_final_review"||N.status==="funded"){const V=y.get(N.id);if(V){const G=P.find(Z=>Z.id===V.selected_option_id);if(G){const Z=Wc({approvedAmount:V.original_amount||G.approved_amount,totalRepayment:G.total_repayment,paymentAmount:G.payment_amount},V.adjusted_amount);z={option_name:G.name,original_amount:V.original_amount,adjusted_amount:V.adjusted_amount,total_repayment:Z.totalRepayment,payment_amount:Z.paymentAmount,payment_frequency:G.payment_frequency,term_length_months:G.term_length_months,accepted_at:V.accepted_at,client_name:V.client_name,client_title:V.client_title}}else{const Z=q.get(V.selected_option_id);Z&&(z={option_name:Z.name,original_amount:V.original_amount||Z.draw_amount,adjusted_amount:V.adjusted_amount,total_repayment:Z.total_payback,payment_amount:Z.payment_amount||null,payment_frequency:Z.payment_frequency||null,term_length_months:Z.term_length_months||null,accepted_at:V.accepted_at,client_name:V.client_name,client_title:V.client_title})}}}const M=P.length>0?[...new Set(P.map(V=>
122V.bank_name).filter(Boolean))]:[];let k=null;if(P.length>0){const V=P.map(G=>G.term_length_months);k={min:Math.min(...V),max:Math.max(...V)}}let w=null,L=null;if(P.length>0){const V=P.map(G=>({min:G.min_amount??G.approved_amount,max:G.max_amount??G.approved_amount}));w=Math.min(...V.map(G=>G.min)),L=Math.max(...V.map(G=>G.max))}const O=x.get(N.id)||[],ae=new Set(C.map(V=>V.custom_document_id)),te=N.type==="document_request"&&N.document_template==="sba_term_loan"?Mn(N.document_request_debt):null;if(te&&Hc(te))for(const V of O)V.request_key==="debt_schedule"&&ae.add(V.id);return{...N,uploaded_documents:nl(C),view_count:I,view_states:H,max_view_duration:S.get(N.id)??null,loan_options_count:P.length,bank_names:M,term_length_range:k,min_loan_amount:w,max_loan_amount:L,accepted_option:z,last_client_viewed_at:N.last_client_viewed_at??p.get(N.id)??null,last_sent_to_client_at:f.get(N.id)??null,required_documents_count:O.length,uploaded_documents_count:O.filter(V=>ae.has(V.id)).length,custom_documents:O.map(V=>({id:V.id,document_title:V.document_title,document_description:V.document_description}))}})}async function Gu(t){const{page:s,pageSize:a,sortBy:n,sortOrder:r,archiveFilter:i,searchQuery:l,agentFilter:o,statusFilter:c,dateFrom:m,dateTo:f,typeFilter:d,leadTempFilter:u,focusProposalIds:g}=t;let D=null;if(u&&u.length>0){const{data:k}=await F.rpc("get_lead_temp_proposal_ids",{categories:u,owner_id:t.userId});if(D=(k||[]).map(w=>w.proposal_id),D.length===0)return{proposals:[],totalCount:0,totalPages:0}}let E=D;if(g&&g.length>0){if(E){const k=new Set(g);E=E.filter(w=>k.has(w))}else E=g;if(E.length===0)return{proposals:[],totalCount:0,totalPages:0}}else if(g&&g.length===0)return{proposals:[],totalCount:0,totalPages:0};const v=!!(g&&g.length>0),x=k=>{let w=F.from("proposals").select("*",k.count?{count:"exact"}:void 0);return E&&(w=w.in("id",E)),v||(i==="active"?w=w.eq("is_archived",!1).neq("status","funded").neq("status","funding_lost").or("status.neq.draft,and(fit_only.eq.false,or(auto_created_from_sf.is.null,auto_created_from_sf.eq.false))"):i==="archived"?w=w.eq("is_archived",!0):i==="funded"?w=w.eq("status","funded").eq("is_archived",!1):i==="funding_lost"&&(w=w.eq("status","funding_lost").eq("is_archived",!1))),v||(w=w.eq("fit_only",!1)),u&&u.length>0&&(w=w.eq("is_archived",!1).not("status","in",Wu).or(`expiration_date.is.null,expiration_date.gte.${Ku()}`)),l.trim()&&(w=w.or(er(d!=null&&d.includes("document_request")?["client_name","business_name","request_title","agent_notes"]:["client_name","business_name","email","agent_email"],l))),o&&(w=w.eq("agent_email",o)),c&&c.length>0&&(w=w.in("status",c)),m&&(w=w.gte("created_at",m)),f&&(w=w.lte("created_at",f+"T23:59:59.999Z")),t.documentTemplate&&(d!=null&&d.includes("document_request"))&&(w=w.eq("document_template",t.documentTemplate)),d&&d.length>0?w=w.in("type",d):v||(w=w.neq("type","document_request")),w};if(t.renewalReadyOnly&&i==="funded"){const k=()=>x({count:!1}).order(n,{ascending:r==="asc",nullsFirst:!1}).order("id",{ascending:!0}),{data:w}=await vt((te,V)=>k().range(te,V),"Funded renewal candidates"),L=[];for(let te=0;te<w.length;te+=100){const V=w.slice(te,te+100),G=await Js(V,!0),Z=new Set(G.filter(se=>{var Y;return(Y=br(se))==null?void 0:Y.isRenewalEligible}).map(se=>se.id));L.push(...V.filter(se=>Z.has(se.id)))}const O=L.length,ae=L.slice((s-1)*a,s*a);return{proposals:await Js(ae),totalCount:O,totalPages:Math.ceil(O/a)}}const $=["accepted","in_final_review"],T=!v&&i==="active"&&!(c&&c.length>0),S=T?x({count:!1}).in("status",$).order(n,{ascending:r==="asc",nullsFirst:!1}).order("id",{ascending:!0}).limit(100):Promise.resolve({data:[],error:null});let p=x({count:!0});T&&(p=p.not("status","in",`(${$.join(",")})`)),p=["deal_health_score","last_sent_to_client_at","last_client_viewed_at"].includes(n)?p.order(n,{ascending:r==="asc",nullsFirst:!1}):p.order(n,{ascending:r==="asc"}),p=p.order("id",{ascending:!0});const _=(s-1)*a,y=_+a-1;p=p.range(_,y);const[q,A]=await Promise.all([S,p]);if(q.error)throw q.error;const N=q.data||[],{data:C,error:I,count:H}=A;if(I)throw I;const P=(H||0)+N.length,z=Math.ceil(Math.max(0,H||0)/a)||(N.length?1:0);return{proposals:await Js([...N,...C||[]]),totalCount:P,totalPages:z}}async function Xu(t){const s=t.business_slug||t.unique_link,a=`${Pt()}/${s}`,{data:n,error:r}=await F.functions.invoke("send-proposal-email",{body:{clientEmail:t.email,clientName:t.client_name,businessName:t.business_name,proposalLink:a,agentEmail:t.agent_email,proposalId:t.id}});if(r)throw r;if((n==null?void 0:n.success)!==!0&&(n!=null&&n.error))throw new Error(typeof n.error=="string"?n.error:"Email was not confirmed as sent");const{error:i}=await F.from("proposals").update({initial_email_sent:!0}).eq("id",t.id);
122i&&console.error("Could not record initial_email_sent:",i);const{error:l}=await F.from("proposals").update({sent_at:new Date().toISOString()}).eq("id",t.id).is("sent_at",null);return l&&console.error("Could not record sent_at:",l),await Yc(t.id),{logged:(n==null?void 0:n.logged)!==!1}}async function Ju(t){const{error:s}=await F.from("proposals").delete().eq("id",t);if(s)throw s}async function Zu(t){const{error:s}=await F.from("proposals").delete().in("id",t);if(s)throw s}async function em(t,s){const{error:a}=await F.from("proposals").update({is_archived:!0,archived_at:new Date().toISOString(),archived_by:s,archive_reason:"Manually archived"}).eq("id",t);if(a)throw a}async function tm(t,s){const{data:a}=await F.from("proposals").select("business_slug, status").eq("id",t).single();if((a==null?void 0:a.status)==="draft"){const{error:i}=await F.from("proposals").update({is_archived:!1,archived_at:null,archived_by:null,archive_reason:null}).eq("id",t);if(i)throw i;return(a==null?void 0:a.business_slug)??""}const n=(a==null?void 0:a.business_slug)||await rl(s,"",t),{error:r}=await F.from("proposals").update({is_archived:!1,archived_at:null,archived_by:null,archive_reason:null,business_slug:n,status:"pending",rejected_at:null,rejection_reason:null,funding_lost_at:null,funding_lost_reason:null,funding_lost_lender:null}).eq("id",t);if(r)throw r;return n}async function sm(t,s){const{error:a}=await F.from("proposals").update({is_archived:!0,archived_at:new Date().toISOString(),archived_by:s,archive_reason:"Bulk archived"}).in("id",t);if(a)throw a}async function am(t,s){const{error:a}=await F.from("proposals").update({status:"funded",funded_at:new Date().toISOString(),...s!=null&&s>0?{funded_amount:s}:{},updated_at:new Date().toISOString()}).eq("id",t);if(a)throw a;try{await F.functions.invoke("send-funded-congratulations",{body:{proposalId:t,fundedAmount:s}})}catch(n){console.error("Error sending congratulations email:",n)}}async function nm(t,s){const{error:a}=await F.from("proposals").update({status:"rejected",rejection_reason:s,rejected_at:new Date().toISOString(),auto_followups_enabled:!1,updated_at:new Date().toISOString()}).eq("id",t);if(a)throw a;try{await F.functions.invoke("send-rejection-feedback",{body:{proposalId:t,rejectionReason:s}})}catch(n){console.error("Error sending rejection feedback email:",n)}}async function rm(t,s,a){const n=a?`Funding Lost â ${a}: ${s}`:`Funding Lost: ${s}`,{error:r}=await F.from("proposals").update({status:"funding_lost",rejected_at:new Date().toISOString(),rejection_reason:n,funding_lost_at:new Date().toISOString(),funding_lost_reason:s,funding_lost_lender:a??null,auto_followups_enabled:!1,updated_at:new Date().toISOString()}).eq("id",t);if(r)throw r}async function Ml(t,s){const{data:a,error:n}=await F.from("proposals").update({auto_followups_enabled:s}).eq("id",t).select("id");if(n)throw n;if(!a||a.length===0)throw new Error("This deal isn't assigned to you, so its follow-up setting can't be changed from here.")}async function im(t,s){const{error:a}=await F.from("proposals").update({status:s,updated_at:new Date().toISOString()}).eq("id",t);if(a)throw a}async function Xb(t,s){let a=F.from("proposals").select("*").eq("status","funded");const n=s==null?void 0:s.trim().toLowerCase();a=n?a.or(`user_id.eq.${t},agent_email.ilike.${n}`):a.eq("user_id",t);const{data:r,error:i}=await a.order("funded_at",{ascending:!1});if(i)throw i;return Js(r||[])}async function lm(t){const{searchQuery:s,agentFilter:a,statusFilter:n,dateFrom:r,dateTo:i,typeFilter:l}=t;let o=F.from("proposals").select("*").eq("is_archived",!1).eq("fit_only",!1);n!=null&&n.includes("draft")||(o=o.neq("status","draft")),s.trim()&&(o=o.or(er(l!=null&&l.includes("document_request")?["client_name","business_name","request_title","agent_notes"]:["client_name","business_name","email","agent_email"],s))),a&&(o=o.eq("agent_email",a)),n&&n.length>0&&(o=o.in("status",n)),r&&(o=o.gte("created_at",r)),i&&(o=o.lte("created_at",i+"T23:59:59.999Z")),t.documentTemplate&&(l!=null&&l.includes("document_request"))&&(o=o.eq("document_template",t.documentTemplate)),l&&l.length>0&&(o=o.in("type",l)),o=o.order("created_at",{ascending:!1});const{data:c,error:m}=await o;
122if(m)throw m;return Js(c||[])}async function om(t){const{data:s,error:a}=await F.from("proposals").select("*").eq("id",t).single();if(a||!s)throw new Error("Could not fetch proposal to clone");const n=await rl(s.business_name),{id:r,unique_link:i,created_at:l,updated_at:o,status:c,initial_email_sent:m,auto_followups_enabled:f,is_archived:d,archived_at:u,archived_by:g,archive_reason:D,funded_at:E,funded_amount:v,last_monthly_email_at:x,monthly_email_count:$,engagement_score:T,last_engagement_analysis:S,optimal_contact_hour:p,last_activity_at:_,rejected_at:y,rejection_reason:q,is_unsubscribed:A,unsubscribed_at:N,origin_state:C,ai_analysis:I,ai_analysis_generated_at:H,converted_from_id:P,converted_at:z,salesforce_opportunity_id:M,approved_event_key:k,sent_at:w,last_client_viewed_at:L,sf_approved_at:O,auto_created_from_sf:ae,creation_request_hash:te,fit_only:V,deal_health_score:G,...Z}=s,{data:se,error:Y}=await F.from("proposals").insert({...Z,business_slug:n,status:"pending",initial_email_sent:!1,auto_followups_enabled:!1,is_archived:!1,send_email_to_client:!1,date:new Date().toISOString().split("T")[0],expiration_date:s.expiration_date?new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0]:null}).select("id").single();if(Y||!se)throw new Error("Failed to create cloned proposal");const ne=se.id;try{if(s.type==="line_of_credit"||s.type==="proposal"){const{data:b,error:W}=await F.from("line_of_credit_options").select("*").eq("proposal_id",t);if(W)throw W;if(b&&b.length>0){const oe=b.map(({id:Q,proposal_id:ie,created_at:ue,...Ee})=>({...Ee,proposal_id:ne})),{error:B}=await F.from("line_of_credit_options").insert(oe);if(B)throw B}}if(s.type!=="line_of_credit"){const{data:b,error:W}=await F.from("loan_options").select("*").eq("proposal_id",t);if(W)throw W;if(b&&b.length>0){const oe=b.map(({id:Q,proposal_id:ie,created_at:ue,...Ee})=>({...Ee,proposal_id:ne})),{error:B}=await F.from("loan_options").insert(oe);if(B)throw B}}const{data:fe,error:_e}=await F.from("custom_documents").select("*").eq("proposal_id",t);if(_e)throw _e;if(fe&&fe.length>0){const b=fe.map(({id:oe,proposal_id:B,created_at:Q,...ie})=>({...ie,proposal_id:ne})),{error:W}=await F.from("custom_documents").insert(b);if(W)throw W}if(s.type==="funding_menu"){const{data:b,error:W}=await F.from("funding_menu_programs").select("*").eq("funding_menu_id",t);if(W)throw W;if(b&&b.length>0){const oe=b.map(({id:Q,funding_menu_id:ie,created_at:ue,...Ee})=>({...Ee,funding_menu_id:ne})),{error:B}=await F.from("funding_menu_programs").insert(oe);if(B)throw B}}const{data:ge,error:me}=await F.from("follow_up_settings").select("*").eq("proposal_id",t).maybeSingle();if(me)throw me;if(ge){const{id:b,proposal_id:W,created_at:oe,updated_at:B,...Q}=ge,{error:ie}=await F.from("follow_up_settings").insert({...Q,proposal_id:ne});if(ie)throw ie}}catch(fe){throw await F.from("proposals").delete().eq("id",ne),fe instanceof Error?fe:new Error("Failed to clone proposal details")}return ne}function cm(t,s={}){var w,L,O,ae,te;const{enabled:a=!0,countsEnabled:n=a,pageSize:r=20,sortBy:i="created_at",sortOrder:l="desc",archiveFilter:o="active",searchQuery:c="",agentFilter:m,statusFilter:f,dateFrom:d,dateTo:u,typeFilter:g,documentTemplate:D,leadTempFilter:E,focusProposalIds:v,renewalReadyOnly:x=!1}=s,[$,T]=h.useState(1),S=Nt();h.useEffect(()=>{T(1)},[o,c,i,l,m,f,d,u,g,D,E,v,x]);const p={userId:t,page:$,pageSize:r,sortBy:i,sortOrder:l,archiveFilter:o,searchQuery:c,agentFilter:m,statusFilter:f,dateFrom:d,dateTo:u,typeFilter:g,documentTemplate:D,leadTempFilter:E,focusProposalIds:v,renewalReadyOnly:x},_=ve({queryKey:Me.proposals.paginated(p),queryFn:()=>Gu({...p,userId:t}),enabled:!!t&&a,refetchInterval:a?90*1e3:!1,placeholderData:wc}),y=ve({queryKey:[...Me.proposals.counts(),g??null,t],queryFn:()=>Yu(g),enabled:!!t&&n}),q=h.useCallback(V=>{var Z;const G=((Z=_.data)==null?void 0:Z.totalPages)||1;T(Math.max(1,Math.min(V,G)))},[(w=_.data)==null?void 0:w.totalPages]),A=h.useCallback(()=>{var G;const V=((G=_.data)==null?void 0:G.totalPages)||1;T(Z=>Math.min(Z+1,V))},[(L=_.data)==null?void 0:L.totalPages]),N=h.useCallback(()=>{T(V=>Math.max(V-1,1))},[]),C=h.useCallback(async()=>{await Promise.all([S.invalidateQueries({queryKey:Me.proposals.all}),S.invalidateQueries({queryKey:Me.proposals.counts()})])},[S]),I=h.useCallback((V,G)=>{S.setQueryData(Me.proposals.paginated(p),Z=>
122{if(!Z)return Z;const se=Z;return{...se,proposals:se.proposals.map(Y=>Y.id===V?{...Y,...G}:Y)}})},[S,p]),H=h.useCallback(V=>{S.setQueryData(Me.proposals.paginated(p),G=>{if(!G)return G;const Z=G;return{...Z,proposals:Z.proposals.filter(se=>se.id!==V),totalCount:Math.max(0,Z.totalCount-1)}})},[S,p]),P=((O=_.data)==null?void 0:O.proposals)??[],z=((ae=_.data)==null?void 0:ae.totalCount)??0,M=((te=_.data)==null?void 0:te.totalPages)??0,k=h.useRef(new Set);return h.useEffect(()=>{if(!a||!P.length)return;const V=P.filter(Z=>Z.engagement_score==null&&(Z.view_count??0)>0&&!k.current.has(Z.id));if(V.length===0)return;const G=V.slice(0,3);G.forEach(Z=>k.current.add(Z.id)),G.forEach(Z=>{F.rpc("analyze_proposal_engagement",{proposal_id_input:Z.id}).then(({data:se})=>{se&&typeof se=="object"&&"score"in se&&I(Z.id,{engagement_score:se.score,optimal_contact_hour:se.optimal_hour})})})},[a,P,I]),{proposals:P,loading:_.isLoading,refreshing:_.isFetching&&!_.isLoading,loadError:_.isError?_.error:null,pagination:{page:$,pageSize:r,totalCount:z,totalPages:M},counts:y.data??{active:0,archived:0,funded:0,fundingLost:0,total:0},countsAvailable:!!y.data&&!y.isError,loadedAt:_.isSuccess?_.dataUpdatedAt:0,goToPage:q,nextPage:A,prevPage:N,refresh:C,updateLocalProposal:I,removeLocalProposal:H}}const Bn="qcf-commission-prefill";function dm(t){try{sessionStorage.setItem(Bn,JSON.stringify(t))}catch{}}function Jb(){try{const t=sessionStorage.getItem(Bn);if(!t)return null;sessionStorage.removeItem(Bn);const s=JSON.parse(t);return!s||typeof s.businessName!="string"?null:s}catch{return null}}function ql(t={}){var H,P,z,M,k;const{userId:s,onProposalUpdated:a,onProposalRemoved:n}=t,r=Nt(),i=Qt(),l=()=>{r.invalidateQueries({queryKey:Me.proposals.all}),r.invalidateQueries({queryKey:Me.proposals.counts()}),r.invalidateQueries({queryKey:Me.leaderboard.all})},o=Le({mutationFn:w=>Xu(w),onSuccess:(w,L)=>{a==null||a(L.id,{initial_email_sent:!0}),U.success(w.logged===!1?`Email accepted for sending to ${L.email}. Inbox delivery is not yet confirmed, and it was NOT recorded in email history.`:`Email accepted for sending to ${L.email}. Inbox delivery is not yet confirmed.`)},onError:it("Failed to send email")}),c=Le({mutationFn:w=>Ju(w),onSuccess:(w,L)=>{n==null||n(L),l(),U.success("Proposal deleted successfully")},onError:it("Failed to delete proposal")}),m=Le({mutationFn:w=>Zu(w),onSuccess:(w,L)=>{l(),U.success(`${L.length} proposal${L.length>1?"s":""} deleted successfully`)},onError:it("Failed to delete proposals")}),f=Le({mutationFn:({proposalId:w})=>em(w,s),onSuccess:(w,{proposalId:L,businessName:O})=>{a==null||a(L,{is_archived:!0,archived_at:new Date().toISOString(),archive_reason:"Manually archived"}),U.success(`"${O}" archived`)},onError:it("Failed to archive proposal")}),d=Le({mutationFn:({proposalId:w,businessName:L})=>tm(w,L),onSuccess:(w,{proposalId:L,businessName:O})=>{a==null||a(L,{is_archived:!1,archived_at:null,archive_reason:null,business_slug:w,status:"pending"}),U.success(`"${O}" restored and set to pending`)},onError:it("Failed to restore proposal")}),u=Le({mutationFn:w=>sm(w,s),onSuccess:(w,L)=>{l(),U.success(`${L.length} proposal${L.length>1?"s":""} archived`)},onError:it("Failed to archive proposals")}),g=Le({mutationFn:({proposal:w,fundedAmount:L})=>am(w.id,L),onSuccess:(w,{proposal:L,fundedAmount:O})=>{l(),U.success(`"${L.business_name}" marked as funded!`,{duration:1e4,action:{label:"Log commission",onClick:()=>{dm({proposalId:L.id,businessName:L.business_name,fundedAmount:O??L.funded_amount??null}),i("/dashboard?tab=commissions")}}})},onError:it("Failed to mark as funded")}),D=Le({mutationFn:({proposal:w,reason:L})=>nm(w.id,L),onSuccess:(w,{proposal:L})=>{l(),U.success(`"${L.business_name}" marked as rejected`)},onError:it("Failed to mark as rejected")}),E=Le({mutationFn:({proposal:w,reason:L,lenderName:O})=>rm(w.id,L,O),onSuccess:(w,{proposal:L})=>{l(),U.success(`"${L.business_name}" marked as funding lost`)},onError:it("Failed to mark as funding lost")}),v=Le({mutationFn:({proposalId:w,enabled:L})=>Ml(w,L),onSuccess:(w,{proposalId:L,enabled:O})=>{a==null||a(L,{auto_followups_enabled:O}),U.success(O?"Auto follow-ups enabled":"Auto follow-ups disabled")},onError:it("Failed to update auto follow-up setting")}),x=h.useCallback(async w=>{o.mutate(w)},[o.mutate]),$=h.useCallback(async(w,L)=>confirm(`Are you sure you want to delete the proposal for ${L}? This action cannot be undone.`)?(c.mutate(w),!0):!1,[c.mutate]),T=h.useCallback(async w=>{if(w.length===0)return!1;const L=w.length;return confirm(`Are you sure you want to delete ${L} proposal${L>1?"s":""}? This action cannot be undone.`)?(m.mutate(w),!0):!1},[m.mutate]),S=h.useCallback(async(w,L)=>(f.mutate({proposalId:w,businessName:L}),!0),[f.mutate]),p=h.useCallback(async(w,L)=>(d.mutate({proposalId:w,businessName:L}),!0),[d.mutate]),_=h.useCallback(async w=>{if(w.length===0)return!1;const L=w.length;return confirm(`Archive ${L} proposal${L>1?"s":""}? They will be hidden from your active view.`)?(u.mutate(w),!0):!1},[u.mutate]),y=h.useCallback(async(w,L)=>{try{return await g.mutateAsync({proposal:w,fundedAmount:L}),!0}catch{return!1}},[g.mutateAsync]),q=h.useCallback(async(w,L)=>{try{return await D.mutateAsync({proposal:w,reason:L}),!0}catch{return!1}},[D.mutateAsync]),A=h.useCallback(async(w,L,O)=>{try{return await E.mutateAsync({proposal:w,reason:L,lenderName:O}),!0}catch{return!1}},[E.mutateAsync]),N=h.useCallback(async(w,L)=>(v.mutate({proposalId:w,enabled:L}),!0),[v.mutate]),C=Le({mutationFn:w=>om(w),onSuccess:w=>(l(),U.success("Proposal cloned! Redirecting to edit..."),w),onError:it("Failed to clone proposal")}),I=h.useCallback(async(w,L)=>{let O;try{O=await C.mutateAsync(w.id)}catch{return}if(O){let ae=`/dashboard/edit/${O}`;w.type==="funding_menu"?ae=`/edit-funding-menu/${O}`:w.type==="line_of_credit"&&(ae=`/dashboard/edit-loc/${O}`),L(ae)}},[C.mutateAsync]);return{sendEmail:x,deleteProposal:$,bulkDelete:T,archiveProposal:S,restoreProposal:p,bulkArchive:_,markAsFunded:y,rejectProposal:q,markAsFundingLost:A,toggleAutoFollowups:N,cloneProposal:I,sendingEmailFor:o.isPending?((H=o.variables)==null?void 0:H.id)??null:null,isArchiving:f.isPending?((P=f.variables)==null?void 0:P.proposalId)??null:d.isPending?((z=d.variables)==null?void 0:z.proposalId)??null:null,markingFundedFor:g.isPending?((k=(M=g.variables)==null?void 0:M.proposal)==null?void 0:k.id)??null:null,isRejecting:D.isPending,isMarkingFundingLost:E.isPending,isDeletingBulk:m.isPending,isBulkArchiving:u.isPending,cloningProposalId:C.isPending?C.variables??null:null}}function Ms(t){const s=(t==null?void 0:t.trim())??"";if(!/^\+?[\d\s().-]+$/.test(s))return null;const a=s.replace(/\D/g,"");return/^(1)?0+$/.test(a)?null:a.length===10&&!s.startsWith("+")?`+1${a}`:a.length===11&&a.startsWith("1")?`+${a}`:s.startsWith("+")&&a.length>=7&&a.length<=15?`+${a}`:null}function yr(t){const s=(t==null?void 0:t.trim())??"";return s.toLowerCase()==="[email protected]"?null:/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(s)?s:null}const um=h.lazy(()=>Ze(()=>import("./OutreachPreviewDialog-FSTchJK2.js").then(t=>t.a),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23])).then(t=>({default:t.OutreachPreviewDialog}
122))),mm={default:"text-blue-700 dark:text-blue-300",muted:"text-muted-foreground hover:text-foreground",subtle:"text-muted-foreground hover:text-blue-700 dark:hover:text-blue-300"};function fa({contact:t,tone:s="default",className:a="mt-1",presentation:n="icons",size:r="default"}){const[i,l]=h.useState(null),o=Ms(t.phone),c=yr(t.email)??"",m=!!c,f=t.client_name||t.business_name||"client",d=mm[s],u=n==="text",g=v=>{l({channel:v,proposal:{...t,phone:o,email:c},message:{scenario:"follow_up",subject:`Checking in â ${t.business_name}`,sms:"",body:"",url:""}})},D=u?`h-7 px-1.5 text-xs font-medium ${d}`:`${r==="compact"?"h-6 w-6":"h-8 w-8"} ${d} [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11`,E=r==="compact"?"h-3.5 w-3.5":"h-4 w-4";return e.jsxs("div",{className:`flex flex-wrap items-center gap-0.5 ${a}`,role:"group","aria-label":`Contact ${f}`,onClick:v=>v.stopPropagation(),onKeyDown:v=>{v.target.closest('[role="dialog"]')||v.stopPropagation()},children:[e.jsxs(We,{delayDuration:200,children:[e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx("span",{className:"inline-flex",tabIndex:o?void 0:0,children:o?e.jsx(R,{asChild:!0,variant:"ghost",size:u?"sm":"icon",className:D,children:e.jsx("a",{href:`tel:${o}`,"aria-label":`Call ${f}`,children:u?"Call":e.jsx(qt,{className:E})})}):e.jsx(R,{disabled:!0,variant:"ghost",size:u?"sm":"icon",className:D,"aria-label":`Call ${f} â no valid phone saved`,children:u?"Call":e.jsx(qt,{className:E})})})}),e.jsx(De,{children:o?`Call ${o} with your calling app`:"Add a valid phone number to this proposal"})]}),["text","email"].map(v=>{const x=!!t.id&&(v==="text"?!!o:m),$=v==="text"?ts:Be,T=v==="text"?"Text":"Email";return e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx("span",{className:"inline-flex",tabIndex:x?void 0:0,children:e.jsx(R,{type:"button",variant:"ghost",size:u?"sm":"icon",disabled:!x,"aria-label":`${T} ${f}${x?"":` â no valid ${v==="text"?"phone":"email"} saved`}`,className:D,onClick:()=>g(v),children:u?T:e.jsx($,{className:E})})})}),e.jsx(De,{children:x?`${T} ${v==="text"?o:c} · review before sending`:`Add a valid ${v==="text"?"phone number":"email address"} to this proposal`})]},v)})]}),i&&e.jsx(h.Suspense,{fallback:e.jsx("span",{role:"status",className:"text-xs",children:"Opening messageâ¦"}),children:e.jsx(um,{open:!0,channel:i.channel,proposal:i.proposal,message:i.message,onOpenChange:v=>{v||l(null)}})})]})}function hm({proposalId:t,businessName:s}){const[a,n]=h.useState(!1),[r,i]=h.useState(""),[l,o]=h.useState(!1),c=Nt(),m=async()=>{if(r.replace(/\D/g,"").length<10){U.error("Enter a valid phone number");return}o(!0);const{error:d}=await F.from("proposals").update({phone:r}).eq("id",t);if(o(!1),d){U.error("Failed to save phone number");return}U.success(`Phone added for ${s}`),n(!1),i(""),c.invalidateQueries({queryKey:["proposals"]}),c.invalidateQueries({queryKey:["kanban-proposals"]})};return e.jsxs(tr,{open:a,onOpenChange:n,children:[e.jsx(sr,{asChild:!0,children:e.jsx(R,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-orange-500 hover:text-orange-600",onClick:f=>f.stopPropagation(),children:e.jsx(Ru,{className:"h-3 w-3"})})}),e.jsxs(ar,{className:"w-56 p-3",align:"center",onClick:f=>f.stopPropagation(),onPointerDown:f=>f.stopPropagation(),children:[e.jsx("p",{className:"text-xs font-medium mb-2",children:"Add phone number"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(he,{placeholder:"(555) 123-4567",value:r,onChange:f=>i(f.target.value),className:"h-7 text-xs",onKeyDown:f=>f.key==="Enter"&&m()}),e.jsx(R,{size:"sm",className:"h-7 px-2 text-xs",onClick:m,disabled:l,children:l?"...":"Save"})]})]})]})}function Ol({score:t,size:s=40}){if(t==null)return e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"â"});const a=Math.max(0,Math.min(Number(t),100)),n=a>=70?"hsl(var(--success))":a>=40?"hsl(var(--warning))":"hsl(var(--destructive))",r=s-9;return e.jsx("div",{className:"grid place-items-center rounded-full shrink-0",style:{width:s,height:s,background:`conic-gradient(${n} ${a}%, hsl(var(--muted)) 0)`},role:"img","aria-label":`Engagement ${Math.round(a)} percent`,children:e.jsx("div",{className:"grid place-items-center rounded-full bg-card",style:{width:r,height:r},children:e.jsx("span",{className:"text-[10px] font-bold tabular-nums leading-none",children:Math.round(a)})})})}function Il({proposalId:t,size:s=8}
122){return vc(t)?e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsxs("span",{className:"relative inline-flex shrink-0",style:{width:s,height:s},"aria-label":"Client viewing right now",children:[e.jsx("span",{className:"absolute inset-0 rounded-full bg-green-500 opacity-75 animate-ping"}),e.jsx("span",{className:"relative inline-flex rounded-full bg-green-500",style:{width:s,height:s}})]})}),e.jsx(De,{side:"top",children:"Client viewing right now"})]}):null}function Ds(t){const s=n=>n.trim().toLowerCase().replace(/\./g,""),a=s(t??"");return a?ll.find(n=>[n.code,n.name,...n.aliases??[]].some(r=>s(r)===a))??null:null}function xm(t){const s=(t??"").toLowerCase();return/sole/.test(s)?"sole":/partnership/.test(s)&&!/limited/.test(s)?"general-partnership":/llc|limited liability|corp|inc\b|incorporated|limited partnership|\bllp\b|\blp\b|professional association/.test(s)?"registered":"other"}function hi(t){const s=Ds(t.formationState),a=Ds(t.addressState),n=Ds(t.ownerState),r=xm(t.entityType),i={owner:n,formation:s,address:a},l=r==="sole"?["owner","address","formation"]:r==="general-partnership"?["address","formation","owner"]:["formation","address","owner"],o=l.find(v=>i[v])??"none",c=o==="none"?null:i[o],m=r==="sole"?"Sole proprietor: liens are filed where the owner lives.":r==="general-partnership"?"General partnership: liens are filed where it does business.":r==="registered"?"Liens are filed in the state where the business was formed.":null,f={owner:"the ownerâs home state",formation:"the State of Incorporation in Salesforce",address:"the business address state"},d=l[0],u=m?`${m} `:"";let g;if(o==="none"){const v={owner:"the owner lives in",formation:"it was formed in",address:"it does business in"}[d];g=`${u}No state found in Salesforce. Pick the state ${v}.`}else if(o===d)g=`${u}Using ${f[o]}.`;else{const v={owner:"The ownerâs home state",formation:"The State of Incorporation",address:"The business address state"}[d];g=`${u}${v} isnât in Salesforce, so using ${f[o]}.`}const D=[],E=(v,x)=>{v&&v.code!==(c==null?void 0:c.code)&&!D.some($=>$.state.code===v.code)&&D.push({state:v,label:x})};return E(s,"State of Incorporation"),E(a,"Business address"),E(n,"Ownerâs address"),{state:c,basis:o,reason:g,others:D}}function Ul({open:t,onOpenChange:s,businessName:a,opportunityId:n}){var x,$;const[r,i]=h.useState({status:"loading"}),[l,o]=h.useState(a),[c,m]=h.useState(""),[f,d]=h.useState(!1);h.useEffect(()=>{if(!t)return;if(d(!1),o(a),m(""),!n){i({status:"unavailable",message:"This deal isnât linked to Salesforce, so pick the state."});return}let T=!1;return i({status:"loading"}),F.functions.invoke("salesforce-fetch-opportunity",{body:{opportunityId:n,include:"ucc"}}).then(({data:S,error:p})=>{var y;if(T)return;const _=S==null?void 0:S.ucc;if(p||!_){i({status:"unavailable",message:"Couldnât read this deal from Salesforce, so pick the state."});return}i({status:"ready",facts:_}),_.legalName&&o(_.legalName),m(((y=hi(_).state)==null?void 0:y.code)??"")}).catch(()=>{T||i({status:"unavailable",message:"Couldnât read this deal from Salesforce, so pick the state."})}),()=>{T=!0}},[t,n,a]);const u=r.status==="ready"?r.facts:null,g=h.useMemo(()=>u?hi(u):null,[u]),D=Ds(c),E=!!u&&(g==null?void 0:g.basis)==="formation"&&((x=Ds(u.formationState))==null?void 0:x.code)===(($=Ds(u.addressState))==null?void 0:$.code),v=l.trim();return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"max-w-md",children:[e.jsxs(ht,{className:"text-left",children:[e.jsx(xt,{children:"Check UCC liens"}),e.jsx(kt,{children:a})]}),r.status==="loading"?e.jsxs("p",{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",role:"status",children:[e.jsx(Ot,{className:"h-4 w-4 animate-spin","aria-hidden":!0})," Getting the legal name and state from Salesforceâ¦"]}):e.jsxs("div",{className:"min-w-0 space-y-4",children:[r.status==="unavailable"&&e.jsx("p",{className:"rounded-md bg-muted px-3 py-2 text-sm text-muted-foreground",role:"status",children:r.message}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(de,{htmlFor:"ucc-name",children:"Search this name"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(he,{id:"ucc-name",value:l,onCh
122ange:T=>o(T.target.value),className:"h-11 min-w-0"}),e.jsx(R,{type:"button",variant:"outline",className:"h-11 shrink-0",disabled:!v,onClick:()=>void Ma(v,"Name copied"),"aria-label":"Copy name",children:e.jsx(_t,{className:"h-4 w-4","aria-hidden":!0})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u!=null&&u.dba&&u.dba.toLowerCase()!==v.toLowerCase()?`DBA: ${u.dba}. Liens are filed under the legal name, not the DBA.`:"Liens are filed under the exact legal name."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(de,{htmlFor:"ucc-state",children:"State to search"}),e.jsxs("select",{id:"ucc-state",value:c,onChange:T=>m(T.target.value),className:"h-11 w-full rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:"Choose a state"}),ll.map(T=>e.jsx("option",{value:T.code,children:T.name},T.code))]}),g&&e.jsx("p",{className:"text-xs text-muted-foreground",children:g.reason}),g&&g.others.length>0&&e.jsxs("p",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:["Salesforce also lists:",g.others.map(T=>e.jsxs("button",{type:"button",className:"font-medium text-primary underline-offset-2 hover:underline",onClick:()=>m(T.state.code),children:[T.state.name," (",T.label,")"]},T.state.code))]}),E&&e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-400",children:"State of Incorporation matches the business address, which is common when it was typed from the address. If the business was formed somewhere else (Delaware is common), pick that state."}),D&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[D.agency,D.note?` · ${D.note}`:""]})]}),D&&v?e.jsx(R,{asChild:!0,className:"h-auto min-h-11 w-full whitespace-normal py-2 text-center",children:e.jsxs("a",{href:D.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>void Ma(v,null).then(d),children:[e.jsx(It,{className:"mr-2 h-4 w-4 shrink-0","aria-hidden":!0}),"Copy name and open ",D.name," UCC search"]})}):e.jsx(R,{className:"h-11 w-full",disabled:!0,children:v?"Choose a state":"Add a name to search"}),f&&D&&e.jsxs("p",{className:"text-sm text-muted-foreground",role:"status",children:["Name copied. Paste it into the search box on the ",D.name," page."]})]})]})})}function pm(t){if(typeof document>"u")return;let s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.type="text/css",s.appendChild(a),a.styleSheet?a.styleSheet.cssText=t:a.appendChild(document.createTextNode(t))}const zl=X.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),ga=()=>{const t=X.useContext(zl);if(!t)throw new Error("useDrawerContext must be used within a Drawer.Root");return t};pm(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,100%,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,-100%,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(-100%,0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(100%,0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not( 123[data-state=closed] 124){opacity:0}
124[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,100%,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,100%,0)}}@keyframes slideFromTop{from{transform:translate3d(0,-100%,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,-100%,0)}}@keyframes slideFromLeft{from{transform:translate3d(-100%,0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(-100%,0,0)}}@keyframes slideFromRight{from{transform:translate3d(100%,0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(100%,0,0)}}`);const fm=24,gm=typeof window<"u"?h.useLayoutEffect:h.useEffect;function xi(...t){return(...s)=>{for(let a of t)typeof a=="function"&&a(...s)}}function bm(){return wr(/^Mac/)}function ym(){return wr(/^iPhone/)}function pi(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function wm(){return wr(/^iPad/)||bm()&&navigator.maxTouchPoints>1}function Bl(){return ym()||wm()}function wr(t){return typeof window<"u"&&window.navigator!=null?t.test(window.navigator.platform):void 0}const _n=typeof document<"u"&&window.visualViewport;function fi(t){let s=window.getComputedStyle(t);return/(auto|scroll)/.test(s.overflow+s.overflowX+s.overflowY)}function Hl(t){for(fi(t)&&(t=t.parentElement);t&&!fi(t);)t=t.parentElement;return t||document.scrollingElement||document.documentElement}const vm=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Ca=0,Nn;function jm(t={}){let{isDisabled:s}=t;gm(()=>{if(!s)return Ca++,Ca===1&&Bl()&&(Nn=_m()),()=>{Ca--,Ca===0&&(Nn==null||Nn())}},[s])}function _m(){let t,s=0,a=d=>{t=Hl(d.target),!(t===document.documentElement&&t===document.body)&&(s=d.changedTouches[0].pageY)},n=d=>
124{if(!t||t===document.documentElement||t===document.body){d.preventDefault();return}let u=d.changedTouches[0].pageY,g=t.scrollTop,D=t.scrollHeight-t.clientHeight;D!==0&&((g<=0&&u>s||g>=D&&u<s)&&d.preventDefault(),s=u)},r=d=>{let u=d.target;Hn(u)&&u!==document.activeElement&&(d.preventDefault(),u.style.transform="translateY(-2000px)",u.focus(),requestAnimationFrame(()=>{u.style.transform=""}))},i=d=>{let u=d.target;Hn(u)&&(u.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{u.style.transform="",_n&&(_n.height<window.innerHeight?requestAnimationFrame(()=>{gi(u)}):_n.addEventListener("resize",()=>gi(u),{once:!0}))}))},l=()=>{window.scrollTo(0,0)},o=window.pageXOffset,c=window.pageYOffset,m=xi(Nm(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let f=xi(Ks(document,"touchstart",a,{passive:!1,capture:!0}),Ks(document,"touchmove",n,{passive:!1,capture:!0}),Ks(document,"touchend",r,{passive:!1,capture:!0}),Ks(document,"focus",i,!0),Ks(window,"scroll",l));return()=>{m(),f(),window.scrollTo(o,c)}}function Nm(t,s,a){let n=t.style[s];return t.style[s]=a,()=>{t.style[s]=n}}function Ks(t,s,a,n){return t.addEventListener(s,a,n),()=>{t.removeEventListener(s,a,n)}}function gi(t){let s=document.scrollingElement||document.documentElement;for(;t&&t!==s;){let a=Hl(t);if(a!==document.documentElement&&a!==document.body&&a!==t){let n=a.getBoundingClientRect().top,r=t.getBoundingClientRect().top,i=t.getBoundingClientRect().bottom;const l=a.getBoundingClientRect().bottom+fm;i>l&&(a.scrollTop+=r-n)}t=a.parentElement}}function Hn(t){return t instanceof HTMLInputElement&&!vm.has(t.type)||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&t.isContentEditable}function km(t,s){typeof t=="function"?t(s):t!=null&&(t.current=s)}function Sm(...t){return s=>t.forEach(a=>km(a,s))}function Vl(...t){return h.useCallback(Sm(...t),t)}const Wl=new WeakMap;function He(t,s,a=!1){if(!t||!(t instanceof HTMLElement))return;let n={};Object.entries(s).forEach(([r,i])=>{if(r.startsWith("--")){t.style.setProperty(r,i);return}n[r]=t.style[r],t.style[r]=i}),!a&&Wl.set(t,n)}function Cm(t,s){if(!t||!(t instanceof HTMLElement))return;let a=Wl.get(t);a&&(t.style[s]=a[s])}const Ve=t=>{switch(t){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return t}};function Da(t,s){if(!t)return null;const a=window.getComputedStyle(t),n=a.transform||a.webkitTransform||a.mozTransform;let r=n.match(/^matrix3d\((.+)\)$/);return r?parseFloat(r[1].split(", ")[Ve(s)?13:12]):(r=n.match(/^matrix\((.+)\)$/),r?parseFloat(r[1].split(", ")[Ve(s)?5:4]):null)}function Dm(t){return 8*(Math.log(t+1)-2)}function kn(t,s){if(!t)return()=>{};const a=t.style.cssText;return Object.assign(t.style,s),()=>{t.style.cssText=a}}function Tm(...t){return(...s)=>{for(const a of t)typeof a=="function"&&a(...s)}}const Re={DURATION:.5,EASE:[.32,.72,0,1]},Kl=.4,Em=.25,$m=100,Yl=8,is=16,Vn=26,Sn="vaul-dragging";function Ql(t){const s=X.useRef(t);return X.useEffect(()=>{s.current=t}),X.useMemo(()=>(...a)=>s.current==null?void 0:s.current.call(s,...a),[])}function Am({defaultProp:t,onChange:s}){const a=X.useState(t),[n]=a,r=X.useRef(n),i=Ql(s);return X.useEffect(()=>{r.current!==n&&(i(n),r.current=n)},[n,r,i]),a}function Gl({prop:t,defaultProp:s,onChange:a=()=>{}}){const[n,r]=Am({defaultProp:s,onChange:a}),i=t!==void 0,l=i?t:n,o=Ql(a),c=X.useCallback(m=>{if(i){const d=typeof m=="function"?m(t):m;d!==t&&o(d)}else r(m)},[i,t,r,o]);return[l,c]}function Pm({activeSnapPointProp:t,setActiveSnapPointProp:s,snapPoints:a,drawerRef:n,overlayRef:r,fadeFromIndex:i,onSnapPointChange:l,direction:o="bottom",container:c,snapToSequentialPoint:m}){const[f,d]=Gl({prop:t,defaultProp:a==null?void 0:a[0],onChange:s}),[u,g]=X.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);X.useEffect(()=>{function y(){g({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[]);const D=X.useMemo(()=>f===(a==null?void 0:a[a.length-1])||null,[a,f]),E=X.useMemo(()=>a==null?void 0:a.findIndex(y=>y===f),[a,f]),v=a&&a.length>0&&(i||i===0)&&!Number.isNaN(i)&&a[i]===f||!a,x=X.useMemo(()=>{const y=c?{width:c.getBoundingClientRect().width,height:c.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var q;return(q=a==null?void 0:a.map(A=>{const N=typeof A=="string";let C=0;if(N&&(C=parseInt(A,10)),Ve(o)){const H=N?C:u?A*y.height:0;return u?o==="bottom"?y.height-H:-y.height+H:H}const I=N?C:u?A*y.width:0;return u?o==="right"?y.width-I:-y.width+I:I}))!=null?q:[]},[a,u,c]),$=X.useMemo(()=>E!==null?x==null?void 0:x[E]:null,[x,E]),T=X.useCallback(y=>{var q;const A=(q=x==null?void 0:x.findIndex(N=>N===y))!=null?q:null;l(A),He(n.current,{transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,transform:Ve(o)?`translate3d(0, ${y}px, 0)`:`translate3d(${y}px, 0, 0)`}),x&&A!==x.length-1&&A!==i&&A<i?He(r.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,opacity:"0"}):He(r.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,opacity:"1"}),d(a==null?void 0:a[Math.max(A,0)])},[n.current,a,x,i,r,d]);X.useEffect(()=>{if(f||t){var y;const q=(y=a==null?void 0:a.findIndex(A=>A===t||A===f))!=null?y:-1;x&&q!==-1&&typeof x[q]=="number"&&T(x[q])}},[f,t,a,x,T]);function S({draggedDistance:y,closeDrawer:q,velocity:A,dismissible:N}){if(i===void 0)return;const C=o==="bottom"||o==="right"?($??0)-y:($??0)+y,I=E===i-1,H=E===0,P=y>0;if(I&&He(r.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`}),!m&&A>2&&!P){N?q():T(x[0]);return}if(!m&&A>2&&P&&x&&a){T(x[a.length-1]);return}const z=x==null?void 0:x.reduce((k,w)=>typeof k!="number"||typeof w!="number"?k:Math.abs(w-C)<Math.abs(k-C)?w:k),M=Ve(o)?window.innerHeight:window.innerWidth;if(A>Kl&&Math.abs(y)<M*.4){const k=P?1:-1;if(k>0&&D){T(x[a.length-1]);return}if(H&&k<0&&N&&q(),E===null)return;T(x[E+k]);return}T(z)}function p({draggedDistance:y}){if($===null)return;const q=o==="bottom"||o==="right"?$-y:$+y;(o==="bottom"||o==="right")&&q<x[x.length-1]||(o==="top"||o==="left")&&q>x[x.length-1]||He(n.current,{transform:Ve(o)?`translate3d(0, ${q}px, 0)`:`translate3d(${q}px, 0, 0)`})}function _(y,q){if(!a||typeof E!="number"||!x||i===void 0)return null;const A=E===i-1;if(E>=i&&q)return 0;if(A&&!q)return 1;if(!v&&!A)return null;const C=A?E+1:E-1,I=A?x[C]-x[C-1]:x[C+1]-x[C],H=y/Math.abs(I);return A?1-H:H}return{isLastSnapPoint:D,activeSnapPoint:f,shouldFade:v,getPercentageDragged:_,setActiveSnapPoint:d,activeSnapPointIndex:E,onRelease:S,onDrag:p,snapPointsOffset:x}}const Rm=()=>()=>{};
124function Fm(){const{direction:t,isOpen:s,shouldScaleBackground:a,setBackgroundColorOnScale:n,noBodyStyles:r}=ga(),i=X.useRef(null),l=h.useMemo(()=>document.body.style.backgroundColor,[]);function o(){return(window.innerWidth-Vn)/window.innerWidth}X.useEffect(()=>{if(s&&a){i.current&&clearTimeout(i.current);const c=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!c)return;Tm(n&&!r?kn(document.body,{background:"black"}):Rm,kn(c,{transformOrigin:Ve(t)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Re.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Re.EASE.join(",")})`}));const m=kn(c,{borderRadius:`${Yl}px`,overflow:"hidden",...Ve(t)?{transform:`scale(${o()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${o()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{m(),i.current=window.setTimeout(()=>{l?document.body.style.background=l:document.body.style.removeProperty("background")},Re.DURATION*1e3)}}},[s,a,l])}let Ys=null;function Lm({isOpen:t,modal:s,nested:a,hasBeenOpened:n,preventScrollRestoration:r,noBodyStyles:i}){const[l,o]=X.useState(()=>typeof window<"u"?window.location.href:""),c=X.useRef(0),m=X.useCallback(()=>{if(pi()&&Ys===null&&t&&!i){Ys={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:d,innerHeight:u}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-c.current}px`,left:`${-d}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const g=u-window.innerHeight;g&&c.current>=u&&(document.body.style.top=`${-(c.current+g)}px`)}),300)}},[t]),f=X.useCallback(()=>{if(pi()&&Ys!==null&&!i){const d=-parseInt(document.body.style.top,10),u=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Ys),window.requestAnimationFrame(()=>{if(r&&l!==window.location.href){o(window.location.href);return}window.scrollTo(u,d)}),Ys=null}},[l]);return X.useEffect(()=>{function d(){c.current=window.scrollY}return d(),window.addEventListener("scroll",d),()=>{window.removeEventListener("scroll",d)}},[]),X.useEffect(()=>{a||!n||(t?(!window.matchMedia("(display-mode: standalone)").matches&&m(),s||window.setTimeout(()=>{f()},500)):f())},[t,n,l,s,a,m,f]),{restorePositionSetting:f}}function Mm({open:t,onOpenChange:s,children:a,onDrag:n,onRelease:r,snapPoints:i,shouldScaleBackground:l=!1,setBackgroundColorOnScale:o=!0,closeThreshold:c=Em,scrollLockTimeout:m=$m,dismissible:f=!0,handleOnly:d=!1,fadeFromIndex:u=i&&i.length-1,activeSnapPoint:g,setActiveSnapPoint:D,fixed:E,modal:v=!0,onClose:x,nested:$,noBodyStyles:T,direction:S="bottom",defaultOpen:p=!1,disablePreventScroll:_=!0,snapToSequentialPoint:y=!1,preventScrollRestoration:q=!1,repositionInputs:A=!0,onAnimationEnd:N,container:C,autoFocus:I=!1}){var H,P;const[z=!1,M]=Gl({defaultProp:p,prop:t,onChange:re=>{s==null||s(re),!re&&!$&&Gt(),setTimeout(()=>{N==null||N(re)},Re.DURATION*1e3),re&&!v&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),re||(document.body.style.pointerEvents="auto")}}),[k,w]=X.useState(!1),[L,O]=X.useState(!1),[ae,te]=X.useState(!1),V=X.useRef(null),G=X.useRef(null),Z=X.useRef(null),se=X.useRef(null),Y=X.useRef(null),ne=X.useRef(!1),fe=X.useRef(null),_e=X.useRef(0),ge=X.useRef(!1),me=X.useRef(0),b=X.useRef(null),W=X.useRef(((H=b.current)==null?void 0:H.getBoundingClientRect().height)||0),oe=X.useRef(((P=b.current)==null?void 0:P.getBoundingClientRect().width)||0),B=X.useRef(0),Q=X.useCallback(re=>{i&&re===Fe.length-1&&(G.current=new Date)},[]),{activeSnapPoint:ie,activeSnapPointIndex:ue,setActiveSnapPoint:Ee,onRelease:Ye,snapPointsOffset:Fe,onDrag:gs,shouldFade:ns,getPercentageDragged:Dt}=Pm({snapPoints:i,activeSnapPointProp:g,setActiveSnapPointProp:D,drawerRef:b,fadeFromIndex:u,overlayRef:V,onSnapPointChange:Q,direction:S,container:C,snapToSequentialPoint:y});jm({isDisabled:!z||L||!v||ae||!k||!A||!_});const{restorePositionSetting:Gt}=Lm({isOpen:z,modal:v,nested:$,hasBeenOpened:k,preventScrollRestoration:q,noBodyStyles:T});function Xt(){return(window.innerWidth-Vn)/window.innerWidth}function K(re){var ce,we;!f&&!i||b.current&&!b.current.contains(re.target)||(W.current=((ce=b.current)==null?void 0:ce.getBoundingClientRect().height)||0,oe.current=((we=b.current)==null?void 0:we.getBoundingClientRect().width)||0,O(!0),Z.current=ne
124w Date,Bl()&&window.addEventListener("touchend",()=>ne.current=!1,{once:!0}),re.target.setPointerCapture(re.pointerId),_e.current=Ve(S)?re.pageY:re.pageX)}function qe(re,ce){var we,Ne;let xe=re;const Ge=(we=window.getSelection())==null?void 0:we.toString(),Oe=b.current?Da(b.current,S):null,tt=new Date;if(xe.hasAttribute("data-vaul-no-drag")||xe.closest("[data-vaul-no-drag]"))return!1;if(S==="right"||S==="left")return!0;if(G.current&&tt.getTime()-G.current.getTime()<500)return!1;if(Oe!==null&&(S==="bottom"?Oe>0:Oe<0))return!0;if(Ge&&Ge.length>0)return!1;if(tt.getTime()-((Ne=Y.current)==null?void 0:Ne.getTime())<m&&Oe===0||ce)return Y.current=tt,!1;for(;xe;){if(xe.scrollHeight>xe.clientHeight){if(xe.scrollTop!==0)return Y.current=new Date,!1;if(xe.getAttribute("role")==="dialog")return!0}xe=xe.parentNode}return!0}function et(re){if(b.current&&L){const ce=S==="bottom"||S==="right"?1:-1,we=(_e.current-(Ve(S)?re.pageY:re.pageX))*ce,Ne=we>0,xe=i&&!f&&!Ne;if(xe&&ue===0)return;const Ge=Math.abs(we),Oe=document.querySelector("[data-vaul-drawer-wrapper]"),tt=S==="bottom"||S==="top"?W.current:oe.current;let st=Ge/tt;
124const Tt=Dt(Ge,Ne);if(Tt!==null&&(st=Tt),xe&&st>=1||!ne.current&&!qe(re.target,Ne))return;if(b.current.classList.add(Sn),ne.current=!0,He(b.current,{transition:"none"}),He(V.current,{transition:"none"}),i&&gs({draggedDistance:we}),Ne&&!i){const rt=Dm(we),Bt=Math.min(rt*-1,0)*ce;He(b.current,{transform:Ve(S)?`translate3d(0, ${Bt}px, 0)`:`translate3d(${Bt}px, 0, 0)`});return}const zt=1-st;if((ns||u&&ue===u-1)&&(n==null||n(re,st),He(V.current,{opacity:`${zt}`,transition:"none"},!0)),Oe&&V.current&&l){const rt=Math.min(Xt()+st*(1-Xt()),1),Bt=8-st*8,ba=Math.max(0,14-st*14);He(Oe,{borderRadius:`${Bt}px`,transform:Ve(S)?`scale(${rt}) translate3d(0, ${ba}px, 0)`:`scale(${rt}) translate3d(${ba}px, 0, 0)`,transition:"none"},!0)}if(!i){const rt=Ge*ce;He(b.current,{transform:Ve(S)?`translate3d(0, ${rt}px, 0)`:`translate3d(${rt}px, 0, 0)`})}}}X.useEffect(()=>{var re;function ce(){if(!b.current||!A)return;const we=document.activeElement;if(Hn(we)||ge.current){var Ne;const xe=((Ne=window.visualViewport)==null?void 0:Ne.height)||0,Ge=window.innerHeight;let Oe=Ge-xe;const tt=b.current.getBoundingClientRect().height||0,st=tt>Ge*.8;B.current||(B.current=tt);const Tt=b.current.getBoundingClientRect().top;if(Math.abs(me.current-Oe)>60&&(ge.current=!ge.current),i&&i.length>0&&Fe&&ue){const zt=Fe[ue]||0;Oe+=zt}if(me.current=Oe,tt>xe||ge.current){const zt=b.current.getBoundingClientRect().height;let rt=zt;zt>xe&&(rt=xe-(st?Tt:Vn)),E?b.current.style.height=`${zt-Math.max(Oe,0)}px`:b.current.style.height=`${Math.max(rt,xe-Tt)}px`}else b.current.style.height=`${B.current}px`;i&&i.length>0&&!ge.current?b.current.style.bottom="0px":b.current.style.bottom=`${Math.max(Oe,0)}px`}}return(re=window.visualViewport)==null||re.addEventListener("resize",ce),()=>{var we;return(we=window.visualViewport)==null?void 0:we.removeEventListener("resize",ce)}},[ue,i,Fe]);function Qe(re){yt(),x==null||x(),re||M(!1),setTimeout(()=>{i&&Ee(i[0])},Re.DURATION*1e3)}function Ue(){if(!b.current)return;const re=document.querySelector("[data-vaul-drawer-wrapper]"),ce=Da(b.current,S);He(b.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`}),He(V.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,opacity:"1"}),l&&ce&&ce>0&&z&&He(re,{borderRadius:`${Yl}px`,overflow:"hidden",...Ve(S)?{transform:`scale(${Xt()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${Xt()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${Re.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Re.EASE.join(",")})`},!0)}function yt(){!L||!b.current||(b.current.classList.remove(Sn),ne.current=!1,O(!1),se.current=new Date)}function Ae(re){if(!L||!b.current)return;b.current.classList.remove(Sn),ne.current=!1,O(!1),se.current=new Date;const ce=Da(b.current,S);
124if(!qe(re.target,!1)||!ce||Number.isNaN(ce)||Z.current===null)return;const we=se.current.getTime()-Z.current.getTime(),Ne=_e.current-(Ve(S)?re.pageY:re.pageX),xe=Math.abs(Ne)/we;if(xe>.05&&(te(!0),setTimeout(()=>{te(!1)},200)),i){Ye({draggedDistance:Ne*(S==="bottom"||S==="right"?1:-1),closeDrawer:Qe,velocity:xe,dismissible:f}),r==null||r(re,!0);return}if(S==="bottom"||S==="right"?Ne>0:Ne<0){Ue(),r==null||r(re,!0);return}if(xe>Kl){Qe(),r==null||r(re,!1);return}var Ge;const Oe=Math.min((Ge=b.current.getBoundingClientRect().height)!=null?Ge:0,window.innerHeight);var tt;const st=Math.min((tt=b.current.getBoundingClientRect().width)!=null?tt:0,window.innerWidth),Tt=S==="left"||S==="right";if(Math.abs(ce)>=(Tt?st:Oe)*c){Qe(),r==null||r(re,!1);return}r==null||r(re,!0),Ue()}X.useEffect(()=>(z&&(He(document.documentElement,{scrollBehavior:"auto"}),G.current=new Date),()=>{Cm(document.documentElement,"scrollBehavior")}),[z]);function pt(re){const ce=re?(window.innerWidth-is)/window.innerWidth:1,we=re?-is:0;fe.current&&window.clearTimeout(fe.current),He(b.current,{transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,transform:`scale(${ce}) translate3d(0, ${we}px, 0)`}),!re&&b.current&&(fe.current=setTimeout(()=>{const Ne=Da(b.current,S);He(b.current,{transition:"none",transform:Ve(S)?`translate3d(0, ${Ne}px, 0)`:`translate3d(${Ne}px, 0, 0)`})},500))}function Pe(re,ce){if(ce<0)return;const we=(window.innerWidth-is)/window.innerWidth,Ne=we+ce*(1-we),xe=-is+ce*is;He(b.current,{transform:Ve(S)?`scale(${Ne}) translate3d(0, ${xe}px, 0)`:`scale(${Ne}) translate3d(${xe}px, 0, 0)`,transition:"none"})}function wt(re,ce){const we=Ve(S)?window.innerHeight:window.innerWidth,Ne=ce?(we-is)/we:1,xe=ce?-is:0;ce&&He(b.current,{transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,transform:Ve(S)?`scale(${Ne}) translate3d(0, ${xe}px, 0)`:`scale(${Ne}) translate3d(${xe}px, 0, 0)`})}return X.createElement(ed,{defaultOpen:p,onOpenChange:re=>{!f&&!re||(re?w(!0):Qe(!0),M(re))},open:z},X.createElement(zl.Provider,{value:{activeSnapPoint:ie,snapPoints:i,setActiveSnapPoint:Ee,drawerRef:b,overlayRef:V,onOpenChange:s,onPress:K,onRelease:Ae,onDrag:et,dismissible:f,handleOnly:d,isOpen:z,isDragging:L,shouldFade:ns,closeDrawer:Qe,onNestedDrag:Pe,onNestedOpenChange:pt,onNestedRelease:wt,keyboardIsOpen:ge,modal:v,snapPointsOffset:Fe,direction:S,shouldScaleBackground:l,setBackgroundColorOnScale:o,noBodyStyles:T,container:C,autoFocus:I}},a))}const Xl=X.forwardRef(function({...t},s){const{overlayRef:a,snapPoints:n,onRelease:r,shouldFade:i,isOpen:l,modal:o}=ga(),c=Vl(s,a),m=n&&n.length>0;return o?X.createElement(ad,{onMouseUp:r,ref:c,"data-vaul-overlay":"","data-vaul-snap-points":l&&m?"true":"false","data-vaul-snap-points-overlay":l&&i?"true":"false",...t}):(typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),null)});Xl.displayName="Drawer.Overlay";const Jl=X.forwardRef(function({onPointerDownOutside:t,style:s,onOpenAutoFocus:a,...n},r){const{drawerRef:i,onPress:l,onRelease:o,onDrag:c,keyboardIsOpen:m,snapPointsOffset:f,modal:d,isOpen:u,direction:g,snapPoints:D,container:E,handleOnly:v,autoFocus:x}=ga(),[$,T]=X.useState(!1),S=Vl(r,i),p=X.useRef(null),_=X.useRef(null),y=X.useRef(!1),q=D&&D.length>0;Fm();const A=(C,I,H=0)=>{if(y.current)return!0;const P=Math.abs(C.y),z=Math.abs(C.x),M=z>P,k=["bottom","right"].includes(I)?1:-1;if(I==="left"||I==="right"){if(!(C.x*k<0)&&z>=0&&z<=H)return M}else if(!(C.y*k<0)&&P>=0&&P<=H)return!M;return y.current=!0,!0};X.useEffect(()=>{q&&window.requestAnimationFrame(()=>{T(!0)})},[]);function N(C){p.current=null,y.current=!1,o(C)}return X.createElement(sd,{"data-vaul-drawer-direction":g,"data-vaul-drawer":"","data-vaul-delayed-snap-points":$?"true":"false","data-vaul-snap-points":u&&q?"true":"false","data-vaul-custom-container":E?"true":"false",...n,ref:S,style:f&&f.length>0?{"--snap-point-height":`${f[0]}px`,...s}:s,onPointerDown:C=>{v||(n.onPointerDown==null||n.onPointerDown.call(n,C),p.current={x:C.pageX,y:C.pageY},l(C))},onOpenAutoFocus:C=>{a==null||a(C),x||C.preventDefault()},onPointerDownOutside:C=>{if(t==null||t(C),!d||C.defaultPrevented){C.preventDefault();return}m.current&&(m.current=!1)},onFocusOutside:C=>{if(!d){C.preventDefault();return}},onPointerMove:C=>{if(_.current=C,v||(n.onPointerMove==null||n.onPointerMove.call(n,C),!p.current))return;const I=C.pageY-p.current.y,H=C.pageX-p.current.x,P=C.pointerType==="touch"?10:2;A({x:H,y:I},g,P)?c(C):(Math.abs(H)>P||Math.abs(I)>P)&&(p.current=null)},onPointerUp:C=>{n.onPointerUp==null||n.onPointerUp.call(n,C),p.current=null,y.current=!1,o(C)},onPointerOut:C=>{n.onPointerOut==null||n.onPointerOut.call(n,C),N(_.current)},onContextMenu:C=>{n.onContextMenu==null||n.onContextMenu.call(n,C),N(_.current)}})});Jl.displayName="Drawer.Content";const qm=250,Om=120,Im=X.forwardRef(function({preventCycle:t=!1,children:s,...a},n){const{closeDrawer:r,isDragging:i,snapPoints:l,activeSnapPoint:o,setActiveSnapPoint:c,dismissible:m,handleOnly:f,isOpen:d,onPress:u,onDrag:g}=ga(),D=X.useRef(null),E=X.useRef(!1);function v(){if(E.current){T();return}window.setTimeout(()=>{x()},Om)}function x(){if(i||t||E.current){T();return}if(T(),(!l||l.length===0)&&m){r();return}if(o===l[l.length-1]&&m){r();return}const p=l.findIndex(y=>y===o);if(p===-1)return;const _=l[p+1];c(_)}function $(){D.current=window.setTimeout(()=>{E.current=!0},qm)}function T(){window.clearTimeout(D.current),E.current=!1}return X.createElement("div",{onClick:v,onPointerCancel:T,onPointerDown:S=>{f&&u(S),$()},onPointerMove:S=>{f&&g(S)},ref:n,"data-vaul-drawer-visible":d?"true":"false","data-vaul-handle":"","aria-hidden":"true",...a},X.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},s))});Im.displayName="Drawer.Handle";
124function Um(t){const s=ga(),{container:a=s.container,...n}=t;return X.createElement(td,{container:a,...n})}const Ut={Root:Mm,Content:Jl,Overlay:Xl,Trigger:Jc,Portal:Um,Title:Zc,Description:nd},Zl=({shouldScaleBackground:t=!0,...s})=>e.jsx(Ut.Root,{shouldScaleBackground:t,...s});Zl.displayName="Drawer";const zm=Ut.Trigger,Bm=Ut.Portal,eo=h.forwardRef(({className:t,...s},a)=>e.jsx(Ut.Overlay,{ref:a,className:dt("fixed inset-0 z-50 bg-black/80",t),...s}));eo.displayName=Ut.Overlay.displayName;const to=h.forwardRef(({className:t,children:s,...a},n)=>e.jsxs(Bm,{children:[e.jsx(eo,{}),e.jsxs(Ut.Content,{ref:n,className:dt("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",t),...a,children:[e.jsx("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),s]})]}));to.displayName="DrawerContent";const so=({className:t,...s})=>e.jsx("div",{className:dt("grid gap-1.5 p-4 text-center sm:text-left",t),...s});so.displayName="DrawerHeader";const ao=h.forwardRef(({className:t,...s},a)=>e.jsx(Ut.Title,{ref:a,className:dt("text-lg font-semibold leading-none tracking-tight",t),...s}));ao.displayName=Ut.Title.displayName;const Hm=h.forwardRef(({className:t,...s},a)=>e.jsx(Ut.Description,{ref:a,className:dt("text-sm text-muted-foreground",t),...s}));Hm.displayName=Ut.Description.displayName;const Vm=({proposalId:t,clientName:s,businessName:a,autoFollowupsEnabled:n,onUpdate:r})=>{const[i,l]=h.useState(!1),[o,c]=h.useState(!1),[m,f]=h.useState(!1),[d,u]=h.useState(n),[g,D]=h.useState({day1:{subject:"",openingLine:"",closingLine:"",enabled:!0},day2:{subject:"",openingLine:"",closingLine:"",enabled:!0},day3:{subject:"",openingLine:"",closingLine:"",enabled:!0}});h.useEffect(()=>{i&&E()},[i,t]);const E=async()=>{var _,y,q,A,N,C,I,H,P,z,M,k;c(!0);try{const{data:w,error:L}=await F.from("follow_up_settings").select("email_customizations, auto_followups_enabled").eq("proposal_id",t).maybeSingle();if(L)throw L;if(w){u(w.auto_followups_enabled??!0);const O=w.email_customizations;O&&D({day1:{subject:String(((_=O.day1)==null?void 0:_.subject)||""),openingLine:String(((y=O.day1)==null?void 0:y.openingLine)||""),closingLine:String(((q=O.day1)==null?void 0:q.closingLine)||""),enabled:!!(((A=O.day1)==null?void 0:A.enabled)??!0)},day2:{subject:String(((N=O.day2)==null?void 0:N.subject)||""),openingLine:String(((C=O.day2)==null?void 0:C.openingLine)||""),closingLine:String(((I=O.day2)==null?void 0:I.closingLine)||""),enabled:!!(((H=O.day2)==null?void 0:H.enabled)??!0)},day3:{subject:String(((P=O.day3)==null?void 0:P.subject)||""),openingLine:String(((z=O.day3)==null?void 0:z.openingLine)||""),closingLine:String(((M=O.day3)==null?void 0:M.closingLine)||""),enabled:!!(((k=O.day3)==null?void 0:k.enabled)??!0)}})}}catch(w){console.error("Error loading email customizations:",w)}finally{c(!1)}},v=async()=>{f(!0);try{const{error:_}=await F.from("proposals").update({auto_followups_enabled:d}).eq("id",t);if(_)throw _;const{error:y}=await F.from("follow_up_settings").upsert({proposal_id:t,auto_followups_enabled:d,email_customizations:g,sequence_emails_enabled:d,updated_at:new Date().toISOString()},{onConflict:"proposal_id"});if(y)throw y;U.success("Email settings saved successfully"),l(!1),r==null||r()}catch(_){console.error("Error saving email customizations:",_),U.error("Failed to save email settings")}finally{f(!1)}},x=(_,y,q)=>{D(A=>({...A,[_]:{...A[_],[y]:q}}))},$=_=>{switch(_){case 1:return`Quick question about your funding, ${s.split(" ")[0]}`;case 2:return`${a} funding update - important next steps`;case 3:return`Last call: Your ${a} funding proposal`;default:return""}},T=_=>{switch(_){case 1:return`Hi ${s.split(" ")[0]}, I wanted to follow up on the funding proposal I sent over.`;case 2:return`Hi ${s.split(" ")[0]}, I noticed you haven't had a chance to review your funding options yet.`;case 3:return`Hi ${s.split(" ")[0]}, I wanted to reach out one more time before your proposal expires.`;default:return""}},S=_=>{switch(_){case 1:return"Let me know if you have any questions - I'm here to help!";
124case 2:return"Would you be available for a quick call to discuss your options?";case 3:return"Don't miss out on this opportunity - the offer expires soon!";default:return""}},p=(_,y)=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(de,{className:"text-sm font-medium",children:["Enable Day ",y," Email"]}),e.jsx(ta,{checked:g[_].enabled,onCheckedChange:q=>x(_,"enabled",q)})]}),e.jsxs("div",{className:"space-y-3 opacity-100 transition-opacity",style:{opacity:g[_].enabled?1:.5},children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(de,{className:"text-xs text-muted-foreground",children:"Subject Line"}),e.jsx(he,{placeholder:$(y),value:g[_].subject,onChange:q=>x(_,"subject",q.target.value),disabled:!g[_].enabled,className:"h-9"}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:['Leave blank to use default: "',$(y),'"']})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(de,{className:"text-xs text-muted-foreground",children:"Opening Line"}),e.jsx(Rt,{placeholder:T(y),value:g[_].openingLine,onChange:q=>x(_,"openingLine",q.target.value),disabled:!g[_].enabled,className:"min-h-[60
124px] text-sm"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Customize how the email starts after the greeting"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(de,{className:"text-xs text-muted-foreground",children:"Closing Line"}),e.jsx(Rt,{placeholder:S(y),value:g[_].closingLine,onChange:q=>x(_,"closingLine",q.target.value),disabled:!g[_].enabled,className:"min-h-[60px] text-sm"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Customize the call-to-action before the signature"})]})]})]});return e.jsxs(ut,{open:i,onOpenChange:l,children:[e.jsx(il,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1.5 text-xs",children:[e.jsx(rd,{className:"h-3 w-3"}),"Edit Emails"]})}),e.jsxs(mt,{className:"sm:max-w-lg",children:[e.jsx(ht,{children:e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-4 w-4"}),"Edit Email Sequence"]})}),o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ot,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between py-2 px-3 bg-muted/50 rounded-lg mb-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(de,{className:"text-sm font-medium",children:"Auto Follow-ups"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d?"Emails will be sent automatically at 7:00 AM PST":"All automated emails are paused"})]}),e.jsx(ta,{checked:d,onCheckedChange:u})]}),e.jsxs(qn,{defaultValue:"day1",className:"w-full",children:[e.jsxs(On,{className:"grid w-full grid-cols-3",children:[e.jsxs($t,{value:"day1",className:"text-xs flex items-center gap-1",children:["Day 1",g.day1.enabled&&e.jsx(At,{className:"h-3 w-3 text-green-600"})]}),e.jsxs($t,{value:"day2",className:"text-xs flex items-center gap-1",children:["Day 2",g.day2.enabled&&e.jsx(At,{className:"h-3 w-3 text-green-600"})]}),e.jsxs($t,{value:"day3",className:"text-xs flex items-center gap-1",children:["Day 3",g.day3.enabled&&e.jsx(At,{className:"h-3 w-3 text-green-600"})]})]}),e.jsxs(ua,{className:"h-[300px] mt-4",children:[e.jsx(Ie,{value:"day1",className:"mt-0 pr-4",children:p("day1",1)}),e.jsx(Ie,{value:"day2",className:"mt-0 pr-4",children:p("day2",2)}),e.jsx(Ie,{value:"day3",className:"mt-0 pr-4",children:p("day3",3)})]})]})]}),e.jsxs(da,{children:[e.jsx(R,{variant:"outline",onClick:()=>l(!1),disabled:m,children:"Cancel"}),e.jsx(R,{onClick:v,disabled:m||o,children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(id,{className:"h-4 w-4 mr-2"}),"Save Changes"]})})]})]})]})},no=({proposalId:t,proposalCreatedAt:s,expirationDate:a,status:n,initialEmailSent:r,autoFollowupsEnabled:i,compact:l=!1,clientName:o="",businessName:c=""})=>{const[m,f]=h.useState([]),[d,u]=h.useState(!0),[g,D]=h.useState(!1),[E,v]=h.useState(i);h.useEffect(()=>{x()},[t,i,n]);const x=async()=>{u(!0);try{const{data:y,error:q}=await F.from("automated_emails").select("id, email_type, sent_at, status, trigger_reason").eq("proposal_id",t).order("sent_at",{ascending:!0});if(q)throw q;const{data:A,error:N}=await F.from("email_logs").select("id, template_type, sent_at, status, html_content").eq("proposal_id",t).order("sent_at",{ascending:!0});if(N)throw N;const C=[],I=new Date(s),H=new Date,P=new Set((y==null?void 0:y.map(ne=>ne.email_type))||[]),z=new Set((A==null?void 0:A.map(ne=>ne.template_type))||[]),M=ka(I,1);M.setUTCHours(15,0,0,0);const k=P.has("sequence_day_1")||z.has("sequence_day_1"),w=y==null?void 0:y.find(ne=>ne.email_type==="sequence_day_1"),L=A==null?void 0:A.find(ne=>ne.template_type==="sequence_day_1");C.push({type:"sequence_day_1",label:"Day 1 Sequence",status:k?"sent":i&&r?n!=="pending"?"skipped":(Sa(H,M),"scheduled"):"blocked",scheduledDate:M,sentAt:(w==null?void 0:w.sent_at)??void 0,reason:i?r?n!=="pending"?`Proposal status: ${n}`:"Sends at 7:00 AM PST":"Initial email not sent":"Auto follow-ups disabled",emailLogId:L==null?void 0:L.id});const O=ka(I,2);O.setUTCHours(15,0,0,0);const ae=P.has("sequence_day_2")||z.has("sequence_day_2"),te=y==null?void 0:y.find(ne=>ne.email_type==="sequence_day_2"),V=A==null?void 0:A.find(ne=>ne.template_type==="sequence_day_2");C.push({type:"sequence_day_2",label:"Day 2 Sequence",status:ae?"sent":i&&r?n!=="pending"?"skipped":"scheduled":"blocked",scheduledDate:O,sentAt:(te==null?void 0:te.sent_at)??void 0,reason:i?r?n!=="pending"?`Proposal status: ${n}`:"Sends at 7:00 AM PST":"Initial email not sent":"Auto follow-ups disabled",emailLogId:V==null?void 0:V.id});const G=ka(I,3);G.setUTCHours(15,0,0,0);const Z=P.has("sequence_day_3")||z.has("sequence_day_3"),se=y==null?void 0:y.find(ne=>ne.email_type==="sequence_day_3"),Y=A==null?void 0:A.find(ne=>ne.template_type==="sequence_day_3");
124if(C.push({type:"sequence_day_3",label:"Day 3 Sequence",status:Z?"sent":i&&r?n!=="pending"?"skipped":"scheduled":"blocked",scheduledDate:G,sentAt:(se==null?void 0:se.sent_at)??void 0,reason:i?r?n!=="pending"?`Proposal status: ${n}`:"Sends at 7:00 AM PST":"Initial email not sent":"Auto follow-ups disabled",emailLogId:Y==null?void 0:Y.id}),a&&n==="pending"){const ne=new Date(a),fe=Ou(H,I),_e=Z||fe>=3;for(const ge of[7,3,1]){const me=ka(ne,-ge),b=y==null?void 0:y.some(Q=>{var ie;return Q.email_type==="expiration_reminder"&&((ie=Q.trigger_reason)==null?void 0:ie.includes(`${ge} days`))}),W=y==null?void 0:y.find(Q=>{var ie;return Q.email_type==="expiration_reminder"&&((ie=Q.trigger_reason)==null?void 0:ie.includes(`${ge} days`))}),oe=Sa(me,H),B=r&&!_e&&Sa(me,G);C.push({type:`expiration_${ge}d`,label:`${ge}-Day Expiration`,status:b?"sent":i?B?"blocked":oe&&!b||Sa(me,H)?"skipped":"scheduled":"blocked",scheduledDate:me,sentAt:(W==null?void 0:W.sent_at)??void 0,reason:i?B?"Waiting for 3-day sequence to complete":oe&&!b?"Date passed":void 0:"Auto follow-ups disabled"})}}if(n==="accepted"){const ne=P.has("document_reminder"),fe=y==null?void 0:y.find(_e=>_e.email_type==="document_reminder");C.push({type:"document_reminder",label:"Document Reminder",status:ne?"sent":i?"scheduled":"blocked",scheduledDate:null,sentAt:(fe==null?void 0:fe.sent_at)??void 0,reason:i?"Sent 48h after acceptance if docs pending":"Auto follow-ups disabled"})}f(C)}catch(y){console.error("Error fetching email schedule:",y)}finally{u(!1)}},$=y=>{switch(y){case"sent":return e.jsx(At,{className:"h-3 w-3 text-green-600"});case"scheduled":return e.jsx(hs,{className:"h-3 w-3 text-blue-600"});case"blocked":return e.jsx(Yt,{className:"h-3 w-3 text-red-500"});case"skipped":return e.jsx(ds,{className:"h-3 w-3 text-muted-foreground"});default:return null}},T=y=>{switch(y){case"sent":return e.jsx(J,{variant:"default",className:"bg-green-100 text-green-700 border-green-300 text-[10px] px-1.5 py-0",children:"Sent"});case"scheduled":return e.jsx(J,{variant:"default",className:"bg-blue-100 text-blue-700 border-blue-300 text-[10px] px-1.5 py-0",children:"Scheduled"});case"blocked":return e.jsx(J,{variant:"default",className:"bg-red-100 text-red-700 border-red-300 text-[10px] px-1.5 py-0",children:"Blocked"});case"skipped":return e.jsx(J,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Skipped"});default:return null}},S=m.filter(y=>y.status==="sent").length,p=m.filter(y=>y.status==="scheduled").length,_=m.filter(y=>y.status==="blocked").length;return d?e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ot,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading..."})]}):l?e.jsxs(ut,{open:g,onOpenChange:D,children:[e.jsx(il,{asChild:!0,children:e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5 text-xs",children:[e.jsx(Be,{className:"h-3 w-3"}),e.jsx("span",{className:"text-green-600",children:S}),e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx("span",{className:"text-blue-600",children:p}),_>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx("span",{className:"text-red-500",children:_})]}),e.jsx(oa,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Wm,{emailSchedule:m,getStatusIcon:$,getStatusBadge:T,autoFollowupsEnabled:E,proposalId:t,clientName:o,businessName:c,onUpdate:()=>{x()}})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx(Oa,{className:"h-3.5 w-3.5"}),"Email Schedule"]}),e.jsx("div",{className:"space-y-1.5",children:m.map(y=>e.jsxs("div",{className:"flex items-center justify-between text-xs bg-muted/30 rounded px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[$(y.status),e.jsx("span",{children:y.label})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[y.sentAt?e.jsx("span",{className:"text-muted-foreground",children:qa(new Date(y.sentAt),"MMM d, h:mm a")}):y.scheduledDate?e.jsx("span",{className:"text-muted-foreground",children:qa(y.scheduledDate,"MMM d")}):null,T(y.status)]})]},y.type))})]})},Wm=({emailSchedule:t,getStatusIcon:s,getStatusBadge:a,autoFollowupsEnabled:n,proposalId:r,clientName:i,businessName:l,onUpdate:o})=>{const[c,m]=h.useState(!1),[f,d]=h.useState(null),[u,g]=h.useState(null),[D,E]=h.useState(null),[v,x]=h.useState(!1),$=async T=>
124{if(T.status==="sent"&&T.emailLogId){d(T.emailLogId),E(null),m(!0);return}x(!0),d(null);try{const S=await F.functions.invoke("generate-email-preview",{body:{proposalId:r,emailType:T.type,daysRemaining:T.type.includes("expiration")?parseInt(T.type.split("_")[1]):void 0}});if(S.error)throw S.error;E({subject:S.data.subject,htmlContent:S.data.htmlContent}),g(T.type),m(!0)}catch(S){console.error("Failed to generate preview:",S)}finally{x(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsx(ht,{children:e.jsxs(xt,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-4 w-4"}),"Email Schedule"]}),e.jsx(Vm,{proposalId:r,clientName:i,businessName:l,autoFollowupsEnabled:n,onUpdate:o})]})}),!n&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-amber-600 bg-amber-50 dark:bg-amber-950/50 rounded-md p-2 border border-amber-200 dark:border-amber-800",children:[e.jsx(ds,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Auto follow-ups are disabled for this proposal"})]}),e.jsx(ua,{className:"max-h-[400px]",children:e.jsx("div",{className:"space-y-2 pr-4",children:t.map(T=>e.jsxs("div",{className:"flex items-start justify-between text-sm bg-muted/30 rounded-lg p-3 gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"mt-0.5",children:s(T.status)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:T.label}),T.reason&&e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:T.reason})]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>$(T),disabled:v,children:v?e.jsx(Ot,{className:"h-3 w-3 animate-spin"}):e.jsx(bt,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})}),e.jsx(De,{children:e.jsx("p",{children:T.status==="sent"?"View sent email":"Preview email"})})]})}),a(T.status)]}),T.sentAt?e.jsx("span",{className:"text-xs text-muted-foreground",children:qa(new Date(T.sentAt),"MMM d, h:mm a")}):T.scheduledDate?e.jsx("span",{className:"text-xs text-muted-foreground",children:qa(T.scheduledDate,"MMM d, yyyy")}):null]})]},T.type))})}),e.jsxs("div",{className:"flex flex-col gap-2 text-xs text-muted-foreground pt-2 border-t",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(At,{className:"h-3 w-3 text-emerald-600"}),"Sent: ",t.filter(T=>T.status==="sent").length]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(hs,{className:"h-3 w-3 text-blue-600"}),"Scheduled: ",t.filter(T=>T.status==="scheduled").length]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yt,{className:"h-3 w-3 text-destructive"}),"Blocked: ",t.filter(T=>T.status==="blocked").length]})]}),e.jsx("div",{className:"text-[10px] text-muted-foreground/70",children:"ð§ Sequence emails send daily at 7:00 AM PST"})]})]}),e.jsx(ld,{open:c,onOpenChange:m,emailLogId:f,generatedPreview:D,previewEmailType:u})]})};function vr({proposal:t,compact:s=!1}){const a=Hu(t);if(!a)return null;const n=br(t);return e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsxs(J,{variant:"secondary",className:`text-[10px] h-5 gap-0.5 ${a.bgClass} ${a.color} border`,children:[e.jsx(Ct,{className:"h-3 w-3"}),s?`${n.percentPaidOff}%`:a.label]})}),e.jsx(De,{children:e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsx("p",{className:"font-medium",children:a.label}),e.jsxs("p",{children:["Est. remaining: $",n.estimatedRemainingBalance.toLocaleString()]}),n.estimatedPayoffDate&&e.jsxs("p",{children:["Est. payoff:"," ",n.estimatedPayoffDate.toLocaleDateString()]})]})})]})})}const ro=X.memo(({proposal:t,isSelected:s,onSelect:a,onView:n,onCopy:r,onEdit:i,onDelete:l,onViewLogs:o,onViewD
124ocuments:c,onSendEmail:m,isSendingEmail:f,getStatusBadge:d,onToggleAutoFollowups:u,onArchive:g,onRestore:D,isArchiving:E,onMarkAsFunded:v,onReject:x,onMarkAsFundingLost:$,onReassign:T,onViewTimeline:S,onViewFollowUpSettings:p,onCreateTask:_,onViewAIInsights:y,onPreviewEmails:q,onSendFinancingFit:A,onSendAprBreakdown:N,onClone:C,onResend:I,isResending:H})=>{var se;const[P,z]=h.useState(!1),[M,k]=h.useState(!1),[w,L]=h.useState(!1),O=h.useCallback(Y=>ne=>{ne.stopPropagation(),k(!1),Y==null||Y()},[]),ae=nn(t),te=an(t),V=rn(t),G=ln(t),Z=()=>Ll(t);return e.jsxs(nt,{className:`w-full hover:shadow-md transition-shadow ${Z()} ${s?"ring-2 ring-primary bg-accent/50":""}`,children:[e.jsxs(Gn,{className:"p-4 pb-3 cursor-pointer",onClick:()=>z(!P),children:[e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx(ct,{checked:s,onCheckedChange:()=>a(),onClick:Y=>Y.stopPropagation(),"aria-label":`Select ${le(t)}`}),t.type==="funding_menu"?e.jsx(cl,{className:"h-4 w-4 text-primary flex-shrink-0"}):t.type==="line_of_credit"?e.jsx(Ft,{className:"h-4 w-4 text-green-600 flex-shrink-0"}):e.jsx(Ft,{className:"h-4 w-4 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[(()=>{var ne;const Y=[V&&{label:"Shopping",node:e.jsxs(J,{variant:"outline",className:"h-4 px-1 text-[11px] font-normal bg-purple-50 border-purple-400 text-purple-700 dark:bg-purple-950 dark:border-purple-600 dark:text-purple-400",children:[e.jsx(en,{className:"h-2.5 w-2.5 mr-0.5"}),"Shopping"]},"shopping")},te&&{label:"Hot",node:e.jsxs(J,{variant:"outline",className:"h-4 px-1 text-[11px] font-normal bg-orange-50 border-orange-400 text-orange-700 dark:bg-orange-950 dar
124k:border-orange-600 dark:text-orange-400",children:[e.jsx(ml,{className:"h-2.5 w-2.5 mr-0.5"}),"Hot"]},"hot")},G&&{label:"Call Client",node:e.jsxs(J,{variant:"outline",className:"h-4 px-1 text-[11px] font-normal bg-yellow-50 border-yellow-500 text-yellow-800 dark:bg-yellow-950 dark:border-yellow-600 dark:text-yellow-400",children:[e.jsx(hl,{className:"h-2.5 w-2.5 mr-0.5"}),"Call Client"]},"call")},ae&&{label:"Cold",node:e.jsxs(J,{variant:"outline",className:"h-4 px-1 text-[11px] font-normal bg-slate-50 border-slate-400 text-slate-600 dark:bg-slate-900 dark:border-slate-600 dark:text-slate-400",children:[e.jsx(Tl,{className:"h-2.5 w-2.5 mr-0.5"}),"Cold"]},"cold")}].filter(Boolean);return e.jsxs("div",{children:[e.jsxs("h3",{className:"flex min-w-0 items-start gap-1.5 text-base font-semibold leading-snug",children:[e.jsx(Il,{proposalId:t.id}),e.jsx("span",{className:"min-w-0 break-words [overflow-wrap:anywhere]",children:le(t)}),t.type==="document_request"&&e.jsx("span",{className:"shrink-0 rounded-full border border-teal-200 bg-teal-50 px-2 py-0.5 text-[11px] text-teal-800",children:el(t)})]}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[(ne=Y[0])==null?void 0:ne.node,Y.length>1&&e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{children:e.jsxs(J,{variant:"outline",className:"h-4 px-1 text-[11px] font-normal flex-shrink-0",children:["+",Y.length-1]})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:Y.slice(1).map(fe=>fe.label).join(" · ")})})]})}),t.status==="funded"&&e.jsx(vr,{proposal:t})]})]})})(),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(t.date).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-t border-border/60 pt-2",children:[t.is_archived&&e.jsxs(J,{variant:"outline",className:"text-xs bg-muted",children:[e.jsx(Es,{className:"h-3 w-3 mr-1"}),"Archived"]}),d(t),t.accepted_option&&t.accepted_option.adjusted_amount&&t.accepted_option.original_amount&&t.accepted_option.adjusted_amount!==t.accepted_option.original_amount&&e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{children:e.jsx(J,{variant:"outline",className:"h-5 px-1.5 gap-0.5 bg-amber-50 border-amber-300 text-amber-700 dark:bg-amber-950 dark:border-amber-700 dark:text-amber-400",children:e.jsx(ul,{className:"h-3 w-3"})})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-xs",children:"Client selected reduced amount:"}),e.jsxs("p",{className:"text-xs font-semibold",children:["$",t.accepted_option.adjusted_amount.toLocaleString()," of $",t.accepted_option.original_amount.toLocaleString()]})]})]})}),e.jsx("button",{onClick:Y=>{Y.stopPropagation(),z(!P)},className:"ml-auto rounded-lg p-2 hover:bg-muted transition-colors","aria-expanded":P,"aria-label":P?"Collapse deal":"Expand deal",children:P?e.jsx(rr,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(ms,{className:"h-5 w-5 text-muted-foreground"})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2 mt-2 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ft,{className:"h-3 w-3"}),t.loan_options_count||0," options"]}),e.jsxs("button",{onClick:Y=>{Y.stopPropagation(),o()},className:"flex items-center gap-1 hover:text-foreground transition-colors",children:[e.jsx($s,{className:"h-3 w-3"}),t.view_count||0," views"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ol,{score:t.engagement_score,size:26}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"engagement"})]})]}),e.jsx(fa,{contact:t})]}),P&&e.jsxs(Zs,{className:"pt-0 space-y-3",children:[(t.type==="document_request"?jt(t)!==le(t)?jt(t):null:t.agent_notes)&&e.jsxs("div",{className:"bg-accent/30 rounded-md p-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Agent Notes"}),e.jsx("p",{className:"text-xs whitespace-pre-wrap leading-relaxed break-words overflow-hidden",children:t.type==="document_request"?jt(t)!==le(t)?jt(t):null:t.agent_notes})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 border-t pt-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-semibold text-muted-foreground mb-1.5",children:"Client Info"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"text-xs",children:[e.jsx("div",{className:"text-muted-foreground text-[11px]",children:"Name"}),e.jsx("div",{className:"truncate",children:t.client_name})]}),e.jsxs("div",{className:"text-xs",children:[e.jsx("div",{className:"text-muted-foreground text-[11px]",children:"Contact"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("a",{href:`mailto:${t.email}`,className:"truncate hover:text-primary hover:underline flex items-center gap-1 max-w-full",onClick:Y=>Y.stopPropagation(),title:t.email,children:[e.jsx(Be,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate max-w-[120px]",children:t.email})]}),t.phone?e.jsxs("a",{href:`tel:${t.phone}`,className:"hover:text-primary hover:underline flex items-center gap-1",onClick:Y=>Y.stopPropagation(),children:[e.jsx(qt,{className:"h-3 w-3 flex-shrink-0"}),t.phone]}):e.jsx("span",{onClick:Y=>Y.stopPropagation(),children:e.jsx(hm,{proposalId:t.id,businessName:le(t)})})]})]}),t.updated_at&&e.jsxs("div",{className:"text-xs",children:[e.jsx("div",{className:"text-muted-foreground text-[11px]",children:"Last Updated"}),e.jsx("div",{children:new Date(t.updated_at).toLocaleDateString()})]}),t.expiration_date&&e.jsxs("div",{className:"text-xs",children:[e.jsx("div",{className:"text-muted-foreground text-[11px]",children:"Expires"}),e.jsx("div",{children:ma(t.expiration_date)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-semibold text-muted-foreground mb-1.5",children:"Loan Details"}),e.jsx("div",{className:"border rounded-md overflow-hidden",children:e.jsx("table",{className:"w-full text-[11px]",children:e.jsxs("tbody",{children:[t.bank_names&&t.bank_names.length>0&&e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"p-1.5 text-muted-foreground bg-muted/30 font-medium",children:"Banks"}),e.jsx("td",{className:"p-1.5",children:e.jsxs("div",{className:"flex flex-wrap gap-0.5",children:[t.bank_names.slice(0,2).map((Y,ne)=>e.jsx(J,{variant:"secondary",className:"text-[11px] px-1 py-0 h-auto",children:Y},ne)),t.bank_names.length>2&&e.jsxs(J,{variant:"outline",className:"text-[11px] px-1 py-0 h-auto",children:["+",t.bank_names.length-2]})]})})]}),t.term_length_range&&e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"p-1.5 text-muted-foreground bg-muted/30 font-medium",children:"Term"}),e.jsx("td",{className:"p-1.5",children:t.term_length_range.min===t.term_length_range.max?`${t.term_length_range.min} months`:`${t.term_length_range.min}-${t.term_length_range.max} months`})]}),t.max_loan_amount!==null&&e.jsxs("tr",{children:[e.jsx("td",{className:"p-1.5 text-muted-foreground bg-muted/30 font-medium",children:"Max Amount"}),e.jsxs("td",{className:"p-1.5",children:["$",(se=t.max_loan_amount)==null?void 0:se.toLocaleStr
124ing()]})]})]})})})]})]}),t.uploaded_documents&&t.uploaded_documents.length>0&&e.jsxs(R,{size:"sm",variant:"outline",className:"w-full h-9 text-xs gap-1.5",onClick:Y=>{Y.stopPropagation(),c()},children:[e.jsx(oi,{className:"h-3.5 w-3.5"}),t.uploaded_documents.length," Document",t.uploaded_documents.length!==1?"s":""," Uploaded"]}),e.jsxs("div",{className:"pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-muted-foreground mb-2",children:[e.jsx(Oa,{className:"h-3.5 w-3.5"}),"Email Schedule"]}),e.jsx(no,{proposalId:t.id,proposalCreatedAt:t.created_at,expirationDate:t.expiration_date,status:t.status,initialEmailSent:t.initial_email_sent||!1,autoFollowupsEnabled:t.auto_followups_enabled||!1,clientName:t.client_name,businessName:le(t)})]}),e.jsxs("div",{className:"flex items-center justify-between pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(Ia,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"text-muted-foreground",children:"Auto Follow-ups"})]}),e.jsx(ta,{checked:t.auto_followups_enabled??!1,onCheckedChange:Y=>{u==null||u(Y)},onClick:Y=>Y.stopPropagation(),className:"data-[state=checked]:bg-primary"})]}),e.jsxs("div",{className:"flex gap-1.5 pt-3 border-t",children:[e.jsxs(R,{size:"sm",variant:"outline",className:"flex-1 h-9 text-xs gap-1",onClick:Y=>{Y.stopPropagation(),n()},children:[e.jsx(bt,{className:"h-3.5 w-3.5"}),"View"]}
124),e.jsxs(R,{size:"sm",variant:"outline",className:"flex-1 h-9 text-xs gap-1",onClick:Y=>{Y.stopPropagation(),i()},children:[e.jsx(Mu,{className:"h-3.5 w-3.5"}),t.type==="document_request"?"Edit request details":"Edit"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"flex-1 h-9 text-xs gap-1",onClick:Y=>{Y.stopPropagation(),r()},children:[e.jsx(_t,{className:"h-3.5 w-3.5"}),"Copy"]}),e.jsxs(Zl,{open:M,onOpenChange:k,children:[e.jsx(zm,{asChild:!0,children:e.jsx(R,{size:"sm",variant:"outline",className:"h-9 w-9 p-0",onClick:Y=>Y.stopPropagation(),children:e.jsx(Ya,{className:"h-4 w-4"})})}),e.jsxs(to,{onClick:Y=>Y.stopPropagation(),children:[e.jsx(so,{children:e.jsx(ao,{children:"More Actions"})}),e.jsxs("div",{className:"px-4 pb-6 space-y-4 max-h-[60vh] overflow-y-auto",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-wider",children:"Communication"}),!t.initial_email_sent&&m&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(m),disabled:f,children:[e.jsx(Be,{className:"h-4 w-4"}),f?"Sending...":"Send Email"]}),t.initial_email_sent&&e.jsxs("div",{className:"flex items-center gap-2 h-10 px-4 text-sm text-muted-foreground",children:[e.jsx(ir,{className:"h-4 w-4 text-green-600"}),"Email Sent"]}),S&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(S),children:[e.jsx(hs,{className:"h-4 w-4"}),"Deal room"]}),t.salesforce_opportunity_id&&e.jsx(R,{asChild:!0,variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",children:e.jsxs("a",{href:Ja(t.salesforce_opportunity_id),target:"_blank",rel:"noreferrer",onClick:()=>k(!1),children:[e.jsx(lr,{className:"h-4 w-4"}),"Open in Salesforce"]})}),e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:()=>{k(!1),L(!0)},children:[e.jsx(Dl,{className:"h-4 w-4"}),"Check UCC liens"]}),p&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(p),children:[e.jsx(or,{className:"h-4 w-4"}),"Follow-Up Settings"]}),_&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(_),children:[e.jsx(Oa,{className:"h-4 w-4"}),"Create Task"]}),q&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(q),children:[e.jsx(bt,{className:"h-4 w-4"}),"Preview Emails"]}),A&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(A),children:[e.jsx(ha,{className:"h-4 w-4"}),"Send Financing Fit"]}),N&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(N),children:[e.jsx(Xn,{className:"h-4 w-4"}),"Send APR breakdown"]}),y&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(y),children:[e.jsx(Ia,{className:"h-4 w-4"}),"AI Insights"]}),I&&t.status==="pending"&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(I),disabled:H,children:[e.jsx(Be,{className:"h-4 w-4"}),H?"Resendingâ¦":"Resend with Fresh Hook"]}),C&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(C),children:[e.jsx(oi,{className:"h-4 w-4"}),"Clone"]})]}),(t.status==="pending"||t.status==="accepted"||t.status==="in_final_review")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-wider",children:"Status"}),v&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2 text-green-600",onClick:O(v),children:[e.jsx(xa,{className:"h-4 w-4"}),"Mark as Funded"]}),x&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2 text-destructive",onClick:O(x),children:[e.jsx(Za,{className:"h-4 w-4"}),"Reject"]}),$&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2 text-orange-600",onClick:O($),children:[e.jsx(pa,{className:"h-4 w-4"}),"Funding Lost"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-wider",children:"Admin"}),t.is_archived?e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(D),disabled:E,children:[e.jsx(Sl,{className:"h-4 w-4"}),"Restore"]}):e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(g),disabled:E,children:[e.jsx(Es,{className:"h-4 w-4"}),"Archive"]}),T&&e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2",onClick:O(T),children:[e.jsx(cr,{className:"h-4 w-4"}),"Reassign"]}),e.jsxs(R,{variant:"ghost",className:"w-full justify-start h-10 text-sm gap-2 text-destructive",onClick:O(l),children:[e.jsx(Is,{className:"h-4 w-4"}),"Delete"]})]})]})]})]})]})]}),w&&e.jsx(Ul,{open:!0,onOpenChange:L,businessName:le(t),opportunityId:t.salesforce_opportunity_id})]})});ro.displayName="MobileProposalCard";function Km(t){if(!t)return"text-muted-foreground";const s=(Date.now()-new Date(t).getTime())/(1e3*60*60);return s<2?"text-green-600 dark:text-green-400":s<24?"text-yellow-600 dark:text-yellow-400":s<24*4?"text-orange-600 dar
124k:text-orange-400":"text-red-600 dark:text-red-400"}function Ym({lastSentAt:t,lastViewedAt:s,compact:a,viewCount:n,onViewsClick:r,viewsLabel:i,dense:l}){const o=a?"text-[11px]":"text-xs",c=n??0,m=`${c} view${c===1?"":"s"}`;return e.jsxs("div",{className:`flex flex-col items-start ${a?"gap-0":"gap-0.5"} leading-tight`,children:[e.jsxs("span",{className:`inline-flex items-center gap-1 ${o} text-muted-foreground whitespace-nowrap tabular-nums`,title:t?`Last email sent to client: ${new Date(t).toLocaleString()}`:"No email sent to the client yet",children:[e.jsx(Be,{className:"h-3 w-3 shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"sr-only",children:"Last sent: "}),t?ei(t,l):"Not sent"]}),e.jsxs("span",{className:`inline-flex items-center gap-1 ${o} ${Km(s)} whitespace-nowrap tabular-nums`,title:s?`Last viewed by client: ${new Date(s).toLocaleString()}`:"Client hasn't viewed it yet",children:[e.jsx(bt,{className:"h-3 w-3 shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"sr-only",children:"Last viewed: "}),s?ei(s,l):"Not viewed",n!=null&&c>0&&(r?e.jsxs("button",{type:"button",onClick:f=>{f.stopPropagation(),r()},"aria-label":i??`View activity (${m})`,className:"rounded-sm text-muted-foreground underline-offset-2 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:["· ",m]}):e.jsxs("span",{className:"text-muted-foreground",children:["· ",m]}))]})]})}const Wn=60*60*1e3,la=24*Wn;function Cn(t,s){const a=s.getTime()-new Date(t).getTime();return!Number.isFinite(a)||a<0?"just now":a<Wn?a<5*60*1e3?"just now":`${Math.round(a/6e4)} min ago`:a<la?`${Math.round(a/Wn)}h ago`:`${Math.round(a/la)}d ago`}function Qm(t,s){const[a,n,r]=t.slice(0,10).split("-").map(Number),i=new Date(a,n-1,r),l=new Date(s.getFullYear(),s.getMonth(),s.getDate());return Math.round((i.getTime()-l.getTime())/la)}function Gm(t,s=new Date){const a=t.required_documents_count??0,n=t.uploaded_documents_count??0;if(t.status==="draft")return{text:"Review, then send",tone:"warn",detail:"Draft · check the options and details, then send it"};if(t.status==="accepted"||t.status==="in_final_review")return a>0&&n<a?{text:`${n} of ${a} docs in`,tone:"warn",detail:`${a-n} requested document${a-n===1?"":"s"} still missing`}:a>0?{text:"All docs in",tone:"good"}:t.status==="accepted"?{text:"No docs requested",tone:"warn",detail:"Accepted, but no documents have been requested yet"}:null;if(t.status!=="pending")return null;if(!!!(t.initial_email_sent||t.last_sent_to_client_at))return{text:"Not sent yet",tone:"warn",detail:"The client hasn't been sent this proposal"};if(t.expiration_date){const i=Qm(t.expiration_date,s);if(i<0)return{text:"Offer expired",tone:"warn"};if(i<=3)return{text:i===0?"Expires today":i===1?"Expires tomorrow":`Expires in ${i} days`,tone:"warn"}}if(t.last_client_viewed_at){if(s.getTime()-new Date(t.last_client_viewed_at).getTime()<la){const l=Cn(t.last_client_viewed_at,s);return{text:`Viewed ${l}
124`,tone:"good",detail:`Opened ${l} · a good time to call`}}return null}return t.last_sent_to_client_at&&s.getTime()-new Date(t.last_sent_to_client_at).getTime()>2*la?{text:`Unopened ${Cn(t.last_sent_to_client_at,s).replace(" ago","")}`,tone:"warn",detail:`Sent ${Cn(t.last_sent_to_client_at,s)} and not opened yet · try a text or call`}:null}var Dn,on="HoverCard",[io]=Cc(on,[Qi]),cn=Qi(),[Xm,jr]=io(on),lo=t=>{const{__scopeHoverCard:s,children:a,open:n,defaultOpen:r,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=t,c=cn(s),m=h.useRef(0),f=h.useRef(0),d=h.useRef(!1),u=h.useRef(!1),[g,D]=jc({prop:n,defaultProp:r??!1,onChange:i,caller:on}),E=h.useCallback(()=>{clearTimeout(f.current),m.current=window.setTimeout(()=>D(!0),l)},[l,D]),v=h.useCallback(()=>{clearTimeout(m.current),!d.current&&!u.current&&(f.current=window.setTimeout(()=>D(!1),o))},[o,D]),x=h.useCallback(()=>D(!1),[D]);return h.useEffect(()=>()=>{clearTimeout(m.current),clearTimeout(f.current)},[]),e.jsx(Xm,{scope:s,open:g,onOpenChange:D,onOpen:E,onClose:v,onDismiss:x,hasSelectionRef:d,isPointerDownOnContentRef:u,children:e.jsx(_c,{...c,children:a})})};lo.displayName=on;var oo="HoverCardTrigger",co=h.forwardRef((t,s)=>{const{__scopeHoverCard:a,...n}=t,r=jr(oo,a),i=cn(a);return e.jsx(Nc,{asChild:!0,...i,children:e.jsx(kc.a,{"data-state":r.open?"open":"closed",...n,ref:s,onPointerEnter:Kt(t.onPointerEnter,Ga(r.onOpen)),onPointerLeave:Kt(t.onPointerLeave,Ga(r.onClose)),onFocus:Kt(t.onFocus,r.onOpen),onBlur:Kt(t.onBlur,r.onClose),onTouchStart:Kt(t.onTouchStart,l=>l.preventDefault())})})});co.displayName=oo;var Jm="HoverCardPortal",[Zb,Zm]=io(Jm,{forceMount:void 0}),Qa="HoverCardContent",uo=h.forwardRef((t,s)=>{const a=Zm(Qa,t.__scopeHoverCard),{forceMount:n=a.forceMount,...r}=t,i=jr(Qa,t.__scopeHoverCard);return e.jsx(Sc,{present:n||i.open,children:e.jsx(eh,{"data-state":i.open?"open":"closed",...r,onPointerEnter:Kt(t.onPointerEnter,Ga(i.onOpen)),onPointerLeave:Kt(t.onPointerLeave,Ga(i.onClose)),ref:s})})});uo.displayName=Qa;var eh=h.forwardRef((t,s)=>{const{__scopeHoverCard:a,onEscapeKeyDown:n,onPointerDownOutside:r,onFocusOutside:i,onInteractOutside:l,...o}=t,c=jr(Qa,a),m=cn(a),f=h.useRef(null),d=Dc(s,f),[u,g]=h.useState(!1);return h.useEffect(()=>{if(u){const D=document.body;return Dn=D.style.userSelect||D.style.webkitUserSelect,D.style.userSelect="none",D.style.webkitUserSelect="none",()=>{D.style.userSelect=Dn,D.style.webkitUserSelect=Dn}}},[u]),h.useEffect(()=>{if(f.current){const D=()=>{g(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var v;((v=document.getSelection())==null?void 0:v.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",D),()=>{document.removeEventListener("pointerup",D),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),h.useEffect(()=>{f.current&&ah(f.current).forEach(E=>E.setAttribute("tabindex","-1"))}),e.jsx(Tc,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:n,onPointerDownOutside:r,onFocusOutside:Kt(i,D=>{D.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(Ec,{...m,...o,onPointerDown:Kt(o.onPointerDown,D=>{D.currentTarget.contains(D.target)&&g(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:d,style:{...o.style,userSelect:u?"text":void 0,WebkitUserSelect:u?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),th="HoverCardArrow",sh=h.forwardRef((t,s)=>{const{__scopeHoverCard:a,...n}=t,r=cn(a);return e.jsx($c,{...r,...n,ref:s})});sh.displayName=th;function Ga(t){return s=>s.pointerType==="touch"?void 0:t()}function ah(t){const s=[],a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;a.nextNode();)s.push(a.currentNode);return s}var nh=lo,rh=co,mo=uo;const ih=nh,lh=rh,ho=h.forwardRef(({className:t,align:s="center",sideOffset:a=4,...n},r)=>e.jsx(mo,{ref:r,align:s,sideOffset:a,className:dt("z-50 w-64 roun
124ded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n}));ho.displayName=mo.displayName;function _r(t){const s=t.engagement_score??0,a=t.view_count??0,n=t.last_activity_at?Date.now()-new Date(t.last_activity_at).getTime():1/0,r=n/(1e3*60*60*24),i=n/(1e3*60*60),l=ol(t.expiration_date),o=t.expiration_date?nr(t.expiration_date):1/0,c=a>0&&t.max_view_duration!=null&&t.max_view_duration<=30;return l||r>=14||s<10&&a>0&&c?{tier:"at_risk",label:"At Risk",color:"red",icon:ds}:s>=1&&s<30||r>=5&&r<14||o>0&&o<7?{tier:"attention",label:"Needs Attention",color:"yellow",icon:es}:s>=60&&i<48&&a>0?{tier:"thriving",label:"Thriving",color:"green",icon:$s}:s>=30||a>=2&&r<5?{tier:"healthy",label:"Healthy",color:"blue",icon:Eu}:{tier:"attention",label:"New",color:"gray",icon:es}}function xo(t){switch(t){case"thriving":return"bg-success";case"healthy":return"bg-success/60";case"attention":return"bg-warning";case"at_risk":return"bg-destructive"}}async function oh(t){if(!t||typeof t!="object")return null;const s="context"in t?t.context:void 0;if(!s)return null;try{const a=await s.clone().json();return typeof a.error=="string"?a.error:null}catch{return null}}function po(t){return(t||"document").replace(/[\\/:*?"<>|]/g,"_").slice(0,120)}function bi(t,s){const a=window.URL.createObjectURL(t),n=document.createElement("a");n.href=a,n.download=s,document.body.appendChild(n),n.click(),setTimeout(()=>window.URL.revokeObjectURL(a),1e4),document.body.removeChild(n)}function ch(t,s){let a=po(t),n=2;for(;s.has(a);){const r=a.lastIndexOf(".");a=r>0?`${a.slice(0,r)} (${n})${a.slice(r)}`:`${a} (${n})`,n++}return s.add(a),a}async function Kn(t){const s=nl(t.uploaded_documents);if(s.length===0){U.error("No documents to download");return}const a=U.loading(s.length===1?"Downloading document...":`Preparing ${s.length} documents...`),n=[],r=new Set,i=[];let l="";try{const{data:o,error:c}=await F.functions.invoke("download-proposal-documents",{body:{proposalId:t.id,paths:s.map(d=>d.file_path)}});if(c)throw new Error(await oh(c)??"The documents could not be prepared.");const m=Array.isArray(o==null?void 0:o.urls)?o.urls:[],f=new Map(m.map(d=>[d.path,d]));for(const d of s){const u=f.get(d.file_path);if(!(u!=null&&u.url)||u.error){l=(u==null?void 0:u.error)??"A secure download link was not returned.",n.push(d.file_name);continue}const g=await fetch(u.url);if(!g.ok){l=`Download returned ${g.status}`,n.push(d.file_name);continue}i.push({name:ch(d.file_name,r),blob:await g.blob()})}if(i.length===0)throw new Error(l?`None of the files could be downloaded (${l}).`:"None of the files could be downloaded.");if(i.length===1)bi(i[0].blob,i[0].name);else{const{default:d}=await Ze(async()=>{const{default:D}=await import("./jszip.min-DDPennXk.js").then(E=>E.j);return{default:D}},__vite__mapDeps([24,1,2])),u=new d;for(const D of i)u.file(D.name,D.blob);const g=await u.generateAsync({type:"blob"});bi(g,`${po(t.business_name)} - documents.zip`)}n.length>0?U.warning(`Downloaded ${i.length} of ${s.length} documents`,{id:a,description:`Could not fetch: ${n.join(", ")}`}):U.success(i.length===1?"Downloaded 1 document":`Downloaded ${i.length} documents as a zip`,{id:a})}catch(o){console.error("Error downloading documents:",o);const c=o instanceof Error?o.message:String(o);U.error("Failed to download documents",{id:a,description:c})}}function dh(){const t=Nt();return async(a,n,r,i)=>{try{const{error:l}=await F.from("uploaded_documents").insert({proposal_id:a.id,custom_document_id:n,file_name:`Manually marked received (${i})`,file_path:`manual/${a.id}/${n}`,file_size:0});if(l)throw l;U.success(`${r} marked as received`),await Promise.all([t.invalidateQueries({queryKey:Me.proposals.all}),t.invalidateQueries({queryKey:Me.proposals.counts()})])}catch(l){U.error(l instanceof Error?l.message:"Failed to mark document received")}}}function uh({proposal:t}){var r,i,l,o;const s=Qt(),a=Ke(c=>c.isSuperAdmin),n=dh();return e.jsxs("div",{className:"space-y-4 [&_p]:break-words",children:[(()=>{const c=_r(t),m=new Date(t.created_at),f=Math.floor((Date.now()-m.getTime())/864e5),d=t.expiration_date?nr(t.expiration_date):null,u=t.last_client_viewed_at?new Date(t.last_client_viewed_at):null,g=u?(()=>{const E=Math.floor((Date.now()-u.getTime())/6e4);return E<60?`${E}m ago`:E<1440?`${Math.floor(E/60)}h ago`:`${Math.floor(E/1440)}d ago`})():"Never",D=[];return an(t)&&D.push({label:"ð¥ Hot lead",cls:"bg-orange-50 border-orange-300 text-orange-700 dark:bg-orange-950 dar
124k:border-orange-700 dark:text-orange-400"}),nn(t)&&D.push({label:"Cold",cls:"bg-slate-50 border-slate-300 text-slate-600 dark:bg-slate-900 dark:border-slate-700 dark:text-slate-400"}),rn(t)&&D.push({label:"Shopping",cls:"bg-purple-50 border-purple-300 text-purple-700 dark:bg-purple-950 dark:border-purple-700 dark:text-purple-400"}),ln(t)&&D.push({label:"Quick bounce",cls:"bg-yellow-50 border-yellow-400 text-yellow-800 dark:bg-yellow-950 dark:border-yellow-700 dark:text-yellow-400"}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(sa,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-semibold text-sm",children:"Deal Intel"}),e.jsx("span",{className:`inline-block w-2 h-2 rounded-full ${xo(c.tier)}`}),e.jsx("span",{className:"text-xs text-muted-foreground",children:c.label}),t.status==="funded"&&e.jsx(vr,{proposal:t,compact:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Engagement"}),e.jsxs("div",{className:"font-semibold",children:["Score ",t.engagement_score??"â"]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.view_count||0," views · last ",g]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Email Outreach"}),e.jsx("div",{className:"flex items-center gap-1.5",children:t.initial_email_sent?e.jsxs(e.Fragment,{children:[e.jsx(ir,{className:"h-3.5 w-3.5 text-green-600"}),e.jsx("span",{className:"text-xs",children:"Initial sent"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Be,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-xs",children:"Not sent yet"})]})}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Auto follow-ups"," ",t.auto_followups_enabled?"on":"off"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Contact"}),e.jsx("div",{className:"text-xs break-all",children:t.email||"â"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t.phone?e.jsx("a",{href:`tel:${t.phone}`,className:"hover:text-foreground",onClick:E=>E.stopPropagation(),children:t.phone}):e.jsx("span",{className:"italic",children:"no phone on file"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Timing"}),e.jsxs("div",{className:"text-xs",children:["Created ",f,"d ago"]}),d!==null&&e.jsx("div",{className:`text-xs ${d<0?"text-destructive":d<7?"text-amber-600 dark:text-amber-400":"text-muted-foreground"}`,children:d<0?`Expired ${Math.abs(d)}d ago`:d===0?"Expires today":`Expires in ${d}d`})]})]}),(D.length>0||u)&&e.jsxs("div",{className:"mt-3 pt-3 border-t space-y-2",children:[D.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:D.map(E=>e.jsx(J,{variant:"outline",className:`text-[11px] ${E.cls}`,children:E.label},E.label))}),u&&e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(bt,{className:"h-3 w-3"}),"Last viewed by client ",g," ·"," ",u.toLocaleString([],{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]})]})]})})(),t.accepted_option&&e.jsxs("div",{className:"bg-gradient-to-r from-success/10 to-success/5 border border-success/25 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(St,{className:"h-5 w-5 text-success"}),e.jsx("span",{className:"font-semibold text-success",children:"Accepted Option"}),e.jsx(J,{className:"bg-success text-success-foreground ml-2",children:t.accepted_option.option_name})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Funding Amount"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(pl,{className:"h-4 w-4 text-success"}),e.jsx("span",{className:"font-semibold tabular-nums",children:((r=t.accepted_option.adjusted_amount)==null?void 0:r.toLocaleStr
124ing())||((i=t.accepted_option.original_amount)==null?void 0:i.toLocaleString())})]})]}),t.accepted_option.total_repayment&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Repayment"}),e.jsxs("div",{className:"font-semibold",children:["$",t.accepted_option.total_repayment.toLocaleString()]})]}),t.accepted_option.payment_amount&&t.accepted_option.payment_frequency&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Payment"}),e.jsxs("div",{className:"font-semibold",children:["$",t.accepted_option.payment_amount.toLocaleString(void 0,{maximumFractionDigits:2}),"/",t.accepted_option.payment_frequency]})]}),t.accepted_option.term_length_months&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Term"}),e.jsxs("div",{className:"font-semibold",children:[t.accepted_option.term_length_months," months"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Signed By"}),e.jsx("div",{className:"text-sm",children:t.accepted_option.client_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t.accepted_option.client_title})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Accepted On"}),e.jsx("div",{className:"text-sm",children:new Date(t.accepted_option.accepted_at).toLocaleDateString()})]})]})]}),(t.status==="accepted"||t.status==="in_final_review")&&(t.required_documents_count||0)>0&&e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-semibold text-sm",children:"Document Checklist"})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.uploaded_documents_count||0," of"," ",t.required_documents_count," received"]})]}),e.jsx(xd,{value:(t.uploaded_documents_count||0)/(t.required_documents_count||1)*100,className:"h-2 mb-3"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(t.custom_documents||[]).map(c=>(t.uploaded_documents||[]).some(f=>f.custom_document_id===c.id)?e.jsxs("div",{className:"flex items-center gap-2 text-xs p-1.5 rounded text-green-700 dark:text-green-400 bg-green-50 dark:bg-green-950/30",children:[e.jsx(St,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:c.document_title})]},c.id):e.jsxs(Ua,{children:[e.jsx(za,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex items-center gap-2 text-xs p-1.5 rounded text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-950/30 hover:bg-amber-100 dark:hover:bg-amber-950/50 transition-colors text-left w-full",title:"Click to mark as received",children:[e.jsx(es,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate flex-1",children:c.document_title}),e.jsx(ms,{className:"h-3 w-3 flex-shrink-0 opacity-60"})]})}),e.jsxs(Ba,{align:"start",className:"w-52 bg-popover",children:[e.jsx(md,{className:"text-xs",children:"Mark as received via"}),e.jsx(Cs,{}),e.jsxs(pe,{onClick:()=>n(t,c.id,c.document_title,"email"),children:[e.jsx(Be,{className:"h-3.5 w-3.5 mr-2"})," Email"]}),e.jsxs(pe,{onClick:()=>n(t,c.id,c.document_title,"text"),children:[e.jsx(qt,{className:"h-3.5 w-3.5 mr-2"})," Text / SMS"]}),e.jsxs(pe,{onClick:()=>n(t,c.id,c.document_title,"in person"),children:[e.jsx(Gi,{className:"h-3.5 w-3.5 mr-2"})," In person"]}),e.jsxs(pe,{onClick:()=>n(t,c.id,c.document_title,"other"),children:[e.jsx(St,{className:"h-3.5 w-3.5 mr-2"})," Other"]}
124)]})]},c.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-muted-foreground text-xs",children:"Email Schedule:"}),e.jsx(no,{proposalId:t.id,proposalCreatedAt:t.created_at,expirationDate:t.expiration_date,status:t.status,initialEmailSent:t.initial_email_sent||!1,autoFollowupsEnabled:t.auto_followups_enabled||!1,clientName:t.client_name,businessName:le(t),compact:!0})]}),a&&e.jsxs(R,{size:"sm",variant:"ghost",onClick:()=>s(`/dashboard/admin/analytics/${t.id}`),className:"h-7 px-2 gap-1 text-xs hover:bg-accent",children:[e.jsx($s,{className:"h-3 w-3"}),"Analytics"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[t.max_loan_amount!==null&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Max Amount"}),e.jsxs("div",{className:"text-sm",children:["$",(l=t.max_loan_amount)==null?void 0:l.toLocaleString()]})]}),t.term_length_range&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Term Length"}),e.jsxs("div",{className:"text-sm",children:[t.term_length_range.min," -"," ",t.term_length_range.max," months"]})]}),t.expiration_date&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Expires"}),e.jsx("div",{className:"text-sm",children:ma(t.expiration_date)})]}),t.updated_at&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Last Updated"}),e.jsx("div",{className:"text-sm",children:new Date(t.updated_at).toLocaleDateString()})]}),t.bank_names&&t.bank_names.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:"Banks"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:t.bank_names.map((c,m)=>e.jsx(J,{variant:"outline",className:"text-xs",children:c},m))})]}),(t.type==="document_request"?jt(t)!==le(t)?jt(t):null:t.agent_notes)&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-1 text-xs",children:t.type==="document_request"?"Internal request title":"Agent Notes"}),e.jsx("div",{className:"text-sm whitespace-pre-wrap leading-relaxed max-w-prose text-foreground/90",children:t.type==="document_request"?jt(t)!==le(t)?jt(t):null:t.agent_notes})]})]}),t.type==="document_request"&&Mn(t.document_request_debt)&&e.jsxs("section",{className:"mt-4 min-w-0 rounded-xl border p-4",children:[e.jsx("h3",{className:"mb-3 font-semibold",children:"Clientâs saved debt schedule"}),(o=t.document_request_debt)!=null&&o.noDebt?e.jsx("p",{children:"No outstanding business debt â confirmed by client."}):e.jsx(Vc,{rows:Mn(t.document_request_debt).rows,onChange:()=>{},disabled:!0})]})]})}function mh(t){const[s,a]=h.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(t).matches:!1);return h.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(t),r=()=>a(n.matches);return r(),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[t]),s}const yi={wide:{gap:"gap-1.5",deal:"flex-[2] min-w-[200px]",contact:"w-[76px] [@media(pointer:coarse)]:w-[140px]",status:"w-[136px]",sentViewed:"w-[172px]",score:"w-[56px]",amount:"w-[80px]",docs:"w-[50px]",followUps:"w-[70px]"},dense:{gap:"gap-1",deal:"flex-[2] min-w-[188px]",contact:"w-[76px] [@media(pointer:coarse)]:w-[140px]",status:"w-[132px]",sentViewed:"w-[128px]",score:"hidden",amount:"w-[72px]",docs:"w-[46px]",followUps:"w-[64px]"}},hh="(min-width: 1440px)",fo=Gs;function xh({score:t}){if(t==null)return null;const s=Math.max(0,Math.min(Number(t),100)),a=s>=70?"border-success/40 text-success":s>=40?"border-warning/50 text-warning":"border-destructive/40 text-destructive";return e.jsx("span",{role:"img","aria-label":`Engagement ${Math.round(s)} percent`,title:`Engagement score ${Math.round(s)}`,className:`inline-flex h-4 shrink-0 items-center rounded-full border px-1 text-[10px] font-semibold tabular-nums leading-none ${a}`,children:Math.round(s)})}function ph(t){const s=t.business_slug||t.unique_link,a=window.location.origin;return t.type==="funding_menu"?`${a}/funding-menu/${s}`:t.type==="document_request"?`${a}/docs/${s}`:t.type==="debt_schedule"?`${a}/debt-schedule/${s}`:`${a}/${s}`}const ls="h-[26px] w-[26px] shrink-0 p-0 text-[15px] leading-none text-muted-foreground hover:text-foreground hover:bg-muted/50 [@media(pointer:coarse)]:h-9 [@media(pointer:coarse)]:w-9";function fh({proposal:t}){const s=Math.floor((Date.now()-new Date(t.created_at).getTime())/864e5),a=t.bank_names||[];return e.jsxs("div",{className:"w-[280px] space-y-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-semibold text-sm",children:le(t)}),e.jsx(J,{variant:"outline",className:"text-[10px]",children:t.type==="funding_menu"?"Menu":t.type==="line_of_credit"?"LOC":"Standard"})]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[e.jsx("p",{children:t.client_name}),t.email&&e.jsx("p",{children:t.email}),t.phone&&e.jsx("p",{children:t.phone})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs",children:[t.max_loan_amount?e.jsx("span",{className:"font-medium",children:fo(t.max_loan_amount)}):e.jsx("span",{className:"text-muted-foreground",children:"â"}),t.term_length_range&&e.jsx("span",{className:"text-muted-foreground",children:t.term_length_range.min===t.term_length_range.max?`${t.term_length_range.min}mo`:`${t.term_length_range.min}â${t.term_length_range.max}mo`})]}),a.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.slice(0,3).map(n=>e.jsx(J,{variant:"secondary",className:"text-[10px] h-5",children:n},n)),a.length>3&&e.jsxs(J,{variant:"secondary",className:"text-[10px] h-5",children:["+",a.length-3]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground pt-1 border-t",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(bt,{className:"h-3 w-3"})," ",t.view_count||0," views"]}),e.jsxs("span",{children:[s,"d ago"]}),t.loan_options_count&&e.jsxs("span",{children:[t.loan_options_count," options"]})]}),(t.type==="document_request"?jt(t)!==le(t)?jt(t):null:t.agent_notes)&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 border-t pt-1",children:t.type==="document_request"?jt(t)!==le(t)?jt(t):null:t.agent_notes})]})}const wi="w-[188px] [@media(pointer:coarse)]:w-[264px] shrink-0 sticky right-0 z-20 self-stretch bg-inherit border-l border-border/60 pl-2",go=X.memo(({proposals:t,selectedProposals:s,onSelect:a,onSelectAll:n,onDelete:r,onCopyLink:i,getStatusBadge:l,onViewLogs:o,onSendEmail:c,sendingEmailFor:m,onToggleAutoFollowups:f,onArchive:d,onRestore:u,isArchiving:g,onMarkAsFunded:D,onReject:E,onMarkAsFundingLost:v,onReassign:x,onViewTimeline:$,onViewFollowUpSettings:T,onCreateTask:S,onPreviewEmails:p,onSendFinancingFit:_,onSendAprBreakdown:y,onViewAIInsights:q,onClone:A,cloningProposalId:N,onResend:C,resendingFor:I,visibleColumns:H={sentViewed:!0,docs:!1,followUps:!1}})=>{const P=Qt(),z=Ke(b=>b.isSuperAdmin),[M,k]=h.useState(null),w=yi[mh(hh)?"wide":"dense"],L=w===yi.dense,O=t.find(b=>b.id===M),[ae,te]=h.useState(null),V=X.useRef(null),G=b=>b?/-\d+$/.test(b):!1,Z=b=>{if(!b)return null;const W=b.match(/-(\d+)$/);return W?W[1]:null},se=Kn,Y=t.reduce((b,W)=>b+(s.has(W.id)?1:0),0),ne=t.length>0&&Y===t.length,fe=Y>0&&Y<t.length,_e=b=>b==="pending"||b==="accepted"||b==="in_final_review",ge=b=>{const W=Math.floor((Date.now()-new Date(b).getTime())/864e5);return W===0?"Today":W===1?"1d":`${W}d`},me=b=>{const W=b.split("@")[0].split(".")[0];return W.charAt(0).toUpperCase()+W.slice(1)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-0 overflow-x-auto rounded-xl bg-card border border-border/70 shadow-card",children:e.jsxs("div",{className:"min-w-full",children:[e.jsxs("div",{className:`flex items-center ${w.gap} px-3 py-2.5 border-b border-x border-l-[5px] border-l-transparent bg-[color-mix(in_srgb,hsl(var(--muted))_45%,hsl(var(--card)))] rounded-t-xl text-[11px] font-semibold uppercase tracking-wider text-muted-foreground`,children:[e.jsx("span",{className:"inline-block w-2 flex-shrink-0","aria-hidden":"true"}),e.jsx(ct,{checked:ne,onCheckedChange:n,"aria-label":"Select all",className:fe?"opacity-50":""}),e.jsx("span",{className:`${w.deal} overflow-hidden sticky left-0 bg-inherit z-10 shadow-[2px_0_4px_-2px_hsl(var(--border))]`,children:"Deal"}),e.jsx("span",{className:`${w.contact} shrink-0 text-center`,children:"Contact"}),e.jsx("span",{className:`${w.status} shrink-0 text-center`,children:"Status"}),H.sentViewed&&e.jsx("span",{className:`${w.sentViewed} shrink-0`,children:"Last sent / viewed"}),e.jsx("span",{className:`${w.score}
124 shrink-0 text-center`,title:"Engagement score",children:"Score"}),e.jsx("span",{className:`${w.amount} shrink-0 text-right`,children:"Amount"}),H.docs&&e.jsx("span",{className:`${w.docs} shrink-0 text-center`,children:"Docs"}),H.followUps&&e.jsx("span",{className:`${w.followUps} shrink-0 text-center`,children:"Follow-Ups"}),e.jsx("span",{className:`${wi} flex items-center justify-end`,children:e.jsx("span",{children:"Actions"})})]}),e.jsx("div",{className:"divide-y border-x border-b rounded-b-lg",children:t.map(b=>{var B;ge(b.created_at);const W=((B=b.uploaded_documents)==null?void 0:B.length)||0,oe=Ll(b);return e.jsx("div",{style:{"--row-background":s.has(b.id)?"color-mix(in srgb, hsl(var(--primary)) 8%, hsl(var(--card)))":"hsl(var(--card))"},className:`${oe||"border-l-4 border-l-transparent"} !bg-[var(--row-background)] hover:!bg-[color-mix(in_srgb,hsl(var(--muted))_30%,var(--row-background))] transition-colors`,children:e.jsxs("div",{className:`flex items-center ${w.gap} px-3 py-2 group/row bg-inherit`,children:[(()=>{const Q=_r(b),ie=xo(Q.tier);return e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{"aria-label":Q.label,children:e.jsx("span",{className:`inline-block w-2 h-2 rounded-full flex-shrink-0 ${ie}`})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:Q.label})})]})})})(),e.jsx(ct,{checked:s.has(b.id),onCheckedChange:()=>a(b.id),"aria-label":`Select ${le(b)}`}),e.jsxs("div",{className:`${w.deal} overflow-hidden sticky left-0 bg-inherit z-10 shadow-[2px_0_4px_-2px_hsl(var(--border))] group-hover/row:bg-inherit`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[b.type==="funding_menu"?e.jsx(cl,{className:"h-3.5 w-3.5 text-primary flex-shrink-0"}):b.type==="line_of_credit"?e.jsx(Ft,{className:"h-3.5 w-3.5 text-green-600 flex-shrink-0"}):e.jsx(Ft,{className:"h-3.5 w-3.5 text-blue-600 flex-shrink-0"}),e.jsxs(ih,{openDelay:400,closeDelay:100,children:[e.jsx(lh,{asChild:!0,children:e.jsxs("button",{type:"button",className:"font-semibold text-sm text-left hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm transition-colors min-w-0 inline-flex items-center gap-1.5","aria-label":`Review ${le(b)}`,"aria-haspopup":"dialog",onClick:Q=>{V.current=Q.currentTarget,k(b.id)},children:[e.jsx(Il,{proposalId:b.id}),e.jsx("span",{className:"truncate",title:le(b),children:le(b)}),b.type==="document_request"&&e.jsx("span",{className:"shrink-0 rounded-full border border-teal-200 bg-teal-50 px-2 py-0.5 text-[11px] text-teal-800",children:el(b)})]})}),e.jsx(ho,{side:"right",align:"start",className:"p-3",children:e.jsx(fh,{proposal:b})})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 mt-0.5",children:[e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[b.client_name," ·"," ",me(b.agent_email)]}),L&&e.jsx(xh,{score:b.engagement_score}),(()=>{const Q=[],ie=b.view_count||0,ue=(b.view_states||[]).length;an(b)&&Q.push({key:"hot",label:`Hot lead: viewed ${ie} times`,node:e.jsx(J,{variant:"outline",className:"h-4 px-1 text-[10px] font-normal bg-orange-50 border-orange-400 text-orange-700 dark:bg-orange-950 dar
124k:border-orange-600 dark:text-orange-400 flex-shrink-0",children:"ð¥"})}),nn(b)&&Q.push({key:"cold",label:"Cold: sent, but never opened",node:e.jsx(J,{variant:"outline",className:"h-4 px-1 text-[10px] font-normal bg-slate-50 border-slate-400 text-slate-600 dark:bg-slate-900 dark:border-slate-600 dark:text-slate-400 flex-shrink-0",children:e.jsx(Tl,{className:"h-2.5 w-2.5"})})}),rn(b)&&Q.push({key:"shopping",label:`Shopping around: opened from ${ue} states`,node:e.jsx(J,{variant:"outline",className:"h-4 px-1 text-[10px] font-normal bg-purple-50 border-purple-400 text-purple-700 dark:bg-purple-950 dark:border-purple-600 dark:text-purple-400 flex-shrink-0",children:e.jsx(en,{className:"h-2.5 w-2.5"})})}),ln(b)&&Q.push({key:"bounce",label:"Quick bounce: left within 30 seconds",node:e.jsx(J,{variant:"outline",className:"h-4 px-1 text-[10px] font-normal bg-yellow-50 border-yellow-500 text-yellow-800 dark:bg-yellow-950 dark:border-yellow-600 dark:text-yellow-400 flex-shrink-0",children:e.jsx(hl,{className:"h-2.5 w-2.5"})})}),G(b.business_slug)&&Q.push({key:"dup",label:`Another proposal exists for this business (#${Z(b.business_slug)})`,node:e.jsxs(J,{variant:"outline",className:"h-4 px-1 text-[10px] font-normal bg-orange-50 border-orange-300 text-orange-700 dark:bg-orange-950 dar
124k:border-orange-700 dark:text-orange-400 flex-shrink-0",children:[e.jsx(Gi,{className:"h-2.5 w-2.5 mr-0.5"}),Z(b.business_slug)]})});const Ee=Q.slice(0,2),Ye=Q.length-2;return e.jsxs(We,{children:[Ee.map(Fe=>e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",tabIndex:0,"aria-label":Fe.label,children:Fe.node})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:Fe.label})})]},Fe.key)),Ye>0&&e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsxs(J,{variant:"outline",className:"h-4 px-1 text-[10px] font-normal flex-shrink-0",children:["+",Ye]})}),e.jsx(De,{children:e.jsx("ul",{className:"space-y-1 text-xs",children:Q.slice(2).map(Fe=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[Fe.node,Fe.label]},Fe.key))})})]})]})})()]})]}),e.jsx("div",{className:`${w.contact} shrink-0 flex items-center justify-center`,children:e.jsx(fa,{contact:b,size:"compact",tone:"subtle",className:"flex-nowrap justify-center"})}),e.jsxs("div",{className:`${w.status} shrink-0 flex flex-col items-center justify-center gap-0.5`,children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 whitespace-nowrap",children:[l(b),b.accepted_option&&b.accepted_option.adjusted_amount&&b.accepted_option.original_amount&&b.accepted_option.adjusted_amount!==b.accepted_option.original_amount&&e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{children:e.jsx(J,{variant:"outline",className:"h-5 px-1 gap-0.5 bg-amber-50 border-amber-300 text-amber-700 dark:bg-amber-950 dark:border-amber-700 dark:text-amber-400",children:e.jsx(ul,{className:"h-3 w-3"})})}),e.jsx(De,{children:e.jsxs("p",{className:"text-xs",children:["Reduced: $",b.accepted_option.adjusted_amount.toLocaleString()," ","of $",b.accepted_option.original_amount.toLocaleString()]})})]})}),b.status==="funded"&&e.jsx(vr,{proposal:b,compact:!0})]}),(()=>{const Q=Gm(b);if(!Q)return null;const ie=Q.tone==="good"?"text-green-700 dark:text-green-400":Q.tone==="warn"?"text-amber-700 dark:text-amber-400":"text-muted-foreground";return e.jsx("button",{type:"button",className:`max-w-full truncate rounded-sm text-xs underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${ie}`,title:Q.detail??Q.text,"aria-label":`${Q.detail??Q.text} · review ${le(b)}`,"data-testid":"deal-next-step",onClick:ue=>{V.current=ue.currentTarget,k(b.id)},children:Q.text})})()]}),H.sentViewed&&e.jsx("div",{className:`${w.sentViewed} shrink-0`,children:e.jsx(Ym,{dense:L,lastSentAt:b.last_sent_to_client_at,lastViewedAt:b.last_client_viewed_at,viewCount:b.view_count,onViewsClick:()=>o(b.id),viewsLabel:`View activity for ${le(b)}`})}),e.jsx("div",{className:`${w.score} flex shrink-0 items-center justify-center`,children:e.jsx(Ol,{score:b.engagement_score})}),e.jsx("div",{className:`${w.amount} shrink-0 text-right`,children:b.max_loan_amount?e.jsx("span",{className:"text-sm font-semibold tabular-nums text-foreground",children:fo(b.max_loan_amount)}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"})}),H.docs&&e.jsx("div",{className:`${w.docs} shrink-0 flex items-center justify-center`,children:(()=>{const Q=b.required_documents_count||0,ie=b.uploaded_documents_count||0;if(W===0&&Q===0)return e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"});if(W===0)return e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-xs text-amber-600 dark:text-amber-400 tabular-nums",children:[e.jsx(es,{className:"h-3 w-3"}),"0"]})}),e.jsx(De,{children:e.jsxs("p",{className:"text-xs",children:[Q," document",Q===1?"":"s"," requested â none uploaded yet"]})})]})});const ue=Q>0&&ie>=Q,Ee=Q===0?"text-foreground":ue?"text-green-600 dark:text-green-400":"text-amber-600 dark:text-amber-400";return e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsxs(R,{size:"sm",variant:"ghost","aria-label":`Download ${W} document${W===1?"":"s"}`,onClick:Ye=>{Ye.stopPropagation(),se(b)},className:`h-6 px-1 gap-0.5 text-xs font-medium tabular-nums ${Ee}`,children:[W,e.jsx(pd,{className:"h-3 w-3"})]})}),e.jsx(De,{children:e.jsxs("p",{className:"text-xs",children:["Download ",W," document",W===1?"":"s",Q>0&&(ue?" · all required received":` · ${ie} of ${Q} required received`)]})})]})})})()}),H.followUps&&e.jsxs("div",{className:`${w.followUps} shrink-0 flex items-center justify-center gap-1.5`,children:[b.initial_email_sent&&e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0",children:e.jsx(ir,{className:"h-3.5 w-3.5 text-green-600 dark:text-green-400"})})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:"Initial email sent"})})]})}),e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx("div",{className:"inline-flex shrink-0 items-center leading-none",children:e.jsx(ta,{checked:b.auto_followups_enabled??!1,onCheckedChange:Q=>f==null?void 0:f(b.id,Q),size:"sm","aria-label":"Auto follow-ups"})})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:b.auto_followups_enabled?"Auto follow-ups enabled":"Auto follow-ups disabled"})})]})})]}),e.jsxs("div",{className:`${wi} flex items-center justify-end gap-0.5`,children:[e.jsxs(We,{delayDuration:300,children:[e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ls,"aria-label":`Edit ${le(b)}`,title:`Edit ${le(b)}`,onClick:()=>P(Lt(b.type,b.id)),children:e.jsx("span",{"aria-hidden":"true",children:"âï¸"})})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:b.type==="document_request"?"Edit request details":"Edit proposal"})})]}),e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ls,"aria-label":`Copy client link for ${le(b)}`,title:`Copy client link for ${le(b)}`,onClick:()=>i(b),children:e.jsx("span",{"aria-hidden":"true",children:"ð"})})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:"Copy client link"})})]}),c&&e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ls,"aria-label":b.initial_email_sent?`Resend email for ${le(b)}`:`Send email for ${le(b)}`,title:b.initial_email_sent?"Resend email":"Send email",disabled:m===b.id||I===b.id,onClick:()=>{b.initial_email_sent&&C?C(b):c(b)},children:e.jsx("span",{"aria-hidden":"true",children:"âï¸"})})})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:b.initial_email_sent?"Resend email":"Send email"})})]}),e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ls,"aria-label":`Preview ${le(b)} as client`,title:`Preview ${le(b)} as client`,onClick:()=>window.open(ph(b),"_blank"),children:e.jsx("span",{"aria-hidden":"true",children:"ð"})})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:"Preview as client"})})]}),$&&e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ls,"aria-label":`Open deal room for ${le(b)}`,title:`Open deal room for ${le(b)}`,onClick:()=>$(b),children:e.jsx("span",{"aria-hidden":"true",children:"ð¼"})})}),e.jsx(De,{children:e.jsx("p",{className:"text-xs",children:"Deal room"})})]})]}),e.jsxs(Ua,{children:[e.jsx(za,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"sm",className:ls,"aria-label":`More actions for ${le(b)}`,title:`More actions for ${le(b)}`,children:e.jsx(aa,{className:"h-3.5 w-3.5","aria-hidden":"true"})})}),e.jsxs(Ba,{align:"end",className:"w-56 max-h-[var(--radix-dropdown-menu-content-available-height)] overflow-y-auto bg-popover",children:[e.jsxs(pe,{onClick:()=>o(b.id),children:[e.jsx(bt,{className:"h-4 w-4 mr-2"})," View activity"]}),b.salesforce_opportunity_id&&e.jsx(pe,{asChild:!0,children:e.jsxs("a",{href:Ja(b.salesforce_opportunity_id),target:"_blank",rel:"noreferrer",children:[e.jsx(lr,{className:"h-4 w-4 mr-2"})," Open in Salesforce"]})}),e.jsxs(pe,{onClick:()=>te(b),children:[e.jsx(Dl,{className:"h-4 w-4 mr-2"})," Check UCC liens"]}),_e(b.status)&&D&&e.jsxs(pe,{onClick:()=>D(b),className:"text-success focus:text-success",children:[e.jsx(xa,{
124className:"h-4 w-4 mr-2"})," Mark Funded"]}),q&&e.jsxs(pe,{onClick:()=>q(b),children:[e.jsx(sa,{className:"h-4 w-4 mr-2"})," AI Insights"]}),z&&e.jsxs(pe,{onClick:()=>P(`/dashboard/admin/analytics/${b.id}`),children:[e.jsx($s,{className:"h-4 w-4 mr-2"})," Analytics"]}),e.jsx(Cs,{}),_e(b.status)&&E&&e.jsxs(pe,{onClick:()=>E(b),className:"text-destructive focus:text-destructive",children:[e.jsx(Za,{className:"h-4 w-4 mr-2"})," Rejected"]}),_e(b.status)&&v&&e.jsxs(pe,{onClick:()=>v(b),className:"text-orange-600",children:[e.jsx(pa,{className:"h-4 w-4 mr-2"})," Funding Lost"]}),S&&e.jsxs(pe,{onClick:()=>S(b),children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"})," Create Task"]}),p&&e.jsxs(pe,{onClick:()=>p(b),children:[e.jsx(Be,{className:"h-4 w-4 mr-2"})," Preview Emails"]}),_&&b.phone&&e.jsxs(pe,{onClick:()=>_(b),children:[e.jsx(ha,{className:"h-4 w-4 mr-2"})," Send Financing Fit"]}),y&&b.phone&&e.jsxs(pe,{onClick:()=>y(b),children:[e.jsx(Xn,{className:"h-4 w-4 mr-2"})," Send APR breakdown"]}),T&&e.jsxs(pe,{onClick:()=>T(b),children:[e.jsx(or,{className:"h-4 w-4 mr-2"})," Follow-Up Settings"]}),e.jsx(Cs,{}),b.is_archived?e.jsxs(pe,{onClick:()=>u==null?void 0:u(b.id,le(b)),disabled:g===b.id,className:"text-primary focus:text-primary",children:[e.jsx(Sl,{className:"h-4 w-4 mr-2"})," ","Restore"]}):e.jsxs(pe,{onClick:()=>d==null?void 0:d(b.id,le(b)),disabled:g===b.id,children:[e.jsx(Es,{className:"h-4 w-4 mr-2"})," Archive"]}),x&&e.jsxs(pe,{onClick:()=>x(b),children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Reassign"]}),A&&e.jsxs(pe,{onClick:()=>A(b),disabled:N===b.id,children:[e.jsx(_t,{className:"h-4 w-4 mr-2"})," ",N===b.id?"Cloning...":"Clone"]}),e.jsx(Cs,{}),e.jsxs(pe,{onClick:()=>r(b.id,le(b)),className:"text-destructive focus:text-destructive",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Delete"]})]})]}),e.jsx(R,{variant:"ghost",size:"sm",className:ls,"aria-label":`Deal details for ${le(b)}`,title:"Deal details",onClick:Q=>{V.current=Q.currentTarget,k(b.id)},children:e.jsx(oa,{className:"h-4 w-4","aria-hidden":"true"})})]})]})},b.id)})})]})}),e.jsx(as,{open:!!O,onOpenChange:b=>{b||k(null)},children:e.jsx(xs,{overlayClassName:"bg-black/20",className:"w-full sm:max-w-lg overflow-y-auto",onCloseAutoFocus:b=>{var W;b.preventDefault(),(W=V.current)==null||W.focus()},children:O&&e.jsxs(e.Fragment,{children:[e.jsxs(ps,{className:"pr-6 mb-5",children:[e.jsx(fs,{children:le(O)}),e.jsxs(tn,{children:[O.client_name," · Deal details"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-5",children:[l(O),e.jsx(R,{size:"sm",onClick:()=>P(Lt(O.type,O.id)),children:O.type==="document_request"?"Edit request details":"Edit proposal"}),e.jsx(R,{size:"sm",variant:"outline",onClick:()=>i(O),children:"Copy client link"})]}),e.jsx(uh,{proposal:O})]})})}),ae&&e.jsx(Ul,{open:!0,onOpenChange:b=>!b&&te(null),businessName:ae.business_name,opportunityId:ae.salesforce_opportunity_id})]})});go.displayName="DesktopProposalTable";const vi=[{value:"term_length",label:"Term Length",description:"Client didn't like the term or duration"},{value:"payment_amount",label:"Payment Amount",description:"Monthly payment was too high"},{value:"interest_rate",label:"Interest Rate / Factor Rate",description:"Cost of capital too high"},{value:"found_better_terms",label:"Found Better Terms",description:"Client secured financing elsewhere"},{value:"not_ready",label:"Not Ready for Funding",description:"Client needs more time to decide"},{value:"no_longer_needs",label:"No Longer Needs Funding",description:"Client changed their mind about funding"},{value:"no_response",label:"No Response",description:"Client stopped responding"},{value:"other",label:"Other",description:"Specify a custom reason"}],gh=({open:t,onOpenChange:s,businessName:a,onConfirm:n,isLoading:r=!1})=>{const[i,l]=h.useState(""),[o,c]=h.useState(""),[m,f]=h.useState(null),d=async()=>{var D;if(f(null),!i){f("Please select a rejection reason");return}if(i==="other"&&!o.trim()){f("Please provide a custom reason");return}const g=i==="other"?o.trim():((D=vi.find(E=>E.value===i))==null?void 0:D.label)||i;await n(g),l(""),c("")},u=()=>{l(""),c(""),f(null),s(!1)};return e.jsx(ut,{open:t,onOpenChange:u,children:e.jsxs(mt,{className:"sm:max-w-[480px]",children:[e.jsxs(ht,{children:[e.jsxs(xt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(es,{className:"h-5 w-5"}),"Mark as Merchant Rejected"]}),e.jsxs(kt,{children:["You're about to mark ",e.jsx("span",{className:"font-medium",children:a})," as rejected. This will stop all automated emails to this client."]})]}),e.jsxs("div",{className:"py-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsx(ss,{className:"h-5 w-5 text-primary flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium text-primary",children:"AI-Powered Follow-up"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Providing a reason helps our AI craft personalized re-engagement emails to bring this client back when conditions change."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(de,{className:"text-sm font-medium",children:"Rejection Reason"}),e.jsx(fd,{value:i,onValueChange:g=>{l(g),f(null)},className:"space-y-2",children:vi.map(g=>e.jsxs("div",{className:`flex items-start space-x-3 p-3 rounded-lg border transition-colors cursor-pointer ${i===g.value?"border-primary bg-primary/5":"border-border hover:border-muted-foreground
124/30"}`,onClick:()=>{l(g.value),f(null)},children:[e.jsx(gd,{value:g.value,id:g.value,className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(de,{htmlFor:g.value,className:"font-medium cursor-pointer",children:g.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:g.description})]})]},g.value))})]}),i==="other"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(de,{htmlFor:"custom-reason",className:"text-sm font-medium",children:"Custom Reason"}),e.jsx(Rt,{id:"custom-reason",placeholder:"Enter the specific reason for rejection...",value:o,onChange:g=>{c(g.target.value),f(null)},className:"min-h-[80px]"})]}),m&&e.jsx("p",{className:"text-sm text-destructive",children:m})]}),e.jsxs(da,{className:"gap-2",children:[e.jsx(R,{variant:"outline",onClick:u,disabled:r,children:"Cancel"}),e.jsx(R,{variant:"destructive",onClick:d,disabled:r,children:r?"Marking...":"Mark as Rejected"})]})]})})};function bh({open:t,onOpenChange:s,proposalId:a,businessName:n,currentAgentEmail:r,onReassigned:i}){const[l,o]=h.useState([]),[c,m]=h.useState(!1),[f,d]=h.useState(""),[u,g]=h.useState(!1);h.useEffect(()=>{t&&(D(),d(""))},[t]);const D=async()=>{m(!0);try{const{data:v,error:x}=await F.functions.invoke("get-users");if(x)throw x;const $=v.users||[];o($.filter(T=>T.email!==r))}catch(v){console.error("Error fetching agents:",v),U.error("Failed to load agents")}finally{m(!1)}},E=async()=>{if(!a||!f)return;const v=l.find(x=>x.id===f);if(v){g(!0);try{const{error:x}=await F.from("proposals").update({user_id:f,agent_email:v.email}).eq("id",a);if(x)throw x;U.success(`"${n}" reassigned to ${v.email}`),s(!1),i()}catch(x){console.error("Error reassigning proposal:",x),U.error("Failed to reassign proposal")}finally{g(!1)}}};return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-[425px]",children:[e.jsxs(ht,{children:[e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5"}),"Reassign Proposal"]}),e.jsxs(kt,{children:["Move ",e.jsx("span",{className:"font-semibold",children:n})," to a different agent. Currently assigned to ",e.jsx("span",{className:"font-semibold",children:r}),"."]})]}),e.jsx("div",{className:"py-4",children:c?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ot,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(As,{value:f,onValueChange:d,children:[e.jsx(Ps,{children:e.jsx(Rs,{placeholder:"Select an agent..."})}),e.jsx(Fs,{className:"bg-popover",children:l.map(v=>e.jsxs(Je,{value:v.id,children:[v.email," ",v.role==="admin"?"(Admin)":""]},v.id))})]})}),e.jsxs(da,{children:[e.jsx(R,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(R,{onClick:E,disabled:!f||u,children:u?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"h-4 w-4 animate-spin mr-2"}),"Reassigning..."]}):"Reassign"})]})]})})}function yh(t){return/<[a-z][\s\S]*?>/i.test(t)}function wh({open:t,onOpenChange:s,channel:a,actionLabel:n,methodNote:r,recipients:i,sampleSubject:l,sampleBody:o,sampleHtml:c,sampleLabel:m,previewLoading:f=!1,warning:d,extraControl:u,confirming:g=!1,onConfirm:D}){const E=a==="email"?Be:ts;return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(ht,{children:[e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(E,{className:"h-4 w-4"}),"Ready to send?",e.jsxs(J,{variant:"secondary",className:"ml-1 font-normal",children:[i.length," recipient",i.length===1?"":"s"]})]}),e.jsx(kt,{children:r})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"rounded-lg border max-h-44 overflow-y-auto divide-y",children:i.map((v,x)=>e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-1.5 text-xs",children:[e.jsx("span",{className:"font-medium truncate",children:v.name}),e.jsx("span",{className:"text-muted-foreground whitespace-nowrap",children:v.destination})]},x))}),(l||o||f)&&e.jsxs("div",{className:"space-y-1",children:[m&&e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:m}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1.5",children:[l&&e.jsx("p",{className:"text-sm font-semibold",children:l}
124),f&&!o?e.jsxs("div",{className:"space-y-2 animate-pulse",children:[e.jsx("div",{className:"h-3 w-3/4 bg-muted rounded"}),e.jsx("div",{className:"h-3 w-1/2 bg-muted rounded"}),e.jsx("div",{className:"h-32 bg-muted rounded"})]}):o&&(c??yh(o)?e.jsx("iframe",{srcDoc:o,title:"Message preview",className:"w-full h-[260px] border rounded bg-white",sandbox:""}):e.jsx("p",{className:"text-xs whitespace-pre-wrap leading-relaxed max-h-44 overflow-y-auto",children:o}))]})]}),d&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 text-xs",children:[e.jsx(es,{className:"h-3.5 w-3.5 text-warning shrink-0 mt-0.5"}),e.jsx("span",{children:d})]}),u]}),e.jsxs(da,{className:"gap-2 sm:gap-2 sm:justify-between",children:[e.jsx("span",{className:"text-xs text-muted-foreground self-center",children:"Nothing goes out until you confirm."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>s(!1),disabled:g,children:"Cancel"}),e.jsxs(R,{size:"sm",className:"gap-1.5",onClick:D,disabled:g||i.length===0,children:[e.jsx(dr,{className:"h-3.5 w-3.5"}),g?"Sendingâ¦":n]})]})]})]})})}function vh(t,s=Date.now()){const a=Math.floor(Math.max(0,s-t)/6e4);if(a<1)return"just now";if(a<60)return`${a} min ago`;const n=Math.floor(a/60);return n<24?`${n} hr ago`:new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function bo({at:t,prefix:s="Updated",className:a}){const n=typeof t=="string"?Date.parse(t):t??0,[r,i]=h.useState(()=>Date.now());return h.useEffect(()=>{const l=window.setInterval(()=>i(Date.now()),3e4);return()=>window.clearInterval(l)},[]),!n||Number.isNaN(n)?null:e.jsxs("time",{dateTime:new Date(n).toISOString(),title:new Date(n).toLocaleString("en-US"),className:a,children:[s," ",vh(n,Math.max(r,Date.now()))]})}const jh=[{tab:"proposals",label:"Deals",icon:Ft},{tab:"document-requests",label:"Document requests",icon:bd},{tab:"drafts",label:"Salesforce drafts",icon:ss}];function ji({active:t,onChange:s}){return e.jsx("div",{role:"group","aria-label":"Pipeline views",className:"mb-4 inline-flex max-w-full items-center gap-1 overflow-x-auto rounded-lg bg-muted p-0.5 scrollbar-none",children:jh.map(a=>{const n=t===a.tab;return e.jsxs("button",{type:"button","aria-pressed":n,onClick:()=>s(a.tab),className:dt("inline-flex min-h-8 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md px-3 text-xs font-medium transition-colors duration-150",n?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(a.icon,{className:"h-3.5 w-3.5","aria-hidden":!0}),a.label]},a.tab)})})}function _i({title:t,description:s,children:a}){return e.jsxs("header",{className:`flex flex-wrap items-end justify-between gap-4 ${s?"mb-6":"mb-4"}`,children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:`font-semibold tracking-tight text-foreground ${s?"text-2xl sm:text-3xl":"text-lg sm:text-xl"}`,children:t}),s?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-relaxed text-muted-foreground",children:s}):null]}),a]})}const Ni=[{id:"calculate",title:"Calculate & compare",description:"Review balances, payments and financing scenarios.",paths:["/dashboard?tab=ondeck"]},{id:"prepare",title:"Prepare & research",description:"Prepare client documents and look up official business records.",paths:["/dashboard?tab=docs","/dashboard/business-search"]},{id:"share",title:"Share & follow up",description:"Explain financing options and prepare client outreach.",paths:["/dashboard?tab=deal-blitz","/dashboard?tab=resources","/dashboard?tab=mailmerge"]}];function _h(t){const s=Ni.map(({paths:r,...i})=>({...i,items:r.flatMap(l=>t.filter(o=>o.path===l))})).filter(r=>r.items.length>0),a=new Set(Ni.flatMap(r=>r.paths)),n=t.filter(r=>!a.has(r.path));return n.length>0&&s.push({id:"other",title:"Other tools",description:"Additional tools available in your workspace.",items:n}),s}function Nh({items:t}){const[s]=Jn(),a=s.get("deal"),n=_h(t);return e.jsxs("section",{"aria-labelledby":"tools-heading",className:"mx-auto max-w-6xl",children:[e.jsx("p",{className:"mb-2 text-xs font-semibold uppercase tracking-[0.14em] text-primary",children:"Agent workspace"}),e.jsx("h2",{id:"tools-heading",className:"text-3xl font-semibold tracking-tight",children:"Tools"}),e.jsx("p",{className:"mt-3 max-w-2xl text-sm leading-relaxed text-muted-foreground sm:text-base",children:"Choose the next task: work through financing, prepare a file, or support a client conversation."}),e.jsx("div",{className:"mt-7 space-y-8",children:n.map(r=>e.jsxs("section",{"aria-labelledby":`tools-group-${r.id}`,children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h3",{id:`tools-group-${r.id}`,className:"text-base font-semibold tracking-tight",children:r.title}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.description})]}),e.jsx("ul",{className:"grid gap-4 sm:grid-cols-2",children:r.items.map(i=>e.jsx("li",{children:e.jsxs(Ac,{to:yd(i.path,a),className:"group flex h-full min-w-0 items-start gap-4 roun
124ded-2xl border border-border/70 bg-card p-5 shadow-card transition-colors hover:border-primary/40 hover:bg-primary/[0.03] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:e.jsx(i.icon,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold",children:[e.jsx("span",{className:"min-w-0 break-words",children:i.label}),e.jsx(La,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground transition-colors group-hover:text-primary","aria-hidden":!0})]}),i.description&&e.jsx("span",{className:"mt-2 block text-sm leading-relaxed text-muted-foreground",children:i.description})]})]})},i.path))})]},r.id))})]})}async function yo(t){const s=[];for(let a=0;;a+=1e3){let n=F.from("proposals").select("id, type, business_name, client_name, email, intended_use_of_funds, salesforce_opportunity_id, created_at, sf_approved_at, user_id, agent_email").eq("status","draft").eq("auto_created_from_sf",!0).eq("fit_only",!1).eq("is_archived",!1).order("created_at",{ascending:!1}).order("id").range(a,a+999);t&&(n=n.eq("user_id",t));const{data:r,error:i}=await n;if(i)throw i;if(!r)throw new Error("Salesforce drafts unavailable");if(s.push(...r),r.length<1e3)return s}}const Ta=30;function Tn(t){const s=t.sf_approved_at??t.created_at;return Math.floor((Date.now()-new Date(s).getTime())/864e5)}const En="__all__",Ea="__mine__";function kh(){const{user:t,isAdmin:s}=Ke(),[a]=Jn(),n=a.get("scope")==="mine",[r,i]=h.useState(!1),[l,o]=h.useState([]),[c,m]=h.useState(!0),[f,d]=h.useState(s&&!n?En:Ea),[u,g]=h.useState(""),[D,E]=h.useState(!1),[v,x]=h.useState(new Set),[$,T]=h.useState(!1),S=Qt(),{agents:p}=dl(s),_=h.useCallback(async()=>{if(!t){m(!1);return}m(!0),i(!1);try{const M=!s||f===Ea?t.id:f===En?void 0:f;o(await yo(M)),x(new Set)}catch{o([]),i(!0),U.error("Failed to load Salesforce drafts. Please retry.")}finally{m(!1)}},[t,s,f]);h.useEffect(()=>{_()},[_]);const y=h.useMemo(()=>{const M=new Map;return p.forEach(k=>M.set(k.id,k.display_name||k.email)),M},[p]),q=h.useMemo(()=>l.filter(M=>Tn(M)>=Ta).length,[l]),A=h.useMemo(()=>{const M=D?l.filter(w=>Tn(w)>=Ta):l,k=u.trim().toLowerCase();return k?M.filter(w=>{const L=w.user_id&&y.get(w.user_id)||w.agent_email||"";return[w.business_name,w.client_name,w.email,w.intended_use_of_funds,w.salesforce_opportunity_id,L].filter(Boolean).some(O=>String(O).toLowerCase().includes(k))}):M},[l,u,y,D]),N=async M=>{if(!confirm("Dismiss this draft? It won't be re-imported from Salesforce."))return;const{error:k}=await F.from("proposals").update({is_archived:!0,archived_at:new Date().toISOString(),archived_by:(t==null?void 0:t.id)??null,archive_reason:"dismissed_sf_draft"}).eq("id",M);if(k)return U.error(k.message);o(w=>w.filter(L=>L.id!==M)),x(w=>{const L=new Set(w);return L.delete(M),L})},C=M=>{x(k=>{const w=new Set(k);return w.has(M)?w.delete(M):w.add(M),w})},I=A.length>0&&A.every(M=>v.has(M.id)),H=()=>{x(I?new Set:new Set(A.map(M=>M.id)))},P=async()=>{const M=[...v];if(M.length!==0&&confirm(`Archive ${M.length} draft${M.length===1?"":"s"}? They won't be re-imported from Salesforce, and can be restored from the Archived view.`)){T(!0);try{const{error:k}=await F.from("proposals").update({is_archived:!0,archived_at:new Date().toISOString(),archived_by:(t==null?void 0:t.id)??null,archive_reason:"bulk_dismissed_sf_draft"}).in("id",M);if(k)throw k;U.success(`Archived ${M.length} draft${M.length===1?"":"s"}.`),o(w=>w.filter(L=>!v.has(L.id))),x(new Set)}catch(k){U.error(k instanceof Error?k.message:"Bulk archive failed")}finally{T(!1)}}};if(c)return e.jsxs("div",{className:"space-y-2",children:[e.jsx(je,{className:"h-20 w-full"}),e.jsx(je,{className:"h-20 w-full"})]});if(r)return e.jsxs("div",{role:"alert",className:"space-y-2",children:[e.jsx("p",{children:"Salesforce drafts are unavailable. Please try again."}),e.jsx(R,{onClick:_,children:"Retry"})]});const z=s?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bl,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs(As,{value:f,onValueChange:d,children:[e.jsx(Ps,{className:"w-[220px] h-8 text-xs",children:e.jsx(Rs,{placeholder:"Filter by agent"})}),e.jsxs(Fs,{children:[e.jsx(Je,{value:Ea,children:"Just mine"}),e.jsx(Je,{value:En,children:"All agents"}),p.slice().sort((M,k)=>(M.display_name||M.email).localeCompare(k.display_name||k.email)).map(M=>e.jsx(Je,{value:M.id,children:M.display_name||M.email},M.id))]})]})]}):null;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(ss,{className:"h-4 w-4 text-primary"}),"Salesforce Drafts",e.jsx(J,{variant:"secondary",children:u?`${A.length} of ${l.length}`:l.length})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[z,e.jsx(R,{variant:"ghost",size:"sm",onClick:_,children:"Refresh"})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(na,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(he,{value:u,onChange:M=>g(M.target.value),placeholder:"Search by business, client, email, SF ID, or agentâ¦",className:"pl-8 pr-8 h-9"}),u&&e.jsx("button",{type:"button",onClick:()=>g(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Yt,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>E(M=>!M),className:`inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded-full border transition-colors ${D?"bg-amber-100 dar
124k:bg-amber-950/40 border-amber-300 text-amber-800 dark:text-amber-300":"bg-muted/50 border-border text-muted-foreground hover:bg-muted"}`,children:[e.jsx(hs,{className:"h-3 w-3"}),"Stale ",Ta,"+ days (",q,")"]}),A.length>0&&e.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer select-none",children:[e.jsx(ct,{checked:I,onCheckedChange:H,"aria-label":"Select all shown drafts"}),"Select all shown"]})]}),v.size>0&&e.jsxs(R,{size:"sm",variant:"destructive",onClick:P,disabled:$,className:"gap-1.5",children:[e.jsx(Es,{className:"h-3.5 w-3.5"}),$?"Archivingâ¦":`Archive ${v.size} selected`]})]}),A.length===0?e.jsxs(nt,{className:"p-8 text-center",children:[e.jsx(ss,{className:"mx-auto h-8 w-8 text-primary mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:u?"No matches":"No drafts yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u?`No drafts match "${u}". Try a different search.`:s&&f!==Ea?"No Salesforce drafts match this filter.":"When one of your Salesforce Opportunities moves to Approved, a draft proposal will appear here for you to review and send."})]}):e.jsx("div",{className:"grid gap-2",children:A.map(M=>
124{const k=M.user_id&&y.get(M.user_id)?y.get(M.user_id):M.agent_email,w=Tn(M);return e.jsxs(nt,{className:"p-4 flex items-center justify-between gap-4",children:[e.jsx(ct,{checked:v.has(M.id),onCheckedChange:()=>C(M.id),"aria-label":`Select ${M.business_name??"draft"}`,className:"shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[M.salesforce_opportunity_id?e.jsxs("a",{href:Ja(M.salesforce_opportunity_id),target:"_blank",rel:"noopener noreferrer",title:"Open Salesforce opportunity",className:"font-medium truncate inline-flex items-center gap-1 hover:text-primary hover:underline",children:[M.business_name??"Untitled",e.jsx(It,{className:"h-3 w-3 opacity-60"})]}):e.jsx("div",{className:"font-medium truncate",children:M.business_name??"Untitled"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-2 mt-1",children:[s&&k&&e.jsx(J,{variant:"outline",className:"text-[10px] py-0",children:k}),M.client_name&&e.jsx("span",{children:M.client_name}),M.email?e.jsx("span",{className:"truncate max-w-[220px]",children:M.email}):e.jsx(J,{variant:"outline",className:"text-[10px] py-0",children:"no client email yet"}),M.intended_use_of_funds&&e.jsx("span",{children:M.intended_use_of_funds}),M.salesforce_opportunity_id&&e.jsxs("span",{className:"font-mono",children:["SF: ",M.salesforce_opportunity_id]}),e.jsx("span",{children:new Date(M.created_at).toLocaleDateString()}),w>=Ta&&e.jsxs(J,{variant:"outline",className:"text-[10px] py-0 border-amber-300 text-amber-700 dark:text-amber-400",children:[w,"d old"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(R,{size:"sm",onClick:()=>S(Lt(M.type,M.id)),className:"gap-1",children:[e.jsx(It,{className:"h-3.5 w-3.5"}),"Review & Send"]}),e.jsx(R,{size:"icon",variant:"ghost",onClick:()=>N(M.id),"aria-label":"Dismiss draft",children:e.jsx(Is,{className:"h-4 w-4 text-destructive"})})]})]},M.id)})})]})}const ki="https://csyxlckznzmelqrzfmna.supabase.co";async function Si(t,s){const a=t==null?void 0:t.context;if(a!=null&&a.text)try{const r=await a.text(),i=JSON.parse(r);if(i!=null&&i.error)return i.error;if(r.trim())return r.trim().slice(0,200)}catch{}const n=t instanceof Error?t.message:"";return n&&!/non-2xx/i.test(n)?n:s}function Sh(){const t=Ke(y=>y.user),[s,a]=h.useState(!1),[n,r]=h.useState(""),[i,l]=h.useState(null),[o,c]=h.useState(!1),[m,f]=h.useState(""),d=h.useRef(null),u=(t==null?void 0:t.email)||"",g=u.toLowerCase().endsWith(`@${ra}`),D=g?ur(u):"",E=g?m||Ls(u):"";h.useEffect(()=>{!(t!=null&&t.id)||!g||F.from("profiles").select("signature_display_name").eq("id",t.id).maybeSingle().then(({data:y})=>{y!=null&&y.signature_display_name&&f(y.signature_display_name)})},[t==null?void 0:t.id,g]);const v=h.useMemo(()=>D?`${Pt()}${yl(D,"shared_link")}`:"",[D]),x=v?`https://api.qrserver.com/v1/create-qr-code/?size=220x220&margin=0&data=${encodeURIComponent(v)}`:"";if(h.useEffect(()=>{if(!(t!=null&&t.id)||!g)return;let y=!1;return(async()=>{for(const q of["jpg","png"]){const A=`${ki}/storage/v1/object/public/email-assets/agent-photos/${t.id}.${q}?v=${Date.now()}`;try{if((await fetch(A,{method:"HEAD"})).ok&&!y){l(A);return}}catch{}}y||l(null)})(),()=>{y=!0}},[t==null?void 0:t.id,g]),!g)return e.jsx(nt,{className:"p-6 max-w-xl mx-auto",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Contact cards are available for Quick Capital Funding agent accounts (@",ra,")."]})});const $=async()=>{try{await navigator.clipboard.writeText(v),U.success("Link copied")}catch{U.error("Copy failed â long-press the field to copy")}},T=async()=>{const y=n.replace(/\D/g,"");if(y.length<10){U.error("Enter a valid 10-digit phone number");return}a(!0);try{const q=y.length===10?`+1${y}`:`+${y}`,A=`This is Quick Capital Funding sharing ${E}'s contact card on their behalf. Save it so ${E}'s direct calls are recognized: ${v}`,N=await Ts({to:q,message:A,templateType:"contact_card_share"});if(!N.ok){U.error(N.message);return}U.success(ea(N,n))}catch(q){console.error(q),U.error("Couldn't send SMS â try copy/paste instead")}finally{a(!1)}},S=y=>new Promise((q,A)=>{const N=new Image;N.crossOrigin="anonymous",N.onload=()=>{const I=Math.min(1024,Math.max(N.width,N.height)),H=document.createElement("canvas");H.width=I,H.height=I;const P=H.getContext("2d");if(!P)return A(new Error("Canvas not available"));P.imageSmoothingEnabled=!0,P.imageSmoothingQuality="high",P.fillStyle="#ffffff",P.fillRect(0,0,I,I);const z=Math.max(I/N.width,I/N.height),M=N.width*z,k=N.height*z;P.drawImage(N,(I-M)/2,(I-k)/2,M,k);const w=N.src,L=()=>URL.revokeObjectURL(w),O=ae=>{H.toBlob(te=>{if(!te)return L(),A(new Error("Encode failed"));if(te.size>800*1024&&ae>.72)return O(ae-.04);L(),q(te)},"image/jpeg",ae)};O(.95)},N.onerror=()=>{URL.revokeObjectURL(N.src),A(new Error("Could not read image"))},N.src=URL.createObjectURL(y)}),p=async y=>{var N;const q=(N=y.target.files)==null?void 0:N[0];if(y.target.value="",!q||!(t!=null&&t.id))return;if(!(q.type.startsWith("image/")||/\.(jpe?g|png|webp|heic|heif|gif|bmp|tiff?)$/i.test(q.name))){U.error("Please pick an image file (JPG, PNG, HEIC or WEBP)");return}if(q.size>25*1024*1024){U.error("Image too large (max 25MB)");return}c(!0);try{let C=q,I=q.type||"image/png",H=/\.png$/i.test(q.name)?"png":"jpg";try{C=await S(q),I="image/jpeg",H="jpg"}catch(L){if(console.warn("Photo conversion failed, uploading original",L),C.size>5*1024*1024)throw new Error("This image is too large to use â please save it under 5MB and try again.");I.startsWith("image/")||(I="image/png")}const P=new File([C],`photo.${H}`,{type:I}),z=new FormData;z.append("photo",P);const{data:M,error:k}=await F.functions.invoke("upload-agent-photo",{body:z});if(k)throw new Error(await Si(k,"Couldn't upload photo"));if(M!=null&&M.error)throw new Error(M.error);H=(M==null?void 0:M.ext)==="png"?"png":"jpg";const w=`${ki}/storage/v1/object/public/email-assets/agent-photos/${t.id}.${H}?v=${Date.now()}`;l(w),U.success("Photo updated â clients who re-save your card will see it")}catch(C){console.error(C),U.error(C instanceof Error?C.message:"Couldn't upload photo")}finally{c(!1)}},_=async()=>
124{if(t!=null&&t.id){c(!0);try{const{data:y,error:q}=await F.functions.invoke("upload-agent-photo",{body:{action:"remove"}});if(q)throw new Error(await Si(q,"Couldn't remove photo"));if(y!=null&&y.error)throw new Error(y.error);l(null),U.success("Photo removed â card falls back to the QCF logo")}catch(y){console.error(y),U.error(y instanceof Error?y.message:"Couldn't remove photo")}finally{c(!1)}}};return e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"My Contact Card"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:'Share this link with clients. When they tap "Save to Contacts", your direct line and Nick Far (Funding Manager) are added together â so future calls from either are recognized instead of showing as unknown.'})]}),e.jsx(nt,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-20 h-20 rounded-full overflow-hidden bg-muted border-2 border-border flex items-center justify-center shrink-0",children:i?e.jsx("img",{src:i,alt:"Your caller-ID photo",className:"w-full h-full object-cover"}):e.jsx(od,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Caller ID photo"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Add your face â it shows on the client's phone when you call after they save your card. JPG / PNG / HEIC. If you skip this, the QCF logo is used."}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3",children:[e.jsx("input",{ref:d,type:"file",accept:"image/*",className:"hidden",onChange:p}),e.jsxs(R,{size:"sm",onClick:()=>{var y;return(y=d.current)==null?void 0:y.click()},disabled:o,children:[e.jsx(vd,{className:"h-4 w-4 mr-1.5"}),o?"Uploading...":i?"Replace photo":"Upload photo"]}),i&&e.jsxs(R,{size:"sm",variant:"outline",onClick:_,disabled:o,children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"}),"Remove"]})]})]})]})}),e.jsxs(nt,{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Your shareable link"}),e.jsxs("div",{className:"flex gap-2 mt-1.5",children:[e.jsx(he,{value:v,readOnly:!0,onFocus:y=>y.currentTarget.select(),className:"font-mono text-sm"}),e.jsxs(R,{onClick:$,variant:"outline",size:"sm",className:"shrink-0",children:[e.jsx(_t,{className:"h-4 w-4 mr-1.5"}),"Copy"]}),e.jsx(R,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsxs("a",{href:v,target:"_blank",rel:"noreferrer",children:[e.jsx(It,{className:"h-4 w-4 mr-1.5"}),"Preview"]})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:["Agent: ",e.jsx("span",{className:"font-medium text-foreground",children:E})," · slug"," ",e.jsx("code",{className:"text-xs",children:D})]})]}),e.jsxs("div",{className:"grid sm:grid-cols-[1fr_220px] gap-5 pt-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Send link to a client by SMS"}),e.jsxs("div",{className:"flex gap-2 mt-1.5",children:[e.jsx(he,{type:"tel",placeholder:"(555) 123-4567",value:n,onChange:y=>r(y.target.value)}),e.jsxs(R,{onClick:T,disabled:s,className:"shrink-0",children:[e.jsx(ts,{className:"h-4 w-4 mr-1.5"}),s?"Sending...":"Send"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:"Goes from the Quick Capital Funding number."})]}),e.jsxs("div",{className:"rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 flex gap-2",children:[e.jsx(qt,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:"Your direct line pulls from your profile. If yours is missing, contact an admin to set it."})]})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-block p-2 bg-white border border-border rounded-lg",children:e.jsx("img",{src:x,alt:"QR code for your contact c
124ard",width:180,height:180})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:"Scan to open"})]})]})]}),e.jsxs(nt,{className:"p-5",children:[e.jsx("h3",{className:"text-sm font-semibold mb-2",children:"How clients use it"}),e.jsxs("ol",{className:"text-sm text-muted-foreground space-y-1.5 list-decimal pl-5",children:[e.jsx("li",{children:"You text/email the link."}),e.jsx("li",{children:'They open it on their phone and tap "Save to Contacts".'}),e.jsx("li",{children:'You and Nick Far are added under one contact â incoming calls show your name, not "Unknown".'})]})]})]})}const $n=[{key:"working-capital",kind:"calculator",path:"/resources/working-capital",title:"What could working capital do?",description:"Explore industry examples, extra profit, payment timing and possible tax write-offs.",useWhen:"Walk through how funding could support extra work, then email or copy the example for your client.",stage:"Comparing options",icon:jd,templateType:"resource_share_working_capital",message:t=>`Hereâs a working-capital example we can walk through together: ${t} Change the numbers to explore extra work, costs, repayment timing and possible tax write-offs. This is a hypothetical example, not a promise of results. Please review the tax assumptions with your tax professional.`},{key:"how-we-work",kind:"guide",path:"/resources/how-we-work",title:"How we work with you",description:"Our process, your specialistâs role, and the next step.",useWhen:"A client wants to know what working with QCF looks like.",stage:"Getting started",icon:Tu,templateType:"resource_share_how_we_work",message:t=>`Hereâs how we work with you, from understanding your business to reviewing financing options: ${t}`},{key:"financing-fit",kind:"guide",path:"/financing-fit",title:"Find your financing fit",description:"Compare long-term financing and working capital around your business needs.",useWhen:"A client is choosing between financing routes.",stage:"Comparing options",icon:ha,templateType:"resource_share_financing_fit",message:t=>`This guide can help you compare long-term financing and working capital, with a short fit check: ${t}`},{key:"bank-loans",kind:"guide",path:"/bank-loans",title:"SBA & Bank Term Loans",description:"Compare the bank-partner programs and prepare an application package.",useWhen:"A client is considering an SBA or bank term loan.",stage:"Comparing options",icon:Pc,templateType:"resource_share_bank_loans",message:t=>`Hereâs our SBA & bank term-loan guide, including program requirements and the application package: ${t}`},{key:"funding-checklist",kind:"guide",path:"/resources/funding-checklist",title:"Your funding checklist",description:"Prepare the right documents and know what to confirm with your specialist.",useWhen:"A client is ready to gather documents.",stage:"Ready to proceed",icon:Xi,templateType:"resource_share_funding_checklist",message:t=>`Hereâs a preparation checklist for your funding request. Iâll confirm which documents apply to your program: ${t}`},{key:"understand-your-offer",kind:"guide",path:"/resources/understand-your-offer",title:"Understand your offer",description:"Review proceeds, payment timing, fees, and early-payoff terms together.",useWhen:"A client has an offer and wants a clear walkthrough.",stage:"Ready to proceed",icon:Rc,templateType:"resource_share_understand_offer",message:t=>`Use this guide alongside your offer to review what you receive, what you pay, and which terms to confirm: ${t}`},{key:"apr-explained",kind:"calculator",path:"/apr-explained",title:"APR vs cents on the dollar",description:"See how APR, total repayment, and dollar cost describe the same offer.",useWhen:"A client asks how the cost measures compare.",stage:"Comparing options",icon:Xn,templateType:"resource_share_apr_explained",message:t=>`This explains APR, cents on the dollar, and total repayment, with a calculator to explore the numbers: ${t}`}];function Ch(t){const s=(t??"").trim().toLowerCase();if(!s.endsWith(`@${ra}`))return null;const a=ur(s);return wd(a)?a:null}function Dh(t,s){return{key:`video-${t.slug}
124`,path:Nd(t,s),title:t.title,description:t.summary,useWhen:t.useWhen,stage:t.stage,icon:hr,templateType:`resource_share_video_${t.slug.replace(/-/g,"_")}`,message:a=>_d(t,a),greeting:t.language==="es"?"Hola":void 0}}const Th=["balance","capital","compare","ondeck","kapitus"],ey=[{id:"quick-estimates",label:"Quick estimates",items:[{key:"balance",label:"Estimate a balance",description:"Estimate remaining scheduled payback, not a lender payoff quote."},{key:"capital",label:"Model working capital",description:"Build a hypothetical client example around costs and payment timing."},{key:"compare",label:"Compare offers & consolidation",description:"Compare up to three offers and model an entered payoff stack on the same payment basis."}]},{id:"lender-tools",label:"Lender-specific tools",items:[{key:"ondeck",label:"OnDeck pricing & amortization",description:"Retention pricing, term-loan pricing and payment schedules."},{key:"kapitus",label:"Kapitus early payoff",description:"Explore the existing lender-specific early-payoff schedules."}]}],wo="financing-fit",vo="resources-personalize";function ty(t){return Th.find(s=>s===t)??"ondeck"}function sy(t,s){const a=new URLSearchParams(t);return a.set("tab","ondeck"),a.set("calculator",s),`/dashboard?${a.toString()}`}function ay(t){const s=new URLSearchParams(t);return s.set("tab","resources"),s.delete("calculator"),s.set("resource",wo),`/dashboard?${s.toString()}#${vo}`}const Eh=[{stage:"Getting started",id:"resources-getting-started",lead:"Early conversations: how we work, and how much to take."},{stage:"Comparing options",id:"resources-comparing-options",lead:"When a client is weighing the cost, the payment or another route."},{stage:"Ready to proceed",id:"resources-ready-to-proceed",lead:"Once thereâs an offer: documents, the offer itself, and growing from here."}],Ci=(...t)=>t.filter(Boolean).join(" ").toLowerCase();function jo(t,s,{query:a,type:n,spanishOnly:r,industry:i="all"}){const l=a.trim().toLowerCase(),o=t.filter(m=>n!=="videos"&&(i==="all"||i==="general")&&(!r||m.language==="es")&&Ci(m.title,m.description,m.useWhen).includes(l)),c=s.filter(m=>n!=="guides"&&(i==="all"||(m.industry??"general")===i)&&(!r||m.language==="es")&&Ci(m.title,m.summary,m.useWhen,mr[m.industry??"general"]).includes(l));return Eh.map(m=>({...m,guides:o.filter(f=>f.stage===m.stage),videos:c.filter(f=>f.stage===m.stage)}))}function $h(t,s,a){const n=jo(t,s,{...a,type:"all"}),r=n.reduce((l,o)=>l+o.guides.length,0),i=n.reduce((l,o)=>l+o.videos.length,0);return{all:r+i,guides:r,videos:i}}function Ah(t){const s=t.replace(/\D/g,"");return s.length===10?`+1${s}`:s.length===11&&s.startsWith("1")?`+${s}`:null}function _o({resource:t,initialChannel:s="text"}){var H;const a=Ke(P=>P.user),[n,r]=h.useState(""),[i,l]=h.useState(""),[o,c]=h.useState(null),[m,f]=h.useState(""),[d,u]=h.useState(""),[g,D]=h.useState(s),[E,v]=h.useState(t.title),x=`${Pt()}${t.path}`,[$,T]=h.useState(t.message(x)),[S,p]=h.useState(!1),[_,y]=h.useState(null);h.useEffect(()=>{const P=setTimeout(()=>l(n.trim()),200);return()=>clearTimeout(P)},[n]);const q=ve({queryKey:["resource-client-search",a==null?void 0:a.id,i],enabled:!!(a!=null&&a.id)&&i.length>=2&&!o,queryFn:async()=>{const{data:P,error:z}=await F.from("proposals").select("id, business_name, client_name, phone, email").eq("user_id",a.id).eq("is_archived",!1).or(er(["business_name","client_name","email"],i)).order("created_at",{ascending:!1}).limit(8);if(z)throw z;return P}});async function A(P){try{await navigator.clipboard.writeText(P),U.success("Copied")}catch{U.error("Copy failed. Select the text and copy it manually.")}}function N(P){var z;c(P),f(P.phone??""),u(P.email??""),y(null),T(`${(z=P.client_name)!=null&&z.trim()?`${t.greeting??"Hi"} ${P.client_name.trim()}, `:""}${t.message(x)}`)}async function C(){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.trim())){y({kind:"error",message:"Enter a valid recipient email address."});return}if(!(!(a!=null&&a.id)||!E.trim()||!$.trim()||S)){p(!0),y(null);try{const{data:P,error:z}=await F.functions.invoke("send-outreach-email",{body:{to:d.trim(),subject:E.trim(),body:$.trim(),proposalId:o==null?void 0:o.id,recipientName:(o==null?void 0:o.client_name)||void 0,scenario:t.templateType,templateLabel:t.title,bccSender:!0}});if(z)throw z;if(P!=null&&P.skipped){y({kind:"error",message:`Not sent: ${P.message||(P.reason==="suppressed"?"this recipient is on the do-not-contact list.":P.reason==="daily_cap"?"the daily email limit has been reached.":"the email service deferred or suppressed this message.")}`});return}if((P==null?void 0:P.success)!==!0)throw new Error("Unconfirmed send");y({kind:"success",message:"Email accepted by the sending service. Delivery is not yet confirmed. A copy was requested for your inbox."})}catch{y({kind:"error",message:"The email send could not be confirmed. Check email history before retrying to avoid sending twice."})}finally{p(!1)}}}async function I(){const P=Ah(m);if(!P){y({kind:"error",message:"Enter a 10-digit US or Canadian number, optionally prefixed with +1."});return}if(!(!(a!=null&&a.id)||!$.trim())){p(!0),y(null);try{const z=await Ts({to:P,message:$.trim(),proposalId:o==null?void 0:o.id,templateType:t.templateType});if(!z.ok&&z.kind==="skipped"){y({kind:"error",message:z.message});return}if(!z.ok)throw new Error(z.message);y({kind:"success",message:z.logged?"Text queued. Delivery will be confirmed by the messaging service.":"Text queued, but it was NOT recorded in SMS History. Tell an admin."})}catch{y({kind:"error",message:"The send could not be confirmed. Check SMS history before retrying to avoid sending twice."})}finally{p(!1)}}}return e.jsxs(xs,{className:"w-full sm:max-w-lg overflow-y-auto",overlayClassName:"bg-black/20",children:[e.jsxs(ps,{className:"text-left",children:[e.jsx(fs,{children:"Share with a client"}),e.jsx(tn,{children:t.title})]}),e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"rounded-xl border bg-muted/30 p-4",children:[e.jsx(de,{htmlFor:"resource-url",className:"text-xs",children:"Public resource link"}),e.jsx(he,{id:"resource-url",readOnly:!0,value:x,className:"mt-2 text-xs",onFocus:P=>P.currentTarget.select()}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>A(x),children:[e.jsx(_t,{className:"mr-2 h-4 w-4"}),"Copy link"]}),e.jsx(R,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:t.path,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(It,{className:"mr-2 h-4 w-4"}),"Preview resource"]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2","aria-label":"Sharing method",children:["email","text"].map(P=>e.jsx(R,{variant:g===P?"default":"outline","aria-pressed":g===P,disabled:S,onClick:()=>{D(P),y(null)},children:P==="email"?"Email":"Text message"},P))}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"resource-client-search",children:"Find a client in your deals"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Optional. Choosing a deal links the message to its timeline."}),o?e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.business_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.client_name})]}),e.jsx(R,{variant:"ghost",size:"sm",disabled:S,onClick:()=>{c(null),f(""),u(""),r(""),T(t.message(x)),y(null)},children:"Change"})]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{id:"resource-client-search",value:n,disabled:S,onChange:P=>r(P.target.value),placeholder:"Business, client name, or email",className:"mt-2"}),n.trim().length>=2&&e.jsx("div",{className:"mt-2 rounded-lg border p-1","aria-label":"Matching clients",children:q.isError?e.jsx("p",{className:"p-2 text-sm",role:"alert",children:"Client search is unavailable. You can enter contact details below."}):q.isFetching||i!==n.trim()?e.jsx("p",{className:"p-2 text-sm",role:"status",children:"Searchingâ¦"}):(H=q.data)!=null&&H.length?q.data.map(P=>e.jsxs("button",{type:"button",className:"block w-full rounded-md p-2 text-left hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>N(P),children:[e.jsx("span",{className:"block text-sm font-medium",children:P.business_name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[P.client_name," · ",P.email]})]},P.id)):e.jsx("p",{className:"p-2 text-sm text-muted-foreground",children:"No matching deals. Enter the clientâs contact details below."})})]})]}),g==="email"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(de,{htmlFor:"resource-email",children:"Recipient email"}),e.jsx(he,{id:"resource-email",type:"email",value:d,disabled:S,onChange:P=>{u(P.target.value),y(null)},className:"mt-2",placeholder:"[email protected]"})]}),o&&d!==o.email&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This address differs from the selected deal. The email will still be logged to ",o.business_name,"."]}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"resource-subject",children:"Email subject"}),e.jsx(he,{id:"resource-subject",value:E,maxLength:200,disabled:S,onChange:P=>{v(P.target.value),y(null)},className:"mt-2"})]})]}):e.jsxs("div",{children:[e.jsx(de,{htmlFor:"resource-phone",children:"Recipient phone"}),e.jsx(he,{id:"resource-phone",type:"tel",inputMode:"tel",placeholder:"(555) 555-5555",value:m,disabled:S,onChange:P=>{f(P.target.value),y(null)},className:"mt-2"}),o&&m!==o.phone&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["This number differs from the selected deal. The text will still be logged to ",o.business_name,"."]})]}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"resource-message",children:"Message preview"}),e.jsx(Rt,{id:"resource-message",value:$,disabled:S,onChange:P=>{T(P.target.value),y(null)},rows:6,maxLength:g==="email"?8e3:1600,className:"mt-2"}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Review the recipient and message before sending. The link contains
124no client identity."})]}),_&&e.jsx("p",{role:_.kind==="error"?"alert":"status",className:`rounded-lg p-3 text-sm ${_.kind==="error"?"bg-destructive/10 text-destructive":"bg-muted"}`,children:_.message}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(R,{disabled:S||!(a!=null&&a.id)||!$.trim()||g==="email"&&(!d.trim()||!E.trim())||g==="text"&&$.length>1600||(_==null?void 0:_.kind)==="success",onClick:()=>void(g==="email"?C():I()),children:[g==="email"&&e.jsx(Be,{className:"mr-2 h-4 w-4"}),S?"Sendingâ¦":g==="email"?"Send email":"Send text"]}),e.jsxs(R,{variant:"outline",onClick:()=>A($),children:[e.jsx(_t,{className:"mr-2 h-4 w-4"}),"Copy message"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g==="email"?"Emails use the existing company email service and its recipient controls.":"Texts use the company number and existing messaging controls."}),e.jsxs("details",{className:"rounded-lg border p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:"Show a QR code"}),e.jsx("img",{loading:"lazy",src:`https://api.qrserver.com/v1/create-qr-code/?size=200x200&margin=0&data=${encodeURIComponent(x)}`,alt:`QR code for ${t.title}`,width:160,height:160,className:"mt-4 rounded bg-white p-2"})]})]})]})}function Ph({video:t,agentSlug:s}){const[a,n]=h.useState(!1),r=Dh(t,s),i=`${Pt()}${r.path}`;async function l(){try{await navigator.clipboard.writeText(i),U.success("Video link copied")}catch{U.error("Copy failed. Open Share with client to copy it from there.")}}return e.jsxs("article",{className:"flex flex-col rounded-xl border bg-card p-4 shadow-sm",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("a",{href:r.path,target:"_blank",rel:"noopener noreferrer",className:"relative block w-20 shrink-0 self-start overflow-hidden rounded-lg border bg-slate-50 sm:w-24","aria-label":`Preview ${t.title}`,children:[e.jsx("img",{src:t.poster,alt:"",className:"aspect-[900/1126] w-full object-cover",loading:"lazy"}),e.jsx(hr,{className:"absolute inset-0 m-auto h-8 w-8 text-white drop-shadow","aria-hidden":"true"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"flex flex-wrap items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:[e.jsx("span",{className:"rounded-full bg-primary/10 px-2 py-0.5 normal-case tracking-normal text-primary",children:mr[t.industry??"general"]}),t.language==="es"&&e.jsx(No,{}),e.jsxs("span",{children:[t.lengthLabel.replace("-"," ")," video"]})]}),e.jsx("h4",{className:"mt-1 text-base font-semibold leading-snug",children:t.title}),e.jsx("p",{className:"mt-1 text-sm leading-relaxed text-muted-foreground",children:t.summary}),t.contentNotice&&e.jsx("p",{className:"mt-2 text-xs text-amber-700",children:t.contentNotice})]})]}),e.jsxs("p",{className:"mt-3 border-t pt-3 text-xs leading-relaxed text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Send when: "}),t.useWhen]}),e.jsxs("div",{className:"mt-auto flex flex-wrap gap-2 pt-3",children:[e.jsxs(as,{open:a,onOpenChange:n,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(R,{size:"sm","aria-label":`Share ${t.title}`,children:[e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Share with client"]})}),a&&e.jsx(_o,{resource:r,initialChannel:"text"})]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>void l(),"aria-label":`Copy link to ${t.title}`,children:[e.jsx(_t,{className:"mr-2 h-4 w-4"}),"Copy link"]}),e.jsx(R,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:r.path,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(It,{className:"mr-2 h-4 w-4"}),"Preview"]})})]})]})}function No(){return e.jsx("span",{className:"rounded-full bg-primary/10 px-1.5 py-0.5 font-semibold normal-case tracking-normal text-primary",children:"En español"})}const Rh=[24,36,60,84,120],Di=(t,s,a)=>Math.min(a,Math.max(s,t));function Fh(){const[t,s]=h.useState(25e4),[a,n]=h.useState(60),[r,i]=h.useState(9.75),l={principal:Di(t||ni,ni,Dd),aprPct:Di(r||ai,ai,Cd),termMonths:a},o=h.useMemo(()=>kd(Pt(),l),[l.principal,l.aprPct,l.termMonths]),c=Sd(l),m=async(d,u)=>{try{await navigator.clipboard.writeText(d),U.success(`${u} copied`)}catch{U.error("Couldn't copy â select and copy manually.")}},f=`Hereâs a comparison using the ${Math.round(l.termMonths/12)}-year offer youâre considering, including repayment timing and future financing needs: ${o}`;return e.jsxs(nt,{children:[e.jsxs(Gn,{children:[e.jsx(Ji,{className:"text-lg",children:"Financing-fit c
124omparison link"}),e.jsx(Fc,{children:"Enter the long-term offer your client is considering. The link opens /financing-fit with the repayment comparison pre-loaded."})]}),e.jsxs(Zs,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(de,{htmlFor:"ffl-amount",children:"Offer amount ($)"}),e.jsx(si,{id:"ffl-amount",value:t,onChange:s,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(de,{children:"Term"}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:Rh.map(d=>e.jsxs("button",{type:"button",onClick:()=>n(d),"aria-pressed":a===d,className:(a===d?"border-primary bg-primary/10 text-primary ":"border-input hover:bg-muted/60 ")+"rounded-md border px-2.5 py-1.5 text-xs font-medium",children:[d/12," yr"]},d))})]}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"ffl-apr",children:"Rate (APR %)"}),e.jsx(si,{id:"ffl-apr",value:r,onChange:i,className:"mt-1"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["That offer's payment: ",e.jsxs("span",{className:"font-semibold text-foreground",children:[In(c),"/mo"]})," ","â explore repayment timing and future financing needs together."]}),e.jsx("div",{className:"rounded-md border bg-muted/40 px-3 py-2 font-mono text-xs break-all",children:o}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs(R,{variant:"outline",className:"flex-1",onClick:()=>void m(o,"Link"),children:[e.jsx(_t,{className:"mr-2 h-4 w-4"})," Copy link"]}),e.jsxs(R,{variant:"outline",className:"flex-1",onClick:()=>void m(f,"Text message"),children:[e.jsx(Au,{className:"mr-2 h-4 w-4"})," Copy as text message"]})]})]})]})}const Ti={all:"All",guides:"Guides & calculators",videos:"Videos"},Fa=vo;function ko(t){var s,a;(a=(s=document.getElementById(t))==null?void 0:s.scrollIntoView)==null||a.call(s,{behavior:"smooth",block:"start"})}function Ei(t){var s;t&&(t.open=!0,(s=t.querySelector("summary"))==null||s.focus({preventScroll:!0}),ko(Fa))}function Lh(){const t=Ke(S=>{var p;return(p=S.user)==null?void 0:p.email}),s=Ch(t),a=Lc(),n=h.useRef(null),r=new URLSearchParams(a.search).get("resource")===wo;h.useEffect(()=>{r&&Ei(n.current)},[r,a.key]);const[i,l]=h.useState(""),[o,c]=h.useState("all"),[m,f]=h.useState("all"),[d,u]=h.useState(!1),g=jo($n,ti,{query:i,type:o,spanishOnly:d,industry:m}),D=$h($n,ti,{query:i,spanishOnly:d,industry:m}),E=g.filter(S=>S.guides.length+S.videos.length>0),v=E.reduce((S,p)=>S+p.guides.length+p.videos.length,0),x=d&&!$n.some(S=>S.language==="es"),$=i!==""||o!=="all"||d||m!=="all";function T(){l(""),c("all"),u(!1),f("all")}return e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6",children:[e.jsxs("header",{children:[e.jsx("h2",{className:"text-2xl font-semibold tracking-tight",children:"Client Share Center"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Guides, calculators and short videos for the next client conversation, in the order a deal moves. Preview one, then share it by text or email."})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative w-full sm:max-w-xs",children:[e.jsx(na,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground","aria-hidden":"true"}),e.jsx(he,{"aria-label":"Search Client Share Center",value:i,onChange:S=>l(S.target.value),placeholder:"Find a guide, calculator or video",className:"pl-9"})]}),e.jsx("div",{className:"-mx-1 flex gap-1 overflow-x-auto px-1 sm:flex-wrap",role:"group","aria-label":"Resource type",children:Object.keys(Ti).map(S=>e.jsxs(R,{variant:o===S?"secondary":"ghost",size:"sm",className:"shrink-0","aria-pressed":o===S,onClick:()=>c(S),children:[Ti[S]," ",e.jsx("span",{className:"ml-1.5 tabular-nums text-muted-foreground",children:D[S]})]},S))}),e.jsxs("div",{className:"flex min-h-9 items-center gap-2 sm:ml-auto",children:[e.jsx(ct,{id:"resources-spanish-only",checked:d,onCheckedChange:S=>u(S===!0)}),e.jsx("label",{htmlFor:"resources-spanish-only",className:"cursor-pointer text-sm font-medium",children:"Spanish only"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3",children:[e.jsx("label",{htmlFor:"resources-industry",className:"w-full text-sm font-medium sm:w-auto",children:"Industry"}),e.jsxs("select",{id:"resources-industry",value:m,onChange:S=>f(S.target.value),className:"h-11 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:w-auto",children:[e.jsx("option",{value:"all",children:"All industries"}
124),Object.entries(mr).map(([S,p])=>e.jsx("option",{value:S,children:p},S))]}),e.jsxs("p",{role:"status",className:"text-xs text-muted-foreground",children:[v," ",v===1?"resource":"resources"," shown"]}),$&&e.jsx(R,{variant:"ghost",size:"sm",onClick:T,className:"ml-auto",children:"Clear filters"})]}),e.jsxs("nav",{"aria-label":"Jump to a stage",className:"-mx-1 flex items-center gap-x-1 gap-y-1 overflow-x-auto whitespace-nowrap border-t px-1 pt-3 text-sm sm:flex-wrap",children:[e.jsx("span",{className:"mr-1 shrink-0 text-muted-foreground",children:"Jump to:"}),g.map(S=>{const p=S.guides.length+S.videos.length;return e.jsxs(R,{variant:"link",size:"sm",className:"h-8 shrink-0 px-2",disabled:p===0,onClick:()=>ko(S.id),children:[S.stage," ",e.jsxs("span",{className:"ml-1 tabular-nums text-muted-foreground",children:["(",p,")"]})]},S.id)}),e.jsx(R,{variant:"link",size:"sm",className:"h-8 shrink-0 px-2",onClick:()=>Ei(n.current),children:"Personalize a comparison"})]}),x&&o!=="videos"&&e.jsx("p",{role:"note",className:"rounded-lg bg-muted/50 px-3 py-2 text-xs text-muted-foreground",children:"Guides and calculators are in English for now. Choose All industries to see every Spanish video."})]}),E.map(S=>e.jsxs("section",{id:S.id,"aria-labelledby":`${S.id}-title`,className:"scroll-mt-20 space-y-4",children:[e.jsxs("div",{className:"border-b pb-2",children:[e.jsx("h3",{id:`${S.id}-title`,className:"text-lg font-semibold",children:S.stage}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.lead})]}),S.guides.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Guides & calculators"}),e.jsx("div",{className:"grid gap-4",style:{gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 280px), 1fr))"},children:S.guides.map(p=>e.jsx(Mh,{resource:p},p.key))})]}),S.videos.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Videos"}),e.jsx("div",{className:"grid gap-4",style:{gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 420px), 1fr))"},children:S.videos.map(p=>e.jsx(Ph,{video:p,agentSlug:s},p.slug))})]})]},S.id)),E.length===0&&e.jsx("p",{className:"rounded-xl border p-6 text-sm text-muted-foreground",children:"No resources match these filters. Change the industry, language or search, or use Clear filters to see everything."}),E.some(S=>S.videos.length>0)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:s?"Video links you share show your contact card under the video.":"Video links show the main Quick Capital Funding number under the video."}),e.jsx("section",{id:Fa,"aria-labelledby":`${Fa}-title`,className:"scroll-mt-20",children:e.jsxs("details",{ref:n,className:"rounded-xl border bg-card p-5",children:[e.jsx("summary",{id:`${Fa}-title`,className:"cursor-pointer text-sm font-medium",children:"Personalize a financing comparison"}),e.jsx("p",{className:"mb-4 mt-3 text-sm text-muted-foreground",children:"Already discussing a long-term offer? Build a comparison using those figures. For an existing QCF offer, use âSend Financing Fitâ or âSend APR breakdownâ on its deal card."}),e.jsx(Fh,{})]})})]})}function Mh({resource:t}){const[s,a]=h.useState(!1);return e.jsxs("article",{className:"flex flex-col rounded-xl border bg-card p-5 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(t.icon,{className:"h-5 w-5 text-primary","aria-hidden":"true"})}),e.jsxs("p",{className:"flex flex-wrap items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:[t.language==="es"&&e.jsx(No,{}),e.jsx("span",{children:t.kind==="calculator"?"Calculator":"Guide"})]})]}),e.jsx("h4",{className:"mt-3 text-base font-semibold leading-snug",children:t.title}),e.jsx("p",{className:"mt-1.5 text-sm leading-relaxed text-muted-foreground",children:t.description}),e.jsxs("p",{className:"mt-3 border-t pt-3 text-xs leading-relaxed text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Use when: "}),t.useWhen]}),t.key==="working-capital"&&e.jsx("a",{href:"/dashboard?tab=ondeck&calculator=capital",className:"mt-3 text-sm font-medium text-primary underline underline-offset-4",children:"Customize an example for a client"}),e.jsxs("div",{className:"mt-auto flex flex-wrap gap-2 pt-4",children:[e.jsxs(as,{open:s,onOpenChange:a,children:[e.jsx(xl,{asChild:!0,children:e.jsxs(R,{size:"sm","aria-label":`Share ${t.title}`,children:[e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Share with client"]})}),s&&e.jsx(_o,{resource:t,initialChannel:t.key==="working-capital"?"email":"text"})]}),e.jsx(R,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:t.path,target:"_blank",rel:"noopener noreferrer","aria-label":`Preview ${t.title}`,children:[e.jsx(It,{className:"mr-2 h-4 w-4"}),"Preview"]})})]})]})}function qh(t){const s=t.replace(/\D/g,"");return s.length===10?`+1${s}`:s.length===11&&s.startsWith("1")?`+${s}`:null}function Oh(t){const s=t.replace(/\D/g,"").slice(0,10);return s.length<4?s:s.length<7?`(${s.slice(0,3)}) ${s.slice(3)}`:`(${s.slice(0,3)}) ${s.slice(3,6)}-${s.slice(6)}`}function Ih({onClear:t}={}){const s=Ke(d=>d.user),[a,n]=h.useState(!1),[r,i]=h.useState(!0),[l,o]=h.useState(""),[c,m]=h.useState(!1);h.useEffect(()=>{if(!(s!=null&&s.id))return;let d=!1;return(async()=>{const{data:u,error:g}=await F.from("profiles").select("phone, talkdesk_phone").eq("id",s.id).maybeSingle();if(d)return;const D=!g&&!!u&&!u.talkdesk_phone&&!u.phone;n(D),i(!1)})(),()=>{d=!0}},[s==null?void 0:s.id]);const f=async()=>{const d=qh(l);if(!d){U.error("Enter a valid 10-digit US phone number");return}if(s!=null&&s.id){m(!0);try{const{error:u}=await F.from("profiles").update({talkdesk_phone:d}).eq("id",s.id);if(u)throw u;
124U.success("Phone saved â your contact card now includes your number."),n(!1)}catch(u){console.error(u),U.error("Failed to save phone. Please try again.")}finally{m(!1)}}};return h.useEffect(()=>{!r&&!a&&(t==null||t())},[r,a,t]),r?null:e.jsx(ut,{open:a,onOpenChange:()=>{},children:e.jsxs(mt,{className:"sm:max-w-md",onPointerDownOutside:d=>d.preventDefault(),onEscapeKeyDown:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault(),children:[e.jsxs(ht,{children:[e.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-amber-100 flex items-center justify-center mb-2",children:e.jsx(es,{className:"h-6 w-6 text-amber-600"})}),e.jsx(xt,{className:"text-center",children:"Add your work phone number"}),e.jsx(kt,{className:"text-center",children:"Your contact card and email signature are missing your phone. Clients who save your card right now only see Nick Far's number. Please add yours to continue."})]}),e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsxs(de,{htmlFor:"phone",className:"flex items-center gap-1.5",children:[e.jsx(qt,{className:"h-3.5 w-3.5"})," Work phone"]}),e.jsx(he,{id:"phone",autoFocus:!0,inputMode:"tel",placeholder:"(555) 123-4567",value:l,onChange:d=>o(Oh(d.target.value)),onKeyDown:d=>{d.key==="Enter"&&f()}}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This becomes your assigned line. Once set, only an admin can change it."})]}),e.jsx(da,{children:e.jsx(R,{className:"w-full",onClick:f,disabled:c,children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"h-4 w-4 mr-2 animate-spin"})," Savingâ¦"]}):"Save and continue"})})]})})}function Uh({ready:t=!0,release:s=Ed}){const a=Ke(l=>{var o;return(o=l.user)==null?void 0:o.id}),[n,r]=h.useState(!1);h.useEffect(()=>{t&&Td(s,a,ri())&&r(!0)},[t,s,a]);const i=()=>{a&&Pd(s,a,ri()),r(!1)};return e.jsx(ut,{open:n,onOpenChange:l=>l?r(!0):i(),children:e.jsxs(mt,{className:"flex max-h-[90dvh] max-w-2xl flex-col gap-0 overflow-hidden p-0",children:[e.jsxs(ht,{className:"border-b px-5 pb-4 pt-5 text-left sm:px-6",children:[e.jsxs(xt,{className:"flex items-center gap-2 pr-6 text-xl",children:[e.jsx(ss,{className:"h-5 w-5 text-primary","aria-hidden":!0}),s.title]}),e.jsxs(kt,{children:[s.period,". Quick updates to help you prepare, compare and follow up."]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-5 sm:px-6",children:e.jsx($d,{sections:s.sections,idPrefix:"whats-new",onNavigate:i})}),e.jsxs("div",{className:"flex flex-col-reverse items-stretch gap-3 border-t px-5 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-6",children:[e.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ad,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),"See every update from the last 30 days any time under Whatâs new in your profile menu."]}),e.jsx(R,{onClick:i,className:"h-11 w-full sm:w-auto",children:"Got it"})]})]})})}const zh="https://csyxlckznzmelqrzfmna.supabase.co";function $i(t){if(!t)return{e164:null,display:null};const s=t.replace(/\D/g,"");if(s.length===10)return{e164:`+1${s}`,display:`(${s.slice(0,3)}) ${s.slice(3,6)}-${s.slice(6)}`};if(s.length===11&&s.startsWith("1")){const a=s.slice(1);return{e164:`+${s}`,display:`(${a.slice(0,3)}) ${a.slice(3,6)}-${a.slice(6)}`}}return{e164:`+${s}`,display:t}}function Bh(){const t=Ke(K=>K.user),s=(t==null?void 0:t.email)||"",a=s.toLowerCase().endsWith(`@${ra}`),n=a?ur(s):"",r=a?Ls(s):"",[i,l]=h.useState(""),[o,c]=h.useState(Jt.defaultTitle),[m,f]=h.useState(Jt.defaultTagline),[d,u]=h.useState(""),[g,D]=h.useState(""),[E,v]=h.useState(""),[x,$]=h.useState(""),[T,S]=h.useState(""),[p,_]=h.useState(!0),[y,q]=h.useState(!0),[A,N]=h.useState(!0),[C,I]=h.useState(!1),[H,P]=h.useState(!0),[z,M]=h.useState(!0),[k,w]=h.useState(null),[L,O]=h.useState(null),[ae,te]=h.useState(""),[V,G]=h.useState(""),[Z,se]=h.useState("idle"),[Y,ne]=h.useState(!1),[fe,_e]=h.useState(!1),ge=h.useRef(""),me=h.useRef(null),b=h.useRef(null);h.useEffect(()=>{if(!(t!=null&&t.id)||!a){_e(!0);return}(async()=>{var xe,Ge;const[{data:K},{data:qe}]=await Promise.all([F.from("profiles").select("phone, talkdesk_phone, signature_title, signature_tagline, signature_calendly_url, signature_linkedin_url, signature_display_name, signature_phone_override, signature_email_override, signature_address_override, signature_show_logo, signature_show_headshot").eq("id",t.id).maybeSingle(),F.from("admin_settings").select("setting_key, setting_value").in("setting_key",["signature_social_proof","signature_compliance_line"])]),et=(K==null?void 0:K.signature_title)||Jt.defaultTitle,Qe=(K==null?void 0:K.signature_tagline)??Jt.defaultTagline,Ue=(K==null?void 0:K.signature_calendly_url)||"",yt=(K==null?void 0:K.signature_linkedin_url)||"",Ae=(K==null?void 0:K.signature_display_name)||"",pt=(K==null?void 0:K.signature_phone_override)||"",Pe=(K==null?void 0:K.signature_email_override)||"",wt=(K==null?void 0:K.signature_address_override)||"",re=(K==null?void 0:K.signature_show_logo)??!0,ce=(K==null?void 0:K.signature_show_headshot)??!0;K&&w(K.talkdesk_phone||K.phone||null),c(et),f(Qe),u(Ue),D(yt),l(Ae),v(pt),$(Pe),S(wt),_(re),q(ce);const we=(xe=qe==null?void 0:qe.find(Oe=>Oe.setting_key==="signature_social_proof"))==null?void 0:xe.setting_value,Ne=(Ge=qe==null?void 0:qe.find(Oe=>Oe.setting_key==="signature_compliance_line"))==null?void 0:Ge.setting_value;te(typeof we=="string"?we:""),G(typeof Ne=="string"?Ne:""),ge.current=JSON.stringify({title:et,tg:Qe,cal:Ue,li:yt,dn:Ae,po:pt,eo:Pe,ao:wt,sl:re,sh:ce}),_e(!0)})()},[t==null?void 0:t.id,a]),h.useEffect(()=>{if(!(t!=null&&t.id)||!a)return;let K=!1;return(async()=>{for(const qe of["jpg","png"]){const et=`${zh}/storage/v1/object/public/email-assets/agent-photos/${t.id}.${qe}?v=${Date.now()}`;try{if((await fetch(et,{method:"HEAD"})).ok&&!K){O(et);return}}catch{}}K||O(null)})(),()=>{K=!0}},[t==null?void 0:t.id,a]);const W=h.useMemo(()=>$i(k),[k]),oe=h.useMemo(()=>E.trim()?$i(E):W,[E,W]),B=n?`${Pt()}${yl(n,"signature")}`:"",Q=i.trim()||r,ie=x.trim()||s,ue={fullName:Q,title:o.trim()||Jt.defaultTitle,tagline:m,email:ie,phoneE164:oe.e164,phoneDis
124play:oe.display,photoUrl:L,vcardUrl:B,calendlyUrl:d.trim()||null,linkedinUrl:g.trim()||null,addressOverride:T.trim()||null,socialProofLine:ae.trim()||null,complianceLine:V.trim()||null,showLogo:p,showHeadshot:y,showWebsite:A,showAddress:C,showVcardButton:H,showTrustpilot:z},Ee=h.useMemo(()=>Jr(ue),[ue]),Ye=h.useMemo(()=>Zr(ue),[ue]),Fe=h.useMemo(()=>Jr({...ue,compact:!0}),[ue]),gs=h.useMemo(()=>Zr({...ue,compact:!0}),[ue]);h.useEffect(()=>{if(!fe||!(t!=null&&t.id)||!a)return;const K=o.trim()||Jt.defaultTitle,qe=m,et=d.trim(),Qe=g.trim(),Ue=i.trim(),yt=E.trim(),Ae=x.trim(),pt=T.trim(),Pe=p,wt=y,re=JSON.stringify({title:K,tg:qe,cal:et,li:Qe,dn:Ue,po:yt,eo:Ae,ao:pt,sl:Pe,sh:wt});if(re!==ge.current)return me.current&&clearTimeout(me.current),me.current=setTimeout(async()=>{se("saving");const{error:ce}=await F.from("profiles").update({signature_title:K,signature_tagline:qe,signature_calendly_url:et||null,signature_linkedin_url:Qe||null,signature_display_name:Ue||null,signature_phone_override:yt||null,signature_email_override:Ae||null,signature_address_override:pt||null,signature_show_logo:Pe,signature_show_headshot:wt}).eq("id",t.id);if(ce){console.error(ce),U.error("Couldn't save signature preferences"),se("idle");return}ge.current=re,se("saved"),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>se("idle"),1800)},700),()=>{me.current&&clearTimeout(me.current)}},[o,m,d,g,i,E,x,T,p,y,fe,t==null?void 0:t.id,a]);const ns=async(K,qe,et)=>{var Qe;try{if(typeof ClipboardItem<"u"&&((Qe=navigator.clipboard)!=null&&Qe.write)){const Ue=new ClipboardItem({"text/html":new Blob([K],{type:"text/html"}),"text/plain":new Blob([qe],{type:"text/plain"})});await navigator.clipboard.write([Ue]),U.success(`${et} copied â paste into Outlook`);return}throw new Error("ClipboardItem unsupported")}catch{try{const Ue=document.createElement("div");Ue.contentEditable="true",Ue.style.position="fixed",Ue.style.left="-9999px",Ue.innerHTML=K,document.body.appendChild(Ue);const yt=document.createRange();yt.selectNodeContents(Ue);const Ae=window.getSelection();Ae==null||Ae.removeAllRanges(),Ae==null||Ae.addRange(yt),document.execCommand("copy"),Ae==null||Ae.removeAllRanges(),document.body.removeChild(Ue),U.success(`${et} copied â paste into Outlook`)}catch{U.error("Copy failed. Try a different browser.")}}},Dt=()=>ns(Ee,Ye,"Full signature"),Gt=()=>ns(Fe,gs,"Reply signature"),Xt=async()=>{try{await navigator.clipboard.writeText(Ye),U.success("Plain text copied")}catch{U.error("Copy failed")}};return a?e.jsxs("div",{className:"max-w-5xl mx-auto space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Email Signature"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Outlook-optimized signature, prefilled with your info. Click ",e.jsx("strong",{children:"Copy signature"}),", then paste it into Outlook's signature editor."]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[360px_1fr] gap-4",children:[e.jsxs(nt,{className:"p-5 space-y-4 h-fit",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Customize"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Everything below is editable. Leave a field blank to use the company default."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(de,{htmlFor:"sig-name",className:"text-xs",children:["Display name ",e.jsxs("span",{className:"text-muted-foreground",children:["(default: ",r,")"]})]}),e.jsx(he,{id:"sig-name",value:i,onChange:K=>l(K.target.value),placeholder:r})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(de,{htmlFor:"sig-title",className:"text-xs",children:"Your title"}),e.jsx(he,{id:"sig-title",value:o,onChange:K=>c(K.target.value),placeholder:"Funding Specialist"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(de,{htmlFor:"sig-tag",className:"text-xs",children:["Tagline ",e.jsx("span",{className:"text-muted-foreground",children:"(under your title â leave blank to hide)"})]}),e.jsx(he,{id:"sig-tag",value:m,onChange:K=>f(K.target.value),placeholder:Jt.defaultTagline,maxLength:90})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(de,{htmlFor:"sig-phone",className:"text-xs",children:["Phone override ",e.jsxs("span",{className:"text-muted-foreground",children:["(company: ",W.display||"not set",")"]})]}),e.jsx(he,{id:"sig-phone",value:E,onChange:K=>v(K.target.value),placeholder:W.display||"(555) 555-5555"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(de,{htmlFor:"sig-email",className:"text-xs",children:["Email override ",e.jsxs("span",{className:"text-muted-foreground",children:["(default: ",s,")"]})]}),e.jsx(he,{id:"sig-email",value:x,onChange:K=>$(K.target.value),placeholder:s,type:"email"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(de,{htmlFor:"sig-ad
124dr",className:"text-xs",children:["Address ",e.jsx("span",{className:"text-muted-foreground",children:"(default: company HQ)"})]}),e.jsx(he,{id:"sig-addr",value:T,onChange:K=>S(K.target.value),placeholder:Jt.companyAddress})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(de,{htmlFor:"sig-cal",className:"text-xs",children:["Calendly / booking link ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(he,{id:"sig-cal",value:d,onChange:K=>u(K.target.value),placeholder:"https://calendly.com/your-handle"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(de,{htmlFor:"sig-li",className:"text-xs",children:["LinkedIn profile ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(he,{id:"sig-li",value:g,onChange:K=>D(K.target.value),placeholder:"https://linkedin.com/in/your-handle"})]}),e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 space-y-2.5",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Show in signature"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer",children:[e.jsx(ct,{checked:p,onCheckedChange:K=>_(K===!0)}),e.jsx("span",{children:"Company logo"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer",children:[e.jsx(ct,{checked:y,onCheckedChange:K=>q(K===!0),disabled:!L}),e.jsxs("span",{children:["My headshot"," ",!L&&e.jsx("span",{className:"text-muted-foreground",children:"(upload one in My Card)"})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer",children:[e.jsx(ct,{checked:A,onCheckedChange:K=>N(K===!0)}),e.jsx("span",{children:"Company website row"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer",children:[e.jsx(ct,{checked:C,onCheckedChange:K=>I(K===!0)}),e.jsx("span",{children:"Office address row"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer",children:[e.jsx(ct,{checked:H,onCheckedChange:K=>P(K===!0)}),e.jsx("span",{children:'"Save my contact card" button'})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer",children:[e.jsx(ct,{checked:z,onCheckedChange:K=>M(K===!0)}),e.jsx("span",{children:"Trustpilot rating link"})]})]}),(ae||V)&&e.jsxs("div",{className:"rounded-md border border-dashed border-primary/30 bg-primary/5 p-3 space-y-1.5",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-primary",children:"Managed by admin"}),ae&&e.jsxs("p",{className:"text-xs text-foreground",children:[e.jsx("strong",{children:"Social proof:"})," ",ae]}),V&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("strong",{children:"Disclaimer:"})," ",V]}),e.jsx("p",{className:"text-[11px] text-muted-foreground italic",children:"These lines appear at the bottom of everyone's signature. Ask an admin to update."})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground h-5","aria-live":"polite",children:[Z==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"h-3.5 w-3.5 animate-spin"})," Savingâ¦"]}),Z==="saved"&&e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"h-3.5 w-3.5 text-emerald-600"})," Saved â will load next time you open this tab"]}),Z==="idle"&&fe&&e.jsx("span",{className:"opacity-70",children:"Changes save automatically"})]})]}),e.jsxs(nt,{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(R,{onClick:Dt,className:"gap-1.5",children:[e.jsx(_t,{className:"h-4 w-4"}),"Copy full signature"]}),e.jsxs(R,{onClick:Gt,variant:"secondary",className:"gap-1.5",children:[e.jsx(_t,{className:"h-4 w-4"}),"Copy reply signature"]}),e.jsxs(R,{onClick:Xt,variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Ft,{className:"h-4 w-4"}),"Copy plain text"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-2",children:e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Full signature â new messages"})}),e.jsx("div",{className:"rounded-md border bg-white p-4 overflow-auto",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:Ee}})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Reply signature â replies & forwards"}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Smaller logo, one-line contact"})]}),e.jsx("div",{className:"rounded-md border bg-white p-4 overflow-auto",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:Fe}})}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:["In Outlook, set this as the signature for ",e.jsx("em",{children:"Replies/forwards"})," so long reply chains stay clean."]})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>ne(K=>!K),className:"flex items-center gap-1.5 text-sm font-medium text-foreground hover:text-primary transition-colors",children:[Y?e.jsx(rr,{className:"h-4 w-4"}):e.jsx(ms,{className:"h-4 w-4"}),"How to install in Outlook"]}),Y&&e.jsxs("div",{className:"mt-3 space-y-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold mb-1",children:"Outlook on the web"}),e.jsxs("ol",{className:"list-decimal pl-5 space-y-1 text-muted-foreground",children:[e.jsxs("li",{children:["Click the gear icon (Settings) â ",e.jsx("em",{children:"Mail"})," â ",e.jsx("em",{children:"Compose and reply"}),"."]}),e.jsxs("li",{children:["Under ",e.jsx("em",{children:"Email signature"}),", click ",e.jsx("em",{children:"+ New signature"}),"."]}),e.jsx("li",{children:"Click in the editor and paste (Ctrl+V / âV)."}),e.jsx("li",{children:"Set it as the default for new messages and replies. Save."})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold mb-1",children:"Outlook Desktop (Windows)"}),e.jsxs("ol",{className:"list-decimal pl-5 space-y-1 text-muted-foreground",children:[e.jsxs("li",{children:[e.jsx("em",{children:"File"})," â ",e.jsx("em",{children:"Options"})," â ",e.jsx("em",{children:"Mail"})," â ",e.jsx("em",{children:"Signaturesâ¦"})]}),e.jsxs("li",{children:["Click ",e.jsx("em",{children:"New"}),', name it "QCF", click into the editor.']}),e.jsx("li",{children:"Paste (Ctrl+V). Set as default for New messages + Replies/forwards. OK."})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold mb-1",children:"Outlook Desktop (Mac)"}),e.jsxs("ol",{className:"list-decimal pl-5 space-y-1 text-muted-foreground",children:[e.jsxs("li",{children:[e.jsx("em",{children:"Outlook"})," menu â ",e.jsx("em",{children:"Settings"})," â ",e.jsx("em",{children:"Signatures"}),"."]}),e.jsxs("li",{children:["Click ",e.jsx("em",{children:"+"}),', name it "QCF", paste into the editor (âV).']}),e.jsxs("li",{children:["Under ",e.jsx("em",{children:"Choose default signature"}),', pick "QCF" for new messages + replies.']})]})]}),e.jsxs("div",{className:"rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900",children:[e.jsx("strong",{children:"Tip:"})," If Outlook strips the formatting, paste again using Keep Source Formatting (Ctrl+Shift+V on Windows). Update your signature any time your title or links change â re-copy and replace."]})]})]})]})]})]}):e.jsx(nt,{className:"p-6 max-w-xl mx-auto",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Email signatures are available for Quick Capital Funding agent accounts (@",ra,")."]})})}const Hh=[{title:"Start from Salesforce",detail:"On Create Proposal, paste the opportunity ID (or open a deal from the SF Drafts tab) and click Pull. Client info, industry, website, and any offers import automatically."}
124,{title:"Add the deal's documents",detail:'Drop the application, offer screenshots, and bank statements into the Document Upload Hub â the AI identifies each file and extracts client info and loan options. If the deal is linked to Salesforce, click "Pull statements from Salesforce" instead of re-uploading.'},{title:"Run AI Analysis",detail:"One click reads the statements and business profile, generates the client consultation, and lights up the Deal Brief â your internal read on revenue, safe sizing, and deal grade."},{title:"Build and check your options",detail:"Enter or adjust loan options. The colored chip on each option shows the payment as a share of the client's revenue â keep it green/blue to right-size the deal."},{title:"Send and track",detail:"Create the proposal and send the email (add a manager under CC if needed). Watch engagement on the Pipeline â you'll see views, hot-lead alerts, and acceptance in real time."}],Ai=[{id:"creating",title:"Creating Proposals",description:"From Salesforce pull to send â the core workflow.",articles:[{id:"sf-import",title:"Importing a deal from Salesforce",intro:"The Salesforce pull fills the form from the opportunity so you never retype what the CRM already knows.",steps:["Open Create Proposal and find the Salesforce Import box at the top.","Paste the opportunity ID (from the SF record's URL) and click Pull.","Review what imported: business/client name, email, phone, industry, website, use of funds, and the deal owner as CC.",'If the opportunity has offers, they import as loan options named by term â "12-Month", "5-Month" â with the lender matched into the internal Bank Name dropdown.'],tips:["Option names are client-visible; the bank name is internal-only. Never put the lender's name in the option name â clients can shop it.","Deals that just got approved also appear in the SF Drafts tab, pre-enriched â starting there saves the copy/paste."]},{id:"upload-hub",title:"Document Upload Hub â one drop zone for everything",intro:"Drop any deal document in one place; the AI classifies it and does the right thing automatically.",points:["Applications â client info (name, email, phone, industry) is extracted and fills the form.","Offer sheets/screenshots â loan options are extracted; you pick which to import.","Bank statements â stored for AI analysis (up to 5).",`Files are classified by reading the PDF's content, not just the filename â but naming statements clearly ("March 2026") never hurts.`]},{id:"sf-statements",title:"Pulling bank statements straight from Salesforce",intro:"If the proposal is linked to a Salesforce opportunity, you don't have to download and re-upload the statements the underwriter already has.",steps:["Link the deal via Salesforce Import (that's what enables the button).",'In the Document Upload Hub, click "Pull statements from Salesforce".',"Statement PDFs load automatically â the application packet is skipped, duplicates are ignored.","Run AI Analysis as usual; the pulled statements feed it exactly like a manual upload."],tips:["When a deal has MoneyThumb data in Salesforce, the tool uses those parsed numbers automatically â even better than re-reading PDFs."]},{id:"ai-analysis",title:"AI Analysis â what it generates and where it's used",intro:"One button runs two analyses: a business read (from website/industry) and a bank-statement read (from the uploaded/pulled statements).",points:["Generates the client consultation: business strength profile, industry insight, use-of-funds validation, and a recommendation.","Powers the proposal's AI teaser, the cash-flow chart, and personalized follow-up emails.","Feeds the internal Deal Brief (revenue, safe sizing, grade).","Documents are analyzed securely and never stored â only the insights are saved."]},{id:"deal-brief",title:"Deal Brief â your internal cheat sheet",intro:"Once the deal has financials, the Deal Brief appears above AI Insights. It's internal only â the client never sees it.",points:[`Paper grade (AâD): the deal's overall quality, revenue-weighted. "(est.)" means it's from the AI read only and will sharpen with full statements.`,"True monthly revenue and average daily balance â real revenue, not transfer-inflated deposits.","Suggested max advance and safe payment ceiling â sizing that keeps the payment near 12% of revenue.","Payment c
124overage per option, plus plain-language strengths and risks (NSFs, negative days, stacking)."],tips:["Use the brief before you finalize offers, not after â it tells you how to structure the deal."]},{id:"loan-options",title:"Loan options â fields, chips, and what the client sees",points:['Name is client-visible. Keep it simple: "12-Month", "6-Month Renewal". Bank Name is internal-only, for your records.',"Enter approved amount + cents-on-dollar (factor) and the totals, payments, and term derive automatically.","The colored chip next to each option is its payment as a % of the client's monthly revenue: green = comfortable, blue = moderate, amber = tight, red = over the safe range.","Duplicate an option to build comparisons fast; mark one as Recommended to highlight it for the client."]},{id:"toggles",title:"Controlling what the client sees",intro:"Every AI/financial element on the client proposal has its own switch in the AI Insights section.",points:[`"Show 'Your Numbers' panel" â the client-facing financial summary (revenue, balance, affordability reassurance).`,'"Show strategic insight" â the AI industry teaser.','"Show cash flow impact chart" â payment vs. deposits visual.','"Use insights in follow-up emails" â personalizes the automated sequence.',"A live preview shows exactly what the client will see before you send."]},{id:"cc-email",title:"CC'ing a manager on the proposal email",points:["Fill the CC Email field in the client info section before creating.","The proposal email goes to the client with you and the CC address copied.","Salesforce import pre-fills the deal owner's email as CC when it isn't you."]},{id:"autosave",title:"Autosave and drafts",points:["The form autosaves as you work â if you navigate away or the browser closes, you'll be offered the draft when you return.","After creating, the success screen gives you the client link, a preview, and a text-message option in one place."]}]},{id:"pipeline",title:"Pipeline & Follow-Up",description:"Tracking deals after you hit send.",articles:[{id:"board",title:"Reading the pipeline board",points:["Cards move through statuses: Pending â Accepted â In Review â Docs â Funded.","The engagement dot + number = how interested the client is (views, time on page, recency).","The Fundability badge = how good the deal is financially (from its statements). Two different things â a hot client on a weak deal, or a great deal going cold, each need different plays.","Hot / Cold / Shopping badges flag behavior: bursts of views, gone quiet, or comparing offers from multiple IPs.","Sort by Fundability to work your strongest paper first; sort by Engagement to strike while clients are looking."]},{id:"action-queue",title:"Action Queue â what to do next",points:["The queue at the top of the Pipeline surfaces deals needing attention: hot leads viewing now, accepted deals missing docs, proposals about to expire, and fresh SF approvals to draft.","Work it top to bottom at the start of your day â it's ordered by urgency."]},{id:"followups",title:"Automatic follow-ups and alerts",points:["Day 1/2/3 follow-up emails go out automatically until the client engages (you can customize or disable each when creating).","You get alerted when a client is viewing the proposal live, opens it repeatedly, or replies to an email.","Client engagement is also pushed to the Salesforce opportunity as activity, so the CRM record stays honest."]},{id:"doc-requests",title:"Document Requests tab",points:["Document-request proposals live in their own tab so the loan pipeline stays clean.","Use them to collect statements or stips with a tracked upload link â you're notified as files land."]}]},{id:"client-view",title:"What the Client Sees",description:"Know their side of the link before you send it.",articles:[{id:"client-page",title:"The proposal page",points:["Options render as cards (or a comparison table) with payments, terms, tax-savings math, and any prepayment schedule.",'"Your Numbers" (if enabled) shows their revenue and balance back to them with an affordability reassurance.',"Each option shows the payment as a share of their monthly revenue â it updates live if they adjust the amount.","Accepting is one flow: pick an option, sign, and get the document checklist. You're notified the moment it happens."]}
124,{id:"adjustments",title:"Client amount adjustments",points:["If you enable adjustments (with a min/max), clients can slide the funding amount â payments and totals scale proportionally.","The affordability line moves with the slider, quietly steering clients toward amounts they can sustain.","You see the adjusted amount they selected when they accept."]},{id:"languages",title:"Spanish-language proposals",points:["Set preferred language to Spanish on the form and the client's proposal page and emails render in Spanish."]}]},{id:"renewals",title:"Renewals & Commissions",description:"The money after the first funding.",articles:[{id:"renewals-tab",title:"Renewals tab",points:["Funded Salesforce deals mirror into your Renewals tab with % paid down â no spreadsheet needed.","Deals past the renewal threshold are flagged; click the business name to open the record in Salesforce directly.","Send a renewal offer email with a statement-upload link in two clicks."]},{id:"commissions",title:"Commission tracker",points:["Log your commission per funded deal in the Commissions tab; funded deals prompt you automatically.","Totals roll up by month so you always know where you stand."]}]},{id:"outreach",title:"Mail Merge & Outreach",description:"Bulk email and SMS without leaving the tool.",articles:[{id:"mm-basics",title:"Running a mail merge",steps:["Open Mail Merge and import contacts: spreadsheet upload, paste from Salesforce, or pull from your pipeline.","Map the columns (the tool auto-detects the usual headers).","Pick or customize a template â merge fields personalize each send.","Send a test to yourself first, then launch. Replies and bounces are tracked."],tips:["Sequences can auto-send proven follow-up templates and stop the moment a contact replies."]},{id:"mm-protection",title:"Contact protection â why a send might be blocked",points:["If you emailed a contact recently, you'll be warned before emailing again (7-day window).","If another agent emailed the contact within the protection window (30 days by default), the send is blocked â that lead is protected.","Admins can tune both windows in Admin Settings."]}]},{id:"tools",title:"Tools & Utilities",description:"The supporting cast.",articles:[{id:"calculators",title:"Lender calculators",points:["The Calculators tab has lender-specific math (OnDeck, Kapitus, and more) for quick quotes without building a proposal."]},{id:"doc-uploader",title:"Doc Uploader",points:['Batch-renames and packages deal documents (statements become "BKST â¦") so submissions to lenders are clean and consistent.']},{id:"sf-drafts",title:"SF Drafts tab",points:["Freshly approved Salesforce opportunities land here automatically, pre-enriched with client contact info â one click starts the proposal."]},{id:"identity",title:"Contact card & email signature",points:["Set up your contact card and HTML signature from the avatar menu â they're used in your outgoing emails and the client-facing pages."]}]},{id:"glossary",title:"Glossary",description:"The terms behind the numbers.",articles:[{id:"terms",title:"Key terms",points:["Factor / cents-on-dollar â total payback per dollar funded. 1.30 means $130k back on $100k.","Coverage ratio â the payment as a share of monthly revenue. Under ~10% is comfortable; over ~20% eats the client's operating cushion.","Paper grade (AâD) â overall deal quality from the financials: revenue first, then banking health, stacking, and consistency.","Fundability vs. engagement â fundability grades the deal; engagement measures the client's interest. Both live on the pipeline card.","Stacking â existing MCA payments already drafting from the client's account. More stacks = less room, lower grade.","True revenue â deposits with transfers stripped out; the number underwriters actually size against.","NSF â a bounced payment (non-sufficient funds). The single fastest way a file gets declined."]}]}];function Vh(t,s){return[t.title,t.intro??"",...t.steps??[],...t.points??[],...t.tips??[]].join(" ").toLowerCase().includes(s)}function Wh({article:t}){return e.jsxs("div",{className:"space-y-3 text-sm",children:[t.intro&&e.jsx("p",{className:"text-muted-foreground",children:t.intro}),t.steps&&e.jsx("ol",{className:"space-y-1.5 list-none",children:t.steps.map((s,a)=>e.jsxs("li",{className:"flex gap-2.5",children:[e.jsx("span",{className:"shrink-0 mt-0.5 h-5 w-5 rounded-full bg-primary/10 text-primary text-[11px] font-semibold flex items-center justify-center",children:a+1}),e.jsx("span",{children:s})]},a))}),t.points&&e.jsx("ul",{className:"space-y-1.5 list-none",children:t.points.map((s,a)=>e.jsxs("li",{className:"flex gap-2.5",children:[e.jsx(St,{className:"shrink-0 mt-0.5 h-4 w-4 text-primary/70"}),e.jsx("span",{children:s})]},a))}),t.tips&&t.tips.length>0&&e.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/5 p-3 space-y-1.5",children:t.tips.map((s,a)=>e.jsxs("p",{className:"flex gap-2 text-xs text-amber-800 dark:text-amber-300",children:[e.jsx(fl,{className:"shrink-0 mt-0.5 h-3.5 w-3.5"}),e.jsx("span",{children:s})]},a))})]})}function Kh(){const[t,s]=h.useState(""),a=t.trim().toLowerCase(),n=h.useMemo(()=>a?Ai.map(i=>({...i,articles:i.articles.filter(l=>Vh(l,a))})).filter(i=>i.articles.length>0):Ai,[a]),r=n.reduce((i,l)=>i+l.articles.length,0);
124return e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs("div",{className:"text-center space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2",children:[e.jsx(Mc,{className:"h-6 w-6 text-primary"}),e.jsx("h2",{className:"text-xl font-semibold",children:"Help & Training"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Everything the tool can do, organized by how you actually work a deal."}),e.jsxs("div",{className:"relative max-w-md mx-auto",children:[e.jsx(na,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(he,{value:t,onChange:i=>s(i.target.value),placeholder:"Search help⦠(e.g. statements, CC, renewals)",className:"pl-9"})]})]}),!a&&e.jsx(nt,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-transparent",children:e.jsxs(Zs,{className:"p-5",children:[e.jsx("h3",{className:"text-sm font-semibold mb-4",children:"Your first proposal in 5 steps"}),e.jsx("ol",{className:"space-y-3 list-none",children:Hh.map((i,l)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"shrink-0 h-6 w-6 rounded-full bg-primary text-primary-foreground text-xs font-bold flex items-center justify-center",children:l+1}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:i.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:i.detail})]})]},l))})]})}),a&&r===0?e.jsxs("p",{className:"text-center text-sm text-muted-foreground py-8",children:["No articles match â",t,"â â try a different term."]}):n.map(i=>e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2",children:[e.jsx("h3",{className:"text-sm font-semibold",children:i.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i.description})]}),e.jsx(Rd,{type:"multiple",value:a?i.articles.map(l=>l.id):void 0,className:"rounded-lg border bg-card divide-y",children:i.articles.map(l=>e.jsxs(Fd,{value:l.id,className:"border-0 px-4",children:[e.jsx(Ld,{className:"text-sm py-3 hover:no-underline",children:l.title}),e.jsx(Md,{className:"pb-4",children:e.jsx(Wh,{article:l})})]},l.id))})]},i.id)),e.jsx("p",{className:"text-center text-xs text-muted-foreground pb-4",children:"Can't find it? Ask your admin â and tell them so it gets added here."})]})}async function Yh(t){const{data:s,error:a}=await F.from("saved_filters").select("*").eq("user_id",t).order("created_at",{ascending:!1});if(a)throw a;return s||[]}async function Qh(t,s,a){const{data:n,error:r}=await F.from("saved_filters").insert({user_id:t,name:s,filter_state:a}).select().single();if(r)throw r;return n}async function Gh(t){const{error:s}=await F.from("saved_filters").delete().eq("id",t);if(s)throw s}function Xh(t){const s=Nt(),{data:a=[],isLoading:n}=ve({queryKey:Me.savedFilters.list(t),queryFn:()=>Yh(t),enabled:!!t,staleTime:60*1e3}),r=Le({mutationFn:({name:l,filterState:o})=>Qh(t,l,o),onSuccess:l=>{s.setQueryData(Me.savedFilters.list(t),(o=[])=>[l,...o]),U.success(`Filter "${l.name}" saved`)},onError:()=>{U.error("Failed to save filter")}}),i=Le({mutationFn:Gh,onSuccess:(l,o)=>{s.setQueryData(Me.savedFilters.list(t),(c=[])=>c.filter(m=>m.id!==o)),U.success("Filter deleted")},onError:()=>{U.error("Failed to delete filter")}});return{filters:a,isLoading:n,saveFilter:(l,o)=>r.mutate({name:l,filterState:o}),deleteFilter:l=>i.mutate(l),isSaving:r.isPending}}function Jh(){return e.jsx("header",{className:"border-b bg-card",children:e.jsxs("div",{className:"max-w-[1600px] mx-auto px-4 lg:px-6 h-16 flex justify-between items-center",children:[e.jsx(je,{className:"h-8 w-40"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(je,{className:"h-8 w-24"}),e.jsx(je,{className:"h-8 w-8 rounded-full"})]})]})})}const Zh=[{value:"created_at",label:"Date Created"},{value:"last_sent_to_client_at",label:"Last sent"},{value:"last_client_viewed_at",label:"Last viewed"},{value:"business_name",label:"Business Name"},{value:"client_name",label:"Client Name"},{value:"status",label:"Status"},{value:"expiration_date",label:"Expiration"},{value:"engagement_score",label:"Engagement"},{value:"deal_health_score",label:"Fundability"}],ex=[{value:"docs_received",label:"Docs Received"},{value:"pending",label:"Pending"},{value:"accepted",label:"Accepted"},{value:"in_final_review",label:"In Review"},{value:"rejected",label:"Rejected"}];function Pi({sortBy:t,onSortByChange:s,sortOrder:a,onSortOrderChange:n,isAdmin:r=!1,agents:i=[],agentFilter:l=null,onAgentFilterChange:o,statusFilter:c=[],onStatusFilterChange:m,leadTempFilter:f=[],onLeadTempFilterChange:d,dateRange:u=null,onDateRangeChange:g,onClearAll:D}){const E=h.useMemo(()=>{let x=0;return c.length&&(x+=c.length),l&&(x+=1),(u!=null&&u.from||u!=null&&u.to)&&(x+=1),x},[c,l,u]),v=x=>{m&&m(c.includes(x)?c.filter($=>$!==x):[...c,x])};return e.jsxs(tr,{children:[e.jsx(sr,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs",children:[e.jsx(Nu,{className:"h-3.5 w-3.5"}),"Sort & Filter",E>0&&e.jsx(J,{variant:"secondary",className:"ml-1 h-4 px-1.5 text-[10px]",children:E})]})}),e.jsx(ar,{className:"w-80 p-0",align:"end",children:e.jsxs("div",{className:"max-h-[70vh] overflow-y-auto",children:[e.jsxs("div",{className:"px-3 py-2.5 border-b",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground mb-1.5",children:"Sort by"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(As,{value:t,onValueChange:x=>s(x),children:[e.jsx(Ps,{className:"h-8 text-xs flex-1",children:e.jsx(Rs,{})}),e.jsx(Fs,{children:Zh.map(x=>e.jsx(Je,{value:x.value,className:"text-xs",children:x.label},x.value))})]}),e.jsx(R,{variant:"outline",size:"icon",className:"h-8 w-8 flex-shrink-0",onClick:()=>n(a==="asc"?"desc":"asc"),title:a==="asc"?"Ascending":"Descending",children:a==="asc"?e.jsx(Od,{className:"h-3.5 w-3.5"}):e.jsx(Id,{className:"h-3.5 w-3.5"})})]})]}),m&&e.jsxs("div",{className:"px-3 py-2.5 border-b",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground mb-1.5",children:"Status"}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:ex.map(x=>e.jsxs("label",{className:"flex items-center gap-1.5 text-xs cursor-pointer hover:bg-muted/50 rounded px-1 py-0.5",children:[e.jsx(ct,{checked:c.includes(x.value),onCheckedChange:()=>v(x.value)}),e.jsx("span",{children:x.label})]},x.value))})]}),r&&o&&i.length>0&&e.jsxs("div",{className:"px-3 py-2.5 border-b",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground mb-1.5",children:"Agent"}),e.jsxs(As,{value:l||"all",onValueChange:x=>o(x==="all"?null:x),children:[e.jsx(Ps,{className:"h-8 text-xs",children:e.jsx(Rs,{})}),e.jsxs(Fs,{children:[e.jsx(Je,{value:"all",className:"text-xs",children:"All agents"}),i.map(x=>e.jsx(Je,{value:x.email,className:"text-xs",children:x.display_name||x.email},x.id))]})]})]}),g&&e.jsxs("div",{className:"px-3 py-2.5 border-b",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground mb-1.5",children:"Date Range (Created)"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(he,{type:"date",value:(u==null?void 0:u.from)||"",onChange:x=>g({from:x.target.value,to:(u==null?void 0:u.to)||""}),className:"h-8 text-xs"}),e.jsx(he,{type:"date",value:(u==null?void 0:u.to)||"",onChange:x=>g({from:(u==null?void 0:u.from)||"",to:x.target.value}),className:"h-8 text-xs"})]})]}),(E>0||D)&&e.jsx("div",{className:"px-3 py-2 flex justify-end",children:e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>D==null?void 0:D(),disabled:E===0,children:[e.jsx(Yt,{className:"h-3 w-3 mr-1"}),"Clear filters"]})})]})})]})}const cs={sentViewed:!0,docs:!0,followUps:!0};function tx({searchQuery:t,onSearchChange:s,sortBy:a,onSortByChange:n,sortOrder:r,onSortOrderChange:i,archiveFilter:l,onArchiveFilterChange:o,counts:c,countsAvailable:m=!0,savedFilters:f=[],activeFilterId:d=null,onApplyFilter:u,onDeleteFilter:g,onSaveFilter:D,isSavingFilter:E=!1,isAdmin:v=!1,agents:x=[],agentFilter:$=null,onAgentFilterChange:T,statusFilter:S=[],onStatusFilterChange:p,dateRange:_=null,onDateRangeChange:y,typeFilter:q=[],onTypeFilterChange:A,leadTempFilter:N=[],onLeadTempFilterChange:C,dealHealthFilter:I=[],onDealHealthFilterChange:H,onClearAdvancedFilters:P,viewMode:z="table",onViewModeChange:M,renewalReadyOnly:k,onRenewalReadyChange:w,filteredCount:L,onViewAllClicked:O,docRequestMode:
124ae=!1,visibleColumns:te=cs,onVisibleColumnsChange:V}){const G=se=>m?se:e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",children:"â"}),e.jsx("span",{className:"sr-only",children:"count not loaded"})]}),Z=[{key:"sentViewed",label:"Sent / Viewed"},{key:"docs",label:"Docs"},{key:"followUps",label:"Follow-ups"}];return e.jsx(e.Fragment,{children:e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b",children:[e.jsxs("div",{className:"flex max-w-full items-center gap-1 overflow-x-auto",children:[e.jsxs("button",{onClick:()=>o("active"),"aria-pressed":l==="active",className:`px-3 py-2 text-xs border-b-2 transition-colors whitespace-nowrap ${l==="active"?"border-primary text-primary font-semibold":"border-transparent text-muted-foreground hover:text-foreground font-medium"}`,children:["Active",e.jsx(J,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:G(c.active)})]}),!ae&&e.jsxs("button",{onClick:()=>o("funded"),"aria-pressed":l==="funded",className:`px-3 py-2 text-xs border-b-2 transition-colors whitespace-nowrap ${l==="funded"?"border-success text-success font-semibold":"border-transparent text-muted-foreground hover:text-foreground font-medium"}`,children:[e.jsx(xa,{className:"inline-block h-3 w-3 mr-1"}),"Funded",e.jsx(J,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0 bg-success/15 text-success",children:G(c.funded)})]}),!ae&&e.jsxs("button",{onClick:()=>o("funding_lost"),"aria-pressed":l==="funding_lost",className:`px-3 py-2 text-xs border-b-2 transition-colors whitespace-nowrap ${l==="funding_lost"?"border-destructive text-destructive font-semibold":"border-transparent text-muted-foreground hover:text-foreground font-medium"}`,children:[e.jsx(pa,{className:"inline-block h-3 w-3 mr-1"}),"Lost",e.jsx(J,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0 bg-destructive/15 text-destructive",children:G(c.fundingLost)})]}),e.jsxs("button",{onClick:()=>o("archived"),"aria-pressed":l==="archived",className:`px-3 py-2 text-xs border-b-2 transition-colors whitespace-nowrap ${l==="archived"?"border-primary text-primary font-semibold":"border-transparent text-muted-foreground hover:text-foreground font-medium"}`,children:["Archived",e.jsx(J,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:G(c.archived)})]}),!ae&&e.jsxs("button",{onClick:()=>o("all"),"aria-pressed":l==="all",className:`px-3 py-2 text-xs border-b-2 transition-colors whitespace-nowrap ${l==="all"?"border-primary text-primary font-semibold":"border-transparent text-muted-foreground hover:text-foreground font-medium"}`,children:["All",e.jsx(J,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:G(c.total)})]})]}),!ae&&e.jsxs(As,{value:q.length===0?"all":q.length===1?q[0]:"multiple",onValueChange:se=>A==null?void 0:A(se==="all"?[]:[se]),children:[e.jsx(Ps,{"aria-label":"Financing type",className:"mb-1 h-9 w-[150px] bg-card text-xs sm:ml-auto",children:e.jsx(Rs,{})}),e.jsxs(Fs,{children:[e.jsx(Je,{value:"all",children:"All financing types"}),e.jsx(Je,{value:"proposal",children:"Loans"}),e.jsx(Je,{value:"line_of_credit",children:"Lines of credit"}),e.jsx(Je,{value:"funding_menu",children:"Funding menus"}),e.jsx(Je,{value:"application",children:"Applications"}),q.length>1&&e.jsxs(Je,{value:"multiple",disabled:!0,children:[q.length," types selected"]})]})]}),l==="funded"&&w&&e.jsxs(R,{variant:k?"default":"outline",size:"sm",className:"h-8 gap-1 text-xs flex-shrink-0",onClick:()=>w(!k),children:[e.jsx(Ct,{className:"h-3 w-3"}),"Renewal Ready"]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"hidden sm:flex w-full flex-wrap items-center gap-2 pb-2",children:[t&&L!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[L," result",L!==1?"s":""]}),M&&e.jsxs("div",{className:"hidden sm:flex items-center border rounded-md",children:[e.jsx(R,{variant:z==="table"?"secondary":"ghost",size:"sm",className:"h-8 px-2 rounded-r-none",onClick:()=>M("table"),title:"Table view","aria-label":"Table view",children:e.jsx($u,{className:"h-4 w-4"})}),e.jsx(R,{variant:z==="kanban"?"secondary":"ghost",size:"sm",className:"h-8 px-2 rounded-l-none",onClick:()=>M("kanban"),title:"Kanban view","aria-label":"Kanban view",children:e.jsx(Du,{className:"h-4 w-4"})})]}),z==="table"&&V&&e.jsxs(tr,{children:[e.jsx(sr,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"h-8 px-2 text-xs gap-1.5",title:"Cho
124ose columns",children:[e.jsx(Cu,{className:"h-3.5 w-3.5"}),"Columns"]})}),e.jsxs(ar,{align:"end",className:"w-44 p-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1.5 px-1",children:"Optional columns"}),e.jsx("div",{className:"space-y-1",children:Z.map(se=>e.jsxs("label",{className:"flex items-center gap-2 px-1 py-1.5 rounded hover:bg-muted cursor-pointer text-sm",children:[e.jsx(ct,{checked:te[se.key],onCheckedChange:Y=>V({...te,[se.key]:Y===!0}),"aria-label":`Show ${se.label} column`}),e.jsx("span",{className:"text-xs",children:se.label})]},se.key))})]})]}),e.jsxs("div",{className:"relative order-first min-w-[220px] flex-1 max-w-md",children:[e.jsx(na,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(he,{type:"text",placeholder:"Search business, client or email","aria-label":"Search deals",value:t,onChange:se=>s(se.target.value),className:"pl-8 pr-7 h-10 w-full rounded-lg bg-card text-sm"}),t&&e.jsx("button",{"aria-label":"Clear deal search",onClick:()=>s(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Yt,{className:"h-3 w-3"})})]}),O&&e.jsx(R,{onClick:O,variant:"ghost",size:"sm",className:"h-8 px-2",title:"Recent views","aria-label":"Recent proposal views",children:e.jsx(bt,{className:"h-3.5 w-3.5"})}),e.jsx(Pi,{sortBy:a,onSortByChange:n,sortOrder:r,onSortOrderChange:i,isAdmin:v,agents:x,agentFilter:$,onAgentFilterChange:T,statusFilter:S,onStatusFilterChange:p,leadTempFilter:N,onLeadTempFilterChange:C,dateRange:_,onDateRangeChange:y,onClearAll:P})]})]}),e.jsxs("div",{className:"flex sm:hidden items-center gap-2 pt-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(na,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(he,{type:"text",placeholder:"Search business, client or email","aria-label":"Search deals",value:t,onChange:se=>s(se.target.value),className:"pl-8 pr-7 h-10 w-full rounded-lg bg-card text-sm"}),t&&e.jsx("button",{"aria-label":"Clear deal search",onClick:()=>s(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Yt,{className:"h-3 w-3"})})]}),t&&L!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[L," result",L!==1?"s":""]}),O&&e.jsx(R,{onClick:O,variant:"ghost",size:"sm",className:"h-8 px-2",title:"Recent views","aria-label":"Recent proposal views",children:e.jsx(bt,{className:"h-3.5 w-3.5"})}),e.jsx(Pi,{sortBy:a,onSortByChange:n,sortOrder:r,onSortOrderChange:i,isAdmin:v,agents:x,agentFilter:$,onAgentFilterChange:T,statusFilter:S,onStatusFilterChange:p,leadTempFilter:N,onLeadTempFilterChange:C,dateRange:_,onDateRangeChange:y,onClearAll:P})]})]})})}function Nr({log:t}){const s=ca(t);return e.jsxs("div",{className:"space-y-1 min-w-[130px]",children:[e.jsx("span",{children:s.location}),s.badge&&s.kind!=="scanner"&&e.jsx("div",{className:"text-[11px] text-sky-700 dark:text-sky-300",children:s.badge}),s.org&&e.jsx("div",{className:"text-[11px] text-muted-foreground",children:s.org})]})}function kr({log:t}){const s=ca(t);return e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:`mt-1 block w-fit rounded px-1.5 py-0.5 text-[11px] ${s.status==="Engaged visitor"?"bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-200":"bg-muted text-muted-foreground"}`,children:s.status})}),e.jsx(De,{side:"bottom",align:"start",collisionPadding:24,className:"max-w-[min(20rem,calc(100vw-3rem))] whitespace-normal",children:s.tooltip})]})})}function So({viewLogs:t}){const s=t.map(ca),a=s.filter(i=>i.status==="Engaged visitor").length,n=s.filter(i=>i.status==="Likely automated scan").length,r=s.filter(i=>i.status==="Unconfirmed visit").length;return e.jsxs("p",{className:"text-xs text-muted-foreground","data-testid":"scan-summary",children:[a," engaged · ",r," unconfirmed · ",n," likely automated. Activity belongs to this proposal; it does not verify who opened it."]})}function Co({log:t}){return e.jsxs("article",{className:"rounded-xl border p-4 space-y-3",children:[t.business_name&&e.jsx("p",{className:"text-sm font-medium",children:t.business_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[new Date(t.viewed_at).toLocaleStr
124ing(),e.jsx(kr,{log:t})]}),e.jsx("div",{className:"text-xs",children:e.jsx(Nr,{log:t})}),e.jsxs("div",{className:"flex gap-2 text-xs text-muted-foreground",children:[Sr(t.device_type),e.jsxs("span",{children:[t.device_type||"Device unknown"," · ",t.browser||"Browser unknown"]})]})]})}const Sr=t=>{if(!t)return e.jsx(Va,{className:"h-4 w-4"});switch(t.toLowerCase()){case"mobile":return e.jsx(pr,{className:"h-4 w-4"});case"tablet":return e.jsx(xr,{className:"h-4 w-4"});default:return e.jsx(Va,{className:"h-4 w-4"})}},sx=t=>!t||t==="unknown"?"Unknown":t,ax=t=>t?t>=60?`${Math.floor(t/60)}m ${t%60}s`:`${t}s`:"â";function nx({open:t,onOpenChange:s,loading:a,viewLogs:n}){return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"max-w-4xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"View Analytics"}),e.jsx(kt,{children:"Visits and interactions on this proposal link"}),e.jsx(So,{viewLogs:n})]}),a?e.jsxs("div",{className:"space-y-2",children:[e.jsx(je,{className:"h-10 w-full"}),e.jsx(je,{className:"h-10 w-full"}),e.jsx(je,{className:"h-10 w-full"})]}):n.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No views recorded yet for this proposal."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3 sm:hidden",children:n.map(r=>e.jsx(Co,{log:r},r.id))}),e.jsx("div",{className:"hidden rounded-md border sm:block",children:e.jsxs(vl,{children:[e.jsx(jl,{children:e.jsxs(Ha,{children:[e.jsx(lt,{children:"Date & Time"}),e.jsx(lt,{children:"Duration"}),e.jsx(lt,{children:"Device"}),e.jsx(lt,{children:"Browser"}),e.jsx(lt,{children:"OS"}),e.jsx(lt,{children:"Location"}),e.jsx(lt,{children:"Referrer"}),e.jsx(lt,{children:"IP Address"})]})}),e.jsx(_l,{children:n.map(r=>e.jsxs(Ha,{children:[e.jsxs(ot,{className:"text-xs whitespace-nowrap",children:[new Date(r.viewed_at).toLocaleString(),e.jsx(kr,{log:r})]}),e.jsx(ot,{className:"text-xs",children:ax(r.session_duration)}),e.jsx(ot,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[Sr(r.device_type),e.jsx("span",{className:"text-xs capitalize",children:r.device_type||"Desktop"})]})}),e.jsx(ot,{className:"text-xs",children:r.browser&&r.browser_version?`${r.browser} ${r.browser_version}`:r.browser||"Unknown"}),e.jsx(ot,{className:"text-xs",children:r.os&&r.os_version?`${r.os} ${r.os_version}`:r.os||"Unknown"}),e.jsx(ot,{className:"text-xs",children:e.jsx(Nr,{log:r})}),e.jsx(ot,{className:"text-xs max-w-[120px] truncate",title:r.referrer||"Direct",children:r.referrer?new URL(r.referrer).hostname:"Direct"}),e.jsx(ot,{className:"text-xs",children:sx(r.viewer_ip)})]},r.id))})]})})]})]})})}function rx({open:t,onOpenChange:s,loading:a,viewLogs:n,onRefresh:r}){return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"max-w-5xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ht,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(xt,{children:"All Proposal Views"}),e.jsx(kt,{children:"Recent views across all your proposals, ordered by time"})]}),r&&e.jsxs(R,{variant:"outline",size:"sm",onClick:r,disabled:a,className:"ml-4 shrink-0",children:[e.jsx(Ct,{className:`mr-1.5 h-3.5 w-3.5 ${a?"animate-spin":""}`}),"Refresh"]})]}),e.jsx(So,{viewLogs:n})]}),a?e.jsxs("div",{className:"space-y-2",children:[e.jsx(je,{className:"h-10 w-full"}),e.jsx(je,{className:"h-10 w-full"}),e.jsx(je,{className:"h-10 w-full"})]}):n.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No views recorded yet for any proposals."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3 sm:hidden",children:n.map(i=>e.jsx(Co,{log:i},i.id))}),e.jsx("div",{className:"hidden rounded-md border sm:block",children:e.jsxs(vl,{children:[e.jsx(jl,{children:e.jsxs(Ha,{children:[e.jsx(lt,{children:"Date & Time"}),e.jsx(lt,{children:"Business"}),e.jsx(lt,{children:"Client"}),e.jsx(lt,{children:"Device"}),e.jsx(lt,{children:"Browser"}),e.jsx(lt,{children:"Location"})]})}),e.jsx(_l,{children:n.map(i=>e.jsxs(Ha,{children:[e.jsxs(ot,{className:"text-xs whitespace-nowrap",children:[new Date(i.viewed_at).toLocaleStr
124ing(),e.jsx(kr,{log:i})]}),e.jsx(ot,{className:"text-xs font-medium",children:i.business_name}),e.jsx(ot,{className:"text-xs",children:i.client_name}),e.jsx(ot,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[Sr(i.device_type),e.jsx("span",{className:"text-xs capitalize",children:i.device_type||"Desktop"})]})}),e.jsx(ot,{className:"text-xs",children:i.browser&&i.browser_version?`${i.browser} ${i.browser_version}`:i.browser||"Unknown"}),e.jsx(ot,{className:"text-xs",children:e.jsx(Nr,{log:i})})]},i.id))})]})})]})]})})}function ix({proposal:t,onNavigate:s,compact:a}){const{data:n,isLoading:r}=ve({queryKey:["readiness",t.id],staleTime:3e4,queryFn:async()=>{var g;const[m,f,d,u]=await Promise.all([F.from("custom_documents").select("id",{count:"exact",head:!0}).eq("proposal_id",t.id),F.from("uploaded_documents").select("custom_document_id, custom_documents!inner(proposal_id)",{count:"exact",head:!0}).eq("custom_documents.proposal_id",t.id),F.from("client_responses").select("id, selected_option_id").eq("proposal_id",t.id).maybeSingle(),F.from("commission_entries").select("id",{count:"exact",head:!0}).eq("proposal_id",t.id)]);return{docsRequired:m.count??0,docsUploaded:f.count??0,hasResponse:!!((g=d.data)!=null&&g.selected_option_id),hasCommission:(u.count??0)>0}}});if(r||!n)return e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground py-2",children:[e.jsx(Ot,{className:"h-3 w-3 animate-spin"})," Checking readinessâ¦"]});const i=t.status==="funded",l=[{key:"response",label:"Client selected an offer",done:n.hasResponse,action:s?()=>s("response"):void 0,actionLabel:"Open"},{key:"docs",label:n.docsRequired===0?"No stips required":`Stips uploaded (${n.docsUploaded}/${n.docsRequired})`,done:n.docsRequired===0||n.docsUploaded>=n.docsRequired,action:s?()=>s("documents"):void 0,actionLabel:"Upload"},{key:"salesforce",label:"Linked to Salesforce opportunity",done:!!t.salesforce_opportunity_id,action:s?()=>s("salesforce"):void 0,actionLabel:"Link"},...i?[{key:"commission",label:"Commission entry recorded",done:n.hasCommission,action:s?()=>s("commission"):void 0,actionLabel:"Add"}]:[]],o=l.filter(m=>m.done).length,c=o===l.length;return e.jsxs("div",{className:a?"space-y-1":"space-y-2 rounded-lg border bg-muted/30 p-3",children:[!a&&e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Handoff readiness"}),e.jsxs("span",{className:`text-xs font-semibold tabular-nums ${c?"text-green-600":"text-muted-foreground"}`,children:[o,"/",l.length]})]}),e.jsx("ul",{className:"space-y-1",children:l.map(m=>e.jsxs("li",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[m.done?e.jsx(St,{className:"h-4 w-4 text-green-600 shrink-0"}):e.jsx(Nl,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:m.done?"text-muted-foreground line-through":"",children:m.label})]}),!m.done&&m.action&&e.jsxs(R,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:m.action,children:[m.actionLabel," ",e.jsx(La,{className:"h-3 w-3 ml-1"})]})]},m.key))})]})}function ny({proposalId:t}){const{data:s}=ve({queryKey:["readiness-pill",t],staleTime:6e4,queryFn:async()=>{var f,d;const[n,r,i,l]=await Promise.all([F.from("custom_documents").select("id",{count:"exact",head:!0}).eq("proposal_id",t),F.from("uploaded_documents").select("custom_document_id, custom_documents!inner(proposal_id)",{count:"exact",head:!0}).eq("custom_documents.proposal_id",t),F.from("proposals").select("salesforce_opportunity_id").eq("id",t).maybeSingle(),F.from("client_responses").select("selected_option_id").eq("proposal_id",t).maybeSingle()]);return{done:((n.count??0)===0||(r.count??0)>=(n.count??0)?1:0)+((f=i.data)!=null&&f.salesforce_opportunity_id?1:0)+((d=l.data)!=null&&d.selected_option_id?1:0),total:3}}});if(!s)return null;const a=s.done===s.total;return e.jsxs("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${a?"bg-green-100 text-green-700":"bg-amber-100 text-amber-700"}`,title:"Handoff readiness",children:[s.done,"/",s.total," ready"]})}function lx({open:t,onOpenChange:s,proposal:a,fundedAmount:n,onFundedAmountChange:r,onConfirm:i,isLoading:l}){return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(xa,{
124className:"h-5 w-5 text-green-600"}),"Mark as Funded"]}),e.jsxs(kt,{children:['Congratulations! Mark "',a==null?void 0:a.business_name,'" as funded to send a congratulations email and start monthly follow-ups.']})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"fundedAmount",className:"text-sm font-medium",children:"Funded Amount (optional)"}),e.jsxs("div",{className:"relative",children:[e.jsx(pl,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(he,{id:"fundedAmount",type:"text",placeholder:"Enter funded amount",value:n,onChange:o=>r(o.target.value),className:"pl-10"})]}),a&&e.jsx(ix,{proposal:a})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(R,{onClick:i,disabled:l,className:"bg-green-600 hover:bg-green-700",children:l?"Processing...":"Mark as Funded & Send Email"})]})]})})}function ox({open:t,onOpenChange:s,proposal:a,onConfirm:n,isLoading:r}){const[i,l]=h.useState(""),[o,c]=h.useState(""),[m,f]=h.useState(null),d=()=>{if(!i.trim()||i.trim().length<10){f("Please provide a reason (at least 10 characters)");return}n(i.trim(),o.trim()||void 0),l(""),c(""),f(null)},u=g=>{g||(l(""),c(""),f(null)),s(g)};return e.jsx(ut,{open:t,onOpenChange:u,children:e.jsxs(mt,{className:"max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(xt,{className:"flex items-center gap-2 text-orange-600",children:[e.jsx(pa,{className:"h-5 w-5"}),"Mark as Funding Lost"]}),e.jsxs(kt,{children:['The lender has rejected the approval for "',a==null?void 0:a.business_name,'". This will stop all automated emails.']})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"fundingLostReason",className:"text-sm font-medium",children:["Reason for Rejection ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Rt,{id:"fundingLostReason",placeholder:"Why did the lender reject the approval...",value:i,onChange:g=>{l(g.target.value),f(null)},className:"min-h-[100px]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"lenderName",className:"text-sm font-medium",children:"Lender Name (optional)"}),e.jsx(he,{id:"lenderName",type:"text",placeholder:"Enter lender name",value:o,onChange:g=>c(g.target.value)})]}),m&&e.jsx("p",{className:"text-sm text-destructive",children:m})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{variant:"outline",onClick:()=>u(!1),disabled:r,children:"Cancel"}),e.jsx(R,{onClick:d,disabled:r,className:"bg-orange-600 hover:bg-orange-700",children:r?"Processing...":"Mark as Funding Lost"})]})]})})}function cx(){const t=Ke(o=>{var c;return(c=o.user)==null?void 0:c.email}),{data:s,isLoading:a,isError:n}=dd("today");if(a)return e.jsx(je,{className:"h-8 w-full rounded-lg"});if(n)return e.jsx("div",{className:"px-3 py-1.5 rounded-lg border border-dashed border-destructive/40 bg-destructive/5 text-xs text-muted-foreground",children:"Today's numbers couldn't load. They'll retry shortly."});const r=ud(s??[],{viewerEmail:t}).filter(o=>o.sent_count>0||o.funded_count>0).sort((o,c)=>c.sent_count-o.sent_count||c.funded_amount-o.funded_amount);if(r.length===0)return e.jsxs("div",{className:"px-3 py-1.5 rounded-lg border border-dashed border-muted-foreground/20 bg-muted/30 flex items-center justify-center gap-2",children:[e.jsx(dr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No proposals sent yet today â be the first!"})]});const i=r.reduce((o,c)=>o+c.sent_count,0),l=r.reduce((o,c)=>o+c.funded_amount,0);return e.jsxs("div",{className:"px-3 py-1.5 rounded-lg border bg-card flex items-center gap-3 overflow-x-auto","aria-label":"Today's activity",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsx(ml,{className:"h-3.5 w-3.5 text-orange-500"}),e.jsx("span",{className:"text-xs font-semibold text-foreground whitespace-nowrap",children:"Today"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums whitespace-nowrap",children:[i," sent",l>0?` · ${In(l)} funded`:""]})]}),e.jsx("div",{className:"h-4 w-px bg-border flex-shrink-0"}),e.jsx("div",{className:"flex items-center gap-3 overflow-x-auto",children:r.map((o,c)=>e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",title:o.agent_email,children:[c===0&&e.jsx(fr,{className:"h-3 w-3 text-amber-500"}),e.jsx("span",{className:`text-xs whitespace-nowrap ${c===0?"font-bold text-foreground":"font-medium text-muted-foreground"} ${o.isYou?"underline decoration-primary/60 underline-offset-2":""}`,children:o.name.split(" ")[0]}),e.jsx("span",{className:`text-xs tabular-nums font-bold ${c===0?"text-foreground":"text-muted-foreground"}`,children:o.sent_count}),o.funded_amount>0&&e.jsx("span",{className:"text-[10px] tabular-nums text-emerald-600 dark:text-emerald-400 whitespace-nowrap",children:In(o.funded_amount)})]},o.agent_email))})]})}const ze={proposal_created:"status",proposal_viewed:"views",email_sent:"emails",email_opened:"emails",email_clicked:"emails",automated_email:"emails",sms_sent:"messages",status_changed:"status",document_uploaded:"documents",client_accepted:"status",proposal_funded:"status",proposal_rejected:"status",proposal_archived:"status",geo_blocked:"security",client_replied:"messages",sms_received:"messages",sf_activity:"messages",digest_click:"messages",financing_fit_quiz:"messages"};async function dx(t){var T,S;const[s,a,n,r,i,l,o,c,m,f,d,u,g]=await Promise.all([F.from("proposals").select("created_at, status, funded_at, funded_amount, rejected_at, rejection_reason, archived_at, salesforce_opportunity_id").eq("id",t).single(),F.from("proposal_view_logs").select("id, viewed_at, device_type, city, state, session_duration, duration_method, browser, os, viewer_ip, viewer_class, network_kind, network_org, engagement_detected_at, engagement_event").eq("proposal_id",t).order("viewed_at",{ascending:!1}).limit(100),F.from("email_logs").select("id, sent_at, subject, template_type, status, recipient_email, sent_by").eq("proposal_id",t).order("sent_at",{ascending:!1}).limit(100),F.from("email_tracking_events").select("id, created_at, event_type, device_type, email_type, link_label, link_url, viewer_class").eq("proposal_id",t).order("created_at",{ascending:!1}).limit(200),F.from("automated_emails").select("id, sent_at, email_type, trigger_reason, followup_number, status").eq("proposal_id",t).order("sent_at",{ascending:!1}).limit(100),F.from("sms_logs").select("id, created_at, status, template_type, recipient_phone, sent_by, message, delivery_status").eq("proposal_id",t).order("created_at",{ascending:!1}).limit(100),F.from("audit_logs").select("id, created_at, action, old_values, new_values, user_email").eq("entity_id",t).order("created_at",{ascending:!1}).limit(100),F.from("uploaded_documents").select("id, uploaded_at, file_name, file_size").eq("proposal_id",t).order("uploaded_at",{ascending:!1}).limit(100),F.from("client_responses").select("id, accepted_at, client_name, selected_option_id").eq("proposal_id",t).limit(50),F.from("proposal_analytics").select("id, created_at, event_type, event_data, viewer_ip").eq("proposal_id",t).in("event_type",["geo_blocked","financing_fit_quiz"]).order("created_at",{ascending:!1}).limit(100),F.from("client_email_replies").select("id, received_at, from_email, from_name, subject, snippet, agent_email").eq("proposal_id",t).order("received_at",{ascending:!1}).limit(100),F.from("digest_click_events").select("id, created_at, action, agent_email, scenario").eq("proposal_id",t).order("created_at",{ascending:!1}).limit(100),F.from("proposal_activity_events").select("*").eq("proposal_id",t).order("occurred_at",{ascending:!1}).limit(1e3)]);if(s.error)throw s.error;const E=[["Visits",a],["Sent emails",n],["Email tracking",r],["Automated emails",i],["Text messages",l],["Status history",o],["Documents",c],["Client responses",m],["Resource activity",f],["Email replies",d],["Agent actions",u],["Detailed offer activity",g]].filter(([,p])=>p.error).map(([p])=>`${p} could not be loaded.`);(((T=g.data)==null?void 0:T.length)||0)===1e3&&E.push("Showing the latest 1,000 offer activity records. Earlier activity may be omitted.");const v=[],x=(S=s.data)==null?void 0:S.salesforce_opportunity_id;if(x){const{data:p}=await F.from("sf_activities").select("id, activity_at, channel, direction, subject, owner_name, owner_email, call_duration_seconds").like("salesforce_opportunity_id",`${x.slice(0,15)}%`).order("activity_at",{ascending:!1}).limit(100);
124(p??[]).forEach(_=>{const y=String(_.channel??"other");v.push({id:`sf-${_.id}`,type:"sf_activity",timestamp:String(_.activity_at),direction:_.direction==="inbound"?"inbound":"outbound",actor:_.owner_email??_.owner_name??void 0,title:y==="call"?`Call logged in Salesforce${_.call_duration_seconds?` (${Math.round(Number(_.call_duration_seconds)/60)}m)`:""}`:`Salesforce ${y==="other"?"activity":y}: ${_.subject??""}`,description:y==="call"?_.subject??void 0:void 0,category:ze.sf_activity})})}if(s.data){const p=s.data;v.push({id:`created-${t}`,type:"proposal_created",timestamp:p.created_at,title:"Proposal created",category:ze.proposal_created}),p.funded_at&&v.push({id:`funded-${t}`,type:"proposal_funded",timestamp:p.funded_at,title:"Proposal funded",description:p.funded_amount?`Amount: $${Number(p.funded_amount).toLocaleString()}`:void 0,category:ze.proposal_funded}),p.rejected_at&&v.push({id:`rejected-${t}`,type:"proposal_rejected",timestamp:p.rejected_at,title:"Proposal rejected",description:p.rejection_reason||void 0,category:ze.proposal_rejected}),p.archived_at&&v.push({id:`archived-${t}`,type:"proposal_archived",timestamp:p.archived_at,title:"Proposal archived",category:ze.proposal_archived})}(a.data||[]).forEach(p=>{if(p.viewer_class==="internal"||!p.viewed_at)return;const _=ca(p),y=_.kind==="scanner",q=p.session_duration?` Recorded ${p.duration_method==="active"?"active":"elapsed"} time: ${Math.round(p.session_duration)}s.`:"";v.push({id:`view-${p.id}`,type:"proposal_viewed",timestamp:p.viewed_at,title:_.status,description:`${_.badge&&!y?_.badge+" · ":""}${_.location}. ${_.tooltip}${q}`,metadata:{browser:p.browser,os:p.os,device:p.device_type,city:p.city,state:p.state,viewer_ip:p.viewer_ip,scanner:y||void 0,network_org:_.org??void 0,confidence:_.status==="Engaged visitor"?"observed":"unknown"},category:ze.proposal_viewed})}),(n.data||[]).forEach(p=>{p.sent_at&&(p.template_type==="documents_complete_notification"&&p.status==="sent"&&v.push({id:`docs-complete-${p.id}`,type:"document_uploaded",timestamp:p.sent_at,direction:"inbound",actor:"client",title:"All requested documents received",description:"Agent alerted by email, bell and text where enabled.",category:ze.document_uploaded}),v.push({id:`email-${p.id}`,type:"email_sent",timestamp:p.sent_at,direction:"outbound",actor:p.sent_by?String(p.sent_by):"automation",title:`Email ${p.status==="sent"?"sent":p.status==="failed"?"failed":"pending"}: ${p.subject||p.template_type||"Unknown"}`,description:`To: ${p.recipient_email}`,metadata:{status:p.status,template:p.template_type},category:ze.email_sent}))}),(r.data||[]).forEach(p=>{if(p.viewer_class==="internal")return;const _=p.viewer_class==="scanner",y=[p.device_type&&`on ${p.device_type}`].filter(Boolean);p.event_type==="open"?v.push({id:`tracking-${p.id}`,type:"email_opened",timestamp:p.created_at,title:_?"Email scanned by mail provider â not the client":`Email open signal${y.length?" "+y.join(" "):""}`,description:"Mail privacy services may trigger this without the recipient reading the email.",metadata:{confidence:"low",emailType:p.email_type,device:p.device_type,scanner:_||void 0},category:ze.email_opened}):p.event_type==="click"&&v.push({id:`tracking-${p.id}`,type:"email_clicked",timestamp:p.created_at,title:_?"Link scanned by mail provider â not the client":`Link clicked${y.length?" "+y.join(" "):""}`,description:p.link_label||p.link_url||void 0,metadata:{url:p.link_url,device:p.device_type,scanner:_||void 0},category:ze.email_clicked})}),(i.data||[]).forEach(p=>{p.sent_at&&v.push({id:`auto-${p.id}`,type:"automated_email",timestamp:p.sent_at,title:`Auto email ${p.status==="sent"?"sent":p.status==="failed"?"failed":"pending"}: ${p.email_type||p.trigger_reason||"Follow-up"}`,description:p.followup_number?`Follow-up #${p.followup_number}`:void 0,metadata:{status:p.status,trigger:p.trigger_reason},category:ze.automated_email})}),(l.data||[]).forEach(p=>{const _=p.template_type==="inbound";v.push({id:`sms-${p.id}`,type:_?"sms_received":"sms_sent",timestamp:p.created_at||new Date().toISOString(),direction:_?"inbound":"outbound",actor:_?"client":p.sent_by?String(p.sent_by):"automation",title:_?"Text received from client":"SMS sent",description:_?p.message||void 0:[p.template_type,p.message].filter(
124Boolean).join(" · ")||void 0,metadata:{status:p.status,delivery_status:p.delivery_status,message:p.message},category:_?ze.sms_received:ze.sms_sent})}),(d.data||[]).forEach(p=>{v.push({id:`reply-${p.id}`,type:"client_replied",timestamp:p.received_at,direction:"inbound",actor:p.from_email||"client",title:`Client replied: ${p.subject||"(no subject)"}`,description:p.snippet||void 0,metadata:{mailbox:p.agent_email,from:p.from_name||p.from_email},category:ze.client_replied})}),(u.data||[]).forEach(p=>{v.push({id:`click-${p.id}`,type:"digest_click",timestamp:p.created_at,direction:"outbound",actor:p.agent_email||void 0,title:`Agent tapped ${p.action==="call"?"Call":p.action==="text"?"Text":"Email"} in the digest`,description:p.scenario||void 0,category:ze.digest_click})}),(o.data||[]).forEach(p=>{var q,A;const _=(q=p.old_values)==null?void 0:q.status,y=(A=p.new_values)==null?void 0:A.status;_&&y&&_!==y&&v.push({id:`audit-${p.id}`,type:"status_changed",timestamp:p.created_at||new Date().toISOString(),title:`Status: ${_} â ${y}`,description:p.user_email?`By: ${p.user_email}`:void 0,category:ze.status_changed})}),(c.data||[]).forEach(p=>{if(!p.uploaded_at)return;const _=p.file_size?`${Math.round(p.file_size/1024)}KB`:null;v.push({id:`doc-${p.id}`,type:"document_uploaded",timestamp:p.uploaded_at,title:`Document: ${p.file_name||"Unknown"}`,description:_||void 0,category:ze.document_uploaded})}),(m.data||[]).forEach(p=>{p.accepted_at&&v.push({id:`accepted-${p.id}`,type:"client_accepted",timestamp:p.accepted_at,title:`Client accepted${p.client_name?`: ${p.client_name}`:""}`,category:ze.client_accepted})});const $={long_term:"leans long-term (SBA / bank term)",working_capital:"leans working capital",blend:"wants a blended capital plan"};return(f.data||[]).filter(p=>p.event_type==="financing_fit_quiz").forEach(p=>{const _=p.event_data,y=String((_==null?void 0:_.recommendation)??"");v.push({id:`fitquiz-${p.id}`,type:"financing_fit_quiz",timestamp:p.created_at,title:`âï¸ Ran the financing-fit quiz â ${$[y]??y}`,description:"Asked for a specialist to review their capital plan",metadata:{recommendation:y},category:ze.financing_fit_quiz,direction:"inbound"})}),(f.data||[]).filter(p=>p.event_type==="geo_blocked").forEach(p=>{const _=p.event_data,y=_!=null&&_.blocked_state?String(_.blocked_state):"Unknown";v.push({id:`geoblock-${p.id}`,type:"geo_blocked",timestamp:p.created_at,title:`ð¡ï¸ Geo-blocked from ${y}`,description:p.viewer_ip?`IP: ${String(p.viewer_ip)}`:void 0,metadata:{state:y},category:ze.geo_blocked})}),v.push(...Ud(g.data||[])),v.sort((p,_)=>new Date(_.timestamp).getTime()-new Date(p.timestamp).getTime()),{events:v,activity:g.data||[],warnings:E}}function ux(t){return ve({queryKey:Me.proposals.timeline(t),queryFn:()=>dx(t),enabled:!!t,staleTime:15*1e3,refetchInterval:30*1e3,refetchIntervalInBackground:!1,refetchOnWindowFocus:!0})}function mx(t){const s=(t||"").trim();return ve({queryKey:["ip-asn",s],enabled:!!s&&s!=="unknown"&&!0,staleTime:24*60*60*1e3,gcTime:24*60*60*1e3,retry:1,queryFn:async()=>{const{data:n,error:r}=await F.functions.invoke("ip-asn-lookup",{body:{ip:s}});if(r)throw r;return n}})}function hx({ip:t,hideIfHuman:s=!0,className:a,size:n="xs",skipAsnLookup:r=!1}){var u,g,D,E;const i=Gc(t),l=mx(r?null:t),o=n==="xs"?"text-[10px]":"text-xs",c=n==="xs"?"px-1.5 py-0":"px-2 py-0.5",m=`gap-1 border-orange-400 bg-orange-50 text-orange-700 dark:bg-orange-950/40 dark:text-orange-300 dark:border-orange-800 font-medium whitespace-nowrap ${o} ${c} ${a??""}`;let f=null,d=null;if(i.relay)return e.jsx(We,{delayDuration:150,children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(J,{variant:"outline",className:`gap-1 border-sky-400 bg-sky-50 text-sky-700 dark:bg-sky-950/40 dark:text-sky-300 dark:border-sky-800 font-medium whitespace-nowrap ${o} ${c} ${a??""}`,children:"Possible privacy relay"})}),e.jsxs(De,{side:"top",className:"max-w-xs text-xs",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Connection type â location unreliable"}),e.jsx("p",{children:i.explanation})]})]})});if(i.provider)f=i.label,d=i.explanation;else if(l.data&&(l.data.is_hosting||l.data.is_proxy)){const v=((g=(u=l.data.org)==null?void 0:u.split(/[,-]/)[0])==null?void 0:g.trim())||((E=(D=l.data.isp)==null?void 0:D.split(/[,-]/)[0])==null?void 0:E.trim())||"Datacenter";f=l.data.is_proxy?"Possible VPN/proxy":"Cloud/shared network",d=l.data.is_proxy?`${v} is a proxy or VPN â this is likely not the actual client's IP.`:`${v} is a hosting/datacenter provider â could carry a person or an automated request.`}return f?e.jsx(We,{delayDuration:150,children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsxs(J,{variant:"outline",className:m,children:[e.jsx(gr,{className:"h-2.5 w-2.5"}),f]})}),e.jsxs(De,{side:"top",className:"max-w-xs text-xs",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Connection type â identity unverified"}),e.jsx("p",{children:d})]})]})}):null}const xx={offer_interaction:{icon:Xs,color:"text-blue-600",bgColor:"bg-blue-50"},active_review:{icon:bt,color:"text-slate-600",bgColor:"bg-slate-100"}
124,proposal_created:{icon:aa,color:"text-slate-600",bgColor:"bg-slate-100"},proposal_viewed:{icon:bt,color:"text-blue-600",bgColor:"bg-blue-100"},email_sent:{icon:Be,color:"text-indigo-600",bgColor:"bg-indigo-100"},email_opened:{icon:Wa,color:"text-green-600",bgColor:"bg-green-100"},email_clicked:{icon:Xs,color:"text-cyan-600",bgColor:"bg-cyan-100"},automated_email:{icon:Ia,color:"text-purple-600",bgColor:"bg-purple-100"},sms_sent:{icon:ts,color:"text-teal-600",bgColor:"bg-teal-100"},status_changed:{icon:Cl,color:"text-amber-600",bgColor:"bg-amber-100"},document_uploaded:{icon:sl,color:"text-orange-600",bgColor:"bg-orange-100"},client_accepted:{icon:St,color:"text-emerald-600",bgColor:"bg-emerald-100"},proposal_funded:{icon:xa,color:"text-green-600",bgColor:"bg-green-100"},proposal_rejected:{icon:Za,color:"text-red-600",bgColor:"bg-red-100"},funding_lost:{icon:pa,color:"text-orange-600",bgColor:"bg-orange-100"},proposal_archived:{icon:Es,color:"text-gray-600",bgColor:"bg-gray-100"},geo_blocked:{icon:Bd,color:"text-red-600",bgColor:"bg-red-100"},financing_fit_quiz:{icon:ha,color:"text-violet-600",bgColor:"bg-violet-100"},client_replied:{icon:Wa,color:"text-emerald-600",bgColor:"bg-emerald-100"},sms_received:{icon:ts,color:"text-emerald-600",bgColor:"bg-emerald-100"},sf_activity:{icon:gr,color:"text-sky-600",bgColor:"bg-sky-100"},digest_click:{icon:Xs,color:"text-violet-600",bgColor:"bg-violet-100"}};function Ss(t){const s=new Date,a=new Date(t),n=s.getTime()-a.getTime(),r=Math.floor(n/1e3),i=Math.floor(r/60),l=Math.floor(i/60),o=Math.floor(l/24);return r<60?"just now":i<60?`${i}m ago`:l<24?`${l}h ago`:o<7?`${o}d ago`:a.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function px(t){return new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function fx({device:t}){switch(t){case"mobile":return e.jsx(pr,{className:"h-3 w-3"});case"tablet":return e.jsx(xr,{className:"h-3 w-3"});default:return e.jsx(Va,{className:"h-3 w-3"})}}function gx(t){return t.metadata?!!(t.metadata.device||t.metadata.browser||t.metadata.city||t.metadata.viewer_ip):!1}function bx({event:t,isLast:s}){var i,l,o,c,m;const a=xx[t.type],n=a.icon,r=gx(t);return e.jsxs("div",{className:"flex gap-3 relative",children:[!s&&e.jsx("div",{className:"absolute left-[15px] top-8 bottom-0 w-px bg-border"}),e.jsx("div",{className:`relative z-10 flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center ${a.bgColor}`,children:e.jsx(n,{className:`h-4 w-4 ${a.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("p",{className:"text-sm font-medium text-foreground leading-tight",children:[t.direction==="inbound"&&e.jsx("span",{className:"inline-block mr-1.5 align-middle text-[10px] font-semibold uppercase tracking-wide text-emerald-700 dark:text-emerald-400 bg-emerald-100 dark:bg-emerald-950 rounded px-1 py-0.5",children:"in"}),t.title,!!((i=t.metadata)!=null&&i.scanner)&&e.jsx("span",{className:"inline-block ml-1.5 align-middle text-[10px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-950 rounded px-1 py-0.5",title:"An automated mail scanner (Apple Mail Privacy, Gmail proxy, Safe Links) triggered this â not evidence of client engagement",children:"ð¤ scanner"})]}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap flex-shrink-0",title:(l=t.metadata)!=null&&l.received_at?`Estimated event time: ${new Date(t.timestamp).toLocaleString()}. Received: ${new Date(String(t.metadata.received_at)).toLocaleString()}`:new Date(t.timestamp).toLocaleString(),children:Ss(t.timestamp)})]}),((o=t.metadata)==null?void 0:o.confidence)==="unknown"&&e.jsx("p",{className:"text-xs text-amber-700 mt-1",children:"Unclassified activity · excluded from the call brief"}),((c=t.metadata)==null?void 0:c.source)==="browser_activity"&&((m=t.metadata)==null?void 0:m.confidence)==="observed"&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Observed on the offer link · viewer identity unverified"}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t.description}),t.actor&&t.actor!=="client"&&t.actor!=="automation"&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:["by ",t.actor]}),r&&t.metadata&&e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[!!t.metadata.device&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground bg-muted/60 rounded px-1.5 py-0.5",children:[e.jsx(fx,{device:String(t.metadata.device)}),`${String(t.metadata.device).charAt(0).toUpperCase()}${String(t.metadata.device).slice(1)}`]}),!!t.metadata.browser&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground bg-muted/60 rounded px-1.5 py-0.5",children:[e.jsx(gr,{className:"h-3 w-3"}),String(t.metadata.browser)]}),!!t.metadata.os&&e.jsx("span",{className:"text-[11px] text-muted-foreground bg-muted/60 rounded px-1.5 py-0.5",children:String(t.metadata.os)}),!!(t.metadata.city||t.metadata.state)&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground bg-muted/60 rounded px-1.5 py-0.5",children:[e.jsx(en,{className:"h-3 w-3"}
124),String([t.metadata.city,t.metadata.state].filter(Boolean).join(", "))]}),!!t.metadata.viewer_ip&&e.jsx(hx,{ip:String(t.metadata.viewer_ip)})]}),e.jsx("p",{className:"text-xs text-muted-foreground/60 mt-0.5",children:px(t.timestamp)})]})]})}function yx({proposalId:t}){const s=Ke(u=>u.user),a=Nt(),n=["deal-followup-actions",s==null?void 0:s.id,t],r=ve({queryKey:n,enabled:!!s,staleTime:15e3,refetchInterval:3e4,queryFn:async()=>{const[u,g,D]=await Promise.all([F.from("proposals").select("id,business_name,client_name,email,phone,agent_email,auto_followups_enabled,is_unsubscribed,is_archived,status").eq("id",t).single(),F.from("client_email_replies").select("subject,snippet,received_at").eq("proposal_id",t).order("received_at",{ascending:!1}).limit(10),F.from("email_logs").select("subject,sent_at,status").eq("proposal_id",t).order("sent_at",{ascending:!1}).limit(1).maybeSingle()]);if(u.error||g.error||D.error)throw new Error("Conversation controls could not be loaded.");if(!u.data)throw new Error("Proposal unavailable.");return{proposal:u.data,replies:g.data||[],lastEmail:D.data}}}),i=Le({mutationFn:()=>Ml(t,!1),onSuccess:async()=>{await a.invalidateQueries({queryKey:n})}});if(r.isPending)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading follow-up controlsâ¦"});if(r.isError)return e.jsxs("div",{role:"alert",className:"rounded-xl border p-4 text-sm",children:["Could not load follow-up controls."," ",e.jsx(R,{variant:"outline",onClick:()=>void r.refetch(),children:"Retry"})]});const{proposal:l,replies:o,lastEmail:c}=r.data,m=o[0],f=m?Hd(m.subject||""):null,d=l.auto_followups_enabled&&!l.is_unsubscribed&&!l.is_archived&&l.status==="pending";return e.jsxs("section",{"aria-label":"Next conversation",className:"mb-4 space-y-3 rounded-2xl border border-blue-100 bg-blue-50/30 p-4 sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"font-semibold",children:"Next conversation"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d?"Follow-ups enabled":"Automated follow-ups stopped or paused"})]}),e.jsx("p",{className:"text-sm",children:f?e.jsxs(e.Fragment,{children:["Client asked about"," ",e.jsx("strong",{children:Vd[f].toLowerCase()}),". Review their message and address that question first."]}):m?"A reply was received. Read it before reaching out; it may be an automatic response.":"Ask what would help the client decide. Record their answer in the conversation notes below."}),m&&e.jsxs("blockquote",{className:"border-l-2 border-blue-200 pl-3 text-sm text-muted-foreground",children:[m.snippet||m.subject,e.jsxs("span",{className:"mt-1 block text-xs",children:["Received ",new Date(m.received_at).toLocaleString()]})]}),c&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Latest email: ",c.subject," ·"," ",new Date(c.sent_at).toLocaleString()," · ",c.status]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(fa,{contact:l,presentation:"text"}),e.jsx(R,{size:"sm",variant:"outline",onClick:()=>ia.getState().openFollowUpInspector(t),children:"Review follow-up settings"}),d&&e.jsx(R,{size:"sm",variant:"outline",disabled:i.isPending,onClick:()=>i.mutate(),children:i.isPending?"Pausingâ¦":"Pause follow-ups"})]}),i.isError&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"Could not pause follow-ups. Please retry."})]})}const An=t=>new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});function wx({state:t}){const s=t.error?void 0:t.data;return e.jsxs("section",{"aria-label":"Payment-fit video engagement",className:"rounded-xl border bg-muted/20 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("h4",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(hr,{className:"h-4 w-4 text-blue-600","aria-hidden":"true"}),"Payment-fit video"]}),e.jsxs(R,{variant:"ghost",size:"sm",className:"min-h-11 shrink-0",disabled:t.pending,onClick:t.onRefresh,"aria-label":"Refresh video activity",children:[e.jsx(Ct,{className:`mr-1.5 h-3.5 w-3.5 ${t.pending?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),t.error?e.jsx("p",{role:"status",className:"mt-2 text-sm text-muted-foreground",children:"Video activity is unavailable. Refresh before using it to guide your call."}):s?s.lastSentAt?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Latest shared video · times shown in your local time"}),e.jsxs("dl",{className:"mt-3 grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Sent"}),e.jsx("dd",{className:"mt-1 text-sm font-medium",children:An(s.lastSentAt)}),e.jsx("dd",{className:"mt-1 text-xs text-muted-foreground",children:"Accepted for sending; delivery unconfirmed"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Playback"}),e.jsx("dd",{className:"mt-1 text-sm font-medium",children:s.nearCompleteAt?"70+ seconds recorded":s.meaningfulWatch?"30+ seconds recorded":s.lastPlayedAt?"Started":s.lastPlayedAt===void 0?"Details unavailable":"Not recorded"}),(s.nearCompleteAt||s.meaningfulAt||s.lastPlayedAt)&&e.jsx("dd",{className:"mt-1 text-xs text-muted-foreground",children:An(s.nearCompleteAt||s.meaningfulAt||s.lastPlayedAt)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Return to offer"}),e.jsx("dd",{className:"mt-1 text-sm font-medium",children:s.returnedAt?"Return link clicked":s.returnedAt===void 0?"Details unavailable":"Not recorded"}),s.returnedAt&&e.jsx("dd",{className:"mt-1 text-xs text-muted-foreground",children:An(s.returnedAt)})]})]}),e.jsx("p",{className:"mt-3 text-xs leading-relaxed text-muted-foreground",children:"Signals from the shared link, not verified client identity or buying intent. A return click does not confirm the offer loaded. Review replies and notes before following up."})]}):e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"No payment-fit video sent yet. If the client has questions about the payment, add it from the email preview."}):e.jsx("p",{role:"status",className:"mt-2 text-sm text-muted-foreground",children:"Loading video activityâ¦"})]})}async function vx(t){const[s,a,n,r]=await Promise.all([F.from("proposals").select("id, business_name, client_name, intended_use_of_funds, status, unique_link, allow_client_adjustments, salesforce_opportunity_id").eq("id",t).single(),F.from("loan_options").select("id, name, approved_amount, total_repayment, payment_amount, payment_frequency, term_length_months, is_recommended, is_adjustable, min_amount, max_amount, show_prepayment_schedule, prepayment_schedule").eq("proposal_id",t).order("created_at"),F.from("line_of_credit_options").select("id, name, draw_amount, total_payback, payment_amount, payment_frequency, term_length_months, is_recommended").eq("proposal_id",t).order("created_at"),F.from("proposal_deal_notes").select("*").eq("proposal_id",t).maybeSingle()]);for(const i of[s,a,n,r])if(i.error)throw i.error;if(!s.data)throw new Error("Deal not available");return{proposal:s.data,notes:r.data,offers:[...(a.data||[]).map(i=>({id:i.id,name:i.name,amount:i.approved_amount,repayment:i.total_repayment,payment:i.payment_amount,frequency:i.payment_frequency,termMonths:i.term_length_months,recommended:!!i.is_recommended,adjustable:!!i.is_adjustable&&!!s.data.allow_client_adjustments,minAmount:i.min_amount??i.approved_amount,maxAmount:i.max_amount??i.approved_amount,earlyPayoff:!!i.show_prepayment_schedule&&Array.isArray(i.prepayment_schedule)&&i.prepayment_schedule.length>0,kind:"working_capital"})),...(n.data||[]).map(i=>({id:i.id,name:i.name,amount:i.draw_amount,repayment:i.total_payback,payment:i.payment_amount,frequency:i.payment_frequency,termMonths:i.term_length_months,recommended:!!i.is_recommended,adjustable:!1,minAmount:i.draw_amount,maxAmount:i.draw_amount,earlyPayoff:!1,kind:"line_of_credit"}))]}}async function jx(t){const{data:s,error:a}=await F.functions.invoke("get-deal-cashflow",{body:{proposalId:t},signal:AbortSignal.timeout(45e3)});if(a||(s==null?void 0:s.source)!=="moneythumb"||!Array.isArray(s.statements)||!Number.isFinite(Date.parse(s.fetchedAt)))throw new Error("Salesforce financials are unavailable");return s}async function _x(t,s,a){var r;const n=a?await F.from("proposal_deal_notes").update(s).eq("proposal_id",t).eq("updated_at",a).select().maybeSingle():await F.from("proposal_deal_notes").insert({...s,proposal_id:t}).select().single();if(((r=n.error)==null?void 0:r.code)==="23505"||!n.error&&!n.data)throw new Error("These notes changed in another window. Copy your draft, then reload the deal before saving.");if(n.error)throw new Error("Notes could not be saved. Your draft is still here; try again.");return n.data}function Nx(t,s,a=Date.now()){var S,p;const n=zd(s).filter(_=>_.viewer_class==="client"&&Date.parse(_.occurred_at)>=a-6048e5&&Date.parse(_.occurred_at)<=a+5e3),i=n.filter(_=>["option_select","amount_adjust"].includes(_.event_type)).find(_=>t.offers.some(y=>y.id===Ws(_).option_id)),l=t.offers.find(_=>_.id===(i&&Ws(i).option_id))||t.offers.find(_=>_.recommended)||t.offers[0]||null,o=i?Ws(i):null,c=o?Number(o.adjusted_amount??o.amount):null,m=!!l&&!!o&&(Number(o.original_amount)!==l.amount||c===null||!Number.isFinite(c)||c!==l.amount&&(!l.adjustable||c<l.minAmount||c>l.maxAmount)),f=l&&c!==null&&!m?c:null,d=l&&f!==null&&l.amount>0?f/l.amount:1,u=new Set(n.filter(_=>_.event_type==="page_view").map(_=>_.session_id)).size,g=n.some(_=>Ws(_).section==="early_payoff"),D=n.some(_=>Ws(_).section==="cost_analysis"),E=[];u&&E.push(`${u} link visit${u===1?"":"s"}`),f!==null&&E.push(`${Mt(f)} explored`),g?E.push("Early-payoff schedule on screen"):D&&E.push("Cost details on screen"),n.some(_=>_.event_type==="compare_open")&&E.push("Compared offers");const v=["accepted","funded"].includes(t.proposal.status),x=f!==null?` at ${Mt(f)}`:"",$=v?"Letâs confirm the next steps and any outstanding paperwork. What would be most helpful to clarify?":g&&(l!=null&&l.earlyPayoff)?`Would it help to walk through the payment${x} and the early-payoff schedule together?`:D?`Would it help to separate the funding amount, scheduled payments, and total repayment${x}?`:`Letâs walk through the payment${x} and make sure the timing fits your business. What would you like to clarify first?`,T=v?["Confirm the remaining paperwork and timing with the funder."]:["Confirm final fees and the amount available after deductions.","Does payment timing fit collections and operating expenses?"];return g&&(l!=null&&l.earlyPayoff)&&T.push("Review the actual early-payoff dates and conditions."),m&&T.unshift("The offer changed after that visit. Reconfirm the amount and current terms."),{goal:((S=t.notes)==null?void 0:S.client_goal)||t.proposal.intended_use_of_funds||"",goalSource:(p=t.notes)!=null&&p.client_goal?"From conversation notes":"From the proposal",observations:E,opener:$,questions:T,offer:l,exploredAmount:f,staleAmount:m,earlyPayoffViewed:g,hasRecentActivity:n.length>0,payment:l?Math.round(l.payment*d*100)/100:null,repayment:l?Math.round(l.repayment*d*100)/100:null}}function kx(t,s){var n;const a=[`Hi ${t.proposal.client_name||"there"},`,"","Here is a short summary for our discussion."];return s.goal&&a.push("",`Your goal: ${s.goal}`),s.offer&&a.push("",`Option to review: ${s.offer.name}`,`Funding amount: ${Mt(s.exploredAmount??s.offer.amount)}`,`Scheduled payment: ${Mt(s.payment)} · ${s.offer.frequency}`,`Total scheduled repayment: ${Mt(s.repayment)}`,"Final fees, deductions, and funding terms need to be confirmed with the funder."),(n=t.notes)!=null&&n.next_step&&a.push("",`Next step: ${t.notes.next_step}`,...[t.notes.next_step_owner&&`Owner: ${t.notes.next_step_owner}`,t.notes.next_step_due&&`By: ${t.notes.next_step_due}
124`].filter(Boolean)),a.push("","Please let me know what you would like to clarify."),a.join(` 125`)}const Zt=t=>typeof t=="number"&&Number.isFinite(t),qs=t=>Math.round(t*100)/100,Do=t=>t.length&&t.every(Zt)?qs(t.reduce((s,a)=>s+a,0)):null,Ri=t=>{const s=Do(t);return s===null?null:qs(s/t.length)};function Xa(t){if(!t||!/^\d{4}-\d{2}-\d{2}$/.test(t))return null;const s=new Date(`${t}T00:00:00Z`);return Number.isFinite(s.getTime())&&s.toISOString().slice(0,10)===t?s:null}function Sx(t,s){const a=Xa(t.startDate),n=Xa(t.endDate);if(!a||!n||a.getUTCDate()!==1||n.getTime()+864e5>s||a.getUTCFullYear()!==n.getUTCFullYear()||a.getUTCMonth()!==n.getUTCMonth())return null;const r=new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth()+1,0)).getUTCDate();return n.getUTCDate()===r?t.startDate.slice(0,7):null}function Cx(t){var a;return!!([t.revenue,t.deposits,t.withdrawals,t.financingPayments,t.financingDeposits,t.nsfs,t.negativeDays].some(n=>n!==null&&(!Zt(n)||n<0))||t.negativeDays!==null&&(!Number.isInteger(t.negativeDays)||t.negativeDays>(((a=Xa(t.endDate))==null?void 0:a.getUTCDate())||31))||t.nsfs!==null&&!Number.isInteger(t.nsfs))}function Dx(t,s=Date.now()){const a=[],n=new Map;let r=0;const i=new Set;for(const C of t.statements){if(i.has(C.id))continue;i.add(C.id);const I=Sx(C,s);if(!I){r++;continue}n.set(I,[...n.get(I)||[],C])}const l=[];let o=0,c=0;for(const[C,I]of[...n].sort(([H],[P])=>P.localeCompare(H)).slice(0,6)){const H=I.map(w=>{var L;return(L=w.bank)==null?void 0:L.trim().toLowerCase()});if(H.some(w=>!w)||new Set(H).size!==H.length){o++;continue}if(I.some(w=>{if(Cx(w))return!0;const{startingBalance:L,endingBalance:O,deposits:ae,withdrawals:te}=w;return[L,O,ae,te].every(Zt)&&Math.abs(L+ae-te-O)>1})){c++;continue}const z=w=>Do(I.map(L=>L[w])),M=Object.fromEntries(["startingBalance","endingBalance","averageBalance","deposits","withdrawals","revenue","financingDeposits","financingPayments","nsfs"].map(w=>[w,z(w)])),k=I.map(w=>w.negativeDays);l.push({period:C,days:Xa(I[0].endDate).getUTCDate(),accounts:H,...M,change:M.startingBalance!==null&&M.endingBalance!==null?qs(M.endingBalance-M.startingBalance):null,negativeDays:k.every(Zt)?Math.max(...k):null})}l.reverse(),r&&a.push(`${r} statement${r===1?"":"s"} left out: dates are missing, incomplete, or not a completed calendar month.`),o&&a.push(`${o} month${o===1?"":"s"} left out: overlapping statements or unidentified accounts need review in Salesforce. Bank name alone cannot distinguish two accounts at the same bank. Summary averages are withheld.`),c&&a.push(`${c} month${c===1?"":"s"} left out: amounts do not reconcile or contain invalid values. Summary averages are withheld.`),t.limited&&a.push("Salesforce returned a limited set of statements. Summary figures are unavailable until the full set is reviewed.");const m=new Set(l.map(C=>[...C.accounts].sort().join("|"))),f=C=>Number(C.slice(0,4))*12+Number(C.slice(5,7));l.some((C,I)=>I>0&&f(C.period)-f(l[I-1].period)>1)&&a.push("There are missing months in this date range. The figures describe only the reviewed months.");const d=m.size<=1;d||a.push("The banks covered change between months. Monthly details remain visible; summary averages and trend guidance are withheld.");const u=t.limited||!d||o||c?[]:l,g=C=>Ri(u.map(I=>I[C])),E=u.length&&u.every(C=>Zt(C.averageBalance))?qs(u.reduce((C,I)=>C+I.averageBalance*I.days,0)/u.reduce((C,I)=>C+I.days,0)):null,v=Ri(u.map(C=>C.change)),x=u.map(C=>C.negativeDays),$=x.length&&x.every(Zt)?Math.max(...x):null,T=l.at(-1),S=T?Date.UTC(Number(T.period.slice(0,4)),Number(T.period.slice(5,7)),0):null,p=S!==null&&s-S>90*864e5;p&&a.push("The latest usable statement ended more than 90 days ago. Get current statements before relying on this pattern."),l.length&&l.some(C=>C.revenue===null)&&a.push("Revenue is missing for some reviewed months. Deposits are shown separately and are not substituted for revenue.");const _=u.filter(C=>C.change!==null&&C.change>0).length,y=u.filter(C=>C.change!==null&&C.change<0).length,q=u.filter(C=>C.change!==null).length,A=q?`Cash rose in ${_} and fell in ${y} of ${q} reviewed month${q===1?"":"s"}${_+y<q?"; the rest were unchanged":""}.`:"More complete statements are needed to describe the cash pattern.",N=p?"Have collections, expenses, or financing payments changed since these statements?":$!==null&&$>0?"What caused the below-zero days, and would the proposed payment fall before customer payments arrive?":v!==null&&v<0?"What drove the cash decline: operating costs, an equipment purchase, owner withdrawals, or debt payments?":v!==null&&v>0?"Is the cash building from customer payments, new financing, or transfersâand what upcoming bills is it reserved for?":"Which payroll, tax, supplier, and financing payments still need to come out of the account?";return{months:l,revenue:g("revenue"),deposits:g("deposits"),averageBalance:E,monthlyChange:v,financingPayments:g("financingPayments"),financingDeposits:g("financingDeposits"),negativeDays:$,warnings:a,stale:p,headline:A,question:N}}function Tx(t,s,a){const n=Yd[a],r=s!==null&&Zt(s)&&s>0&&Zt(n)?qs(s*n):null,i=r!==null&&t.revenue!==null&&t.revenue>0?r/t.revenue:null,l=r!==null&&t.financingPayments!==null?qs(r+t.financingPayments):null;return{proposedMonthly:r,revenueShare:i,combined:l}}const at=t=>t===null?"Not available":Mt(t),Fi=t=>t===null?"Not available":`${t>0?"+":""}${Mt(t)}`,Pn=t=>new Date(`${t}-01T12:00:00Z`).toLocaleDateString("en-US",{month:"short",year:"numeric",timeZone:"UTC"});function $a({label:t,value:s,detail:a}){return e.jsxs("div",{className:"rounded-xl bg-muted/35 p-3",children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:t}),e.jsx("dd",{className:"mt-1 text-lg font-semibold tabular-nums break-words",children:s}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:a})]})}function Ex({state:t,read:s,payment:a,frequency:n}){var i;const r=s?Tx(s,a,n):null;return e.jsxs("section",{id:"deal-room-cashflow",className:"rounded-2xl border bg-card p-5 shadow-sm","aria-labelledby":"deal-cashflow-title",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h3",{id:"deal-cashflow-title",className:"flex items-center gap-2 font-semibold",children:[e.jsx(Zi,{className:"h-4 w-4 text-blue-600"})," Cash flow at a glance"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[((i=t.data)==null?void 0:i.source)==="mca_bank_statements"?"Bank Statements via Salesforce":"MoneyThumb via Salesforce"," ","· private agent view"]})]}),t.linked&&e.jsx(R,{size:"sm",variant:"ghost",disabled:t.pending,onClick:t.onRefresh,"aria-label":"Refresh Salesforce financials",children:e.jsx(Ct,{className:`h-4 w-4 ${t.pending?"animate-spin":""}`})})]}),t.linked?t.error?e.jsxs("div",{role:"alert",className:"mt-4 text-sm",children:[e.jsx("p",{children:"Salesforce financials couldnât be refreshed. Previous figures are withheld from this conversation until you retry."}),e.jsx(R,{className:"mt-3",variant:"outline",onClick:t.onRefresh,disabled:t.pending,children:"Retry financials"})]}):t.data?t.data.statements.length?s&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-4 text-xs text-muted-foreground",children:s.months.length?`${s.months.length} completed month${s.months.length===1?"":"s"} · ${Pn(s.months[0].period)}${s.months.length>1?` â ${Pn(s.months[s.months.length-1].period)}`:""}
125`:"No complete, unambiguous months available"}),e.jsx("p",{className:"mt-2 text-sm font-medium",children:s.headline}),e.jsxs("dl",{className:"mt-4 grid grid-cols-2 gap-3",children:[e.jsx($a,{label:"Monthly business revenue",value:at(s.revenue),detail:t.data.source==="mca_bank_statements"?"Average of deposits minus transfers and disallowed items; separate from total deposits.":"Average identified by MoneyThumb; separate from total deposits."}),e.jsx($a,{label:"Cash usually in the bank",value:at(s.averageBalance),detail:"Average daily balance across the reviewed statements."}),e.jsx($a,{label:"Monthly change in cash",value:Fi(s.monthlyChange),detail:"Ending minus starting balance. This is not profit."}),e.jsx($a,{label:"Existing financing payments",value:at(s.financingPayments),detail:"Monthly average of detected MCA debits; other debts may be missing."})]}),s.negativeDays!==null&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:[s.negativeDays," below-zero day",s.negativeDays===1?"":"s"," in the most affected account-month. This is not a combined count across accounts."]}),s.financingDeposits!==null&&s.financingDeposits>0&&e.jsxs("p",{className:"mt-3 rounded-lg border border-amber-200 bg-amber-50/50 p-3 text-sm dark:border-amber-900 dark:bg-amber-950/20",children:["New financing was detected: ",at(s.financingDeposits)," per month on average. It can raise cash balances without being sales or profit."]}),(r==null?void 0:r.proposedMonthly)!==null&&(r==null?void 0:r.proposedMonthly)!==void 0&&e.jsxs("div",{className:"mt-4 rounded-xl border border-blue-100 bg-blue-50/40 p-4 dark:border-blue-900 dark:bg-blue-950/20",children:[e.jsx("h4",{className:"text-sm font-medium",children:"How this offer fits the discussion"}),e.jsxs("p",{className:"mt-2 text-sm",children:["The ",at(a)," ",n," payment is approximately"," ",e.jsxs("strong",{children:[at(r.proposedMonthly)," per month"]}),r.revenueShare!==null?`, or ${(r.revenueShare*100).toFixed(1)}% of the recorded revenue`:"","."]}),r.combined!==null&&e.jsxs("p",{className:"mt-2 text-sm",children:["With the detected existing payments: approximately"," ",e.jsxs("strong",{children:[at(r.combined)," per month"]}),", if all existing financing remains."]}),e.jsx("p",{className:"mt-2 text-xs leading-relaxed text-muted-foreground",children:"This comparison does not establish affordability. Confirm payroll, suppliers, taxes, other debts, and collection dates. Remove any financing being paid off to avoid counting it twice. Monthly equivalents use averages; actual payment dates vary."})]}),s.warnings.length>0&&e.jsxs("div",{role:"note",className:"mt-4 rounded-lg border border-amber-200 p-3 dark:border-amber-900",children:[e.jsx("p",{className:"text-xs font-semibold",children:"Before using these numbers"}),e.jsx("ul",{className:"mt-2 space-y-2 text-xs leading-relaxed text-muted-foreground",children:s.warnings.map(l=>e.jsx("li",{children:l},l))})]}),s.months.length>0&&e.jsxs("details",{className:"mt-4 border-t pt-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:"See month-by-month details"}),e.jsx("div",{className:"mt-3 space-y-3",children:s.months.map(l=>e.jsxs("article",{className:"rounded-xl border p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:Pn(l.period)}),e.jsxs("span",{className:"text-xs tabular-nums",children:["Cash change ",Fi(l.change)]})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-[1fr_auto_1fr] items-center gap-2 rounded-lg bg-muted/35 p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Started with"}),e.jsx("p",{className:"mt-1 font-semibold tabular-nums",children:at(l.startingBalance)})]}),e.jsx("span",{"aria-hidden":"true",className:"text-muted-foreground",children:"â"}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ended with"}),e.jsx("p",{className:"mt-1 font-semibold tabular-nums",children:at(l.endingBalance)})]})]}),e.jsx("dl",{className:"mt-3 grid grid-cols-2 gap-3 text-xs",children:[["All money deposited",at(l.deposits)],["All money withdrawn",at(l.withdrawals)],["Identified revenue",at(l.revenue)],["Average daily balance",at(l.averageBalance)],["Detected financing in",at(l.financingDeposits)],["Detected financing out",at(l.financingPayments)],["Most negative days in one account",l.negativeDays===null?"Not available":String(l.negativeDays)],["Insufficient-funds events",l.nsfs===null?"Not available":String(l.nsfs)]].map(([o,c])=>e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted-foreground",children:o}),e.jsx("dd",{className:"mt-1 font-medium tabular-nums",children:c})]},o))}),e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:[l.accounts.length," reported bank",l.accounts.length===1?"":"s",". Transfers between accounts may inflate total deposits and withdrawals."]})]},l.period))})]}),e.jsx("p",{className:"mt-4 text-xs leading-relaxed text-muted-foreground",children:"Cash balances alone do not show profit or money free to spend. Loans, transfers, equipment purchases, and owner withdrawals can change them. Review the P&L and upcoming obligations to assess profit and available cash."}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Retrieved ",new Date(t.data.fetchedAt).toLocaleStr
125ing()," · Only the available statements are represented."]})]}):e.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:"No bank statement figures were found on this Salesforce opportunity (MoneyThumb or Bank Statements). Review the linked opportunity or add current statements there."}):e.jsxs("div",{role:"status",className:"mt-4",children:[e.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"Loading bank statement figuresâ¦"}),e.jsx(je,{className:"h-36 rounded-xl"})]}):e.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:"Link this proposal to its Salesforce opportunity to show the clientâs statement analysis here."}),t.opportunityId&&e.jsx("a",{className:"mt-3 inline-block text-xs text-blue-700 hover:underline dark:text-blue-300",href:Ja(t.opportunityId),target:"_blank",rel:"noreferrer",children:"Review source in Salesforce â"})]})}function $x({context:t,onSave:s,onClose:a}){var d;const[n,r]=h.useState(()=>{var u,g,D,E,v;return{client_goal:((u=t.notes)==null?void 0:u.client_goal)||t.proposal.intended_use_of_funds||"",client_concerns:((g=t.notes)==null?void 0:g.client_concerns)||"",next_step:((D=t.notes)==null?void 0:D.next_step)||"",next_step_owner:((E=t.notes)==null?void 0:E.next_step_owner)||"",next_step_due:((v=t.notes)==null?void 0:v.next_step_due)||null}}),[i]=h.useState(((d=t.notes)==null?void 0:d.updated_at)||null),[l,o]=h.useState(!1),[c,m]=h.useState(""),f=(u,g)=>r(D=>({...D,[u]:g}));return e.jsxs("form",{className:"space-y-4 rounded-xl border bg-muted/20 p-4",onSubmit:async u=>{u.preventDefault(),o(!0),m("");try{await s(n,i),a()}catch(g){m(g instanceof Error?g.message:"Could not save notes. Please try again.")}finally{o(!1)}},children:[e.jsxs("div",{children:[e.jsx(de,{htmlFor:"deal-goal",children:"Clientâs goal"}),e.jsx(Rt,{id:"deal-goal",maxLength:2e3,rows:2,value:n.client_goal,onChange:u=>f("client_goal",u.target.value),placeholder:"What does the client need the funding for?"})]}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"deal-concerns",children:"What the client told you"}),e.jsx(Rt,{id:"deal-concerns",maxLength:4e3,rows:3,value:n.client_concerns,onChange:u=>f("client_concerns",u.target.value),placeholder:"Their concerns, questions, or preferences â in their own words."})]}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"deal-next-step",children:"Agreed next step"}),e.jsx(Rt,{id:"deal-next-step",maxLength:2e3,rows:2,value:n.next_step,onChange:u=>f("next_step",u.target.value),placeholder:"What did you agree to do next?"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(de,{htmlFor:"deal-owner",children:"Who will do it?"}),e.jsx(he,{id:"deal-owner",maxLength:200,value:n.next_step_owner,onChange:u=>f("next_step_owner",u.target.value),placeholder:"e.g., Me, client, or funder"})]}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"deal-due",children:"By when?"}),e.jsx(he,{id:"deal-due",type:"date",value:n.next_step_due||"",onChange:u=>f("next_step_due",u.target.value||null)})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Private team notes. Saving a date records the agreement; it does not send a reminder."}),c&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:c}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{type:"submit",disabled:l,children:l?"Savingâ¦":"Save conversation"}),e.jsx(R,{type:"button",variant:"outline",disabled:l,onClick:a,children:"Cancel"})]})]})}function Ax({context:t,activity:s,activityUnavailable:a=!1,cashflow:n,video:r,onSave:i}){var g,D,E,v;const[l,o]=h.useState(!1),[c,m]=h.useState(null),f=Nx(t,a?[]:s),d=r&&!r.error?Wd(r.data,t.proposal.status):null,u=n!=null&&n.data&&!n.error?Dx(n.data):null;return e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs("section",{id:"deal-room-conversation",className:"rounded-2xl border bg-card p-5 sm:p-6 shadow-sm","aria-labelledby":"deal-conversation-title",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"deal-conversation-title",className:"text-xl font-semibold tracking-tight",children:"Your next conversation"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"The clientâs goal. The facts. A useful next step."})]}),e.jsx(kl,{className:"h-5 w-5 shrink-0 text-blue-600","aria-label":"Private agent workspace"})]}),e.jsxs("div",{className:"mt-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Clientâs goal"}),e.jsx("p",{className:"mt-1.5 text-sm leading-relaxed whitespace-pre-wrap break-words",children:f.goal||"Record what the client wants to accomplish."}),f.goal&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:f.goalSource})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"What was explored · last 7 days"}),a?e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Activity is unavailable. Use your conversation notes and confirm preferences with the client."}):f.observations.length?e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:f.observations.map(x=>e.jsx("span",{className:"rounded-md border bg-muted/30 px-2.5 py-1 text-xs",children:x},x))}):e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"No recent classified offer activity recorded. Start by asking what matters most."}),f.observations.length>0&&e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Link activity suggests questions to ask; it does not identify the visitor or confirm their intent."})]}),r&&e.jsx(wx,{state:r}),e.jsxs("div",{className:"rounded-xl border border-blue-200 bg-blue-50/60 p-4 dark:border-blue-900 dark:bg-blue-950/25",children:[e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-blue-700 dark:text-blue-300",children:[e.jsx(ts,{className:"h-4 w-4"})," A useful way to start"]}),e.jsxs("p",{className:"mt-2 text-base leading-relaxed",children:["â",d??f.opener,"â"]})]}),((g=t.notes)==null?void 0:g.client_concerns)&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold",children:"What the client told you"}),e.jsx("p",{className:"mt-2 whitespace-pre-wrap break-words text-sm leading-relaxed text-muted-foreground",children:t.notes.client_concerns})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold",children:"Questions to resolve"}),e.jsx("ul",{className:"mt-2 space-y-2",children:[...f.questions,...u!=null&&u.months.length?[u.question]:[]].map(x=>e.jsxs("li",{className:"flex gap-2 text-sm leading-relaxed",children:[e.jsx("span",{className:"mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full border border-muted-foreground
125/60","aria-hidden":"true"}),e.jsx("span",{children:x})]},x))})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"text-sm font-semibold",children:"Agreed next step"}),e.jsx("p",{className:"mt-2 text-sm whitespace-pre-wrap break-words",children:((D=t.notes)==null?void 0:D.next_step)||"No next step recorded yet."}),((E=t.notes)==null?void 0:E.next_step)&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:[t.notes.next_step_owner,t.notes.next_step_due&&`By ${ma(t.notes.next_step_due)}`].filter(Boolean).join(" · ")})]}),l?e.jsx($x,{context:t,onSave:i,onClose:()=>o(!1)}):e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(R,{onClick:()=>o(!0),children:[e.jsx(Pu,{className:"mr-2 h-4 w-4"}),"Record conversation"]}),e.jsx(R,{variant:"outline",onClick:()=>m(kx(t,f)),children:"Draft recap"})]})]})]}),n&&e.jsx(Ex,{state:n,read:u,payment:f.payment,frequency:((v=f.offer)==null?void 0:v.frequency)||""}),f.offer&&e.jsxs("section",{className:"rounded-2xl border bg-card p-5 shadow-sm","aria-labelledby":"deal-terms-title",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{id:"deal-terms-title",className:"font-semibold",children:"Numbers for this conversation"}),e.jsxs("a",{className:"inline-flex items-center gap-1 text-sm text-blue-700 hover:underline",href:`/proposal/${encodeURIComponent(t.proposal.unique_link)}`,target:"_blank",rel:"noreferrer",children:["View offer",e.jsx(zn,{className:"h-4 w-4"})]})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[f.offer.name," ·"," ",f.exploredAmount!==null?"Amount explored on the link; current offer terms":"Current offer; confirm their preferred option"]}),e.jsxs("dl",{className:"mt-4 grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Funding amount"}),e.jsx("dd",{className:"mt-1 text-xl font-semibold tabular-nums",children:Mt(f.exploredAmount??f.offer.amount)})]}),e.jsxs("div",{children:[e.jsxs("dt",{className:"text-xs text-muted-foreground",children:[f.offer.frequency," payment"]}),e.jsx("dd",{className:"mt-1 text-xl font-semibold tabular-nums",children:Mt(f.payment)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Total scheduled repayment"}),e.jsx("dd",{className:"mt-1 text-sm font-semibold tabular-nums",children:Mt(f.repayment)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Term"}),e.jsxs("dd",{className:"mt-1 text-sm font-semibold",children:[f.offer.termMonths," months"]})]})]}),e.jsx("p",{className:"mt-4 text-xs leading-relaxed text-muted-foreground",children:"Final fees and deductions must be confirmed with the funder. Payment-to-revenue alone does not establish affordability."})]}),e.jsxs("a",{href:"/resources/understand-your-offer",target:"_blank",rel:"noreferrer",className:"flex items-center justify-between gap-3 rounded-xl border bg-card p-4 text-sm hover:bg-muted/30",children:[e.jsxs("span",{children:[e.jsx("span",{className:"block font-medium",children:"Helpful for this call"}),e.jsx("span",{className:"mt-1 block text-muted-foreground",children:"Understand your offer · client guide"})]}),e.jsx(zn,{className:"h-4 w-4 shrink-0"})]}),e.jsx(ut,{open:c!==null,onOpenChange:x=>{x||m(null)},children:e.jsxs(mt,{className:"max-w-xl",children:[e.jsxs(ht,{children:[e.jsx(xt,{children:"Review your client recap"}),e.jsx(kt,{children:"Edit this draft before copying it into your email. Nothing is sent from this window."})]}),e.jsx(de,{htmlFor:"deal-recap",className:"sr-only",children:"Client recap"}),e.jsx(Rt,{id:"deal-recap",className:"min-h-[320px]",value:c||"",onChange:x=>m(x.target.value)}),e.jsxs(R,{onClick:async()=>{try{await navigator.clipboard.writeText(c||""),U.success("Recap copied")}catch{U.error("Could not copy. Select the text and copy it manually.")}},children:[e.jsx(ku,{className:"mr-2 h-4 w-4"}),"Copy recap"]})]})})]})}function Px({proposalId:t,activity:s,activityUnavailable:a}){var d;const n=Nt(),r=Ke(u=>{var g;return(g=u.user)==null?void 0:g.id}),i=["deal-room",t],l=ve({queryKey:i,queryFn:()=>vx(t),staleTime:15e3,refetchInterval:3e4,refetchIntervalInBackgroun
125d:!1}),o=ve({queryKey:["deal-room-video",t,r],queryFn:()=>Kd(t),enabled:!!r&&!!l.data&&!l.isError,staleTime:3e4,retry:!1,refetchOnWindowFocus:!0}),c=(d=l.data)==null?void 0:d.proposal.salesforce_opportunity_id,m=ve({queryKey:["deal-room-cashflow",t,r,c],queryFn:()=>jx(t),enabled:!!r&&!!c&&!l.isError,staleTime:5*60*1e3,gcTime:5*60*1e3,retry:!1,refetchOnWindowFocus:!1}),f=Le({mutationFn:({input:u,version:g})=>_x(t,u,g),onSuccess:u=>{n.setQueryData(i,g=>g&&{...g,notes:u}),U.success("Conversation saved")}});return l.isLoading?e.jsx(je,{className:"h-96 rounded-2xl"}):l.isError||!l.data?e.jsxs("div",{role:"alert",className:"rounded-xl border p-5",children:[e.jsx("p",{className:"text-sm",children:"The deal brief could not be loaded. Retry to get current offer terms and conversation notes."}),e.jsx(R,{className:"mt-3",variant:"outline",onClick:()=>void l.refetch(),children:"Retry deal brief"})]}):e.jsxs(e.Fragment,{children:[e.jsx(yx,{proposalId:t}),e.jsx(Ax,{context:l.data,activity:s,activityUnavailable:a,video:{data:o.data,pending:o.isFetching,error:o.isError,onRefresh:()=>{o.refetch()}},cashflow:{linked:!!c,opportunityId:c,data:m.data,pending:m.isFetching,error:m.isError,onRefresh:()=>{m.refetch()}},onSave:async(u,g)=>{await f.mutateAsync({input:u,version:g})}},t)]})}async function Li(t,s){const{data:a,error:n}=await F.functions.invoke("salesforce-offer-sync",{body:{proposalId:t,action:s}});if(n||a!=null&&a.error||typeof(a==null?void 0:a.total)!="number")throw new Error("Offer sync status is unavailable");return a}const Mi=t=>!!t&&t.skipped-(t.notActive??0)>0;function Rx({proposalId:t}){const s=Nt(),a=["salesforce-offer-sync",t],{data:n,isPending:r,isError:i,isFetching:l,refetch:o}=ve({queryKey:a,queryFn:()=>Li(t,"status"),refetchInterval:3e4}),c=Le({mutationFn:()=>Li(t,"retry"),onSuccess:f=>{s.setQueryData(a,f),U.success(f.pending||f.attention?"Retry saved. Salesforce updates are still pending.":"Offer sync checked.")},onError:()=>{U.error("Could not confirm the retry. Refresh the status before trying again."),o()}}),m=i?"Unavailable":r?"Checkingâ¦":n!=null&&n.attention||n!=null&&n.delayed?"Needs attention":n!=null&&n.pending?"Pending":Mi(n)?"Review required":n!=null&&n.synced?"Synced":n!=null&&n.skipped?"No update needed":"No offer updates";return e.jsxs("section",{"aria-label":"Offer status sync",className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Offer status"}),e.jsx(J,{variant:i||n!=null&&n.attention||n!=null&&n.delayed?"destructive":"secondary","aria-live":"polite",children:m})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i?"We couldnât check Salesforce. Refresh to see the current status.":n!=null&&n.attention?"Automatic retries paused after repeated failures. Check the Salesforce connection and Opportunity, then retry.":n!=null&&n.delayed?"Automatic recovery is overdue. Retry now and ask an administrator to check the recovery schedule.":n!=null&&n.pending?"Your offer is saved. Weâre retrying its Salesforce status automatically.":Mi(n)?"Some updates were not applied because the offer was withdrawn or the proposal is unavailable. Review the Opportunity.":n!=null&&n.synced?"Salesforce offer-status updates are confirmed.":n!=null&&n.skipped?"Salesforce is already past the approval stage for this deal, so no substage update applies.":"A successful offer email or client acceptance will appear here."}),!i&&(n==null?void 0:n.lastSyncedAt)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last confirmed ",Ka(new Date(n.lastSyncedAt),{addSuffix:!0})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[!!(n!=null&&n.pending||n!=null&&n.attention)&&!i&&e.jsxs(R,{size:"sm",variant:"outline",disabled:c.isPending,onClick:()=>c.mutate(),children:[e.jsx(Ct,{className:`mr-1 h-3.5 w-3.5 ${c.isPending?"animate-spin":""}`}),c.isPending?"Retryingâ¦":"Retry sync"]}),e.jsx(R,{size:"sm",variant:"ghost",disabled:l||c.isPending,onClick:()=>void o(),children:"Refresh status"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Retry updates Salesforce only. It wonât resend client emails or repeat activity notes."})]})}function Fx({proposalId:t}){const[s,a]=h.useState(null),[n,r]=h.useState([]),[i,l]=h.useState(""),[o,c]=h.useState(!1),[m,f]=h.useState(!0),d=async()=>{const[{data:x},{data:$}]=await Promise.all([F.from("proposals").select("salesforce_opportunity_id, salesforce_stage, salesforce_owner_email, salesforce_last_synced_at, salesforce_last_modified_at, salesforce_sync_status, salesforce_sync_error").eq("id",t).maybeSingle(),F.from("salesforce_sync_log").select("id, direction, event_type, status, error_message, created_at").eq("proposal_id",t).order("created_at",{ascending:!1}).limit(10)]);a(x??null),l((x==null?void 0:x.salesforce_opportunity_id)??""),r($??[]),f(!1)};h.useEffect(()=>{d()},[t]);const u=async()=>
125{if(!i.trim())return;c(!0);const{data:x,error:$}=await F.functions.invoke("salesforce-link-opportunity",{body:{proposalId:t,salesforceOpportunityId:i.trim()}});if(c(!1),$||x!=null&&x.error){U.error((x==null?void 0:x.error)??($==null?void 0:$.message)??"Failed to link");return}U.success("Linked to Salesforce. First sync queued."),await d()},g=async()=>{if(!confirm("Unlink this proposal from Salesforce? No data is deleted in SF."))return;c(!0);const{error:x}=await F.functions.invoke("salesforce-link-opportunity",{body:{proposalId:t,unlink:!0}});if(c(!1),x){U.error(x.message);return}U.success("Unlinked"),l(""),await d()},D=async()=>{var S,p,_;c(!0);const{error:x,data:$}=await F.functions.invoke("salesforce-push-event",{body:{proposalId:t,eventType:"status_changed"}});if(c(!1),x||$!=null&&$.error){U.error(($==null?void 0:$.error)??(x==null?void 0:x.message)??"Push failed");return}const T=$;if((T==null?void 0:T.ok)===!1||T!=null&&T.failures&&T.failures.length>0){U.error(((S=T.failures)==null?void 0:S.join("; "))||((p=T.note)==null?void 0:p.error)||"Salesforce did not accept the status note"),await d();return}if((_=T==null?void 0:T.note)!=null&&_.error){U.warning(`Fields may be current, but the status note failed: ${T.note.error}`),await d();return}T!=null&&T.queued?U.success("Status note queued for Salesforce. Refresh Recent sync activity in a moment."):U.success("Status note accepted by Salesforce."),await d()};if(m)return e.jsx(nt,{children:e.jsx(Zs,{className:"p-6 text-sm text-muted-foreground",children:"Loadingâ¦"})});const E=!!(s!=null&&s.salesforce_opportunity_id),v=(s==null?void 0:s.salesforce_sync_status)??"unlinked";return e.jsxs(nt,{children:[e.jsxs(Gn,{className:"flex flex-row items-center justify-between gap-2 space-y-0",children:[e.jsxs(Ji,{className:"flex items-center gap-2 text-base",children:[E?e.jsx(lr,{className:"h-4 w-4 text-primary"}):e.jsx(Su,{className:"h-4 w-4 text-muted-foreground"}),"Salesforce sync"]}),e.jsx(J,{variant:v==="linked"?"default":v==="error"?"destructive":"secondary",className:"capitalize",children:v})]}),e.jsxs(Zs,{className:"space-y-4",children:[!E&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Salesforce Opportunity ID"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(he,{placeholder:"006XXXXXXXXXXXXXXX",value:i,onChange:x=>l(x.target.value),disabled:o}),e.jsxs(R,{onClick:u,disabled:o||!i.trim(),children:[e.jsx(Qd,{className:"mr-1 h-4 w-4"})," Link"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste the 15- or 18-character Opportunity ID from Salesforce. Once linked, stage and owner updates flow in automatically and proposal events push out in real time."})]}),E&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Rx,{proposalId:t}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 text-sm sm:grid-cols-2 [&>div]:min-w-0 [&>div]:break-words",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Opportunity ID"}),e.jsx("div",{className:"break-all font-mono",children:s.salesforce_opportunity_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"SF Stage"}),e.jsx("div",{children:s.salesforce_stage??e.jsx("span",{className:"text-muted-foreground",children:"â"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"SF Owner"}),e.jsx("div",{children:s.salesforce_owner_email??e.jsx("span",{className:"text-muted-foreground",children:"â"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Last general sync"}),e.jsx("div",{children:s.salesforce_last_synced_at?Ka(new Date(s.salesforce_last_synced_at),{addSuffix:!0}):e.jsx("span",{className:"text-muted-foreground",children:"never"})})]})]}),s.salesforce_sync_error&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive",children:[e.jsx(ds,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:s.salesforce_sync_error})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(R,{size:"sm",variant:"outline",onClick:D,disabled:o,children:[e.jsx(Ct,{className:"mr-1 h-3.5 w-3.5"})," Post status note"]}),e.jsxs(R,{size:"sm",variant:"ghost",onClick:g,disabled:o,children:[e.jsx(qu,{className:"mr-1 h-3.5 w-3.5"})," Unlink"]})]})]}),n.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Recent sync activity"}),e.jsx("ul",{className:"divide-y rounded-md border text-xs",children:n.map(x=>e.jsxs("li",{className:"flex flex-col gap-0.5 px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[x.status==="success"?e.jsx(St,{className:"h-3.5 w-3.5 text-emerald-600"}):x.status==="error"?e.jsx(ds,{className:"h-3.5 w-3.5 text-destructive"}):x.status==="partial"?e.jsx(ds,{className:"h-3.5 w-3.5 text-amber-600"}):e.jsx(Ct,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:x.event_type}),e.jsx("span",{className:"text-muted-foreground",children:x.direction==="app_to_sf"?"â SF":"â SF"}),x.status==="partial"&&e.jsx("span",{className:"rounded bg-amber-100 px-1 text-[10px] font-medium text-amber-900 dark:bg-amber-950/50 dark:text-amber-200",children:"partial"})]}),e.jsx("span",{className:"text-muted-foreground",children:Ka(new Date(x.created_at),{addSuffix:!0})})]}),x.error_message&&e.jsx("p",{className:"pl-5 text-muted-foreground",children:x.error_message})]},x.id))})]})]})]})}const Lx=[],Mx=[{value:"all",label:"All"},{value:"views",label:"Offer activity"},{value:"emails",label:"Emails"},{value:"messages",label:"Replies & texts"},{value:"status",label:"Status"},{value:"documents",label:"Docs"},{value:"security",label:"Security"}];function qx(t){const s=new Map;for(const a of t){const n=new Date(a.timestamp).toLocaleDateString("en-US",{weekday:"long",month:"short",day:"numeric",year:"numeric"});s.has(n)||s.set(n,[]),s.get(n).push(a)}return s}function Ox({open:t,onOpenChange:s,proposalId:a,businessName:n}){var E,v,x;const r=Nt(),[i,l]=h.useState("all"),[o,c]=h.useState(40),m=ux(t?a:null),f=((E=m.data)==null?void 0:E.events)||Lx,d=((v=m.data)==null?void 0:v.warnings)||[];h.useEffect(()=>{l("all"),c(40)},[a]);const u=h.useMemo(()=>i==="all"?f:f.filter($=>$.category===i),[f,i]),g=qx(u.slice(0,o)),D=m.isError||d.some($=>$.startsWith("Detailed offer activity"));return e.jsx(as,{open:t,onOpenChange:s,children:e.jsxs(xs,{side:"right",className:"flex w-full flex-col p-0 sm:max-w-[min(1180px,95vw)] [--primary:217_91%_50%]",children:[e.jsxs(ps,{className:"border-b px-5 py-5 pr-12 sm:px-7 sm:pr-14",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"mb-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(kl,{className:"h-3.5 w-3.5"}),"Agent workspace · private"]}),e.jsx(fs,{className:"text-2xl tracking-tight",children:"Deal room"}),e.jsx(tn,{className:"mt-1",children:n||"Client conversation and activity"})]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>
125{m.refetch(),r.invalidateQueries({queryKey:["deal-room",a]}),r.invalidateQueries({queryKey:["deal-room-cashflow",a]})},disabled:m.isFetching,children:[e.jsx(Ct,{className:`mr-1.5 h-3.5 w-3.5 ${m.isFetching?"animate-spin":""}`}),"Refresh"]})]}),e.jsx("nav",{"aria-label":"Deal room sections",className:"flex flex-wrap gap-1 pt-2",children:[["Conversation","deal-room-conversation"],["Cash flow","deal-room-cashflow"],["Activity","deal-room-activity"]].map(([$,T])=>e.jsx(R,{variant:"ghost",size:"sm",className:"text-blue-700 dark:text-blue-300",onClick:()=>{var S;return(S=document.getElementById(T))==null?void 0:S.scrollIntoView({behavior:"smooth",block:"start"})},children:$},T))})]}),e.jsx(ua,{className:"min-h-0 flex-1 bg-muted/20",children:e.jsxs("div",{className:"grid items-start gap-5 p-4 sm:p-6 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[t&&a&&e.jsx(Px,{proposalId:a,activity:((x=m.data)==null?void 0:x.activity)||[],activityUnavailable:D||m.isLoading}),e.jsxs("section",{id:"deal-room-activity",className:"min-w-0 scroll-mt-4 rounded-2xl border bg-card p-5 shadow-sm lg:sticky lg:top-4 lg:max-h-[calc(100dvh-220px)] lg:overflow-y-auto",tabIndex:0,"aria-labelledby":"deal-activity-title",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{id:"deal-activity-title",className:"text-lg font-semibold",children:"Client activity"}),e.jsx(hs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:"Recent history from this offer link. A forwarded link may be viewed by someone else."}),e.jsx("div",{className:"my-4 flex flex-wrap gap-1.5","aria-label":"Filter activity",children:Mx.map($=>e.jsx(R,{variant:i===$.value?"default":"outline",size:"sm",className:"h-8 px-2.5 text-xs","aria-pressed":i===$.value,onClick:()=>{l($.value),c(40)},children:$.label},$.value))}),(m.isError||d.length>0)&&e.jsxs("div",{role:"alert",className:"mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-100",children:[e.jsx("p",{className:"font-medium",children:"Activity history is incomplete"}),e.jsx("p",{className:"mt-1 text-xs",children:m.isError?"The latest activity could not be loaded. Refresh to try again.":d.join(" ")})]}),m.isLoading?e.jsxs("div",{className:"space-y-3",children:[e.jsx(je,{className:"h-14"}),e.jsx(je,{className:"h-14"}),e.jsx(je,{className:"h-14"})]}):u.length?e.jsx("div",{children:[...g.entries()].map(([$,T])=>e.jsxs("div",{className:"mb-5",children:[e.jsx("p",{className:"mb-3 text-xs font-semibold text-muted-foreground",children:$}),T.map((S,p)=>e.jsx(bx,{event:S,isLast:p===T.length-1},S.id))]},$))}):!m.isError&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:d.length?"No events available from the sources that loaded.":"No activity recorded in this category yet."}),u.length>o&&e.jsx(R,{variant:"outline",className:"w-full",onClick:()=>c($=>$+40),children:"Show more activity"}),e.jsx("p",{className:"border-t pt-3 text-xs leading-relaxed text-muted-foreground",children:"Staff previews are excluded. Suspected scans and unclassified events are labeled. Email opens are signals, not proof of reading. Times use your deviceâs time zone."}),a&&e.jsxs("details",{className:"mt-4 border-t pt-3",children:[e.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground",children:"Salesforce sync details"}),e.jsx("div",{className:"mt-3",children:e.jsx(Fx,{proposalId:a})})]})]})]})})]})})}const qi=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Yn(t){return t===0?"12 AM":t===12?"12 PM":t<12?`${t} AM`:`${t-12} PM`}function Ix(t){return t>=6&&t<12?"morning":t>=12&&t<17?"afternoon":t>=17&&t<22?"evening":"unknown"}function Ux(t,s){var v;const a=[];for(const x of t)x.viewed_at&&a.push({timestamp:x.viewed_at,weight:1});for(const x of s)if(x.created_at){const $=x.event_type==="click"?3:2;a.push({timestamp:x.created_at,weight:$})}if(a.length===0)return{optimalHour:null,optimalDayOfWeek:null,contactWindows:[],lastActiveAt:null,engagementPattern:"unknown",confidence:"low",summary:"No engagement data yet"};const n=Date.now(),r=new Float64Array(24),i=new Float64Array(7),l=new Float64Array(168);let o=null;for(const x of a){const $=new Date(x.timestamp);(!o||$>o)&&(o=$);const T=$.getHours(),S=$.getDay(),p=x.weight??1,y=(n-$.getTime())/(1e3*60*60*24),q=Math.pow(.5,y/7),A=p*q;r[T]+=A,i[S]+=A,l[S*24+T]+=A}let c=0;for(let x=1;x<24;x++)r[x]>r[c]&&(c=x);let m=0;for(let x=1;x<7;x++)i[x]>i[m]&&(m=x);const f=[];for(let x=0;x<7;x++)for(let $=0;$<24;$++){const T=l[x*24+$];T>0&&f.push({hour:$,dayOfWeek:x,score:Math.round(T*100)/100,reason:`Active on ${qi[x]} at ${Yn($)}`})}f.sort((x,$)=>$.score-x.score);const d=((v=f[0])==null?void 0:v.score)||1;for(const x of f)x.score=Math.round(x.score/d*100);const u=f.slice(0,5),g=a.length>=8?"high":a.length>=3?"medium":"low",D=Ix(c);let E;return g==="low"?E=`Limited data (${a.length} event${a.length===1?"":"s"})`:E=`Best: ${[...new Set(u.slice(0,3).map(T=>qi[T.dayOfWeek]))].join("/")} ${Yn(c)} (${a.length} events)`,{optimalHour:c,optimalDayOfWeek:m,contactWindows:u,lastActiveAt:(o==null?void 0:o.toISOString())??null,engagementPattern:D,confidence:g,summary:E}}async function zx(t){const[s,a]=await Promise.all([F.from("proposal_view_logs").select("viewed_at").eq("viewer_class","client").eq("proposal_id",t).order("viewed_at",{ascending:!1}).limit(50),F.from("email_tracking_events").select("created_at, event_type").eq("proposal_id",t).order("created_at",{ascending:!1}).limit(50)]);return Ux((s.data||[]).map(n=>({viewed_at:n.viewed_at||""})),(a.data||[]).map(n=>({created_at:n.created_at,event_type:n.event_type})))}function Bx(t){return ve({queryKey:["timing","insight",t],queryFn:()=>zx(t),enabled:!!t,staleTime:10*60*1e3,gcTime:15*60*1e3})}const Hx=h.lazy(()=>Ze(()=>import("./AgentLinkActivity-DeSoEC9x.js"),__vite__mapDeps([25,1,2,26,27,28,29,30,8,31,32,33,34,35,36,37,38,22,39,40,41,23,18,17,42,43,44,45,46,47,48,14,49,50,51,52,53,54,55,56,57,58,59,21,60,12,61,62,63,64,10,11,13,15,65,66,67,68,69,9,70,71,72,73,74,16,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,20,100,
125101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,4,5,6,7,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,3,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169]))),Vx={"agent-links":[],all:["view","email_open","email_click","accepted","status_change","document_upload"],views:["view"],emails:["email_open","email_click"],status:["accepted","status_change"],docs:["document_upload"]},Wx={view:{icon:bt,color:"text-blue-600 dark:text-blue-400",bg:"bg-blue-100 dark:bg-blue-950"},email_open:{icon:Wa,color:"text-green-600 dark:text-green-400",bg:"bg-green-100 dark:bg-green-950"},email_click:{icon:Xs,color:"text-cyan-600 dark:text-cyan-400",bg:"bg-cyan-100 dark:bg-cyan-950"},accepted:{icon:St,color:"text-emerald-600 dark:text-emerald-400",bg:"bg-emerald-100 dark:bg-emerald-950"},status_change:{icon:Cl,color:"text-amber-600 dark:text-amber-400",bg:"bg-amber-100 dark:bg-amber-950"},document_upload:{icon:sl,color:"text-violet-600 dark:text-violet-400",bg:"bg-violet-100 dark:bg-violet-950"}},Kx={email_open:{icon:Wa,color:"text-muted-foreground",bg:"bg-muted"},email_click:{icon:Xs,color:"text-muted-foreground",bg:"bg-muted"}};function Oi(t){const s=new Date,a=new Date(t),n=s.getTime()-a.getTime(),r=Math.floor(n/1e3),i=Math.floor(r/60),l=Math.floor(i/60),o=Math.floor(l/24);return r<60?"now":i<60?`${i}m ago`:l<24?`${l}h ago`:o<7?`${o}d ago`:a.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function Yx(t){const s=new Date(t),a=new Date,n=s.getFullYear()===a.getFullYear()&&s.getMonth()===a.getMonth()&&s.getDate()===a.getDate(),r=s.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"});return n?r:`${s.toLocaleDateString("en-US",{month:"short",day:"numeric"})} · ${r}`}function Ii(t){return(t.split("@")[0]||t).split(/[._-]+/).filter(Boolean).map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}function Qx({deviceType:t}){const s=t.toLowerCase();return s==="mobile"?e.jsx(pr,{className:"h-2.5 w-2.5"}):s==="tablet"?e.jsx(xr,{className:"h-2.5 w-2.5"}):e.jsx(Va,{className:"h-2.5 w-2.5"})}const Gx=[{value:"all",label:"All"},{value:"views",label:"Views"},{value:"emails",label:"Emails"},{value:"status",label:"Status"},{value:"docs",label:"Docs"},{value:"agent-links",label:"Agent links"}];async function Xx(t,s){const{data:a,error:n}=await F.storage.from("proposal-documents").download(t);if(n||!a){U.error("Could not download that file");return}const r=URL.createObjectURL(a),i=document.createElement("a");i.href=r,i.download=s,document.body.appendChild(i),i.click(),URL.revokeObjectURL(r),i.remove()}function Jx({expanded:t,onToggle:s,docked:a=!1,onToggleDocked:n}){const r=ia(A=>A.openTimeline),i=al(),[l,o]=h.useState("all"),{events:c,isLoading:m}=Gd({enabled:t&&(!a||!i)&&l!=="agent-links"}),f=Ke(A=>A.isAdmin),d=Ke(A=>A.isSuperAdmin),u=f||d,[g,D]=h.useState("all"),E=u?Array.from(new Set(c.map(A=>A.agentEmail).filter(Boolean))).sort():[],v=c.filter(A=>Vx[l].includes(A.type)&&(!u||g==="all"||A.agentEmail===g)),x=[],$=new Map;for(const A of v){const N=A.proposalId||A.businessSlug||A.businessName||A.id;let C=$.get(N);C===void 0&&(C=x.length,$.set(N,C),x.push({key:N,businessName:A.businessName,businessSlug:A.businessSlug,counts:{},latest:A,latestUpload:null,allInternal:!0,agentEmail:A.agentEmail||null}));const I=x[C];I.counts[A.type]=(I.counts[A.type]||0)+1,A.isInternal||(I.allInternal=!1),A.type==="document_upload"&&!I.latestUpload&&(I.latestUpload=A)}const T=A=>{const N=[],C=(I,H,P=`${H}s`)=>{const z=A[I];z&&N.push({type:I,label:`${z} ${z===1?H:P}`})};return C("view","view"),C("email_open","email open"),C("email_click","click"),C("document_upload","document uploaded","documents uploaded"),A.accepted&&N.push({type:"accepted",label:"accepted"}),A.status_change&&N.push({type:"status_change",label:"status update"}),N},S=n?e.jsx(We,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:n,"aria-label":a?"Unpin activity feed":"Pin activity feed to sidebar",children:a?e.jsx(ci,{className:"h-3.5 w-3.5"}):e.jsx(Fu,{className:"h-3.5 w-3.5"})})}),e.jsx(De,{side:"bottom",children:e.jsx("p",{children:a?"Unpin (use as overlay)":"Pin to sidebar"})})]})}):null,p=v[0],_=p?Oi(p.timestamp):null,y=A=>e.jsxs("div",{className:"px-4 py-3 border-b space-y-2 text-left shrink-0",children:[e.jsxs("div",{className:`flex items-center justify-between gap-2 ${A?"pr-8":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx($s,{className:"h-4 w-4 text-muted-foreground"})," Activity"]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[S,a&&e.jsx(R,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:s,"aria-label":"Collapse activity feed",children:e.jsx(oa,{className:"h-3.5 w-3.5"})})]})]}),_&&e.jsxs("div",{className:"flex items-baseline justify-between gap-2",title:new Date(p.timestamp).toLocaleStr
125ing(),children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Last activity"}),e.jsx("span",{className:"text-xs font-semibold text-foreground tabular-nums",children:_})]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:Gx.map(N=>e.jsx("button",{type:"button","aria-pressed":l===N.value,onClick:()=>o(N.value),className:`text-[11px] px-2 py-0.5 rounded transition-colors ${l===N.value?"bg-primary text-primary-foreground font-medium":"text-muted-foreground hover:bg-muted"}`,children:N.label},N.value))}),l!=="agent-links"&&u&&E.length>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(di,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("select",{value:g,onChange:N=>D(N.target.value),"aria-label":"Filter activity by agent",className:"flex-1 min-w-0 h-6 text-[11px] rounded border bg-background px-1.5 text-foreground",children:[e.jsx("option",{value:"all",children:"All agents"}),E.map(N=>e.jsx("option",{value:N,children:Ii(N)},N))]})]})]}),q=l==="agent-links"?t&&(!a||!i)?e.jsx(h.Suspense,{fallback:e.jsx("p",{role:"status",className:"p-3 text-xs",children:"Opening agent linksâ¦"}),children:e.jsx(Hx,{})}):null:e.jsx(ua,{className:"min-h-0 flex-1",children:e.jsx("div",{className:"px-3 py-2 space-y-1",children:m?Array.from({length:8}).map((A,N)=>e.jsxs("div",{className:"flex items-start gap-2.5 p-2",children:[e.jsx(je,{className:"w-9 h-9 rounded-full flex-shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(je,{className:"w-3/4 h-3 rounded"}),e.jsx(je,{className:"w-full h-2.5 rounded"})]})]},N)):x.length===0?e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"No recent activity"})}):x.map(A=>{var H;const N=A.allInternal&&Kx[A.latest.type]||Wx[A.latest.type],C=N.icon,I=T(A.counts);return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{A.latest.proposalId&&r(A.latest.proposalId,A.businessName)},onKeyDown:P=>{P.target===P.currentTarget&&(P.key==="Enter"||P.key===" ")&&A.latest.proposalId&&(P.preventDefault(),r(A.latest.proposalId,A.businessName))},className:`flex items-start gap-2.5 p-2.5 rounded-lg hover:bg-muted/60 transition-colors w-full text-left cursor-pointer ${A.allInternal?"opacity-60":""}`,children:[e.jsx("div",{className:`w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5 ${N.bg}`,children:e.jsx(C,{className:`h-4 w-4 ${N.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-2 items-start",children:[e.jsx("p",{className:"text-sm font-semibold truncate min-w-0",children:A.businessName}),e.jsxs("div",{className:"flex items-start gap-1 w-[84px] shrink-0 justify-end",children:[e.jsxs("div",{className:"flex flex-col items-end gap-0 leading-tight",title:new Date(A.latest.timestamp).toLocaleString(),children:[e.jsx("span",{className:"text-[11px] font-medium text-foreground whitespace-nowrap tabular-nums",children:Oi(A.latest.timestamp)}),e.jsx("span",{className:"text-[10px] text-muted-foreground whitespace-nowrap tabular-nums",children:Yx(A.latest.timestamp)})]}),A.businessSlug&&e.jsx("button",{type:"button","aria-label":"View as client",title:"View as client",onClick:P=>{P.stopPropagation(),window.open(`/${A.businessSlug}`,"_blank")},className:"text-muted-foreground/70 hover:text-foreground transition-colors mt-0.5 flex-shrink-0",children:e.jsx(It,{className:"h-3 w-3"})})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:[u&&A.agentEmail&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-medium rounded-full px-2 py-0.5 bg-primary/10 text-primary max-w-[150px]",title:A.agentEmail,children:[e.jsx(di,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:Ii(A.agentEmail)})]}),I.map(P=>e.jsx("span",{className:"text-[10px] font-medium rounded-full px-2 py-0.5 bg-muted text-muted-foreground",children:P.label},P.type))]}),e.jsx(fa,{contact:{id:A.latest.proposalId,business_name:A.businessName,client_name:A.latest.clientName||"",phone:A.latest.clientPhone||null,email:A.latest.clientEmail||null,agent_email:A.latest.agentEmail||""}}),((H=A.latestUpload)==null?void 0:H.filePath)&&e.jsxs("button",{type:"button",onClick:P=>{P.stopPropagation(),Xx(A.latestUpload.filePath,A.latestUpload.fileName||"document")},className:"mt-1.5 inline-flex items-center gap-1 text-[10px] font-medium text-primary hover:underline max-w-full",title:`Download ${A.latestUpload.fileName||"document"}`,children:[e.jsx(Xd,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:A.latestUpload.fileName||"Download document"})]}),(A.latest.location||A.latest.deviceType)&&e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[A.latest.location&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-muted-foreground
125/80",children:[e.jsx(en,{className:"h-2.5 w-2.5 flex-shrink-0"}),e.jsx("span",{className:"truncate max-w-[140px]",children:A.latest.location})]}),A.latest.deviceType&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-muted-foreground/80 min-w-0",children:[e.jsx(Qx,{deviceType:A.latest.deviceType}),e.jsx("span",{className:"capitalize truncate",children:A.latest.deviceType})]})]})]})]},A.key)})})});return a?t?e.jsxs("aside",{className:"hidden md:flex sticky top-16 h-[calc(100dvh-7rem)] w-[340px] shrink-0 self-start border-l bg-card flex-col",children:[y(!1),q]}):e.jsxs("aside",{className:"hidden md:flex w-14 shrink-0 border-l bg-card flex-col items-center py-2 gap-1",children:[e.jsxs(We,{children:[e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:s,"aria-label":"Expand activity feed",children:e.jsx(Zn,{className:"h-4 w-4"})})}),e.jsx(De,{side:"left",children:e.jsx("p",{children:"Expand activity"})})]}),e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:s,"aria-label":"Activity feed",children:e.jsx($s,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(De,{side:"left",children:e.jsxs("p",{children:["Activity",_&&e.jsxs("span",{className:"block text-[10px] text-muted-foreground tabular-nums",children:["Last loaded activity ",_]})]})})]}),n&&e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:n,"aria-label":"Unpin activity feed",children:e.jsx(ci,{className:"h-3.5 w-3.5"})})}),e.jsx(De,{side:"left",children:e.jsx("p",{children:"Unpin"})})]})]}),_&&e.jsxs("div",{className:"mt-auto mb-2 px-1 text-center",children:[e.jsx("p",{className:"text-[8px] uppercase tracking-wide text-muted-foreground leading-tight",children:"Last loaded"}),e.jsx("p",{className:"text-[9px] font-semibold text-foreground tabular-nums leading-tight",children:_})]})]}):e.jsx(as,{open:t,onOpenChange:A=>{A||s()},children:e.jsxs(xs,{side:"right",className:"w-full sm:w-[420px] sm:max-w-[420px] p-0 flex flex-col gap-0",children:[e.jsx(ps,{className:"sr-only",children:e.jsx(fs,{children:"Activity"})}),y(!0),q]})})}async function Zx(t){const{data:s,error:a}=await F.from("follow_up_settings").select("*").is("proposal_id",null).maybeSingle();if(a)throw a;const n={auto_followups_enabled:(s==null?void 0:s.auto_followups_enabled)??!0,expiration_reminder_days:(s==null?void 0:s.expiration_reminder_days)??[7,3,1],document_reminder_hours:(s==null?void 0:s.document_reminder_hours)??48,followup_after_view_hours:(s==null?void 0:s.followup_after_view_hours)??24,max_followups:(s==null?void 0:s.max_followups)??3,ai_tone:(s==null?void 0:s.ai_tone)??"professional",sequence_emails_enabled:(s==null?void 0:s.sequence_emails_enabled)??!1,funded_congratulations_enabled:(s==null?void 0:s.funded_congratulations_enabled)??!0,monthly_followup_enabled:(s==null?void 0:s.monthly_followup_enabled)??!1,monthly_followup_interval_days:(s==null?void 0:s.monthly_followup_interval_days)??30,use_smart_timing:(s==null?void 0:s.use_smart_timing)??!1,preferred_hours:(s==null?void 0:s.preferred_hours)??[]},{data:r,error:i}=await F.from("automated_emails").select("id, email_type, status, sent_at, trigger_reason").eq("proposal_id",t).order("sent_at",{ascending:!1}).limit(1).maybeSingle();if(i)throw i;return{settings:n,lastEmail:r??null}}function ep(t){return ve({queryKey:Me.followUp.settings(t||""),queryFn:()=>Zx(t),enabled:!!t})}function ks({enabled:t}){return t?e.jsxs(J,{className:"bg-green-100 text-green-700 dark:bg-green-950 dark:text-green-400 text-[10px] gap-0.5",children:[e.jsx(St,{className:"h-3 w-3"}),"On"]}):e.jsxs(J,{variant:"outline",className:"text-[10px] gap-0.5",children:[e.jsx(Za,{className:"h-3 w-3"}),"Off"]})}function tp(t){const s=t%12||12,a=t<12?"AM":"PM";return`${s} ${a}`}function sp(t){return ve({queryKey:["proposals","followup-flag",t??""],enabled:!!t,queryFn:async()=>{const{data:s,error:a}=await F.from("proposals").select("id, business_name, client_name, auto_followups_enabled").eq("id",t).maybeSingle();if(a)throw a;return s}})}function ap(){const t=Qt(),s=Ke(u=>
125u.isSuperAdmin),{showFollowUpInspector:a,followUpInspectorProposalId:n,closeFollowUpInspector:r}=ia(),i=a?n:null,{data:l,isLoading:o}=ep(i),{data:c,isLoading:m}=sp(i),f=ql(),d=(c==null?void 0:c.auto_followups_enabled)??!1;return e.jsx(as,{open:a,onOpenChange:u=>!u&&r(),children:e.jsxs(xs,{side:"right",className:"w-full sm:max-w-md p-0 flex flex-col",children:[e.jsxs(ps,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(fs,{className:"flex items-center gap-2",children:[e.jsx(or,{className:"h-5 w-5 text-primary"}),"Follow-Up Settings"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c!=null&&c.business_name?`${c.business_name} · `:"","this deal's switch, then the company cadence"]})]}),e.jsx(ua,{className:"flex-1",children:e.jsxs("div",{className:"px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border-2 border-primary/30 rounded-lg bg-primary/5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ia,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Auto follow-ups for this deal"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d?"Sending on the company cadence":"Paused â no automated emails go out"})]})]}),m?e.jsx(je,{className:"h-6 w-11 rounded-full"}):e.jsx(ta,{checked:d,disabled:!i,"aria-label":"Auto follow-ups for this deal",onCheckedChange:u=>{i&&f.toggleAutoFollowups(i,u)}})]}),o?e.jsx("div",{className:"space-y-4",children:Array.from({length:5}).map((u,g)=>e.jsx(je,{className:"h-16 rounded-lg"},g))}):l?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(Jd,{className:"h-3.5 w-3.5"}),"Company cadence (set by admins)"]}),e.jsx(ks,{enabled:l.settings.auto_followups_enabled})]}),e.jsxs("div",{className:"p-3 border rounded-lg space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground mb-2",children:"Active Automations"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Sequences"}),e.jsx(ks,{enabled:l.settings.sequence_emails_enabled})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Monthly"}),e.jsx(ks,{enabled:l.settings.monthly_followup_enabled})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Funded Congrats"}),e.jsx(ks,{enabled:l.settings.funded_congratulations_enabled})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Expiry Reminders"}),e.jsx(ks,{enabled:l.settings.expiration_reminder_days.length>0})]})]})]}),e.jsxs("div",{className:"p-3 border rounded-lg space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground mb-2 flex items-center gap-1",children:[e.jsx(hs,{className:"h-3.5 w-3.5"}),"Timing"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1.5 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Follow-up after view"}),e.jsxs("span",{className:"font-medium",children:[l.settings.followup_after_view_hours,"h"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Document reminder"}),e.jsxs("span",{className:"font-medium",children:[l.settings.document_reminder_hours,"h"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Max follow-ups"}),e.jsx("span",{className:"font-medium",children:l.settings.max_followups})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Expiry reminders"}),e.jsx("span",{className:"font-medium",children:l.settings.expiration_reminder_days.length>0?`${l.settings.expiration_reminder_days.join(", ")}d before`:"None"})]}),l.settings.monthly_followup_enabled&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Monthly interval"}),e.jsxs("span",{className:"font-medium",children:[l.settings.monthly_followup_interval_days,"d"]})]})]})]}),e.jsxs("div",{className:"p-3 border rounded-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground mb-1 flex items-center gap-1",children:[e.jsx(sa,{className:"h-3.5 w-3.5"}),"AI Tone"]}),e.jsx(J,{variant:"secondary",className:"capitalize",children:l.settings.ai_tone})]}),e.jsxs("div",{className:"p-3 border rounded-lg space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Smart Timing"}),e.jsx(ks,{enabled:l.settings.use_smart_timing})]}),l.settings.preferred_hours.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Preferred hours: ",l.settings.preferred_hours.map(tp).join(", ")
125]})]}),e.jsxs("div",{className:"p-3 border rounded-lg",children:[e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground mb-2 flex items-center gap-1",children:[e.jsx(Be,{className:"h-3.5 w-3.5"}),"Last Automated Email"]}),l.lastEmail?e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Type"}),e.jsx(J,{variant:"outline",className:"text-[10px]",children:l.lastEmail.email_type})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("span",{className:"font-medium capitalize",children:l.lastEmail.status})]}),l.lastEmail.sent_at&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sent"}),e.jsx("span",{className:"font-medium",children:Ka(new Date(l.lastEmail.sent_at),{addSuffix:!0})})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Reason"}),e.jsx("span",{className:"font-medium truncate max-w-[160px]",children:l.lastEmail.trigger_reason})]})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No automated emails sent yet"})]}),s&&e.jsxs(R,{variant:"outline",size:"sm",className:"w-full gap-2 text-xs",onClick:()=>{r(),t("/dashboard/admin/settings")},children:[e.jsx(It,{className:"h-3.5 w-3.5"}),"Edit company cadence in Admin Settings"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No settings found"})]})})]})})}function np(t,s,a,n){var m;const r=s.trim().toLowerCase();if(a.has(r)||n.size>0&&!n.has(r))return{value:"Not ranked",note:"Your results still countâtrack your progress in Performance."};const i=su(((m=au(t,a,n))==null?void 0:m.reps)??[],"volume"),l=i.find(f=>{var d;return((d=f.email)==null?void 0:d.trim().toLowerCase())===r});if(!l)return{value:"Not ranked yet",note:"A new month brings new opportunities. Start with your next client."};const o=i.filter(f=>f.volume>l.volume).length,c=l.fundings===0?"A new month brings new opportunities. Start with your next client.":l.rank===1?"Youâre setting the paceâkeep up the great work.":o<i.length/3?"Strong workâyouâre among this monthâs leaders.":o<i.length*2/3?"Keep buildingâevery client you help moves you forward.":"Thereâs room to climb. Focus on your next client win.";return{value:`#${l.rank} of ${i.length} agents`,note:c}}function rp(t,s){if(t===void 0||!s||s.count===0)return;const a=t-s.total,n=a>0?"up":a<0?"down":"even",r=n==="even"?`Even with the same point last month (${Gs(s.total)})`:`${n==="up"?"â²":"â¼"} ${Gs(Math.abs(a))} vs same point last month (${Gs(s.total)} · ${s.count})`;return{direction:n,delta:a,text:r}}function ip(t,s,a){const n=s.filter(l=>l.proposal_id===t),r=a.filter(l=>l.proposal_id===t),i=new Set(r.map(l=>l.custom_document_id));return{requested:n.length,missing:n.filter(l=>!i.has(l.id)).map(l=>l.document_title||"Untitled document"),revision:JSON.stringify([n.map(l=>l.id).sort(),r.map(l=>`${l.id}:${l.custom_document_id}:${l.uploaded_at||""}`).sort()])}}function Qn(t){return t?t.requested?t.missing.length?`Missing: ${t.missing.join(" · ")}`:"Checklist received · confirm funding":"No checklist set · confirm funding requirements":"Document checklist unavailable · open the deal to check"}const us=(t=new Date)=>`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`;function lp(t,s,a=new Date){var f;const n=us(a),r=new Map(t.map(d=>[d.id,d])),i=s.filter(d=>d.status==="pending"&&d.due_date<=n),l=i.map(d=>{const u=d.proposal_id?r.get(d.proposal_id):void 0,g=d.due_date<n;return{id:`task-${d.id}`,task:d,deal:u,title:(u==null?void 0:u.business_name)||d.title,reason:`${u?`${d.title} · `:""}${g?`Due ${ma(d.due_date,{month:"short",day:"numeric"})}`:d.due_time?`Today at ${d.due_time.slice(0,5)}`:"Due today"}`,label:g?"Overdue":"Today",rank:g?0:1,at:`${d.due_date}T${d.due_time||"23:59"}`,kind:"followups",overdue:g}});for(const d of t){const u={id:d.id,deal:d,title:d.business_name||"Untitled business",at:d.created_at},g=d.last_reply_at?a.getTime()-Date.parse(d.last_reply_at):1/0;
125if(g>=0&&g<=7*24*60*60*1e3&&l.push({...u,kind:"replies",rank:1.5,label:"Recent reply",reason:"Client replied in the last 7 days · review the conversation before following up",at:d.last_reply_at}),d.status!=="draft"&&((f=d.checklist)!=null&&f.missing.length)&&!["accepted","in_final_review"].includes(d.status)&&l.push({...u,kind:"documents",rank:2.5,label:"Missing documents",reason:Qn(d.checklist)}),d.status==="accepted"||d.status==="in_final_review")l.push({...u,kind:"funding",rank:2,label:"Awaiting funding",reason:Qn(d.checklist)});else if(d.status==="draft")l.push({...u,kind:"drafts",rank:4,label:"Draft",reason:"Check the options and details before sending"});else if(d.status==="pending"){const D=d.expiration_date?nr(d.expiration_date,a):1/0;D>=0&&D<=3&&l.push({...u,kind:"expiring",rank:3,label:D===0?"Expires today":"Expiring soon",reason:`Offer expires ${D===0?"today":D===1?"tomorrow":`in ${D} days`} · confirm the client's next step`,at:d.expiration_date});const E=d.last_client_viewed_at?a.getTime()-Date.parse(d.last_client_viewed_at):1/0;if(E>=0&&E<=2*60*60*1e3){const v=Math.floor(E/6e4);l.push({...u,kind:"recent",rank:3.5,label:"Recent visit",reason:`Proposal opened ${v<1?"just now":`${v} min ago`} · check the activity before calling`,at:d.last_client_viewed_at})}}}l.sort((d,u)=>d.rank-u.rank||(["recent","replies"].includes(d.kind)&&d.kind===u.kind?u.at.localeCompare(d.at):d.at.localeCompare(u.at))||d.id.localeCompare(u.id));const o=new Set,c=l.filter(d=>{var g;const u=((g=d.deal)==null?void 0:g.id)||d.id;return o.has(u)?!1:(o.add(u),!0)}),m=d=>t.filter(d).map(u=>u.id);return{items:c,buckets:{followups:{count:i.length,ids:[...new Set(i.flatMap(d=>d.proposal_id&&r.has(d.proposal_id)?[d.proposal_id]:[]))]},drafts:{count:t.filter(d=>d.status==="draft").length,ids:m(d=>d.status==="draft")},funding:{count:t.filter(d=>["accepted","in_final_review"].includes(d.status)).length,ids:m(d=>["accepted","in_final_review"].includes(d.status))},documents:{count:t.filter(d=>{var u;return d.status!=="draft"&&!!((u=d.checklist)!=null&&u.missing.length)}).length,ids:m(d=>{var u;return d.status!=="draft"&&!!((u=d.checklist)!=null&&u.missing.length)})},replies:{count:l.filter(d=>d.kind==="replies").length,ids:l.filter(d=>d.kind==="replies").map(d=>d.deal.id)}},followups:l.filter(d=>d.kind==="followups")}}const To="agent_tasks";async function op(t){const s=us(),{data:a,error:n}=await F.from(To).select("*").eq("user_id",t).eq("status","pending").lte("due_date",s).order("due_date",{ascending:!0}).order("due_time",{ascending:!0,nullsFirst:!1});if(n)throw n;return a||[]}async function cp(t,s){const{data:a,error:n}=await F.from("agent_tasks").insert({user_id:t,proposal_id:s.proposal_id||null,title:s.title,description:s.description||null,due_date:s.due_date,due_time:s.due_time||null,priority:s.priority||"medium",status:"pending"}).select().single();if(n)throw n;return a}async function dp(t){const{error:s}=await F.from("agent_tasks").update({status:"completed",completed_at:new Date().toISOString()}).eq("id",t);if(s)throw s}async function up(t){const{error:s}=await F.from(To).delete().eq("id",t);if(s)throw s}function Eo(t){const s=Nt(),a=ve({queryKey:Me.tasks.today(t),queryFn:()=>op(t),enabled:!!t,refetchInterval:5*60*1e3}),n=Le({mutationFn:l=>cp(t,l),onSuccess:()=>{s.invalidateQueries({queryKey:Me.tasks.all}),U.success("Task created")},onError:it("Failed to create task")}),r=Le({mutationFn:l=>dp(l),onSuccess:()=>{s.invalidateQueries({queryKey:Me.tasks.all}),U.success("Task completed")},onError:it("Failed to complete task")}),i=Le({mutationFn:l=>up(l),onSuccess:()=>{s.invalidateQueries({queryKey:Me.tasks.all})},onError:it("Failed to delete task")});return{tasks:a.data??[],isLoading:a.isLoading,isError:a.isError,refetch:a.refetch,isCompleting:r.isPending,createTask:n.mutate,isCreating:n.isPending,completeTask:r.mutate,deleteTask:i.mutate}}async function mp(t){if(!t)throw new Error("Sign in to view your priorities");const s=[];for(let a=0;;a+=500){const{data:n,error:r}=await F.from("proposals").select("id, user_id, business_name, client_name, phone, email, agent_email, unique_link, business_slug, salesforce_opportunity_id, type, status, created_at, expiration_date, last_client_viewed_at, initial_email_sent").eq("user_id",t).eq("is_archived",!1).eq("fit_only",!1).in("status",["draft","pending","accepted","in_final_review"]).in("type",["proposal","line_of_credit","funding_menu"]).order("id").range(a,a+499);if(r)throw r;if(!n)throw new Error("Priorities unavailable");if(s.push(...n),n.length<500)return s}}function hp(t=new Date){return{today:new Date(t.getFullYear(),t.getMonth(),t.getDate()).toISOString(),month:new Date(t.getFullYear(),t.getMonth(),1).toISOString(),until:t.toISOString()}}async function $o(t,s,a){const n=[];let r=0;for(let i=0;;i+=1e3){const{data:l,error:o}=await F.from("proposals").select("id, funded_amount").eq("user_id",t).eq("status","funded").gte("funded_at",s).lte("funded_at",a).order("id").range(i,i+999);if(o)throw o;if(!l)throw new Error("Funding totals unavailable");if(n.push(...l.map(c=>c.id)),r+=l.reduce((c,m)=>c+(m.funded_amount??0),0),l.length<1e3)return{total:r,ids:n,count:n.length}}}async function xp(t,s=new Date){if(!t)throw new Error("Sign in to view funding progress");const{month:a,until:n}=hp(s);return $o(t,a,n)}function pp(t=new Date){const s=new Date(t.getFullYear(),t.getMonth(),1),a=new Date(t.getFullYear(),t.getMonth()-1,1),n=t.getTime()-s.getTime(),r=new Date(Math.min(a.getTime()+n,s.getTime()-1));return{month:a.toISOString(),until:r.toISOString()}}async function fp(t,s=new Date){if(!t)throw new Error("Sign in to view funding progress");const{month:a,until:n}=pp(s);return $o(t,a,n)}function gp({compact:t=!1,rank:s,rankError:a,rankStale:n,rankUpdatedAt:r,performanceVisible:i=!0,draftCount:l,draftsError:o,fundedCount:c,fundedAmount:m,fundedLastMonth:f,monthRow:d,fundingError:u,onPerformance:g,onDrafts:D,onFunded:E}){const v=u?"Unavailable":c===void 0&&m===void 0?"â":t&&m!==void 0?`${Gs(m)}${c!==void 0?` · ${c}`:""}`:c===void 0?"â":String(c),x=u?void 0:rp(m,f),$=[{label:"Your rank",icon:fr,value:i?a?"Unavailable":(s==null?void 0:s.value)??"â":"Not available",hint:"This month · New-business funded volume",note:i?a?"Your ranking couldnât be loaded. Try refreshing your workspace.":(s==null?void 0:s.note)??"Loading your rankingâ¦":"Keep buildingâevery client you help moves you forward.",onClick:g,disabled:!i,notice:!!a},{label:"Salesforce drafts",icon:nu,value:o?"Unavailable":l===void 0?"â":String(l),hint:"Assigned to you · To review",note:o?"Drafts couldnât be counted. Open your queue to retry.":"Review your drafts and prepare your next client offer.",onClick:D,disabled:!1,notice:!!o},{label:"Deals funded this month",icon:Zi,value:v,hint:(x==null?void 0:x.text)??"Your funded proposals",hintTone:x==null?void 0:x.direction,note:"Completed results · View your funded deals",onClick:E,disabled:u||c===void 0&&m===void 0,notice:!!u}],T=S=>S==="up"?"text-green-700 dark:text-green-400":S==="down"?"text-amber-700 dark:text-amber-400":"";return e.jsxs("div",{"data-testid":"month-summary",className:t?"px-4 pb-4 sm:px-6 sm:pb-5":void 0,children:[t&&e.jsxs("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx("span",{children:"This month"}),d&&e.jsxs("span",{className:"font-medium normal-case tracking-normal tabular-nums",children:[" ","· ",d.submissions," submitted · ",d.approvals," approved"]})]}),e.jsx("div",{className:t?"grid grid-cols-1 gap-2 lg:grid-cols-3 sm:gap-3":"grid grid-cols-1 border-y border-border/60 bg-muted/40 sm:grid-cols-3","aria-label":"Your performance and drafts",children:$.map(({label:S,icon:p,value:_,hint:y,hintTone:q,note:A,onClick:N,disabled:C,notice:I})=>e.jsxs("button",{type:"button",onClick:N,disabled:C||!N,className:t?"group relative grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1 rounded-xl border border-border/70 bg-background/60 p-3 text-left transition-colors hover:border-primary/30 hover:bg-primary/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 lg:block lg:p-4":"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 border-b border-border/60 px-4 py-3 text-left transition-colors last:border-b-0 hover:bg-muted/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-60 sm:block sm:border-b-0 sm:border-r sm:px-6 sm:py-5 sm:last:border-r-0",children:[e.jsxs("p",{className:t?"flex items-center gap-2 text-xs font-medium text-muted-foreground lg:pr-4":"flex items-center gap-2 text-[13px] font-semibold",children:[e.jsx(p,{"aria-hidden":"true",className:t?"h-4 w-4 shrink-0 text-primary":"h-4 w-4 shrink-0 text-muted-foreground"}),S]}
125),t&&!C&&N&&e.jsx(zn,{"aria-hidden":!0,className:"absolute right-3 top-3 hidden h-3.5 w-3.5 text-muted-foreground/60 group-hover:text-primary lg:block"}),e.jsx("p",{className:t?"text-base font-semibold tracking-tight tabular-nums lg:mt-2 lg:text-xl":"text-base font-semibold tracking-tight tabular-nums sm:mt-2 sm:text-2xl",children:_}),e.jsxs("p",{className:`${t?"col-span-2 text-[11px] text-muted-foreground lg:mt-1":"sr-only sm:not-sr-only sm:mt-1 sm:block sm:text-xs sm:text-muted-foreground"} ${T(q)}`,children:[y,S==="Your rank"&&i&&!a&&r&&e.jsxs(e.Fragment,{children:[" · ",e.jsx(bo,{at:r,prefix:"Salesforce, updated"})]})]}),e.jsx("p",{className:t?"sr-only":I?"col-span-2 mt-1 text-xs leading-relaxed text-muted-foreground":"sr-only sm:not-sr-only sm:mt-2 sm:block sm:text-xs sm:leading-relaxed sm:text-muted-foreground",children:A}),S==="Your rank"&&n&&e.jsx("p",{className:"col-span-2 mt-1 text-xs text-amber-700 dark:text-amber-300",children:"Last saved ranking · Update delayed"})]},S))})]})}function bp({contacts:t}){return t.length===0?null:e.jsxs("section",{"aria-label":"Client shortcuts",className:"border-b border-border/60 bg-muted/20 px-4 py-5 sm:px-6",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Reach clients"}),e.jsx("ul",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-x-4 sm:gap-y-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5",children:t.map(s=>{const a=s.client_name||s.business_name||"Client",n=s.client_name&&s.business_name?s.business_name:null;return e.jsxs("li",{className:"min-w-0 rounded-xl border border-border/60 bg-card p-3 transition-colors duration-150 hover:border-primary/25",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:a}),n&&e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:n})]}),e.jsx(fa,{contact:s,tone:"muted",presentation:"text",className:"mt-1.5"})]},s.id)})})]})}const yp=[{key:"followups",label:"Follow-ups due",short:"follow-up",hint:"Today and overdue"},{key:"replies",label:"Recent replies",short:"reply",hint:"Last 7 days · not an unread count"},{key:"documents",label:"Missing documents",short:"missing doc",hint:"Deals with requested items outstanding"},{key:"drafts",label:"Drafts to finish",short:"draft",hint:"Review before sending"}];function wp(t,s){const a=t===1?s:s==="reply"?"replies":`${s}s`;return`${t} ${a}`}function vp({data:t,loading:s,error:a,documentsUnavailable:n,repliesUnavailable:r,active:i,onSelect:l}){return e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-x-1 gap-y-1.5 sm:mt-4","aria-label":"Today's workload",children:yp.map(({key:o,label:c,short:m,hint:f},d)=>{const u=a||o==="documents"&&n||o==="replies"&&r,g=u||s||!t?null:t.buckets[o].count,D=i===o,E=g===null?u?"Unavailable":"â":wp(g,m);return e.jsxs("span",{className:"inline-flex items-center gap-x-1",children:[d>0&&e.jsx("span",{className:"px-0.5 text-muted-foreground/50","aria-hidden":"true",children:"·"}),e.jsxs("button",{type:"button",title:f,"aria-label":`${c}: ${u?"Unavailable":s||!t?"Loading":t.buckets[o].count}. ${f}`,"aria-pressed":D,disabled:s||u||!t,onClick:()=>l(D?null:o),className:`inline-flex min-h-9 items-center rounded-full border px-2.5 text-left text-xs transition-colors duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-60 sm:min-h-8 ${D?"border-foreground
125/30 bg-muted/70 font-semibold text-foreground":g?"border-border bg-card font-medium text-foreground hover:bg-muted/50":"border-transparent text-muted-foreground hover:bg-muted/40 hover:text-foreground"}`,children:[e.jsx("span",{className:"tabular-nums",children:E}),e.jsxs("span",{className:"sr-only",children:[" ",c]})]})]},o)})})}const Ui={followups:0,replies:1,funding:2,expiring:3,documents:4,recent:5,reminder:6,drafts:7};function jp(t,s){const a=t.deal;if(!(a!=null&&a.id))return null;const n=Ms(a.phone),r=yr(a.email);return!n&&!r?null:{id:a.id,business_name:a.business_name,client_name:a.client_name,phone:a.phone??null,email:a.email??null,agent_email:a.agent_email??s??""}}function _p(t,s){const a=s==null?void 0:s.limit;if(!t||a<=0)return[];const n=[...t.items,...t.followups].filter(l=>l.deal&&l.kind!=="drafts").sort((l,o)=>(Ui[l.kind]??99)-(Ui[o.kind]??99)||l.rank-o.rank),r=new Set,i=[];for(const l of n){const o=jp(l,s==null?void 0:s.agentEmail);if(!(!o||r.has(o.id))&&(r.add(o.id),i.push(o),i.length>=a))break}return i}const Os=t=>{var s;return t.deal?`deal:${t.deal.id}`:`task:${(s=t.task)==null?void 0:s.id}`};function Np(t=new Date){return new Date(t.getFullYear(),t.getMonth(),t.getDate()+1,8)}function Ao(t,s,a=new Date){var i;const n=s.filter(l=>{var o;return l.status==="pending"&&l.due_date<=us(a)&&(t.deal?l.proposal_id===t.deal.id:l.id===((o=t.task)==null?void 0:o.id))}),r=t.deal;return JSON.stringify([1,r?[r.status,r.last_client_viewed_at,r.last_reply_at,r.initial_email_sent,r.expiration_date,r.expiration_date===us(a),(i=r.checklist)==null?void 0:i.revision]:null,n.map(l=>[l.id,l.due_date,l.due_time,l.priority]).sort((l,o)=>String(l[0]).localeCompare(String(o[0])))])}function kp(t,s,a,n,r,i=new Date){const l=new Map(s.filter(m=>m.user_id===r).map(m=>[m.item_key,m])),o=[...t.items];for(const m of a)l.has(`deal:${m.id}`)&&!o.some(f=>{var d;return((d=f.deal)==null?void 0:d.id)===m.id})&&o.push({id:`reminder-${m.id}`,deal:m,title:m.business_name,kind:"reminder",label:"Follow-up reminder",rank:1,reason:"You asked to revisit this deal · check the latest activity",at:l.get(`deal:${m.id}`).resume_at});o.sort((m,f)=>m.rank-f.rank);const c=m=>{const f=l.get(Os(m));return!!f&&Date.parse(f.resume_at)>i.getTime()&&f.wake_signature===Ao(m,n,i)};return{data:{...t,items:o.filter(m=>!c(m)),followups:t.followups.filter(m=>!c(m))},snoozed:o.filter(c).map(m=>({item:m,resumeAt:l.get(Os(m)).resume_at}))}}const zi=t=>`rounded px-1.5 py-0.5 text-[10px] font-medium ${t?"bg-amber-50 text-amber-800 dark:bg-amber-950/40 dark:text-amber-300":"bg-muted text-muted-foreground"}`;function Sp({item:t,loading:s}){var n;const a=(n=t.deal)==null?void 0:n.checklist;return s&&!a?e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Checking requested documentsâ¦"}):a&&a.missing.length>1?e.jsxs("details",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:[e.jsxs("summary",{className:"cursor-pointer rounded focus-visible:outline-primary",children:["Missing: ",a.missing[0]," + ",a.missing.length-1," more"]}),e.jsx("ul",{className:"mt-1 list-disc space-y-1 pl-4",children:a.missing.map((r,i)=>e.jsx("li",{children:r},i))})]}):e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:Qn(a)})}function Cp({firstName:t,agentEmail:s,performance:a,data:n,funded:r,fundingError:i,loading:l,error:o,refreshing:c,completing:m,snoozed:f=[],snoozeDisabled:d,snoozeError:u,checklistLoading:g,checklistError:D,repliesUnavailable:E,onOutreach:v,onLogCall:x,renderContext:$,onSnooze:T,onRestore:S,activeBucket:p,onBucket:_,onNewProposal:y,onNextStep:q,onOpenDeal:A,onReview:N,onFinishDraft:C,onCall:I,onComplete:H,onInsights:P,onRetry:z,now:M=new Date}){const[k,w]=h.useState(!1),L=h.useId(),[O,ae]=h.useState(!1),[te,V]=h.useState(!1),G=f.filter(({item:B})=>!p||(p==="followups"?!!B.task:!!B.deal&&!!(n!=null&&n.buckets[p].ids.includes(B.deal.id)))),Z=new Map(G.map(B=>[Os(B.item),B.resumeAt])),se=M.getHours()<12?"Good morning":M.getHours()<18?"Good afternoon":"Good evening",Y=n?p==="followups"?n.followups:p?n.items.filter(B=>B.deal&&n.buckets[p].ids.includes(B.deal.id)):n.items:[],ne=te?G.map(B=>B.item):Y,fe=O?ne:ne.slice(0,3),_e=l||o||!n,ge=(B,Q)=>{var Ee,Ye,Fe;
125const ie=Q?"Restore now":B.kind==="drafts"?"Finish proposal":v&&((Ye=(Ee=B.deal)==null?void 0:Ee.checklist)!=null&&Ye.missing.length)&&B.deal.status!=="draft"?"Request missing items":v&&B.deal&&B.kind==="expiring"?"Confirm next step":B.kind==="funding"?"Review funding":v&&B.deal&&B.deal.status!=="draft"&&B.kind!=="recent"?"Follow up":Ms((Fe=B.deal)==null?void 0:Fe.phone)?"Call":B.task?"Mark done":"Open deal";return{primary:ie,run:()=>ie==="Restore now"?S==null?void 0:S(B):ie==="Finish proposal"?(C||N)(B):["Request missing items","Follow up","Confirm next step"].includes(ie)?v==null?void 0:v(B):ie==="Call"?I(B):ie==="Mark done"?H(B):A(B)}},me=!_e&&!te?Y[0]:void 0,b={followups:"Follow-ups due",replies:"Recent replies",documents:"Missing documents",drafts:"Drafts to finish",funding:"Awaiting funding"},W=me?ge(me):void 0,oe=_p(n,{limit:8,agentEmail:s});return e.jsxs("section",{"aria-label":"Your daily workspace",className:"pipeline-today mb-6 overflow-hidden rounded-2xl border border-border/70 bg-card",children:[e.jsxs("header",{className:"pipeline-today-header flex flex-wrap items-start justify-between gap-4 px-4 pb-4 pt-5 sm:px-6 sm:pt-6",children:[e.jsxs("div",{className:"min-w-0 flex-1 basis-full lg:basis-0",children:[e.jsx("p",{className:"pipeline-today-date mb-2 text-xs font-medium tracking-wide",children:M.toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})}),e.jsxs("h2",{className:"pipeline-greeting text-2xl font-semibold leading-tight tracking-tight sm:text-3xl",children:[se,t?`, ${t}`:""]}),e.jsx(vp,{data:n,loading:l,error:o,documentsUnavailable:D||g,repliesUnavailable:E,active:p,onSelect:B=>{w(!0),V(!1),ae(!0),_(B)}})]}),e.jsxs("div",{className:"flex w-full flex-wrap items-center gap-2 sm:w-auto",children:[e.jsxs(R,{onClick:y,className:"h-10 gap-1.5 rounded-xl px-4 text-sm font-semibold shadow-none",children:[e.jsx(aa,{className:"h-4 w-4"}),"New proposal"]}),e.jsxs(R,{type:"button",variant:"outline",onClick:()=>w(B=>!B),"aria-expanded":k,"aria-controls":L,className:"h-10 gap-2 rounded-xl bg-card px-3 text-xs font-medium shadow-none",children:[k?"Hide daily details":"Show daily details",e.jsx(ms,{"aria-hidden":!0,className:`h-4 w-4 ${k?"rotate-180":""}`})]})]})]}),!k&&me&&W&&e.jsxs("div",{role:"region","aria-label":"Up next","data-testid":"up-next",className:"mx-4 mb-4 flex flex-col gap-3 rounded-xl border border-primary/20 bg-primary/[0.04] p-3 sm:mx-6 sm:flex-row sm:items-center sm:p-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"flex flex-wrap items-center gap-x-2 text-[11px] font-semibold uppercase tracking-wide text-primary",children:[e.jsxs("span",{children:["Up next",p?` in ${b[p]}`:""]}),p&&e.jsxs("button",{type:"button",onClick:()=>_(null),className:"inline-flex items-center gap-0.5 rounded font-medium normal-case tracking-normal text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx(Yt,{className:"h-3 w-3","aria-hidden":"true"}),"Clear filter"]})]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1",children:[me.deal?e.jsx("button",{type:"button",onClick:()=>A(me),className:"max-w-full break-words text-left text-base font-semibold hover:text-foreground/80 focus-visible:outline-ring",children:me.title}):e.jsx("p",{className:"text-base font-semibold",children:me.title}),e.jsx("span",{className:zi(me.overdue),children:me.label})]}),me.kind!=="funding"&&me.reason&&e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:me.reason})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(R,{disabled:W.primary==="Mark done"&&m,onClick:W.run,className:"h-10 gap-2 rounded-lg px-4 text-sm font-semibold shadow-none",children:[W.primary==="Call"?e.jsx(qt,{className:"h-4 w-4"}):W.primary==="Mark done"?e.jsx(At,{className:"h-4 w-4"}):e.jsx(La,{className:"h-4 w-4"}),W.primary]}),Y.length>1&&e.jsxs(R,{type:"button",variant:"ghost",onClick:()=>w(!0),"aria-controls":L,className:"h-10 px-3 text-xs font-medium text-muted-foreground hover:text-foreground",children:["See all ",Y.length,p?" in this group":" priorities"]})]})]}),e.jsx(gp,{...a,compact:!0,fundingError:i,fundedAmount:r}),e.jsxs("div",{id:L,hidden:!k,className:"border-t border-border/60",children:[e.jsx(bp,{contacts:oe}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4 pb-4 pt-6 sm:px-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:te?"Snoozed":p?b[p]:"Next up"}),!_e&&e.jsx("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-[10px] tabular-nums text-muted-foreground",children:ne.length}),p&&e.jsxs("button",{onClick:()=>_(null),className:"flex min-h-9 items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(Yt,{className:"h-3 w-3"}),"Clear"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(R,{variant:"ghost",className:"h-9 gap-1.5 px-2 text-xs text-muted-foreground",onClick:()=>q(),children:[e.jsx(aa,{className:"h-3.5 w-3.5"}),"Set next step"]}),e.jsxs(Ua,{children:[e.jsx(za,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"icon",className:"h-9 w-9","aria-label":"Workspace tools",children:e.jsx(Ya,{className:"h-4 w-4"})})}),e.jsxs(Ba,{align:"end",children:[e.jsxs(pe,{onSelect:P,children:[e.jsx(ss,{className:"mr-2 h-4 w-4"}),"More insights"]}
125),e.jsx(pe,{onSelect:z,disabled:c,children:"Refresh workspace"})]})]})]})]}),u&&e.jsxs("p",{role:"status",className:"px-4 pb-2 text-xs text-muted-foreground sm:px-6",children:["Reminders couldnât be checked. All available priorities are shown."," ",e.jsx("button",{onClick:z,className:"text-muted-foreground underline hover:text-foreground",children:"Retry"})]}),te&&e.jsx("p",{className:"px-4 pb-2 text-xs text-muted-foreground sm:px-6",children:"Reminders use your local time. Task due dates and the totals above are unchanged."}),e.jsx("div",{"aria-live":"polite",className:"pipeline-next-up-list",children:o?e.jsxs("div",{role:"alert",className:"px-6 pb-5 text-sm text-muted-foreground",children:["Priorities are unavailable. Your deals are still in the pipeline."," ",e.jsx("button",{disabled:c,onClick:z,className:"font-medium text-muted-foreground underline hover:text-foreground",children:"Retry"})]}):_e?e.jsxs("div",{role:"status",className:"space-y-3 px-6 pb-5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading your prioritiesâ¦"}),e.jsx("div",{className:"h-10 animate-pulse rounded-lg bg-muted"})]}):fe.length===0?e.jsxs("div",{className:"flex items-center gap-3 px-6 py-6",children:[e.jsx(At,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:te?"No snoozed priorities in this group":G.length?"Your remaining priorities are snoozed":p?"Nothing in this group right now":"You're clear on today's priorities"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Set a next step or choose a deal from Pipeline."})]})]}):e.jsx("ol",{className:"space-y-2 px-4 pb-4 sm:px-6 sm:pb-6",children:fe.map((B,Q)=>{var Ye;const ie=te?Z.get(Os(B)):void 0,{primary:ue,run:Ee}=ge(B,ie);return e.jsxs("li",{className:`${!O&&Q>0?"hidden sm:grid":"grid"} pipeline-next-up-row group grid-cols-[24px_minmax(0,1fr)] items-start gap-x-2 rounded-xl border border-border/60 bg-background/60 p-3 hover:bg-muted/35 lg:grid-cols-[28px_minmax(0,1fr)_auto] lg:items-center sm:p-4`,children:[e.jsx("span",{className:"pt-0.5 text-xs font-medium tabular-nums text-muted-foreground/60",children:String(Q+1).padStart(2,"0")}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[B.deal?e.jsx("button",{onClick:()=>A(B),className:"max-w-full break-words text-left text-sm font-semibold hover:text-foreground/80 focus-visible:outline-ring",children:B.title}):e.jsx("p",{className:"text-sm font-semibold",children:B.title}),e.jsx("span",{className:zi(B.overdue),children:B.label})]}),B.kind!=="funding"&&e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:B.reason}),((Ye=B.deal)==null?void 0:Ye.client_name)&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Contact: ",B.deal.client_name]}),$==null?void 0:$(B),B.deal&&["accepted","in_final_review"].includes(B.deal.status)&&e.jsx(Sp,{item:B,loading:g}),ie&&e.jsxs("p",{className:"mt-1 text-xs font-medium text-muted-foreground",children:["Returns"," ",new Date(ie).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]})]}),e.jsxs("div",{className:"col-start-2 mt-2 flex flex-wrap items-center gap-1 lg:col-start-auto lg:mt-0 lg:pl-4",children:[e.jsxs(R,{variant:"outline",disabled:ue==="Mark done"&&m||ue==="Restore now"&&d,onClick:Ee,className:"h-10 min-w-[100px] shrink-0 gap-2 rounded-lg bg-card px-3 text-xs font-medium shadow-none sm:h-9",children:[ue==="Call"?e.jsx(qt,{className:"h-3.5 w-3.5"}):ue==="Mark done"?e.jsx(At,{className:"h-3.5 w-3.5"}):e.jsx(La,{className:"h-3.5 w-3.5"}),ue]}),B.task&&ue!=="Mark done"&&!ie&&e.jsxs(R,{variant:"ghost",disabled:m,onClick:()=>H(B),className:"h-10 gap-1.5 px-2 text-xs text-muted-foreground sm:h-9",children:[e.jsx(At,{className:"h-3.5 w-3.5"}),"Mark done"]}),e.jsxs(Ua,{children:[e.jsx(za,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"icon",className:"h-10 w-10 sm:h-9 sm:w-9","aria-label":`Actions for ${B.title}`,children:e.jsx(Ya,{className:"h-4 w-4"})})}),e.jsxs(Ba,{align:"end",children:[B.deal&&e.jsxs(e.Fragment,{children:[Ms(B.deal.phone)&&e.jsx(pe,{onSelect:()=>I(B),children:"Call client"}),v&&B.deal.status!=="draft"&&e.jsx(pe,{onSelect:()=>v(B),children:"Write text or email"}),x&&e.jsx(pe,{onSelect:()=>x(B),children:"Log call outcome"}),e.jsx(Cs,{})]}),B.kind==="reminder"&&!ie&&S&&e.jsx(pe,{disabled:d,onSelect:()=>S(B),children:"Clear reminder"}),T&&!ie&&e.jsxs(pe,{disabled:d,onSelect:()=>T(B),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),"Remind me tomorrow"]}),B.deal&&e.jsxs(e.Fragment,{children:[e.jsx(pe,{onSelect:()=>A(B),children:"Open deal room"}),e.jsxs(pe,{onSelect:()=>q(B),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),"Set next step"]})]}),B.task&&e.jsxs(pe,{disabled:m,onSelect:()=>H(B),children:[e.jsx(Xi,{className:"mr-2 h-4 w-4"}),"Mark task complete"]}),B.deal&&e.jsxs(e.Fragment,{children:[e.jsx(Cs,{}),e.jsx(pe,{onSelect:()=>N(B),children:"Edit proposal"})]})]})]})]})]},B.id)})})},`${te?"snoozed":"active"}-${p??"all"}`),!_e&&ne.length>1&&e.jsxs("button",{onClick:()=>ae(!O),"aria-expanded":O,className:`${ne.length<=3?"sm:hidden":""} flex min-h-10 w-full items-center justify-center gap-1.5 border-t border-border/40 text-xs text-muted-foreground hover:bg-muted/40 hover:text-foreground`,children:[O?"Show less":`View all ${ne.length} priorities`,e.jsx(ms,{className:`h-3.5 w-3.5 ${O?"rotate-180":""}`})]}),!_e&&(f.length>0||te)&&e.jsxs("button",{onClick:()=>{V(!te),ae(!1)},className:"flex min-h-11 w-full items-center justify-center gap-2 border-t border-border/40 px-4 text-xs text-muted-foreground hover:bg-muted/40 hover:text-foreground",children:[e.jsx(vn,{className:"h-3.5 w-3.5"}),te?"Back to next up":`Snoozed (${G.length})`]})]})]})]})}function Po({open:t,onOpenChange:s,userId:a,preselectedProposal:n,prefilledTitle:r,nextStepMode:i=!1}){const{createTask:l,isCreating:o}=Eo(a),{data:c}=Bx(n==null?void 0:n.id),[m,f]=h.useState(""),[d,u]=h.useState(""),[g,D]=h.useState(us()),[E,v]=h.useState(""),[x,$]=h.useState("medium"),T=h.useRef(null);h.useEffect(()=>{if(!t){T.current=null;return}const p=(n==null?void 0:n.id)??"unlinked";if(T.current===p)return;T.current=p,f(n?`Follow up with ${n.business_name}`:r||""),u(""),D(us()),$("medium");const y=((c==null?void 0:c.confidence)!=="low"?c==null?void 0:c.optimalHour:null)??(n==null?void 0:n.optimal_contact_hour);v(y!=null?`${y.toString().padStart(2,"0")}:00`:"")},[n,t,c,r]);const S=()=>{m.trim()&&l({proposal_id:(n==null?void 0:n.id)||null,title:m.trim(),description:d.trim()||void 0,due_date:g,due_time:E||null,priority:x},{onSuccess:()=>{f(""),u(""),v(""),$("medium"),s(!1)}})};return e.jsx(ut,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"max-w-md",children:[e.jsxs(ht,{children:[e.jsx(xt,{children:i?"Set next step":"Create Task"}),e.jsx(kt,{children:"Choose an action and a date. It will appear with your follow-ups when due."})]}),e.jsxs("div",{className:"space-y-4",children:[n&&e.jsxs("div",{className:"text-xs text-muted-foreground bg-muted/50 rounded px-3 py-2",children:["Linked to: ",n.business_name]}),i&&e.jsx("div",{className:"flex flex-wrap gap-2","aria-label":"Next step shortcuts",children:["Call tomorrow","Check documents","Review proposal"].map(p=>e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"h-9 text-xs",onClick:()=>{f(`${p}${n?` · ${n.business_name}`:""}`);const _=new Date;p==="Call tomorrow"&&_.setDate(_.getDate()+1),D(us(_))},children:p},p))}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"task-title",className:"text-xs",children:"Title"}),e.jsx(he,{id:"task-title",value:m,onChange:p=>f(p.target.value),placeholder:"e.g., Follow up call",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"task-description",className:"text-xs",children:"Description (optional)"}),e.jsx(Rt,{id:"task-description",value:d,onChange:p=>u(p.target.value),placeholder:"Notes...",className:"mt-1",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(de,{htmlFor:"task-date",className:"text-xs",children:"Date"}),e.jsx(he,{id:"task-date",type:"date",value:g,onChange:p=>D(p.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(de,{htmlFor:"task-time",className:"text-xs",children:"Time"}),e.jsx(he,{id:"task-time",type:"time",value:E,onChange:p=>v(p.target.value),className:"mt-1"}),c&&c.confidence!=="low"&&c.optimalHour!=null?e.jsxs("p",{className:"text-[10px] text-primary mt-0.5 flex items-center gap-0.5",children:[e.jsx(hs,{className:"h-2.5 w-2.5"}
125),"Suggested: ",Yn(c.optimalHour)," (client most active)"]}):(n==null?void 0:n.optimal_contact_hour)!=null?e.jsxs("p",{className:"text-[10px] text-primary mt-0.5",children:["Optimal:"," ",n.optimal_contact_hour%12||12," ",n.optimal_contact_hour<12?"AM":"PM"]}):null]}),e.jsxs("div",{children:[e.jsx(de,{className:"text-xs",children:"Priority"}),e.jsxs(As,{value:x,onValueChange:p=>$(p),children:[e.jsx(Ps,{className:"mt-1",children:e.jsx(Rs,{})}),e.jsxs(Fs,{children:[e.jsx(Je,{value:"low",children:"Low"}),e.jsx(Je,{value:"medium",children:"Medium"}),e.jsx(Je,{value:"high",children:"High"})]})]})]})]}),e.jsx(R,{onClick:S,disabled:!m.trim()||o,className:"w-full",children:o?"Saving...":i?"Save next step":"Create Task"})]})]})})}const Rn=500,Dp=4,Bi=100,Tp=30;async function Wt(t,s,a,n,r,i){const l=[];try{for(let o=0;o<Dp;o++){let c=F.from(t).select(s);c=c.in(t==="proposals"?"id":"proposal_id",a),n&&(c=c.eq("user_id",n)),r&&i&&(c=c.gte(i,r)),r&&t==="agent_tasks"&&(c=c.or(`status.eq.pending,and(status.eq.completed,completed_at.gte.${r})`));const m=await c.order("id",{ascending:!0}).range(o*Rn,(o+1)*Rn-1);if(m.error||!m.data)return{rows:l,status:l.length?"partial":"unavailable"};if(l.push(...m.data),m.data.length<Rn)return{rows:l,status:"available"}}return{rows:l,status:"partial"}}catch{return{rows:l,status:l.length?"partial":"unavailable"}}}function Aa(t,s){const a=s.every(n=>n.status==="available")?"available":s.every(n=>n.status==="unavailable")?"unavailable":"partial";return{value:t,status:a}}const Xe=t=>typeof t=="string"?t:"",Fn=t=>Ms(Xe(t))??"",Ln=t=>{var s;return((s=yr(Xe(t)))==null?void 0:s.toLowerCase())??""},Pa=t=>typeof t=="string"&&Number.isFinite(Date.parse(t)),Hi=t=>t.sort((s,a)=>Date.parse(a.at)-Date.parse(s.at))[0]??null,Ep=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:null;async function $p(t,s){const a=[...new Set(s.filter(Boolean))],n={};if(!t||!a.length)return n;const r=new Date(Date.now()-Tp*864e5).toISOString();for(let i=0;i<a.length;i+=Bi){const l=a.slice(i,i+Bi),[o,c,m,f,d,u,g,D,E]=await Promise.all([Wt("proposals","id, email, phone",l),Wt("email_logs","id, proposal_id, sent_at, status, recipient_email",l,void 0,r,"sent_at"),Wt("automated_emails","id, proposal_id, sent_at, status, recipient_email",l,void 0,r,"sent_at"),Wt("sms_logs","id, proposal_id, created_at, status, delivery_status, recipient_phone, template_type",l,void 0,r,"created_at"),Wt("client_email_replies","id, proposal_id, received_at",l,void 0,r,"received_at"),Wt("agent_tasks","id, proposal_id, status, title, description, completed_at, due_date, due_time",l,t,r),Wt("client_responses","id, proposal_id, accepted_at, selected_option_id, adjusted_amount, original_amount, product_acceptances",l),Wt("loan_options","i
125d, proposal_id, approved_amount",l),Wt("line_of_credit_options","id, proposal_id, draw_amount",l)]);for(const v of l){const x=P=>P.rows.filter(z=>z.proposal_id===v),$=o.rows.find(P=>P.id===v),T=[],S=[];for(const[P,z]of[[c,"Email sent"],[m,"Automatic email sent"]])for(const M of x(P))M.status==="sent"&&Pa(M.sent_at)&&Ln($==null?void 0:$.email)&&Ln(M.recipient_email)===Ln($==null?void 0:$.email)&&T.push({at:M.sent_at,channel:"email",label:z});for(const P of x(f))!Pa(P.created_at)||P.status==="compliance"||(P.template_type==="inbound"?S.push({at:P.created_at,channel:"sms",label:"Text reply"}):P.status==="sent"&&!["failed","undelivered"].includes(Xe(P.delivery_status))&&Fn($==null?void 0:$.phone)&&Fn(P.recipient_phone)===Fn($==null?void 0:$.phone)&&T.push({at:P.created_at,channel:"sms",label:"Text sent"}));for(const P of x(d))Pa(P.received_at)&&S.push({at:P.received_at,channel:"email",label:"Email reply"});const p=x(u);for(const P of p)P.status==="completed"&&Xe(P.description).startsWith(`[QCF_CALL_OUTCOME] 126`)&&Xe(P.title).startsWith("Call outcome:")&&Pa(P.completed_at)&&T.push({at:P.completed_at,channel:"call",label:Xe(P.title)});const _=p.filter(P=>P.status==="pending"&&/^\d{4}-\d{2}-\d{2}$/.test(Xe(P.due_date))).sort((P,z)=>`${P.due_date} ${P.due_time||"99"}`.localeCompare(`${z.due_date} ${z.due_time||"99"}`)||Xe(P.id).localeCompare(Xe(z.id)))[0],y=[],q=x(g).sort((P,z)=>Xe(z.accepted_at).localeCompare(Xe(P.accepted_at)))[0],A=x(D),N=x(E),C=Kc({clientResponse:q,loanIds:A.map(P=>Xe(P.id)),locIds:N.map(P=>Xe(P.id))});let I=!1;for(const[P,z,M,k]of[["working_capital",C.wc,A,"approved_amount"],["line_of_credit",C.loc,N,"draw_amount"]]){if(!z)continue;const w=M.find(O=>O.id===z.optionId),L=Ep(z.adjustedAmount??(w==null?void 0:w[k]));if(!w||L===null){I=!0;continue}y.push({optionId:z.optionId,product:P,amount:L})}q!=null&&q.selected_option_id&&!C.wc&&!C.loc&&(I=!0);const H=Aa(y,[g,D,E]);I&&H.status==="available"&&(H.status="partial"),n[v]={lastContact:Aa(Hi(T),[o,c,m,f,u]),lastReply:Aa(Hi(S),[d,f]),nextTask:Aa(_?{id:Xe(_.id),title:Xe(_.title),dueDate:Xe(_.due_date),dueTime:Xe(_.due_time)||null}:null,[u]),acceptedOffers:H}}}return n}function Vi(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function Ap({context:t,loading:s,error:a,taskId:n}){var c;if(s&&!t)return e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Loading recent contextâ¦"});if(a||!t)return e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Recent context unavailable · open the deal to check."});const{lastContact:r,lastReply:i,nextTask:l,acceptedOffers:o}=t;return e.jsxs("div",{className:"mt-2 space-y-1 text-xs leading-relaxed text-muted-foreground",children:[(c=o.value)==null?void 0:c.map(m=>e.jsxs("p",{className:"font-medium text-foreground",children:["Accepted ",m.product==="line_of_credit"?"LOC draw":"working capital",": ",new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(m.amount),o.status!=="available"&&" · incomplete records"]},m.product)),e.jsxs("p",{title:"Recorded QCF calls and messages in the last 30 days. Messages may include automatic follow-ups; external phone activity may not be included.",children:[r.value?`${r.value.label} · ${Vi(r.value.at)}`:r.status==="available"?"No QCF contact recorded in the last 30 days":"Contact history unavailable",r.value&&r.status!=="available"&&" · history incomplete"]}),i.value&&e.jsxs("p",{className:"text-primary",children:[i.value.label," · ",Vi(i.value.at),i.status!=="available"&&" · history incomplete"]}),l.value&&l.value.id!==n&&e.jsxs("p",{children:["Next step: ",l.value.title," · ",ma(l.value.dueDate,{month:"short",day:"numeric"}),l.value.dueTime?` at ${l.value.dueTime.slice(0,5)}`:"",l.status!=="available"&&" · task list incomplete"]})]})}async function Pp(t){const s={};for(let a=0;a<t.length;a+=100){const n=t.slice(a,a+100),[r,i]=await Promise.all([vt((l,o)=>F.from("custom_documents").select("id,proposal_id,document_title").in("proposal_id",n).order("id").range(l,o),"Requested documents"),vt((l,o)=>F.from("uploaded_documents").select("id,proposal_id,custom_document_id,uploaded_at").in("proposal_id",n).order("id").range(l,o),"Received documents")]);for(const l of n)s[l]=ip(l,r.data,i.data)}return s}async function Rp(t){if(!t)throw new Error("Sign in to view reminders");return(await vt((a,n)=>F.from("pipeline_priority_snoozes").select("user_id,item_key,wake_signature,resume_at").eq("user_id",t).order("item_key").range(a,n),"Priority reminders")).data}async function Fp(t){if(!t.user_id)throw new Error("Sign in to save a reminder");const{data:s,error:a}=await F.from("pipeline_priority_snoozes").upsert({...t,updated_at:new Date().toISOString()},{onConflict:"user_id,item_key"}).select("item_key").single();if(a||!s)throw new Error("The reminder could not be saved. Please retry.")}async function Lp(t,s){if(!t)throw new Error("Sign in to update a reminder");const{error:a}=await F.from("pipeline_priority_snoozes").delete().eq("user_id",t).eq("item_key",s);if(a)throw new Error("The reminder could not be restored. Please retry.")}const Mp=h.lazy(()=>Ze(()=>import("./TodayOutreachDialog-BimlXG5m.js"),__vite__mapDeps([170,1,2,10,11,12,13,15,94,20,21,22,31,32,26,33,34,35,36,37,38,39,40,41,23,18,17,42,43,44,45,46,47,48,14,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,29,69,9,70,71,72,73,74,16,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,4,5,6,7,8,128,129,130,131,132,133,134,27,135,136,137,138,139,140,141,142,143,144,145,3,146,147,148,149,150,151,152,153,30,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169])).then(t=>({default:t.TodayOutreachDialog}
126))),qp=h.lazy(()=>Ze(()=>import("./TodayCallOutcomeDialog-K_4Qxd7s.js"),__vite__mapDeps([171,1,2,10,11,12,13,14,16,15,64,113,83,9,71,31,32,26,33,34,35,36,37,38,22,39,40,41,23,18,17,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,21,60,61,62,63,65,66,67,68,29,69,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,20,100,101,102,103,104,105,106,107,108,109,110,111,112,114,115,116,117,118,119,120,121,122,123,124,125,126,127,4,5,6,7,8,128,129,130,131,132,133,134,27,135,136,137,138,139,140,141,142,143,144,145,3,146,147,148,149,150,151,152,153,30,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169])).then(t=>({default:t.TodayCallOutcomeDialog}))),Op=h.lazy(()=>Ze(()=>import("./TodayDraftReviewDialog-Cf8GDtb8.js"),__vite__mapDeps([172,1,2,173,174,10,11,12,13,9,83,91,175])).then(t=>({default:t.TodayDraftReviewDialog})));function Wi({userId:t,performanceVisible:s=!0,firstName:a,onFocus:n,onOpenDeal:r,onInsights:i}){var Y,ne,fe,_e,ge,me;const l=Qt(),o=Nt(),[c,m]=h.useState(()=>new Date),[f,d]=h.useState(!1),[u,g]=h.useState(),[D,E]=h.useState(null),[v,x]=h.useState(),[$,T]=h.useState(),[S,p]=h.useState(),_=Eo(t),y=ve({queryKey:["pipeline-next-up",t],queryFn:()=>mp(t),enabled:!!t,staleTime:3e4,refetchInterval:6e4}),q=ve({queryKey:["pipeline-funding-summary",t],queryFn:()=>xp(t),enabled:!!t,staleTime:6e4,refetchInterval:5*6e4}),A=ve({queryKey:["pipeline-funding-summary-last-month",t],queryFn:()=>fp(t),enabled:!!t,staleTime:10*6e4,refetchInterval:30*6e4,retry:1}),N=Ke(b=>{var W;return(W=b.user)==null?void 0:W.email}),C=Zd(s),I=eu(),H=ve({queryKey:["pipeline-sf-drafts",t],queryFn:()=>yo(t),enabled:!!t,staleTime:3e4,refetchInterval:2*6e4}),P=h.useMemo(()=>{var W,oe,B;const b=(oe=(W=C.data)==null?void 0:W.snapshot)==null?void 0:oe.periods.month;if(!(!b||!I.data||!N))return np(b,N,tu(I.data),new Set((((B=C.data)==null?void 0:B.boardEmails)??[]).map(Q=>Q.trim().toLowerCase())))},[C.data,I.data,N]),z=h.useMemo(()=>{var B,Q;const b=(Q=(B=C.data)==null?void 0:B.snapshot)==null?void 0:Q.periods.month.reps,W=N==null?void 0:N.trim().toLowerCase();if(!b||!W||!P||!P.value.startsWith("#"))return;const oe=b.find(ie=>{var ue;return((ue=ie.email)==null?void 0:ue.trim().toLowerCase())===W});return oe?{submissions:oe.submissions,approvals:oe.approvals}:void 0},[C.data,N,P]),M=h.useMemo(()=>(y.data||[]).map(b=>b.id),[y.data]),k=ve({queryKey:["pipeline-checklists",t,M],queryFn:()=>Pp(M),enabled:!!t&&!!y.data,staleTime:3e4,refetchInterval:3*6e4}),w=ve({queryKey:["today-context",t,M],queryFn:()=>$p(t,M),enabled:!!t&&M.length>0,staleTime:2*6e4,refetchOnWindowFocus:!1,retry:1}),L=ve({queryKey:["pipeline-snoozes",t],queryFn:()=>Rp(t),enabled:!!t,staleTime:15e3,refetchInterval:3*6e4,retry:1}),O=Le({onMutate:({user:b})=>o.cancelQueries({queryKey:["pipeline-snoozes",b],exact:!0}),mutationFn:({user:b,key:W})=>Lp(b,W),onSuccess:(b,{user:W,key:oe})=>{o.setQueryData(["pipeline-snoozes",W],(B=[])=>B.filter(Q=>Q.item_key!==oe)),U.success("Reminder cleared · priorities updated")},onError:()=>U.error("Couldnât restore the priority. Please retry.")}),ae=Le({onMutate:b=>o.cancelQueries({queryKey:["pipeline-snoozes",b.user_id],exact:!0}),mutationFn:Fp,onSuccess:(b,W)=>{o.setQueryData(["pipeline-snoozes",W.user_id],(oe=[])=>[...oe.filter(B=>B.item_key!==W.item_key),W]),U.success("Reminder set for tomorrow at 8:00 AM",{description:"Your local time. New activity may bring it back sooner. Tasks and due dates are unchanged.",action:{label:"Undo",onClick:()=>O.mutate({user:W.user_id,key:W.item_key})}})},onError:()=>U.error("Couldnât save the reminder. The priority is still visible.")});h.useEffect(()=>{const b=setInterval(()=>m(new Date),6e4);return()=>clearInterval(b)},[]);const te=h.useMemo(()=>(y.data||[]).map(b=>{var W,oe,B,Q;return{...b,checklist:k.isError||(W=k.data)==null?void 0:W[b.id],last_reply_at:(Q=(B=(oe=w.data)==null?void 0:oe[b.id])==null?void 0:B.lastReply.value)==null?void 0:Q.at}}),[y.data,k.data,k.isError,w.data]),V=!!k.data&&!k.isError&&!L.isError&&!!L.data&&!y.isError&&!_.isError,{data:G,snoozed:Z}=h.useMemo(()=>kp(lp(te,_.tasks,c),V?L.data||[]:[],te,_.tasks,t||"",c),[te,_.tasks,c,V,L.data,t]),se=()=>{w.refetch(),_.refetch(),o.invalidateQueries({queryKey:["today-call-outcomes"]})};return e.jsxs(e.Fragment,{children:[e.jsx(Cp,{firstName:a,agentEmail:N,data:G,funded:(Y=q.data)==null?void 0:Y.total,performance:{rank:P,rankError:C.isError||I.isError||!!C.data&&!C.data.snapshot,rankStale:(ne=C.data)==null?void 0:ne.stale,rankU
126pdatedAt:(_e=(fe=C.data)==null?void 0:fe.snapshot)==null?void 0:_e.updatedAt,performanceVisible:s,draftCount:(ge=H.data)==null?void 0:ge.length,draftsError:H.isError,fundedCount:(me=q.data)==null?void 0:me.count,fundedLastMonth:A.data&&A.data.count>0?{total:A.data.total,count:A.data.count}:void 0,monthRow:z,onPerformance:()=>l("/dashboard?tab=performance"),onDrafts:()=>l("/dashboard?tab=drafts&scope=mine"),onFunded:()=>{q.data&&n("Your funded deals this month",q.data.ids)}},fundingError:q.isError,loading:y.isLoading||_.isLoading||k.isLoading||L.isLoading,error:y.isError||_.isError,refreshing:y.isFetching||q.isFetching||k.isFetching||L.isFetching,completing:_.isCompleting,snoozed:Z,snoozeDisabled:!V||ae.isPending||O.isPending,snoozeError:L.isError||k.isError,checklistLoading:k.isLoading,checklistError:k.isError,repliesUnavailable:!!M.length&&(w.isLoading||w.isError||!w.data||Object.values(w.data).some(b=>b.lastReply.status!=="available")),renderContext:b=>{var W,oe;return b.deal&&e.jsx(Ap,{context:(W=w.data)==null?void 0:W[b.deal.id],loading:w.isLoading,error:w.isError,taskId:(oe=b.task)==null?void 0:oe.id})},onOutreach:b=>x(structuredClone(b)),onLogCall:b=>T(structuredClone(b)),onSnooze:b=>{if(!t||!V)return;const W=new Date;ae.mutate({user_id:t,item_key:Os(b),wake_signature:Ao(b,_.tasks,W),resume_at:Np(W).toISOString()})},onRestore:b=>{t&&O.mutate({user:t,key:Os(b)})},now:c,activeBucket:D,onBucket:E,onNewProposal:()=>l("/create-choice"),onNextStep:b=>{g(b),d(!0)},onOpenDeal:b=>{b.deal&&r(b.deal.id,b.deal.business_name)},onReview:b=>{b.deal&&l(Lt(b.deal.type,b.deal.id))},onFinishDraft:b=>p(structuredClone(b)),onCall:b=>{var oe;const W=Ms((oe=b.deal)==null?void 0:oe.phone);W&&window.location.assign(`tel:${W}`),b.deal&&T(structuredClone(b))},onComplete:b=>{b.task&&_.completeTask(b.task.id)},onInsights:i,onRetry:()=>{y.refetch(),_.refetch(),q.refetch(),H.refetch(),s&&C.refetch(),I.refetch(),k.refetch(),L.refetch(),M.length&&w.refetch()}}),v&&e.jsx(h.Suspense,{fallback:e.jsx("p",{role:"status",children:"Opening messageâ¦"}),children:e.jsx(Mp,{item:v,agentEmail:N,onClose:()=>x(void 0),onSent:({markTaskDone:b})=>{se(),b&&v.task&&_.completeTask(v.task.id)}})}),(S==null?void 0:S.deal)&&e.jsx(h.Suspense,{fallback:e.jsx("p",{role:"status",children:"Checking draftâ¦"}),children:e.jsx(Op,{deal:S.deal,onClose:()=>p(void 0),onEdit:()=>{l(Lt(S.deal.type,S.deal.id)),p(void 0)}})}),($==null?void 0:$.deal)&&t&&e.jsx(h.Suspense,{fallback:e.jsx("p",{role:"status",children:"Opening call outcomeâ¦"}),children:e.jsx(qp,{deal:$.deal,userId:t,onClose:()=>T(void 0),onSaved:se,onReview:()=>{l(Lt($.deal.type,$.deal.id)),T(void 0)},onFollowUp:()=>{x($),T(void 0)},onOpenDeal:()=>{r($.deal.id,$.deal.business_name),T(void 0)}})}),f&&e.jsx(Po,{open:!0,onOpenChange:d,userId:t,preselectedProposal:u!=null&&u.deal?{id:u.deal.id,business_name:u.deal.business_name}:null,nextStepMode:!0})]})}function Ip({userId:t,onCreateTask:s,onApplyFocus:a}){const{data:n,isLoading:r,isError:i,refetch:l,isRefetching:o}=ve({queryKey:["ai-agent-focus",t],queryFn:async()=>{ru("ai_focus");const{data:c,error:m}=await F.functions.invoke("ai-agent-focus");if(m)throw m;return c},enabled:!!t,staleTime:9e5,refetchOnWindowFocus:!1});return e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-primary/5 via-card to-card h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"text-xs font-semibold text-foreground",children:"AI Focus"})]}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>l(),disabled:o||r,children:e.jsx(Ct,{className:`h-3 w-3 ${o?"animate-spin":""}`})})]}),e.jsx("div",{className:"px-3 py-2 space-y-2",children:r?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(je,{className:"h-3 w-full"}),e.jsx(je,{className:"h-3 w-5/6"}),e.jsx(je,{className:"h-3 w-4/6"})]}):i||!(n!=null&&n.briefing)?e.jsxs("div",{className:"flex items-start gap-2 text-[11px] text-muted-foreground py-1",children:[e.jsx(ds,{className:"h-3.5 w-3.5 flex-shrink-0 mt-0.5"}),e.jsx("span",{children:"Briefing unavailable. Tap refresh to retry."})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs font-semibold text-foreground leading-snug",children:n.briefing.headline}),n.briefing.focus_areas.length>0&&e.jsx("ul",{className:"space-y-1",children:n.briefing.focus_areas.map((c,m)=>e.jsx("li",{children:e.jsxs("button",{onClick:()=>a(c.filter_label,c.proposal_ids),className:"w-full text-left flex items-start gap-1.5 px-1.5 py-1 rounded-md hover:bg-primary/10 transition-colors group",title:`Filter dashboard to ${c.count} deal${c.count===1?"":"s"}`,children:[e.jsx(bl,{className:"h-3 w-3 text-primary flex-shrink-0 mt-0.5 opacity-60 group-hover:opacity-100"}
126),e.jsx("span",{className:"text-[11px] text-foreground/90 leading-snug flex-1",children:c.label}),e.jsx(J,{variant:"secondary",className:"text-[9px] px-1 py-0 h-4 flex-shrink-0",children:c.count})]})},m))}),n.briefing.insight&&e.jsx("p",{className:"text-[10px] italic text-muted-foreground/80 border-l-2 border-primary/30 pl-2 leading-snug",children:n.briefing.insight}),n.briefing.suggested_tasks.length>0&&e.jsxs("div",{className:"pt-1 border-t border-border/40",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground mb-1",children:"Suggested tasks:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:n.briefing.suggested_tasks.map((c,m)=>e.jsxs("button",{onClick:()=>s(c),className:"inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-md bg-primary/10 hover:bg-primary/20 text-primary transition-colors",children:[e.jsx(aa,{className:"h-2.5 w-2.5"}),c]},m))})]})]})})]})}const Up={proposal:"Initial Email",day1:"Day 1",day2:"Day 2",day3:"Day 3",funded:"Funded"},zp={proposal:{kind:"proposal_initial"},day1:{kind:"sequence",day:1},day2:{kind:"sequence",day:2},day3:{kind:"sequence",day:3},funded:{kind:"funded_congrats"}};function Bp(t){return ve({queryKey:["email-preview","proposal",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:a}=await F.from("proposals").select("id, client_name, business_name, email, agent_email, business_slug, unique_link, status, funded_amount").eq("id",t).single();if(a)throw a;return s}})}function Hp(t,s,a){return ve({queryKey:["email-preview","render",(t==null?void 0:t.id)??"",s],enabled:a&&!!t,staleTime:5*60*1e3,retry:!1,queryFn:()=>gl(t,zp[s])})}function Vp({open:t,onOpenChange:s,proposalId:a}){const[n,r]=h.useState("proposal"),{data:i,isLoading:l}=Bp(t?a:null),{data:o,isLoading:c,error:m}=Hp(i,n,t),f=h.useMemo(()=>{if(!i)return["proposal"];const u=["proposal","day1","day2","day3"];return i.status==="funded"&&u.push("funded"),u},[i]),d=o&&!Un(o)?o:null;return e.jsx(as,{open:t,onOpenChange:s,children:e.jsxs(xs,{side:"right",className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsxs(ps,{className:"px-4 pt-4 pb-2",children:[e.jsxs(fs,{className:"flex items-center gap-2 text-base",children:[e.jsx(Be,{className:"h-4 w-4"}),"Email Preview",i&&e.jsxs("span",{className:"text-sm font-normal text-muted-foreground ml-1 truncate",children:["â ",i.business_name]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Rendered by the same function that sends it. Nothing is sent, and this does not count as a client open."})]}),e.jsx("div",{className:"flex gap-1 px-4 pb-2 border-b overflow-x-auto",children:f.map(u=>e.jsx(R,{variant:n===u?"default":"ghost",size:"sm",className:"text-xs h-7 px-3 flex-shrink-0",onClick:()=>r(u),children:Up[u]},u))}),l||c?e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsx(je,{className:"h-6 w-3/4"}),e.jsx(je,{className:"h-[400px] w-full rounded-lg"})]}):m?e.jsx("div",{className:"p-4",children:e.jsx(ii,{variant:"destructive",children:e.jsx(li,{className:"text-sm",children:m instanceof Error?m.message:"This email could not be rendered."})})}):o&&Un(o)?e.jsx("div",{className:"p-4",children:e.jsxs(ii,{children:[e.jsx(iu,{className:"h-4 w-4"}),e.jsxs(li,{className:"text-sm",children:["This email would not go out for this deal: ",o.skippedReason]})]})}):d?e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2 border-b bg-muted/30",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider font-medium mb-0.5",children:"Subject"}),e.jsx("p",{className:"text-sm font-medium truncate",children:d.subject})]}),e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs flex-shrink-0",onClick:()=>void Ma(d.html,"HTML copied to clipboard"),children:[e.jsx(_t,{className:"h-3 w-3 mr-1"}),"Copy HTML"]})]})}),e.jsx("div",{className:"flex-1 p-2",children:e.jsx("iframe",{srcDoc:d.html,title:"Email Preview",className:"w-full h-full border rounded-lg bg-white",sandbox:"",style:{minHeight:500}})})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-sm text-muted-foreground",children:"No preview available"})]})})}const Wp=[{id:"docs_received",title:"Docs Received",color:"bg-teal-500",bgColor:"bg-teal-50"},{id:"pending",title:"Pending",color:"bg-gray-500",bgColor:"bg-gray-50"},{id:"accepted",title:"Accepted",color:"bg-blue-500",bgColor:"bg-blue-50"}
126,{id:"in_final_review",title:"In Review",color:"bg-amber-500",bgColor:"bg-amber-50"},{id:"funded",title:"Funded",color:"bg-green-500",bgColor:"bg-green-50"},{id:"funding_lost",title:"Funding Lost",color:"bg-orange-500",bgColor:"bg-orange-50"},{id:"rejected",title:"Rejected",color:"bg-red-500",bgColor:"bg-red-50"}];function Kp(t,s){const a=Nt(),n=Me.proposals.kanban(t),{data:r=[],isLoading:i,error:l,refetch:o}=ve({queryKey:n,queryFn:()=>lm(t),staleTime:60*1e3,enabled:(s==null?void 0:s.enabled)??!0}),c=h.useMemo(()=>Wp.map(d=>{const u=r.filter(g=>g.status===d.id);return{...d,proposals:u,count:u.length}}),[r]),m=Le({mutationFn:({proposalId:d,status:u})=>im(d,u),onMutate:async({proposalId:d,status:u})=>{await a.cancelQueries({queryKey:n});const g=a.getQueryData(n);return a.setQueryData(n,(D=[])=>D.map(E=>E.id===d?{...E,status:u}:E)),{previousProposals:g}},onError:(d,u,g)=>{g!=null&&g.previousProposals&&a.setQueryData(n,g.previousProposals),U.error("Failed to update proposal status")},onSettled:()=>{a.invalidateQueries({queryKey:Me.proposals.all})}}),f=h.useCallback((d,u)=>{m.mutate({proposalId:d,status:u})},[m]);return{columns:c,isLoading:i,loadError:l,refresh:o,moveProposal:f}}function Yp({proposal:t,open:s,onOpenChange:a}){var g,D,E,v;const{data:n}=ve({queryKey:["proposal-ai-details",t==null?void 0:t.id],queryFn:async()=>{if(!(t!=null&&t.id))return null;const{data:x,error:$}=await F.from("proposals").select("ai_analysis, financial_consultation, intended_use_of_funds, company_website, hide_business_profile, auto_followups_enabled").eq("id",t.id).single();if($)throw $;return x},enabled:s&&!!(t!=null&&t.id)});if(!t)return null;const r=n==null?void 0:n.ai_analysis,i=n==null?void 0:n.financial_consultation,l=!!i,o=!!(i!=null&&i.emailContext),c=[{label:"Business Analysis",collected:!!r,detail:r?String(r.industry||"Complete"):null},{label:"Financial Consultation",collected:l,detail:l?"Generated":null},{label:"Email Personalization",collected:o,detail:o?"4 snippets ready":null},{label:"Use of Funds",collected:!!(n!=null&&n.intended_use_of_funds),detail:(n==null?void 0:n.intended_use_of_funds)||null},{label:"Company Website",collected:!!(n!=null&&n.company_website),detail:(n==null?void 0:n.company_website)||null}],m=c.filter(x=>x.collected).length,f=[{icon:bt,label:"Client Teaser Card",active:l&&!!(n!=null&&n.hide_business_profile)},{icon:Be,label:"Day 1 â Strength & Industry",active:o},{icon:Be,label:"Day 2 â Funds Hook & Urgency",active:o},{icon:dr,label:"Day 3 â Success Story & Comparison",active:o},{icon:lu,label:"Cash Flow Impact Chart",active:l}],d=o?[{label:"Strength Highlight",value:(g=i==null?void 0:i.emailContext)==null?void 0:g.strengthHighlight},{label:"Use of Funds Hook",value:(D=i==null?void 0:i.emailContext)==null?void 0:D.useOfFundsHook},{label:"Industry Success Story",value:(E=i==null?void 0:i.emailContext)==null?void 0:E.industrySuccessStory},{label:"Urgency Factor",value:(v=i==null?void 0:i.emailContext)==null?void 0:v.urgencyFactor}].filter(x=>x.value):[],u=i==null?void 0:i.recommendation;return i==null||i.industryContext,i==null||i.businessProfile,e.jsx(as,{open:s,onOpenChange:a,children:e.jsxs(xs,{className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(ps,{children:[e.jsxs(fs,{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"w-5 h-5 text-primary"}),"AI Intelligence â ",t.business_name]}),e.jsx(tn,{children:"Full breakdown of AI data collected and where it's being used."})]}),e.jsxs("div",{className:"space-y-5 mt-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(J,{variant:m>=4?"default":"secondary",children:[m,"/",c.length," collected"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m>=4?"Strong personalization":m>=2?"Basic personalization":"No AI data yet"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Data Collected"}),c.map(x=>e.jsxs("div",{className:`flex items-center gap-2.5 p-2.5 rounded-md border text-sm ${x.collected?"bg-emerald-500/10 border-emerald-500/20":"bg-muted/30 border-border/50"}`,children:[x.collected?e.jsx(St,{className:"w-4 h-4 text-emerald-500 flex-shrink-0"}
126):e.jsx(Nl,{className:"w-4 h-4 text-muted-foreground/40 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:x.collected?"font-medium":"text-muted-foreground",children:x.label}),x.detail&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:x.detail})]})]},x.label))]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Where It Goes"}),f.map(x=>{const $=x.icon;return e.jsxs("div",{className:`flex items-center gap-2.5 p-2 rounded-md border text-sm ${x.active?"bg-primary/5 border-primary/20":"bg-muted/20 border-border/30"}`,children:[e.jsx($,{className:`w-4 h-4 flex-shrink-0 ${x.active?"text-primary":"text-muted-foreground/40"}`}),e.jsx("span",{className:x.active?"font-medium":"text-muted-foreground",children:x.label}),x.active&&e.jsx(J,{variant:"outline",className:"ml-auto h-5 text-[10px] bg-primary/10 text-primary border-primary/20",children:"Active"})]},x.label)})]}),u&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"AI Recommendation"}),e.jsxs("div",{className:"p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[e.jsx(ou,{className:"w-4 h-4 text-primary flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium",children:["Recommended: ",e.jsx("span",{className:"text-primary",children:u.recommendedOption})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:u.reasoning})]})]}),u.industryTactic&&e.jsxs("div",{className:"flex items-start gap-2 pt-2 border-t border-primary/10",children:[e.jsx(fl,{className:"w-4 h-4 text-amber-500 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u.industryTactic})]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Email Content Being Used"}),d.map(x=>e.jsxs("div",{className:"p-2.5 bg-muted/30 rounded-md border border-border/50",children:[e.jsx("p",{className:"text-[10px] font-medium text-primary mb-0.5",children:x.label}),e.jsxs("p",{className:"text-sm text-muted-foreground leading-relaxed",children:['"',x.value,'"']})]},x.label))]}),m===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(sa,{className:"w-10 h-10 mx-auto mb-3 opacity-20"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No AI Data"}),e.jsx("p",{className:"text-xs",children:"Edit this proposal and run AI Analysis to generate insights."})]})]})]})})}const Ki=new Set(["76.97.150.76","107.213.39.9","107.213.39.90"]);function Qp(t){const s=h.useRef(new Map),a=h.useRef(new Set(Ki));h.useEffect(()=>{if(!t)return;(async()=>{const[o,c]=await Promise.all([F.from("proposals").select("id, client_name, business_name, phone").eq("user_id",t).eq("is_archived",!1),F.from("allowed_ips").select("ip_address").eq("is_active",!0)]);if(o.data){const f=new Map;o.data.forEach(d=>f.set(d.id,{client_name:d.client_name,business_name:d.business_name,phone:d.phone})),s.current=f}const m=new Set(Ki);c.data&&c.data.forEach(f=>m.add(f.ip_address)),a.current=m})();const r=new Set,i=()=>{try{const o=new AudioContext,c=o.createOscillator(),m=o.createGain();c.connect(m),m.connect(o.destination),c.frequency.value=880,c.type="sine",m.gain.value=.15,m.gain.exponentialRampToValueAtTime(.001,o.currentTime+.3),c.start(o.currentTime),c.stop(o.currentTime+.3)}catch{}},l=F.channel("live-client-views").on("postgres_changes",{event:"*",schema:"public",table:"proposal_view_logs"},o=>{const c=o.new;if(c.viewer_class==="internal"||c.viewer_ip&&a.current.has(c.viewer_ip))return;const m=s.current.get(c.proposal_id);if(!m)return;const f=ca(c);if(o.eventType!=="DELETE"&&!(o.eventType==="UPDATE"&&(!c.engagement_detected_at||o.old.engagement_detected_at))&&f.kind!=="scanner"){if(f.status!=="Engaged visitor"){U(`Proposal link opened · ${m.business_name}`,{description:"Unconfirmed visit â no offer interaction recorded yet. This may be the client or someone with their link.",duration:6e3});return}r.has(c.id)||Date.now()-Date.parse(c.engagement_detected_at||"")>3e4||(r.add(c.id),r.size>1e3&&r.delete(r.values().next().value),i(),U.info(`Offer interaction · ${m.business_name}`,{description:`Someone using this proposal link interacted with an offer.${f.badge?" "+f.badge+" â location unreliable.":""}`,duration:12e3,action:{label:"Call client",onClick:()=>window.open(`tel:${m.phone}`,"_self")}}))}}).subscribe();return()=>{F.removeChannel(l)}},[t])}function Gp(t){return ve({queryKey:["stuck-proposals",t],enabled:!!t,staleTime:6e4,queryFn:async()=>{const{data:s,error:a}=await F.rpc("get_stuck_proposals",{_owner:t});if(a)throw a;return s||[]}})}function Xp({latest_email_status:t,latest_email_error:s,phone:a}){const n=(t||"").toLowerCase(),r=(s||"").toLowerCase();return n==="bounced"||r.includes("bounce")||r.includes("invalid")||r.includes("not exist")?{kind:"alt-email",reason:"Delivery bounced â the email address is likely wrong."}:n==="complained"||n==="suppressed"||r.includes("spam")?{kind:"call-only",reason:"Recipient marked previous email as spam â don't resend, call directly."}:a&&a.replace(/\D/g,"").length>=10?{kind:"sms",reason:"Email delivered but no opens after 24h â SMS reaches 3à more."}:{kind:"resend-new-subject",reason:"Email delivered but no opens â try a fresh subject line."}}function Jp(t){switch(t){case"sms":return"Send SMS";case"alt-email":return"Fix email address";case"resend-new-subject":return"Resend with new subject";case"call-only":return"Call client";case"wait":return"Wait"}}function Zp({kind:t}){switch(t){case"sms":return e.jsx(ts,{className:"h-3.5 w-3.5"});case"alt-email":return e.jsx(Be,{className:"h-3.5 w-3.5"});case"call-only":return e.jsx(qt,{className:"h-3.5 w-3.5"});case"resend-new-subject":return e.jsx(ss,{className:"h-3.5 w-3.5"});default:return e.jsx(Lu,{className:"h-3.5 w-3.5"})}}function ef({ownerId:t}){const s=Qt(),{data:a,isLoading:n}=Gp(t),[r,i]=h.useState(null);if(n||!a||a.length===0)return null;const l=async(o,c)=>{i(o.proposal_id);try{if(c.kind==="alt-email"){s(Lt("proposal",o.proposal_id));return}if(c.kind==="call-only"){o.phone?(await navigator.clipboard.writeText(o.phone),U.success(`Copied ${o.phone}`)):U.info("No phone on file â open the deal to add one.");return}if(c.kind==="sms"&&o.phone){const m=await Ts({proposalId:o.proposal_id,to:o.phone,message:`Hi ${o.client_name.split(" ")[0]}, ${Ls(o.agent_email||"")||"your Funding Specialist"} with Quick Capital Funding here. Want me to walk you through the funding options I sent? ${uu}`,templateType:"stuck_deal_followup"});if(!m.ok){U.error(m.message);return}U.success(ea(m));return}if(c.kind==="resend-new-subject"){const{error:m}=await F.functions.invoke("send-proposal-email",{body:{proposalId:o.proposal_id,isResend:!0,useAiSubject:!0}});if(m)throw m;U.success("Resent with a fresh subject line")}}catch(m){U.error(m instanceof Error?m.message:"Action failed")}finally{i(null)}};return e.jsxs(nt,{className:"p-4 border-amber-200 bg-amber-50/40 dark:bg-amber-950/10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(es,{className:"h-4 w-4 text-amber-600"}),e.jsxs("h3",{className:"text-sm font-semibold",children:["Needs attention · ",a.length," stuck ",a.length===1?"deal":"deals"]}
126),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"Sent 24h+ ago, no opens yet"})]}),e.jsx("ul",{className:"divide-y",children:a.slice(0,8).map(o=>{const c=Xp({latest_email_status:o.latest_email_status,latest_email_error:o.latest_email_error,latest_email_sent_at:o.latest_email_sent_at,phone:o.phone});return e.jsxs("li",{className:"flex items-center gap-3 py-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.business_name}),o.latest_email_status&&e.jsx(J,{variant:"outline",className:"text-[10px] h-4 px-1",children:o.latest_email_status})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:c.reason})]}),e.jsxs(R,{size:"sm",variant:"outline",disabled:r===o.proposal_id,onClick:()=>l(o,c),className:"shrink-0 gap-1",children:[e.jsx(Zp,{kind:c.kind}),r===o.proposal_id?"â¦":Jp(c.kind)]})]},o.proposal_id)})})]})}const Ra={long_term:"Leans long-term",working_capital:"Leans working capital",blend:"Blend / sequence"};function tf({userId:t,isAdmin:s}){const a=Qt(),n=Ke(k=>{var w;return(w=k.user)==null?void 0:w.email}),[r,i]=h.useState([]),[l,o]=h.useState([]),[c,m]=h.useState(!1),[f,d]=h.useState(null),[u,g]=h.useState(!1),[D,E]=h.useState(null),[v,x]=h.useState(null);h.useEffect(()=>{if(!t)return;let k=!1;const w=async()=>{let O=F.from("proposals").select("id, client_name, business_name, email, phone, business_slug, unique_link, created_at").eq("fit_only",!0).eq("is_archived",!1).order("created_at",{ascending:!1}).limit(100);s||(O=n?O.or(`user_id.eq.${t},agent_email.ilike.${n}`):O.eq("user_id",t));const[ae,te]=await Promise.all([F.from("financing_fit_leads").select("id, email, client_name, phone, recommendation, matched_proposal_id, created_at, dismissed_at").order("created_at",{ascending:!1}).limit(200),O]);k||(!ae.error&&ae.data&&i(ae.data),!te.error&&te.data&&o(te.data))};w();const L=vu(w,6e4);return()=>{k=!0,L()}},[t,s,n]);const $=r.filter(k=>!k.dismissed_at),T=r.filter(k=>!!k.dismissed_at),S=new Map;for(const k of $)k.matched_proposal_id&&!S.has(k.matched_proposal_id)&&S.set(k.matched_proposal_id,k);const p=new Set(l.map(k=>k.id)),_=[...S.values()].filter(k=>!p.has(k.matched_proposal_id)),y=$.filter(k=>!k.matched_proposal_id);if(l.length===0&&_.length===0&&y.length===0&&T.length===0)return null;const q=k=>`${Pt()}/fit/${k.business_slug||k.unique_link}`,A=async k=>{try{await navigator.clipboard.writeText(q(k)),U.success("Link copied.")}catch{U.error("Couldn't copy the link.")}},N=async k=>{if(k.phone){d(k.id);try{const w=await Ts({to:k.phone,message:wl({firstName:(k.client_name||"").split(" ")[0],businessName:k.business_name,link:q(k),agentName:n?Ls(n):""}),proposalId:k.id,templateType:"financing_fit_link"});if(!w.ok){U.error(w.message);return}U.success(ea(w))}catch(w){console.error("[fit-panel] text failed:",w),U.error("Couldn't send the text.")}finally{d(null)}}},C=l.filter(k=>!S.has(k.id)).length,I=l.length-C,H=async k=>{if(!s||!t)return;E(k.id);const w=new Date().toISOString(),{error:L}=await F.from("financing_fit_leads").update({dismissed_at:w,dismissed_by:t}).eq("id",k.id);if(E(null),L)return void U.error("Couldn't dismiss this result.");i(O=>O.map(ae=>ae.id===k.id?{...ae,dismissed_at:w}:ae)),U.success("Result dismissed.")},P=async k=>{if(!s)return;E(k.id);const{error:w}=await F.from("financing_fit_leads").update({dismissed_at:null,dismissed_by:null}).eq("id",k.id);if(E(null),w)return void U.error("Couldn't restore this result.");i(L=>L.map(O=>O.id===k.id?{...O,dismissed_at:null}:O)),U.success("Result restored.")},z=async()=>{if(!s||!v)return;const k=v;E(k.id);const{error:w}=await F.from("financing_fit_leads").delete().eq("id",k.id);if(E(null),w)return void U.error("Couldn't delete this result.");i(L=>L.filter(O=>O.id!==k.id)),x(null),U.success("Result permanently deleted.")},M=(k,w=!1)=>s?e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(R,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>void(w?P(k):H(k)),disabled:D===k.id,"aria-label":`${w?"Restore":"Dismiss"} ${k.client_name||k.email}`,title:w?"Restore":"Dismiss",children:w?e.jsx(ju,{className:"h-3.5 w-3.5"}):e.jsx(_u,{className:"h-3.5 w-3.5"})}),e.jsx(R,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>x(k),disabled:D===k.id,"aria-label":`Delete ${k.client_name||k.email}`,title:"Delete permanently",children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]}):null;return e.jsxs("div",{className:"rounded-md border border-primary/30 bg-primary/5",children:[e.jsxs("button",{type:"button",onClick:()=>m(k=>
126!k),className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left hover:bg-primary/10 transition-colors","aria-expanded":c,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4 shrink-0 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Financing Fit"}),l.length>0&&e.jsxs(J,{variant:"default",children:[I," done",C>0?` · ${C} waiting`:""]}),_.length>0&&e.jsxs(J,{variant:"outline",children:[_.length," on deals"]}),y.length>0&&e.jsxs(J,{variant:"secondary",children:[y.length," request",y.length===1?"":"s"]}),s&&T.length>0&&e.jsxs(J,{variant:"outline",children:[T.length," dismissed"]}),e.jsx("span",{className:"hidden truncate text-xs text-muted-foreground sm:inline",children:"Survey links you've sent, results on your deals, and plan-review requests"})]}),c?e.jsx(rr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ms,{className:"h-4 w-4 text-muted-foreground"})]}),c&&e.jsxs("div",{className:"border-t",children:[l.length>0&&e.jsx("ul",{className:"divide-y",children:l.map(k=>{const w=S.get(k.id);return e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"truncate font-medium",children:[k.client_name||k.email," ",e.jsxs("span",{className:"text-muted-foreground",children:["· ",k.business_name]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:w?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-foreground",children:Ra[w.recommendation]})," · finished"," ",Ss(w.created_at)]}):e.jsxs(e.Fragment,{children:["Waiting on the client · sent ",Ss(k.created_at)]})})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(R,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>void A(k),"aria-label":`Copy ${k.business_name} link`,children:e.jsx(_t,{className:"h-3.5 w-3.5"})}),k.phone&&e.jsx(R,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>void N(k),disabled:f===k.id,"aria-label":`Text ${k.business_name} link`,children:e.jsx(ts,{className:"h-3.5 w-3.5"})}),e.jsx(R,{variant:"ghost",size:"icon",className:"h-7 w-7",asChild:!0,children:e.jsx("a",{href:q(k),target:"_blank",rel:"noreferrer","aria-label":`Open ${k.business_name} link`,children:e.jsx(It,{className:"h-3.5 w-3.5"})})}),e.jsxs(R,{variant:"outline",size:"sm",className:"h-7 gap-1 text-xs",onClick:()=>a(`/dashboard/edit/${k.id}`),title:"Add loan options â becomes a normal proposal on the same link",children:[e.jsx(hd,{className:"h-3.5 w-3.5"})," Add options"]})]})]},k.id)})}),_.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"border-t bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground",children:"Survey results on your other deals"}),e.jsx("ul",{className:"divide-y border-t",children:_.map(k=>e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:k.client_name||k.email}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:Ra[k.recommendation]})," · finished ",Ss(k.created_at)]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsxs(R,{variant:"outline",size:"sm",className:"h-7 gap-1 text-xs",onClick:()=>a(`/dashboard/edit/${k.matched_proposal_id}`),children:[e.jsx(Ft,{className:"h-3.5 w-3.5"})," Open deal"]}),M(k)]})]},k.id))})]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"border-t bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground",children:"Specialist requests from /financing-fit"}),e.jsx("ul",{className:"divide-y border-t",children:y.map(k=>e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:k.client_name||k.email}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[Ra[k.recommendation]," · ",Ss(k.created_at)," · new"]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(R,{variant:"ghost",size:"icon",className:"h-7 w-7",asChild:!0,children:e.jsx("a",{href:`mailto:${k.email}`,"aria-label":`Email ${k.email}`,children:e.jsx(Be,{className:"h-3.5 w-3.5"})})}),k.phone&&e.jsx(R,{variant:"ghost",size:"icon",className:"h-7 w-7",asChild:!0,children:e.jsx("a",{href:`tel:${k.phone}`,"aria-label":`Call ${k.client_name||k.email}`,children:e.jsx(qt,{className:"h-3.5 w-3.5"})})}),M(k)]})]},k.id))})]}),s&&T.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border-t bg-muted/30 px-3 py-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Dismissed results"}),e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>g(k=>!k),children:[u?"Hide":"Show"," ",T.length]})]}),u&&e.jsx("ul",{className:"divide-y border-t",children:T.map(k=>e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:k.client_name||k.email}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[Ra[k.recommendation]," · dismissed ",Ss(k.dismissed_at)]})]}),M(k,!0)]},k.id))})]})]}),e.jsx(hu,{open:!!v,onOpenChange:k=>{!k&&!D&&x(null)},children:e.jsxs(xu,{children:[e.jsxs(pu,{children:[e.jsx(fu,{children:"Delete this survey result permanently?"}),e.jsxs(gu,{children:["This removes the completed Financing Fit result for ",(v==null?void 0:v.client_name)||(v==null?void 0:v.email),". It cannot be restored."]})]}),e.jsxs(bu,{children:[e.jsx(yu,{disabled:!!D,children:"Cancel"}),e.jsx(wu,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:k=>{k.preventDefault(),z()},disabled:!!D,children:"Delete permanently"})]})]})})]})}const sf=h.lazy(()=>Ze(()=>import("./KanbanBoard-BhlBQRYy.js"),__vite__mapDeps([176,1,2,152,42,17,72,73,74,177,178,114,12,76,47,115,64,179,146,147,99,85,84,86,87,88,93,92,70,105,106,22,107,121,180,112,111,117,31,32,26,33,34,35,36,37,38,39,40,41,23,18,43,44,45,46,48,14,49,50,51,52,53,54,55,56,57,58,59,21,60,61,62,63,10,11,13,15,65,66,67,68,29,69,9,71,16,75,77,78,79,80,81,82,83,89,90,91,94,95,96,97,98,20,100,
126101,102,103,104,108,109,110,113,116,118,119,120,122,123,124,125,126,127,4,5,6,7,8,128,129,130,131,132,133,134,27,135,136,137,138,139,140,141,142,143,144,145,3,148,149,150,151,153,30,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169])).then(t=>({default:t.KanbanBoard}))),af=h.lazy(()=>Ze(()=>import("./WarRoomTab-BW7KmJVN.js"),__vite__mapDeps([181,1,2,26,17,14,63,62,16,182,183,184,148,83,185])).then(t=>({default:t.WarRoomTab}))),nf=h.lazy(()=>Ze(()=>import("./ContactCardInsightsDashboard-2n7jvzuf.js"),__vite__mapDeps([186,1,2,26,27,17,75,76,73,187,28,30,29,188,22,31,32,33,34,35,36,37,38,39,40,41,23,18,42,43,44,45,46,47,48,14,49,50,51,52,53,54,55,56,57,58,59,21,60,12,61,62,63,64,10,11,13,15,65,66,67,68,69,9,70,71,72,74,16,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,20,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,4,5,6,7,8,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,3,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169])).then(t=>({default:t.ContactCardInsightsDashboard}))),rf=h.lazy(()=>Ze(()=>import("./DocumentUploaderTab-Br1xp8G2.js"),__vite__mapDeps([189,1,2,190,167,11,12,100,163,52,53,14,15,118,123,74,73,62,102,101,191,69,33,36,22,119,117,127,70,30,9,83,13,23])).then(t=>({default:t.DocumentUploaderTab}))),lf=h.lazy(()=>Ze(()=>import("./DealBlitzPanel-BB62rrfn.js"),__vite__mapDeps([192,1,2,14,16,10,11,12,13,66,67,26,126,21,22,70,31,32,33,34,35,36,37,38,39,40,41,23,18,17,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,15,65,68,29,69,9,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,20,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,127,4,5,6,7,8,128,129,130,131,132,133,134,27,135,136,137,138,139,140,141,142,143,144,145,3,146,147,148,149,150,151,152,153,30,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169])).then(t=>({default:t.DealBlitzPanel}))),of=h.lazy(()=>Ze(()=>import("./MailMergePanel-NOVW8tK5.js"),__vite__mapDeps([193,1,2,17,19,20,77,49,92,21,15,123,74,73,12,62,102,101,14,16,50,70,168,78,61,138,83,150,85,86,151,10,11,13,22,46,194,18,72,195,118,196,197,42,198,142,84,87,88,166,162,126,96,26,57,97,98,99,89,127,185,23,36,199,31,32,33,34,35,37,38,39,40,41,43,44,45,47,48,51,52,53,54,55,56,58,59,60,63,64,65,66,67,68,29,69,9,71,75,76,79,80,81,82,90,91,93,94,95,100,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,119,120,121,122,124,125,4,5,6,7,8,128,129,130,131,132,133,134,27,135,136,137,139,140,141,143,144,145,3,146,147,148,149,152,153,30,154,155,156,157,158,159,160,161,163,164,165,167,169])).then(t=>({default:t.MailMergePanel}))),cf=h.lazy(()=>Ze(()=>import("./RenewalsTab-DSYD0tvZ.js"),__vite__mapDeps([200,1,2,26,58,96,57,97,88,85,87,98,99,89,20,53,196,19,14,17,118,42,10,11,12,13,138,123,74,73,62,102,101,64,34,201,112,32,33,35,36,37,38,22,39,40,41,23,202,50,71,83,150,86,151,84,31,18,43,44,45,46,47,48,49,51,52,54,55,56,59,21,60,61,63,15,65,66,67,68,29,69,9,70,72,16,75,76,77,78,79,80,81,82,90,91,92,93,94,95,100,103,104,105,106,107,108,109,110,111,113,114,115,116,117,119,120,121,122,124,125,126,127,4,5,6,7,8,128,129,130,131,132,133,134,27,135,136,137,139,140,141,142,143,144,145,3,146,147,148,149,152,153,30,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169])).then(t=>({default:t.RenewalsTab}))),df=h.lazy(()=>Ze(()=>import("./CommissionsTab-C2hhx7wS.js"),__vite__mapDeps([203,1,2,26,58,53,14,15,17,42,123,74,73,12,62,102,101,138,120,204,163,50,49,84,85,86,87,88,31,32,33,34,35,36,37,38,22,39,40,41,23,18,43,44,45,46,47,48,51,52,54,55,56,57,59,21,60,61,63,64,10,11,13,65,66,67,68,29,69,9,70,71,72,16,75,76,77,78,79,80,81,82,83,89,90,91,92,93,94,95,96,97,98,99,20,100,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,121,122,124,125,126,127,4,5,6,7,8,128,129,130,131,132,133,134,27,135,136,137,139,140,141,142,143,144,145,3,146,147,148,149,150,151,152,153,30,154,155,156,157,158,159,160,161,162,164,165,166,167,168,169])).then(t=>({default:t.CommissionsTab}))),uf=h.lazy(()=>Ze(()=>import("./CalculatorsTab-q9-GDsOI.js"),__vite__mapDeps([205,1,2,14,15,17,123,74,73,12,62,102,101,135,194,138,75,76,85,89,99,87,84,86,88,70,30,122,115,53,206,207,31,32,26,33,34,35,36,37,38,22,39,40,41,23,18,42,43,44,45,46,47,48,49,50,51,52,54,5
1265,56,57,58,59,21,60,61,63,64,10,11,13,65,66,67,68,29,69,9,71,72,16,77,78,79,80,81,82,83,90,91,92,93,94,95,96,97,98,20,100,103,104,105,106,107,108,109,110,111,112,113,114,116,117,118,119,120,121,124,125,126,127,4,5,6,7,8,128,129,130,131,132,133,134,27,136,137,139,140,141,142,143,144,145,3,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169])).then(t=>({default:t.CalculatorsTab}))),mf=h.lazy(()=>Ze(()=>import("./AgentPerformanceDashboard-m7IDMie2.js"),__vite__mapDeps([208,1,2,26,14,209,17,42,187,154,155,58,156,210,15,63,62,10,11,12,13,211,108,212,168,92,77,50,185,126,37,23,83,120,188,169,132,36,149])).then(t=>({default:t.AgentPerformanceDashboard}))),os=()=>e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}),Yi=new Set(["accepted","in_final_review"]),hf=["document_request"],xf=()=>{const t=Qt(),[s,a]=Jn(),n=al(),{user:r,isAdmin:i,roleCheckFailed:l,isLoading:o}=Ke(),{mailMergeEnabled:c}=qc(),[m,f]=h.useState(!1),d=h.useCallback(()=>f(!0),[]),{performanceVisible:u}=cu();Qp(r==null?void 0:r.id);const{searchQuery:g,debouncedSearch:D,sortBy:E,sortOrder:v,archiveFilter:x,selectedProposals:$,viewLogs:T,loadingViewLogs:S,selectedProposalForViews:p,showAllViewsDialog:_,allViewLogs:y,loadingAllViews:q,showFundedDialog:A,fundedAmount:N,selectedProposalForFunding:C,showRejectDialog:I,selectedProposalForRejection:H,showReassignDialog:P,selectedProposalForReassign:z,setSearchQuery:M,setDebouncedSearch:k,setSortBy:w,setSortOrder:L,setArchiveFilter:O,toggleSelectProposal:ae,toggleSelectAll:te,clearSelection:V,removeFromSelection:G,setViewLogs:Z,setLoadingViewLogs:se,setSelectedProposalForViews:Y,setShowAllViewsDialog:ne,setAllViewLogs:fe,setLoadingAllViews:_e,openFundedDialog:ge,closeFundedDialog:me,setFundedAmount:b,openRejectDialog:W,closeRejectDialog:oe,showFundingLostDialog:B,selectedProposalForFundingLost:Q,openFundingLostDialog:ie,closeFundingLostDialog:ue,openReassignDialog:Ee,closeReassignDialog:Ye,activeFilterId:Fe,applyFilterState:gs,showTimelineSheet:ns,timelineProposal:Dt,openTimeline:Gt,closeTimeline:Xt,viewMode:K,setViewMode:qe,activityFeedExpanded:et,toggleActivityFeed:Qe,activityFeedDocked:Ue,toggleActivityFeedDocked:yt,agentFilter:Ae,statusFilter:pt,dateRange:Pe,typeFilter:wt,leadTempFilter:re,dealHealthFilter:ce,setAgentFilter:we,setStatusFilter:Ne,setDateRange:xe,setTypeFilter:Ge,setLeadTempFilter:Oe,setDealHealthFilter:tt,clearAdvancedFilters:st,openFollowUpInspector:Tt,closeFollowUpInspector:zt,renewalReadyOnly:rt,setRenewalReadyOnly:Bt,showCreateTaskDialog:ba,createTaskProposal:Ro,openCreateTaskDialog:dn,closeCreateTaskDialog:Fo,showEmailPreview:Lo,emailPreviewProposalId:Mo,openEmailPreview:Cr,closeEmailPreview:qo,focusFilter:ft,setFocusFilter:bs}=ia(),gt=Oc(s);h.useEffect(()=>{ia.setState({activityFeedExpanded:!1})},[gt]),h.useEffect(()=>{gt==="today"&&a(j=>{const ee=new URLSearchParams(j);return ee.delete("tab"),ee},{replace:!0})},[gt,a]);const ys=gt==="commissions"?"performance":gt==="today"?"proposals":gt;h.useEffect(()=>{if(gt!=="commissions")return;const j=window.requestAnimationFrame(()=>{var ee;return(ee=document.getElementById("commissions"))==null?void 0:ee.scrollIntoView({block:"start"})});return()=>window.cancelAnimationFrame(j)},[gt]);const[ws,Oo]=h.useState("all"),Et=gt==="document-requests",un=gt==="proposals"||Et,Ht=un&&K==="kanban"&&!n&&!ft&&!rt,Dr=Et?hf:wt,Us=h.useCallback((j,ee)=>{st(),M(""),k(""),Bt(!1),qe("table"),O("all"),V(),bs({label:j,proposalIds:ee})},[st,M,k,Bt,qe,O,V,bs]);h.useEffect(()=>{const j=s.get("proposal");j&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(j)&&Us("Selected deal",[j]),a(ee=>{const ye=new URLSearchParams(ee);return ye.delete("proposal"),ye.set("tab","proposals"),ye},{replace:!0}))},[s,a,Us]);const vs=j=>{j==="document-requests"&&!["active","archived"].includes(x)&&O("active"),a(ee=>{const ye=new URLSearchParams(ee);return j===zc?ye.delete("tab"):ye.set("tab",j),ye})},[pf,ff]=h.useState(!1),[ya,Io]=h.useState(()=>{try{const j=(r==null?void 0:r.id)||"default",ee=localStorage.getItem(`dashboard.visibleColumns.v4.${j}`);if(ee)return{...cs,...JSON.parse(ee)};const ye=localStorage.getItem(`dashboard.visibleColumns.v3.${j}`);if(ye)return{...cs,...JSON.parse(ye),sentViewed:!0};const ke=localStorage.getItem(`dashboard.visibleColumns.v2.${j}`);if(ke)return{...cs,...JSON.parse(ke),docs:!0,sentViewed:!0};const rs=localStorage.getItem(`dashboard.visibleColumns.${j}`);return rs?{...cs,...JSON.parse(rs),followUps:!0,docs:!0,sentViewed:!0}:cs}catch{return cs}});h.useEffect(()=>{r!=null&&r.id&&localStorage.setItem(`dashboard.visibleColumns.v4.${r.id}`,JSON.stringify(ya))},[ya,r==null?void 0:r.id]);const[wa,Uo]=h.useState(!0),[zo,mn]=h.useState(!1),Tr=r!=null&&r.email?r.email.split("@")[0].split(/[._-]/)[0].replace(/^\w/,j=>j.toUpperCase()):"",[Er,$r]=h.useState(null),[Bo,Ar]=h.useState(null),[hn,Pr]=h.useState(null),[Te,va]=h.useState(null),[js,Rr]=h.useState(null),[Ho,Fr]=h.useState(!1),[Lr,ja]=h.useState(null),{agents:Vo}=dl(i),{filters:Wo,saveFilter:Mr,deleteFilter:Ko,isSaving:Yo}=Xh(r==null?void 0:r.id),Qo=h.useCallback(j=>{gs({id:j.id,...j.filter_state})},[gs]),Go=h.useCallback(j=>{Mr(j,{searchQuery:g,sortBy:E,sortOrder:v,archiveFilter:x,agentFilter:Ae,statusFilter:pt,dateRange:Pe,typeFilter:wt,leadTempFilter:re})},[Mr,g,E,v,x,Ae,pt,Pe,wt,re]),Xo={searchQuery:D,agentFilter:Ae,statusFilter:pt,dateFrom:(Pe==null?void 0:Pe.from)||null,dateTo:(Pe==null?void 0:Pe.to)||null,typeFilter:Dr,documentTemplate:Et&&ws!=="all"?ws:void 0},{columns:Jo,isLoading:Zo,loadError:ec,refresh:tc,moveProposal:sc}=Kp(Xo,{enabled:!!(r!=null&&r.id)&&Ht}),xn=h.useCallback(j=>{Gt(j.id,le(j))},[Gt]),qr=h.useCallback(j=>{Tt(j.id)},[Tt]),pn=h.useCallback(j=>{dn(j)},[dn]),fn=h.useCallback(j=>{Cr(j.id)},[Cr]),gn=h.useCallback(async j=>{if(!j.phone){U.error("This deal has no phone number.");return}const ee=`${Pt()}/fit/${j.business_slug||j.unique_link}`,ye=wl({firstName:(j.client_name||"").split(" ")[0],businessName:le(j),link:ee,agentName:r!=null&&r.email?Ls(r.email):""});try{const ke=await Ts({to:j.phone,message:ye,proposalId:j.id,templateType:"financing_fit_link"});if(!ke.ok){U.error(ke.message);return}U.success(ea(ke))}catch(ke){console.error("[dashboard] send financing fit failed:",ke),U.error("Couldn't send the text. Please try again.")}},[r==null?void 0:r.email]),bn=h.useCallback(async j=>{if(!j.phone){U.error("This deal has no phone number.");return}const ee=`${Pt()}/apr/${j.business_slug||j.unique_link}`,ye=qd({firstName:(j.client_name||"").split(" ")[0],businessName:le(j),link:ee,agentName:r!=null&&r.email?Ls(r.email):""});try{const ke=await Ts({to:j.phone,message:ye,proposalId:j.id,templateType:"apr_explainer_link"});if(!ke.ok){U.error(ke.message);return}U.success(ea(ke))}catch(ke){console.error("[dashboard] send apr breakdown failed:",ke),U.error("Couldn't send the text. Please try again.")}},[r==null?void 0:r.email]),Or=h.useCallback(j=>{$r(j)},[]),ac=h.useCallback(async j=>{Pr(j.id);try{const ee=Math.floor((Date.now()-new Date(j.created_at).getTime())/864e5),{data:ye,error:ke}
126=await F.functions.invoke("generate-resend-hook",{body:{businessName:le(j),clientName:j.client_name,preferredLanguage:j.preferred_language||"en",viewCount:j.view_count||0,daysSinceCreated:ee,lastViewedDaysAgo:j.last_client_viewed_at?Math.floor((Date.now()-new Date(j.last_client_viewed_at).getTime())/(1e3*60*60*24)):null}});if(ke)throw ke;const rs=(ye==null?void 0:ye.subject)||`Updated funding proposal for ${le(j)}`,{error:Vs}=await F.functions.invoke("send-proposal-email",{body:{proposalId:j.id,clientEmail:j.email,clientName:j.client_name,businessName:le(j),agentEmail:j.agent_email,proposalLink:`${window.location.origin}/${j.business_slug||j.unique_link}`,subject:rs,isResend:!0}});if(Vs)throw Vs;U.success(`Resent to ${j.client_name} with fresh subject line`)}catch(ee){console.error("Resend error:",ee),U.error("Failed to resend proposal")}finally{Pr(null)}},[]);h.useEffect(()=>{if(!Te){Rr(null),ja(null);return}let j=!1;return Fr(!0),ja(null),gl(Te.proposal,{kind:"proposal_initial"}).then(ee=>{j||(Un(ee)?ja(ee.skippedReason):Rr(ee))}).catch(ee=>{j||ja(ee instanceof Error?ee.message:"Could not render preview")}).finally(()=>{j||Fr(!1)}),()=>{j=!0}},[Te]),h.useEffect(()=>{const j=setTimeout(()=>k(g),300);return()=>clearTimeout(j)},[g,k]);const{proposals:Ir,loading:nc,loadError:yn,pagination:zs,counts:Bs,countsAvailable:rc,loadedAt:Ur,goToPage:ic,refresh:Hs,updateLocalProposal:lc,removeLocalProposal:oc}=cm(r==null?void 0:r.id,{enabled:un&&!Ht,countsEnabled:un,pageSize:20,sortBy:E,sortOrder:v,archiveFilter:x,searchQuery:D,agentFilter:Ae,statusFilter:pt,dateFrom:(Pe==null?void 0:Pe.from)||null,dateTo:(Pe==null?void 0:Pe.to)||null,typeFilter:Dr,documentTemplate:Et&&ws!=="all"?ws:void 0,leadTempFilter:re,focusProposalIds:(ft==null?void 0:ft.proposalIds)??null,renew
126alReadyOnly:rt&&x==="funded"}),_s=h.useMemo(()=>{let j=Ir.filter(ee=>!(ee.type==="application"&&ee.status==="application_submitted"));return ce.length>0&&(j=j.filter(ee=>{const ye=_r(ee);return ce.includes(ye.tier)})),j},[Ir,ce]),be=ql({userId:r==null?void 0:r.id,onProposalUpdated:lc,onProposalRemoved:j=>{oc(j),G(j)}}),cc=h.useCallback(async()=>{await Hs()},[Hs]),_a=h.useCallback((j,ee=!1)=>{const ye=j.business_slug||j.unique_link,ke=ee?window.location.origin:Pt();return j.type==="document_request"?`${ke}/docs/${ye}`:j.type==="debt_schedule"?`${ke}/debt-schedule/${ye}`:j.type==="funding_menu"?`${ke}/funding-menu/${ye}`:`${ke}/${ye}`},[]),wn=h.useCallback(j=>{Ma(_a(j),"Proposal link copied to clipboard!")},[_a]),dc=async()=>{await be.bulkArchive(Array.from($))&&V()},uc=async()=>{await be.bulkDelete(Array.from($))&&V()},mc=async()=>{if(!C)return;const j=N?parseFloat(N.replace(/[^0-9.]/g,"")):void 0;await be.markAsFunded(C,j)&&me()},hc=async j=>{if(!H)return;await be.rejectProposal(H,j)&&oe()},xc=async(j,ee)=>{if(!Q)return;await be.markAsFundingLost(Q,j,ee)&&ue()},zr=h.useCallback(async j=>{se(!0),Y(j);try{const{data:ee,error:ye}=await F.from("proposal_view_logs").select("*").eq("proposal_id",j).order("viewed_at",{ascending:!1});if(ye)throw ye;Z((ee||[]).map(ke=>({...ke,viewed_at:ke.viewed_at||""})))}catch(ee){console.error("Error fetching view logs:",ee),U.error("Failed to load view logs")}finally{se(!1)}},[se,Y,Z]),Br=async()=>{_e(!0),ne(!0);try{const{data:j,error:ee}=await F.from("proposal_view_logs").select("*, proposals!inner(business_name, client_name)").order("viewed_at",{ascending:!1}).limit(100);if(ee)throw ee;const ye=(j||[]).map(ke=>{var Vs,Gr;const rs=ke;return{...ke,business_name:((Vs=rs.proposals)==null?void 0:Vs.business_name)||"Unknown",client_name:((Gr=rs.proposals)==null?void 0:Gr.client_name)||"Unknown"}});fe(ye)}catch(j){console.error("Error fetching all view logs:",j),U.error("Failed to load view logs")}finally{_e(!1)}},Hr=h.useCallback(j=>{if(ol(j.expiration_date)&&j.status!=="funded")return e.jsx(J,{variant:"destructive",children:"Expired"});switch(j.status){case"funded":return e.jsx(J,{className:"bg-success text-success-foreground hover:bg-success/90",children:"Funded"});case"in_final_review":return e.jsx(J,{className:"bg-warning/15 text-warning hover:bg-warning/25 border-transparent",children:"In Final Review"});case"accepted":return e.jsx(J,{className:"bg-success/15 text-success hover:bg-success/25 border-transparent",children:"Accepted"});case"rejected":return e.jsx(J,{variant:"destructive",children:"Rejected"});case"funding_lost":return e.jsx(J,{className:"bg-destructive/15 text-destructive hover:bg-destructive/25 border-transparent",children:"Funding Lost"});case"draft":return e.jsx(J,{variant:"outline",className:"border-dashed text-muted-foreground",children:"Draft"});default:return e.jsx(J,{variant:"secondary",children:"Pending"})}},[]),{acceptedDeals:Vt,otherDeals:Ns}=h.useMemo(()=>({acceptedDeals:_s.filter(j=>Yi.has(j.status)),otherDeals:_s.filter(j=>!Yi.has(j.status))}),[_s]),Vr=h.useCallback(j=>{j.type==="document_request"?t(Lt(j.type,j.id)):va({proposal:j,resend:!1})},[t]),Wr=h.useCallback(j=>{j.type==="document_request"?t(Lt(j.type,j.id)):va({proposal:j,resend:!0})},[t]),pc=h.useCallback(j=>Ee(j),[Ee]),fc=h.useCallback(j=>be.cloneProposal(j,t),[be.cloneProposal,t]),gc=h.useCallback(()=>te(Vt.map(j=>j.id)),[te,Vt]),bc=h.useCallback(()=>te(Ns.map(j=>j.id)),[te,Ns]),Kr=j=>e.jsx(ro,{proposal:j,isSelected:$.has(j.id),onSelect:()=>ae(j.id),onView:()=>window.open(_a(j,!0),"_blank"),onCopy:()=>wn(j),onEdit:()=>t(Lt(j.type,j.id)),onDelete:()=>be.deleteProposal(j.id,le(j)),onViewLogs:()=>zr(j.id),onViewDocuments:()=>Kn(j),onSendEmail:()=>Vr(j),isSendingEmail:be.sendingEmailFor===j.id,getStatusBadge:Hr,onToggleAutoFollowups:ee=>be.toggleAutoFollowups(j.id,ee),onArchive:()=>be.archiveProposal(j.id,le(j)),onRestore:()=>be.restoreProposal(j.id,le(j)),isArchiving:be.isArchiving===j.id,onMarkAsFunded:()=>ge(j),onReject:()=>W(j),onMarkAsFundingLost:()=>ie(j),onReassign:i?()=>Ee(j):void 0,onViewTimeline:()=>xn(j),onViewFollowUpSettings:()=>qr(j),onCreateTask:()=>pn(j),onViewAIInsights:()=>Or(j),onPreviewEmails:()=>fn(j),onSendFinancingFit:j.phone?()=>gn(j):void 0,onSendAprBreakdown:j.phone?()=>bn(j):void 0,onClone:()=>be.cloneProposal(j,t),onResend:()=>Wr(j),isResending:hn===j.id},j.id),Yr=(j,ee)=>e.jsx(go,{proposals:j,selectedProposals:$,onSelect:ae,onSelectAll:ee,onCopyLink:wn,onDelete:be.deleteProposal,onViewLogs:zr,onSendEmail:Vr,sendingEmailFor:be.sendingEmailFor,getStatusBadge:Hr,onToggleAutoFollowups:be.toggleAutoFollowups,onArchive:be.archiveProposal,onRestore:be.restoreProposal,isArchiving:be.isArchiving,onMarkAsFunded:ge,onReject:W,onMarkAsFundingLost:ie,onReassign:i?pc:void 0,onViewTimeline:xn,onViewFollowUpSettings:qr,onCreateTask:pn,onPreviewEmails:fn,onSendFinancingFit:gn,onSendAprBreakdown:bn,onViewAIInsights:Or,onClone:fc,cloningProposalId:be.cloningProposalId,onResend:Wr,resendingFor:hn,visibleColumns:ya}),Qr=e.jsxs("button",{onClick:()=>Uo(j=>!j),className:"w-full flex items-center gap-2 px-4 py-2.5 rounded-xl border border-success/25 bg-success/[0.07] text-success font-semibold text-sm hover:bg-success/[0.12] transition-colors",children:[e.jsx(St,{className:"h-4 w-4"}
126),"Accepted deals",e.jsx("span",{className:"text-xs font-bold bg-success/15 rounded-full px-2 py-0.5 tabular-nums",children:Vt.length}),e.jsx("span",{className:"ml-auto text-xs font-medium text-success/80",children:wa?"Hide":"Show"}),e.jsx(ms,{className:`h-4 w-4 transition-transform ${wa?"":"-rotate-90"}`})]});return o?e.jsxs("div",{className:"flex-1 bg-background",children:[e.jsx(Jh,{}),e.jsx("main",{className:"max-w-[1600px] mx-auto px-4 lg:px-6 py-8",children:e.jsx(Na,{})})]}):e.jsxs("div",{className:"flex-1 flex flex-col bg-background",children:[e.jsx(Ih,{onClear:d}),e.jsx(Uh,{ready:m}),e.jsxs("div",{className:"flex flex-1 items-start",children:[e.jsx("main",{className:"min-w-0 flex-1 px-4 sm:px-6 lg:px-8 pt-5 sm:pt-8 pb-8",children:e.jsxs("div",{className:"max-w-[1440px] mx-auto w-full",children:[["proposals","document-requests","drafts"].includes(ys)&&e.jsx(_i,{title:"Pipeline"}),["ondeck","docs","resources","mailmerge","deal-blitz"].includes(ys)&&e.jsx(R,{variant:"ghost",size:"sm",className:"mb-4 -ml-3 text-muted-foreground",onClick:()=>vs("tools"),children:"Back to Tools"}),["tools","ondeck","docs","resources"].includes(ys)&&e.jsx(Xc,{}),e.jsxs(qn,{value:ys,onValueChange:j=>vs(j),className:"mb-3",children:[e.jsx("div",{className:"-mx-3 sm:mx-0 overflow-x-auto scrollbar-none md:hidden",children:e.jsxs(On,{className:"inline-flex w-max h-8 px-3 sm:px-0",children:[e.jsxs($t,{value:"proposals",className:"gap-1.5 text-xs h-7 shrink-0 whitespace-nowrap",children:[e.jsx(Ft,{className:"h-3.5 w-3.5"}),"Pipeline"]}),e.jsx($t,{value:"war-room",className:"gap-1.5 text-xs h-7 shrink-0 whitespace-nowrap",children:"War Room"}),e.jsxs($t,{value:"renewals",className:"gap-1.5 text-xs h-7 shrink-0 whitespace-nowrap",children:[e.jsx(du,{className:"h-3.5 w-3.5"}),"Renewals"]}),e.jsxs($t,{value:"performance",className:"gap-1.5 text-xs h-7 shrink-0 whitespace-nowrap",children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),"Performance"]}),e.jsxs($t,{value:"tools",className:"gap-1.5 text-xs h-7 shrink-0 whitespace-nowrap",children:[e.jsx(Ic,{className:"h-3.5 w-3.5"}),"Tools"]})]})}),ft&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 px-2.5 py-1.5 rounded-md bg-primary/10 border border-primary/30 text-xs",children:[e.jsx("span",{className:"font-medium text-primary",children:"Focus:"}),e.jsx("span",{className:"text-foreground",children:ft.label}),e.jsx(J,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:ft.proposalIds.length}),e.jsxs("button",{onClick:()=>bs(null),className:"ml-auto inline-flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors","aria-label":"Clear focus filter",children:[e.jsx(Yt,{className:"h-3 w-3"})," Clear"]})]}),e.jsxs(Ie,{value:Et?"document-requests":"proposals",className:"mt-2",children:[Et&&e.jsx("div",{className:"mb-4 flex flex-wrap gap-2","aria-label":"Document package filter",children:[["all","All"],["sba_term_loan","SBA & Term Loan"],["standard","Standard"]].map(([j,ee])=>e.jsx(R,{variant:ws===j?"default":"outline",onClick:()=>Oo(j),"aria-pressed":ws===j,children:ee},j))}),!Et&&e.jsx(Wi,{performanceVisible:u,userId:r==null?void 0:r.id,firstName:Tr,activeFocusLabel:ft==null?void 0:ft.label,onFocus:(j,ee)=>{Us(j,ee)},onClearFocus:()=>bs(null),onOpenDeal:Gt,onInsights:()=>mn(j=>!j)}),!Et&&zo&&e.jsxs("section",{"aria-label":"More pipeline insights",className:"mb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"More insights"}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>mn(!1),children:"Close insights"})]}),e.jsx(ef,{ownerId:(r==null?void 0:r.id)??null}),e.jsx(Ip,{userId:r==null?void 0:r.id,onCreateTask:j=>{Ar(j||null),dn()},onApplyFocus:(j,ee)=>{Us(j,ee)}})]}),l?e.jsxs("div",{className:"mb-3 rounded-md border border-amber-400/50 bg-amber-50 dark:bg-amber-950/30 p-3",children:[e.jsx("p",{className:"text-sm font-medium text-amber-800 dark:text-amber-300",children:"We couldn't confirm your permissions"}),e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-400 mt-1",children:"Admin features are hidden until this succeeds â you have not lost access. Usually a temporary server problem; reload to retry."})]}):null,(Ht?ec:yn)?e.jsxs("div",{role:"alert",className:"mb-3 rounded-xl border border-destructive/30 bg-destructive/5 p-4",children:[e.jsxs("p",{className:"text-sm font-semibold",children:["Couldn't load your ",Ht?"board":"pipeline"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Your deals are still saved. Please retry the connection."}),e.jsxs(R,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>{Ht?tc():Hs()},children:["Retry loading ",Ht?"board":"pipeline"]})]}):null,e.jsxs("div",{className:Et?void 0:"pipeline-deals-region mt-2 border-t border-border/50 pt-6",children:[e.jsx(ji,{active:gt,onCh
126ange:vs}),e.jsx(tx,{searchQuery:g,onSearchChange:M,sortBy:E,onSortByChange:w,sortOrder:v,onSortOrderChange:L,archiveFilter:x,onArchiveFilterChange:O,counts:{active:Bs.active,archived:Bs.archived,funded:Bs.funded,fundingLost:Bs.fundingLost,total:Bs.total},countsAvailable:rc,savedFilters:Wo,activeFilterId:Fe,onApplyFilter:Qo,onDeleteFilter:Ko,onSaveFilter:Go,isSavingFilter:Yo,isAdmin:i,agents:Vo,agentFilter:Ae,onAgentFilterChange:we,statusFilter:pt,onStatusFilterChange:Ne,dateRange:Pe,onDateRangeChange:xe,typeFilter:wt,onTypeFilterChange:Ge,leadTempFilter:re,onLeadTempFilterChange:Oe,onClearAdvancedFilters:st,dealHealthFilter:ce,onDealHealthFilterChange:tt,viewMode:Ht?"kanban":"table",onViewModeChange:j=>{j==="kanban"&&(bs(null),Bt(!1)),qe(j)},renewalReadyOnly:rt,onRenewalReadyChange:j=>{qe("table"),Bt(j)},filteredCount:D?_s.length:void 0,onViewAllClicked:Br,docRequestMode:Et,visibleColumns:ya,onVisibleColumnsChange:Io}),!Ht&&!yn&&Ur>0&&e.jsxs("p",{className:"-mt-2 mb-3 flex items-center gap-2 text-xs text-muted-foreground","data-testid":"pipeline-freshness",children:[e.jsx(bo,{at:Ur,prefix:"Deals updated"}),e.jsx("button",{type:"button",onClick:()=>{Hs()},className:"inline-flex min-h-8 items-center rounded-md px-1.5 font-medium text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Refresh"})]}),$.size>0&&x!=="archived"&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 px-3 py-2 rounded-md border bg-muted/40",children:[e.jsxs(J,{variant:"secondary",className:"text-xs",children:[$.size," selected"]}),e.jsxs(R,{onClick:dc,variant:"outline",size:"sm",className:"h-8",disabled:be.isBulkArchiving,children:[e.jsx(Es,{className:"mr-1.5 h-3.5 w-3.5"}),be.isBulkArchiving?"Archiving...":"Archive"]}),e.jsxs(R,{onClick:uc,variant:"destructive",size:"sm",className:"h-8",disabled:be.isDeletingBulk,children:[e.jsx(Is,{className:"mr-1.5 h-3.5 w-3.5"}),be.isDeletingBulk?"Deleting...":"Delete"]})]}),e.jsx(mu,{userId:r==null?void 0:r.id,isAdmin:i,agentEmail:r==null?void 0:r.email}),e.jsx(tf,{userId:r==null?void 0:r.id,isAdmin:i}),Ht?e.jsx(h.Suspense,{fallback:e.jsx(Na,{}),children:e.jsx(sf,{columns:Jo,isLoading:Zo,onMoveProposal:sc,onViewProposal:j=>window.open(_a(j,!0),"_blank"),onCopyLink:wn,onMarkAsFunded:ge,onReject:W,onMarkAsFundingLost:ie,onViewTimeline:xn,onCreateTask:pn,onPreviewEmails:fn,onSendFinancingFit:gn,onSendAprBreakdown:bn,onToggleAutoFollowups:(j,ee)=>be.toggleAutoFollowups(j.id,ee),onDownloadDocuments:Kn})}):e.jsx(e.Fragment,{children:nc?e.jsxs("div",{className:"bg-card border rounded-lg p-8 space-y-4",children:[e.jsx(je,{className:"h-10 w-full"}),e.jsx(je,{className:"h-10 w-full"}),e.jsx(je,{className:"h-10 w-full"})]}):yn&&_s.length===0?null:_s.length===0?e.jsxs("div",{className:"bg-card border rounded-lg p-6 sm:p-8 text-center",children:[e.jsx("p",{className:"text-sm sm:text-base text-muted-foreground mb-4",children:"No deals match this view. Try another status or adjust your filters."}),e.jsx(R,{onClick:()=>t("/create-choice"),children:"Create proposal"})]}):e.jsxs(e.Fragment,{children:[n?e.jsx(Uu,{onRefresh:cc,children:e.jsxs("div",{className:"space-y-3",children:[Vt.length>0&&e.jsxs("div",{className:"space-y-3",children:[Qr,wa&&Vt.map(Kr)]}),Ns.length>0&&e.jsx("div",{className:Vt.length>0?"mt-6":void 0,children:Ns.map(Kr)})]})}):e.jsx(Bc,{children:e.jsxs("div",{className:"space-y-3",children:[Vt.length>0&&e.jsxs("div",{className:"space-y-2",children:[Qr,wa&&Yr(Vt,gc)]}),Ns.length>0&&e.jsx("div",{className:Vt.length>0?"mt-6":void 0,children:Yr(Ns,bc)})]})}),zs.totalPages>1&&e.jsx(Iu,{currentPage:zs.page,totalPages:zs.totalPages,totalCount:zs.totalCount,pageSize:zs.pageSize,onPageChange:ic})]})})]})]}),e.jsx(Ie,{value:"today",className:"mt-2",children:e.jsx(Wi,{performanceVisible:u,userId:r==null?void 0:r.id,firstName:Tr,activeFocusLabel:ft==null?void 0:ft.label,onFocus:(j,ee)=>{Us(j,ee),vs("proposals")},onClearFocus:()=>bs(null),onOpenDeal:Gt,onInsights:()=>mn(j=>!j)})}),e.jsx(Ie,{value:"war-room",className:"mt-6",children:e.jsx(h.Suspense,{fallback:e.jsx(Na,{}),children:e.jsx(af,{})})}),e.jsx(Ie,{value:"contact-downloads",className:"mt-6",children:e.jsx(h.Suspense,{fallback:e.jsx(Na,{}),children:e.jsx(nf,{})})}),e.jsxs(Ie,{value:"performance",className:"mt-6 space-y-6",children:[e.jsx(_i,{title:"Performance",description:"See the team's results and keep track of your commissions."}),e.jsxs(qn,{value:gt==="commissions"||!u?"commissions":"company",onValueChange:j=>vs(j==="commissions"?"commissions":"performance"),children:[e.jsxs(On,{className:"mb-6 h-auto rounded-xl border bg-card p-1",children:[u&&e.jsx($t,{value:"company",className:"rounded-lg px-4 py-2",children:"Company results"}),e.jsx($t,{value:"commissions",className:"rounded-lg px-4 py-2",children:"My commissions"})]}),u&&e.jsxs(Ie,{value:"company",className:"space-y-5",children:[e.jsx(cx,{}),e.jsx(h.Suspense,{fallback:e.jsx(os,{}),children:e.jsx(mf,{embedded:!0})})]}),e.jsx(Ie,{value:"commissions",children:e.jsx("section",{id:"commissions","aria-label":"Commissions",className:"scroll-mt-20",children:e.jsx(h.Suspense,{fallback:e.jsx(os,{}),children:e.jsx(df,{})})})})]})]}),e.jsx(Ie,{value:"renewals",className:"mt-6",children:e.jsx(h.Suspense,{fallback:e.jsx(os,{}),children:e.jsx(cf,{})})}),e.jsx(Ie,{value:"tools",className:"mt-6",children:e.jsx(Nh,{items:Uc(!!c)})}),e.jsx(Ie,{value:"ondeck",className:"mt-6",children:e.jsx(h.Suspense,{fallback:e.jsx(os,{}),children:e.jsx(uf,{})})}),e.jsx(Ie,{value:"docs",className:"mt-6",children:e.jsx(h.Suspense,{fallback:e.jsx(os,{}),children:e.jsx(rf,{})})}),e.jsx(Ie,{value:"contact-card",className:"mt-6",children:e.jsx(Sh,{})}),e.jsx(Ie,{value:"resources",className:"mt-6",children:e.jsx(Lh,{})}),e.jsx(Ie,{value:"signature",className:"mt-6",children:e.jsx(Bh,{})}),e.jsx(Ie,{value:"deal-blitz",className:"mt-6",children:e.jsx(h.Suspense,{fallback:e.jsx(os,{}),children:e.jsx(lf,{})})}),c&&e.jsx(Ie,{value:"mailmerge",className:"mt-6",children:e.jsx(h.Suspense,{fallback:e.jsx(os,{}),children:e.jsx(of,{})})}),e.jsxs(Ie,{value:"drafts",className:"mt-2",children:[e.jsx(ji,{active:gt,onCh
126ange:vs}),e.jsx(kh,{})]}),e.jsx(Ie,{value:"help",className:"mt-6",children:e.jsx(Kh,{})})]})]})}),e.jsx(Jx,{expanded:et,onToggle:Qe,docked:Ue&&!n&&["proposals","document-requests","drafts"].includes(ys),onToggleDocked:!n&&["proposals","document-requests","drafts"].includes(ys)?yt:void 0})]}),e.jsx(nx,{open:p!==null,onOpenChange:j=>!j&&Y(null),loading:S,viewLogs:T}),e.jsx(rx,{open:_,onOpenChange:ne,loading:q,viewLogs:y,onRefresh:Br}),e.jsx(wh,{open:!!Te,onOpenChange:j=>!j&&va(null),channel:"email",actionLabel:Te!=null&&Te.resend?"Resend proposal email":"Send proposal email",methodNote:Te!=null&&Te.resend?"Resends the proposal email with a fresh AI-generated subject line. Opens and clicks are tracked and the send lands on the deal's timeline.":"Sends the full proposal email with the client's personal link through QCF. Opens and clicks are tracked and the send lands on the deal's timeline.",recipients:Te?[{name:[Te.proposal.client_name,le(Te.proposal)].filter(Boolean).join(" · ")||"â",destination:Te.proposal.email||"no email on file"}]:[],sampleSubject:Te&&!Te.resend?js==null?void 0:js.subject:null,sampleBody:(js==null?void 0:js.html)??null,sampleHtml:!0,previewLoading:Ho,sampleLabel:Te?Te.resend?"Email preview â the subject line will be regenerated by AI when you confirm":`Email preview for ${Te.proposal.client_name||"client"}`:void 0,warning:[Te&&!Te.resend&&Te.proposal.initial_email_sent?"This client already received the proposal email â confirming sends it again.":null,Lr?`Preview unavailable: ${Lr}`:null].filter(Boolean).join(" ")||null,confirming:!!Te&&(be.sendingEmailFor===Te.proposal.id||hn===Te.proposal.id),onConfirm:()=>{const j=Te;if(va(null),!!j){if(!j.proposal.email){U.error("This deal has no client email on file â add one before sending.");return}j.resend?ac(j.proposal):be.sendEmail(j.proposal)}}}),e.jsx(lx,{open:A,onOpenChange:j=>!j&&me(),proposal:C,fundedAmount:N,onFundedAmountChange:b,onConfirm:mc,isLoading:be.markingFundedFor!==null}),e.jsx(gh,{open:I,onOpenChange:j=>!j&&oe(),businessName:(H==null?void 0:H.business_name)||"",onConfirm:hc,isLoading:be.isRejecting}),e.jsx(ox,{open:B,onOpenChange:j=>!j&&ue(),proposal:Q,onConfirm:xc,isLoading:be.isMarkingFundingLost}),e.jsx(Ox,{open:ns,onOpenChange:j=>!j&&Xt(),proposalId:(Dt==null?void 0:Dt.id)??null,businessName:(Dt==null?void 0:Dt.businessName)??""}),e.jsx(bh,{open:P,onOpenChange:j=>!j&&Ye(),proposalId:(z==null?void 0:z.id)||null,businessName:(z==null?void 0:z.business_name)||"",currentAgentEmail:(z==null?void 0:z.agent_email)||"",onReassigned:Hs}),e.jsx(ap,{}),e.jsx(Vp,{open:Lo,onOpenChange:j=>!j&&qo(),proposalId:Mo}),e.jsx(Po,{open:ba,onOpenChange:j=>{j||(Fo(),Ar(null))},userId:r==null?void 0:r.id,preselectedProposal:Ro,prefilledTitle:Bo}),e.jsx(Yp,{proposal:Er,open:!!Er,onOpenChange:j=>!j&&$r(null)})]})},ry=Object.freeze(Object.defineProperty({__proto__:null,default:xf},Symbol.toStringTag,{value:"Module"}));export{fa as C,qi as D,Ya as E,Il as L,ny as R,Mu as S,di as U,nn as a,rn as b,Ym as c,xo as d,Tl as e,Yn as f,_r as g,vr as h,an as i,yr as j,Ms as k,Du as l,wh as m,br as n,Xb as o,ty as p,ay as q,ey as r,sy as s,Jb as t,Bx as u,us as v,$n as w,_o as x,ry as y};
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.