1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CcMLSBG6.js","assets/index-Au-A0kGn.css","assets/SessionTracker-Cg5flV89.js","assets/ChatManager-ph9D-sj7.js","assets/pricing-C7Zud4u1.js","assets/servicePresentation-DbBxiSKI.js","assets/integrations-dFjHZNPi.js","assets/ChatSessionManager-PA2eI_uj.js","assets/refinance-CLo5cqU1.js","assets/mortgageCalculations-Br3m_BjG.js"])))=>i.map(i=>d[i]); 2import{s as dn,r as m,ah as fn,aK as _n,ai as ma,j as n,aL as hn,aM as Ca,aN as yn,aO as gn,aP as bn,aQ as Sa,aR as wn,aS as vn,aT as ot,aU as Pa,aV as xn,aW as Cn,aX as Sn,aY as Pn,aZ as Tn,a_ as An,a7 as kn,b as K,a$ as Nn,B as nt,m as Ta,g as be,A as $n,aa as Nt,ad as ht,ab as it,a6 as Te,y as De,b0 as Rn,b1 as In,b2 as jn,b3 as yt,b4 as Lt,b5 as da,b6 as Fn,b7 as Dn,c as En,l as Ln,I as Mn,aw as On,b8 as qn,W as Hn,X as Bn,t as Un,b9 as zn,ba as Vn}from"./index-CcMLSBG6.js";import{I as lt}from"./input-6C8gsjbZ.js";import{C as ft}from"./ChatBubble-B8otggAC.js";import{g as Gn,C as Ie,a as Jt,b as Yn}from"./ChatManager-ph9D-sj7.js";import Ae from"./ChatSessionManager-PA2eI_uj.js";import{L as at}from"./label-6YVF-Fk-.js";import{S as Mt,a as Ot,b as qt,c as Ht,d as Bt}from"./select-DljSOX27.js";import"./tabs-3XcCUx4u.js";import{T as Jn}from"./textarea-CLfkUcY6.js";import{calculatePrice as Qe}from"./pricing-C7Zud4u1.js";import{t as _t}from"./index-BWPxfoG4.js";import{L as Xn}from"./loader-circle-DrqN3EDc.js";import{B as Kn}from"./bot-C7e4-GsS.js";import{A as fa}from"./arrow-right-CsLZV7dP.js";import{s as Qn,a as Zn,l as Aa}from"./applicationAnalysis-ieIxmXML.js";import{B as _a}from"./BinaWaitingScreen-Bow5TJ0Z.js";import{A as Wn}from"./index-CLVZmgfN.js";import"./integrations-dFjHZNPi.js";import{b as er}from"./mortgageCalculations-Br3m_BjG.js";import{c as Ut}from"./confetti.module-Cx83yTHA.js";import{t as tr}from"./voiceProspectHandoff-DZ4UeVfl.js";import ha from"./SessionTracker-Cg5flV89.js";import{T as ar}from"./trash-2-ClxNGV40.js";import{S as nr}from"./send-RBdaxugo.js";import"./target-D5Mje5dm.js";import"./banknote-C4Huogt4.js";import"./calendar-clock-Bjx9ZSc-.js";import"./percent-Cwsb90t5.js";import"./credit-card-B8_33X1t.js";import"./plus-B7SL8aOC.js";import"./AISupportDialog-DEEmNS1X.js";import"./slider-lQ-qzISm.js";import"./alert-Di-_xroR.js";import"./formatters-Dml3cA-o.js";import"./ExpensesCalculator-DTtoijXQ.js";import"./CalculatorShell-CDWL9G8O.js";import"./chevron-up-YKflUX3z.js";import"./info-BLrq3-KS.js";import"./lightbulb-CgTQ1c2W.js";import"./pencil-a5D9n1_C.js";import"./dollar-sign-DMrgMiCk.js";import"./circle-alert-BwI6hGhc.js";import"./triangle-alert-B1Ayw7eC.js";import"./voiceContactPreference-DhDFwX9i.js";import"./trending-down-D43ANNEP.js";import"./wallet-BIm85lAu.js";import"./route-Dbjcixir.js";import"./popover-CfdIuF7b.js";import"./accordion-Dw-mToqJ.js";import"./badge-Dneubc8N.js";import"./linkedMortgageCalculations-DYsvYGW9.js";import"./layers-DuRgwagd.js";import"./landmark-C-dy90zf.js";import"./calendar-70KlfpAC.js";import"./chart-no-axes-column-increasing-CRBXRXei.js";import"./Disclaimer-BGSuoBcN.js";import"./BuyingCapacityCalculator-BFBAyt2w.js";import"./VoiceContactOptOut-DZiwV07k.js";import"./circle-x-Byk2wOBp.js";import"./radio-group-D8sOWlyy.js";import"./file-up-BHAxvV4p.js";import"./index-C8ahqQRk.js";import"./servicePresentation-DbBxiSKI.js";import"./refinance-CLo5cqU1.js";/** 3 * @license lucide-react v0.475.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 rr=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],sr=dn("ArrowDown",rr),or=m.createContext(null);function ir(){const e=m.useRef(!1);return fn(()=>(e.current=!0,()=>{e.current=!1}),[]),e}function lr(){const e=ir(),[a,t]=m.useState(0),s=m.useCallback(()=>{e.current&&t(a+1)},[a]);return[m.useCallback(()=>_n.postRender(s),[s]),a]}const cr=e=>!e.isLayoutDirty&&e.willUpdate(!1);function ya(){const e=new Set,a=new WeakMap,t=()=>e.forEach(cr);return{add:s=>{e.add(s),a.set(s,s.addEventListener("willUpdate",t))},remove:s=>{e.delete(s);const o=a.get(s);o&&(o(),a.delete(s)),t()},dirty:t}}const ka=e=>e===!0,ur=e=>ka(e===!0)||e==="id",pr=({children:e,id:a,inherit:t=!0})=>{const s=m.useContext(ma),o=m.useContext(or),[y,f]=lr(),$=m.useRef(null),u=s.id||o;$.current===null&&(ur(t)&&u&&(a=a?u+"-"+a:u),$.current={id:a,group:ka(t)&&s.group||ya()});const r=m.useMemo(()=>({...$.current,forceRender:y}),[f]);return n.jsx(ma.Provider,{value:r,children:e})};var[$t]=hn("Tooltip",[Ca]),Rt=Ca(),Na="TooltipProvider",mr=700,Gt="tooltip.open",[dr,Xt]=$t(Na),$a=e=>
vendor: 4,241 bytes, line 7
7{const{__scopeTooltip:a,delayDuration:t=mr,skipDelayDuration:s=300,disableHoverableContent:o=!1,children:y}=e,f=m.useRef(!0),$=m.useRef(!1),u=m.useRef(0);return m.useEffect(()=>{const r=u.current;return()=>window.clearTimeout(r)},[]),n.jsx(dr,{scope:a,isOpenDelayedRef:f,delayDuration:t,onOpen:m.useCallback(()=>{window.clearTimeout(u.current),f.current=!1},[]),onClose:m.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>f.current=!0,s)},[s]),isPointerInTransitRef:$,onPointerInTransitChange:m.useCallback(r=>{$.current=r},[]),disableHoverableContent:o,children:y})};$a.displayName=Na;var gt="Tooltip",[fr,bt]=$t(gt),Ra=e=>{const{__scopeTooltip:a,children:t,open:s,defaultOpen:o,onOpenChange:y,disableHoverableContent:f,delayDuration:$}=e,u=Xt(gt,e.__scopeTooltip),r=Rt(a),[p,T]=m.useState(null),k=yn(),R=m.useRef(0),h=f??u.disableHoverableContent,D=$??u.delayDuration,A=m.useRef(!1),[B,Y]=gn({prop:s,defaultProp:o??!1,onChange:g=>{g?(u.onOpen(),document.dispatchEvent(new CustomEvent(Gt))):u.onClose(),y==null||y(g)},caller:gt}),ae=m.useMemo(()=>B?A.current?"delayed-open":"instant-open":"closed",[B]),q=m.useCallback(()=>{window.clearTimeout(R.current),R.current=0,A.current=!1,Y(!0)},[Y]),j=m.useCallback(()=>{window.clearTimeout(R.current),R.current=0,Y(!1)},[Y]),N=m.useCallback(()=>{window.clearTimeout(R.current),R.current=window.setTimeout(()=>{A.current=!0,Y(!0),R.current=0},D)},[D,Y]);return m.useEffect(()=>()=>{R.current&&(window.clearTimeout(R.current),R.current=0)},[]),n.jsx(bn,{...r,children:n.jsx(fr,{scope:a,contentId:k,open:B,stateAttribute:ae,trigger:p,onTriggerChange:T,onTriggerEnter:m.useCallback(()=>{u.isOpenDelayedRef.current?N():q()},[u.isOpenDelayedRef,N,q]),onTriggerLeave:m.useCallback(()=>{h?j():(window.clearTimeout(R.current),R.current=0)},[j,h]),onOpen:q,onClose:j,disableHoverableContent:h,children:t})})};Ra.displayName=gt;var Yt="TooltipTrigger",Ia=m.forwardRef((e,a)=>{const{__scopeTooltip:t,...s}=e,o=bt(Yt,t),y=Xt(Yt,t),f=Rt(t),$=m.useRef(null),u=Sa(a,$,o.onTriggerChange),r=m.useRef(!1),p=m.useRef(!1),T=m.useCallback(()=>r.current=!1,[]);return m.useEffect(()=>()=>document.removeEventListener("pointerup",T),[T]),n.jsx(wn,{asChild:!0,...f,children:n.jsx(vn.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...s,ref:u,onPointerMove:ot(e.onPointerMove,k=>{k.pointerType!=="touch"&&!p.current&&!y.isPointerInTransitRef.current&&(o.onTriggerEnter(),p.current=!0)}),onPointerLeave:ot(e.onPointerLeave,()=>{o.onTriggerLeave(),p.current=!1}),onPointerDown:ot(e.onPointerDown,()=>{o.open&&o.onClose(),r.current=!0,document.addEventListener("pointerup",T,{once:!0})}),onFocus:ot(e.onFocus,()=>{r.current||o.onOpen()}),onBlur:ot(e.onBlur,o.onClose),onClick:ot(e.onClick,o.onClose)})})});Ia.displayName=Yt;var Kt="TooltipPortal",[_r,hr]=$t(Kt,{forceMount:void 0}),ja=e=>{const{__scopeTooltip:a,forceMount:t,children:s,container:o}=e,y=bt(Kt,a);return n.jsx(_r,{scope:a,forceMount:t,children:n.jsx(Pa,{present:t||y.open,children:n.jsx(xn,{asChild:!0,container:o,children:s})})})};ja.displayName=Kt;var ct="TooltipContent",Fa=m.forwardRef((e,a)=>{const t=hr(ct,e.__scopeTooltip),{forceMount:s=t.forceMount,side:o="top",...y}=e,f=bt(ct,e.__scopeTooltip);return n.jsx(Pa,{present:s||f.open,children:f.disableHoverableContent?n.jsx(Da,{side:o,...y,ref:a}):n.jsx(yr,{side:o,...y,ref:a})})}),yr=m.forwardRef((e,a)=>{const t=bt(ct,e.__scopeTooltip),s=Xt(ct,e.__scopeTooltip),o=m.useRef(null),y=Sa(a,o),[f,$]=m.useState(null),{trigger:u,onClose:r}=t,p=o.current,{onPointerInTransitChange:T}=s,k=m.useCallback(()=>{$(null),T(!1)},[T]),R=m.useCallback((h,D)=>{const A=h.currentTarget,B={x:h.clientX,y:h.clientY},Y=xr(B,A.getBoundingClientRect()),ae=Cr(B,Y),q=Sr(D.getBoundingClientRect()),j=Tr([...ae,...q]);$(j),T(!0)},[T]);return m.useEffect(()=>()=>k(),[k]),m.useEffect(()=>{if(u&&p){const h=A=>R(A,p),D=A=>R(A,u);return u.addEventListener("pointerleave",h),p.addEventListener("pointerleave",D),()=>{u.removeEventListener("pointerleave",h),p.removeEventListener("pointerleave",D)}}},[u,p,R,k]),m.useEffect(()=>{if(f){const h=D=>{const A=D.target,B={x:D.clientX,y:D.clientY},Y=(u==null?void 0:u.contains(A))||(p==null?void 0:p.contains(A)),ae=!Pr(B,f);
vendor: 1,918 bytes, line 7
7Y?k():ae&&(k(),r())};return document.addEventListener("pointermove",h),()=>document.removeEventListener("pointermove",h)}},[u,p,f,r,k]),n.jsx(Da,{...e,ref:y})}),[gr,br]=$t(gt,{isInside:!1}),wr=Pn("TooltipContent"),Da=m.forwardRef((e,a)=>{const{__scopeTooltip:t,children:s,"aria-label":o,onEscapeKeyDown:y,onPointerDownOutside:f,...$}=e,u=bt(ct,t),r=Rt(t),{onClose:p}=u;return m.useEffect(()=>(document.addEventListener(Gt,p),()=>document.removeEventListener(Gt,p)),[p]),m.useEffect(()=>{if(u.trigger){const T=k=>{const R=k.target;R!=null&&R.contains(u.trigger)&&p()};return window.addEventListener("scroll",T,{capture:!0}),()=>window.removeEventListener("scroll",T,{capture:!0})}},[u.trigger,p]),n.jsx(Cn,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:y,onPointerDownOutside:f,onFocusOutside:T=>T.preventDefault(),onDismiss:p,children:n.jsxs(Sn,{"data-state":u.stateAttribute,...r,...$,ref:a,style:{...$.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[n.jsx(wr,{children:s}),n.jsx(gr,{scope:t,isInside:!0,children:n.jsx(Tn,{id:u.contentId,role:"tooltip",children:o||s})})]})})});Fa.displayName=ct;var Ea="TooltipArrow",vr=m.forwardRef((e,a)=>{const{__scopeTooltip:t,...s}=e,o=Rt(t);return br(Ea,t).isInside?null:n.jsx(An,{...o,...s,ref:a})});vr.displayName=Ea;function xr(e,a){const t=Math.abs(a.top-e.y),s=Math.abs(a.bottom-e.y),o=Math.abs(a.right-e.x),y=Math.abs(a.left-e.x);switch(Math.min(t,s,o,y)){case y:return"left";case o:return"right";case t:return"top";case s:return"bottom";default:throw new Error("unreachable")}}function Cr(e,a,t=5){const s=[];
7switch(a){case"top":s.push({x:e.x-t,y:e.y+t},{x:e.x+t,y:e.y+t});break;case"bottom":s.push({x:e.x-t,y:e.y-t},{x:e.x+t,y:e.y-t});break;case"left":s.push({x:e.x+t,y:e.y-t},{x:e.x+t,y:e.y+t});break;case"right":s.push({x:e.x-t,y:e.y-t},{x:e.x-t,y:e.y+t});break}return s}function Sr(e){const{top:a,right:t,bottom:s,left:o}=e;return[{x:o,y:a},{x:t,y:a},{x:t,y:s},{x:o,y:s}]}function Pr(e,a){const{x:t,y:s}=e;let o=!1;for(let y=0,f=a.length-1;y<a.length;f=y++){const $=a[y],u=a[f],r=$.x,p=$.y,T=u.x,k=u.y;p>s!=k>s&&t<(T-r)*(s-p)/(k-p)+r&&(o=!o)}return o}function Tr(e){const a=e.slice();return a.sort((t,s)=>t.x<s.x?-1:t.x>s.x?1:t.y<s.y?-1:t.y>s.y?1:0),Ar(a)}function Ar(e){if(e.length<=1)return e.slice();const a=[];for(let s=0;s<e.length;s++){const o=e[s];for(;a.length>=2;){const y=a[a.length-1],f=a[a.length-2];if((y.x-f.x)*(o.y-f.y)>=(y.y-f.y)*(o.x-f.x))a.pop();else break}a.push(o)}a.pop();const t=[];for(let s=e.length-1;s>=0;s--){const o=e[s];for(;t.length>=2;){const y=t[t.length-1],f=t[t.length-2];if((y.x-f.x)*(o.y-f.y)>=(y.y-f.y)*(o.x-f.x))t.pop();else break}t.push(o)}return t.pop(),a.length===1&&t.length===1&&a[0].x===t[0].x&&a[0].y===t[0].y?a:a.concat(t)}var kr=$a,Nr=Ra,$r=Ia,Rr=ja,La=Fa;const Ir=kr,zt=Nr,Vt=$r,kt=m.forwardRef(({className:e,sideOffset:a=4,...t},s)=>n.jsx(Rr,{children:n.jsx(La,{ref:s,sideOffset:a,className:kn("z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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",e),...t})}));kt.displayName=La.displayName;function jr(){return n.jsxs("div",{className:"flex items-center space-x-2 h-6",children:[n.jsxs("div",{className:"typing",children:[n.jsx("div",{className:"dot"}),n.jsx("div",{className:"dot"}),n.jsx("div",{className:"dot"})]}),n.jsx("style",{jsx:!0,children:` 8 .typing { 9 display: flex; 10 align-items: center; 11 column-gap: 5px; 12 } 13 14 .dot { 15 width: 6px; 16 height: 6px; 17 background-color: #3b82f6; 18 border-radius: 50%; 19 animation: bounce 1.5s infinite; 20 } 21 22 .dot:nth-child(1) { 23 animation-delay: 0s; 24 } 25 26 .dot:nth-child(2) { 27 animation-delay: 0.2s; 28 } 29 30 .dot:nth-child(3) { 31 animation-delay: 0.4s; 32 } 33 34 @keyframes bounce { 35 0%, 60%, 100% { 36 transform: translateY(0); 37 opacity: 0.6; 38 } 39 30% { 40 transform: translateY(-5px); 41 opacity: 1; 42 } 43 } 44 `})]})}const ga=60;function Fr(e){return!e||e<55?0:e<60?15:e<65?20:e<70?28:e<75?35:e<80?40:e<85?45:e<90?50:55}function Ma({borrowerAge:e,spouseAge:a,propertyValue:t}){const s=[e,a].filter($=>$&&$>=55),o=s.length>0?Math.min(...s):e||0,y=Fr(o),f=Math.round((t||0)*(y/100));return{decidingAge:o,maxEligiblePercentage:y,maxEligibleAmount:f}}const Dr=[{value:"help_children",label:"×¢××¨× ××××××"},{value:"supplement_income",label:"ת×ספת ××× ×¡×"},{value:"renovation",label:"ש×פ××¥ ×××ת"},{value:"healthcare",label:"××צ××ת רפ××××ת"},{value:"other",label:"××ר"}],Er=[{value:"lump_sum",label:"ס××× ××-פע××"},{value:"monthly_annuity",label:"קצ×× ×××ש×ת"},{value:"hybrid",label:"×ש××× (ס××× + קצ××)"}],Lr=[{value:"free",label:"× ×§× ×שע×××"},{value:"partial",label:"×ש×× ×ª× ×××§×ת ×§×××ת"},{value:"none",label:"×ש××¢×× ××××××"}],Mr=4,Ct="reverse_mortgage_pending",St=e=>`âª${new Intl.NumberFormat("he-IL").format(Math.round(e||0))}`,Or=e=>Ma({borrowerAge:Number(e.borrower_age),spouseAge:e.spouse_age?Number(e.spouse_age):void 0,propertyValue:Number(e.property_value_estimate)});async function ba(e,a,t,s){return K.entities.MortgageApplication.create({application_type:"reverse_mortgage",status:"pending_payment",selected_service_type:s,data_source:"manual",user_id:a.id,email:a.email,client_name:a.full_name||"",property_value:Number(e.property_value_estimate),property_location:e.property_location||null,requested_amount:e.requested_amount?Number(e.requested_amount):t.maxEligibleAmount,reverse_mortgage_details:{borrower_age:Number(e.borrower_age),spouse_age:e.spouse_age?Number(e.spouse_age):null,property_value_estimate:Number(e.property_value_estimate),property_lien_status:e.property_lien_status,payout_type:e.payout_type,requested_amount:e.requested_amount?Number(e.requested_amount):t.maxEligibleAmount,max_eligible_percentage:t.maxEligiblePercentage,purpose:e.purpose,legal_advice_status:"pending"}})}const qr=e=>e==="human"?"human_consultation_deposit":"automated_consultation";
44function wa(e,a){window.location.href=`${be("Payment")}?type=${qr(a)}&applicationId=${e}`}function Pt({children:e}){return n.jsxs("div",{className:"flex items-end gap-2 animate-enter-left",children:[n.jsx(Nt,{size:"tiny",variant:"chat"}),n.jsx("div",{className:"max-w-lg w-full rounded-2xl rounded-bl-sm bg-white border border-gray-100 shadow-sm px-4 py-3 space-y-3",children:e})]})}function Hr({isOpen:e,onClose:a,prefillData:t={},source:s="flow"}){const[o,y]=m.useState(1),[f,$]=m.useState(!1),[u,r]=m.useState({}),[p,T]=m.useState({borrower_age:t.age||"",spouse_age:"",property_value_estimate:t.property_value||"",property_location:"",property_lien_status:"",payout_type:"",purpose:"",purpose_details:"",requested_amount:""}),[k,R]=m.useState({automated:null,human:null});m.useEffect(()=>{e&&(async()=>{const g=await K.auth.me().catch(()=>null),[_,H]=await Promise.all([Qe("automated_consultation",g),Qe("human_consultation_deposit",g)]);R({automated:(_==null?void 0:_.finalPrice)??null,human:(H==null?void 0:H.finalPrice)??null})})()},[e]);const h=g=>T(_=>({..._,...g})),D=g=>r(_=>_[g]?{..._,[g]:null}:_);m.useEffect(()=>{if(!e)return;const g=(()=>{try{return sessionStorage.getItem(Ct)}catch{return null}})();if(!g)return;let _;try{_=JSON.parse(g)}catch{_=null}if(!(_!=null&&_.form)){try{sessionStorage.removeItem(Ct)}catch{}return}(async()=>{let H=null;try{H=await K.auth.me()}catch{}if(H){try{sessionStorage.removeItem(Ct)}catch{}Ae.clearAuthContext(),T(l=>({...l,..._.form})),$(!0);try{const l=Or(_.form),C=_.serviceType==="human"?"human":"automated",S=await ba(_.form,H,l,C);_t.success("×××§×©× × ××¦×¨× ××צ×××! ð ××¢×××¨× ×××ª× ×תש×××..."),wa(S.id,C)}catch(l){console.error("[ReverseMortgageFlow] resume create failed:",l),_t.error("ש×××× ××צ×רת ××קש×. ×× × × ×¡× ×©××."),$(!1)}}})()},[e]);const A=m.useMemo(()=>Ma({borrowerAge:Number(p.borrower_age),spouseAge:p.spouse_age?Number(p.spouse_age):void 0,propertyValue:Number(p.property_value_estimate)}),[p.borrower_age,p.spouse_age,p.property_value_estimate]),B=g=>{const _={};return g===1&&(p.borrower_age?Number(p.borrower_age)<ga?_.borrower_age=`×××× ×××× ${ga}+`:Number(p.borrower_age)>105&&(_.borrower_age="××× ×× ×ª×§××"):_.borrower_age="ש×× ××××",p.spouse_age&&(Number(p.spouse_age)<55||Number(p.spouse_age)>105)&&(_.spouse_age="××× ×× ×ª×§××")),g===2&&((!p.property_value_estimate||Number(p.property_value_estimate)<=0)&&(_.property_value_estimate="ש×× ××××"),p.property_lien_status||(_.property_lien_status="×ש ××××ר")),g===3&&(p.payout_type||(_.payout_type="×ש ××××ר"),p.purpose||(_.purpose="×ש ××××ר")),r(_),Object.keys(_).length===0},Y=()=>{B(o)&&y(g=>Math.min(Mr,g+1))},ae=()=>y(g=>Math.max(1,g-1)),q=async g=>{$(!0);try{let _=null;try{_=await K.auth.me()}catch{}if(!_){try{sessionStorage.setItem(Ct,JSON.stringify({form:p,source:s,serviceType:g}))}catch{}Ae.saveContextForAuth({action:"resume_reverse_mortgage",flow:"reverse_mortgage",returnToChat:!0}),_t.message("ר××¢ ××¤× × ×©× ×ש×× â צר×× ××ת××ר ××× ×ש××ר ×ת ×××§×©× ð"),await new Promise(l=>setTimeout(l,1200)),window.location.href=Ta(`${be("AuthRedirect")}?auth_completed=true`);return}const H=await ba(p,_,A,g);_t.success("×××§×©× × ××¦×¨× ××צ×××! ð ××¢×××¨× ×××ª× ×תש×××..."),wa(H.id,g)}catch(_){console.error("[ReverseMortgageFlow] create failed:",_),_t.error("ש×××× ××צ×רת ××קש×. ×× × × ×¡× ×©××."),$(!1)}},j=g=>`h-10 text-sm rounded-lg border-gray-200 bg-gray-50 focus:bg-white ${u[g]?"border-red-400 bg-red-50":""}`,N=()=>n.jsxs("div",{className:"flex gap-2 pt-1",children:[o>1?n.jsxs(nt,{type:"button",variant:"outline",onClick:ae,disabled:f,className:"h-10 text-sm rounded-lg border-gray-200 text-gray-600",children:[n.jsx(fa,{className:"w-4 h-4 ml-1"})," ××ר×"]}):n.jsx(nt,{type:"button",variant:"outline",onClick:a,disabled:f,className:"h-10 text-sm rounded-lg border-gray-200 text-gray-600",children:"×××××"}),n.jsxs(nt,{type:"button",onClick:Y,className:"flex-1 h-10 text-sm rounded-lg bg-gradient-to-l from-indigo-600 to-purple-700 hover:from-indigo-700 hover:to-purple-800 text-white font-semibold",children:["×××©× ",n.jsx($n,{className:"w-4 h-4 mr-1"})]})]});return e?o===1?n.jsxs(Pt,{children:[n.jsx("p",{className:"text-sm text-gray-700",children:"×××× ×§×××¢ ×ת ×××× ×××××ת. ×× ×ש ××/×ת ××× â ×××× ×צע×ר ×××× ××× ×§×××¢."}),n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs(at,{className:"text-xs font-semibold text-gray-700",children:["××× ××××× ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx(lt,{type:"number",value:p.borrower_age,onChange:g=>{h({borrower_age:g.target.value}),D("borrower_age")},placeholder:"70",className:j("borrower_age")}),u.borrower_age&&n.jsx("p",{className:"text-xs text-red-500",children:u.borrower_age})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx(at,{className:"text-xs font-semibold text-gray-700",children:"××× ××/×ת ××××"}),n.jsx(lt,{type:"number",value:p.spouse_age,onChange:g=>{h({spouse_age:g.target.value}),D("spouse_age")},placeholder:"×× ××××",className:j("spouse_age")}),u.spouse_age&&n.jsx("p",{className:"text-xs text-red-500",children:u.spouse_age})]})]}),n.jsx(N,{})]}):o===2?n.jsxs(Pt,{children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs(at,{className:"text-xs font-semibold text-gray-700",children:["ש××× ×× ×ס ××ש×ער (âª) ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx(lt,{type:"number",step:1e5,value:p.property_value_estimate,onChange:g=>{h({property_value_estimate:g.target.value}),D("property_value_estimate")},placeholder:"2,000,000",className:j("property_value_estimate")}),u.property_value_estimate&&n.jsx("p",{className:"text-xs text-red-500",children:u.property_value_estimate})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx(at,{className:"text-xs font-semibold text-gray-700",children:"×××§×× ×× ×ס"}),n.jsx(lt,{value:p.property_location,onChange:g=>h({property_location:g.target.value}),placeholder:"×ª× ××××, ר××× ××¨×¦× 1",className:j("property_location")})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsxs(at,{className:"text-xs font-semibold text-gray-700",children:["××¦× ×©×¢××× ×× ×ס ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsxs(Mt,{value:p.property_lien_status,onValueChange:g=>{h({property_lien_status:g}),D("property_lien_status")},children:[n.jsx(Ot,{className:j("property_lien_status"),children:n.jsx(qt,{placeholder:"××ר ×צ×"})}),n.jsx(Ht,{children:Lr.map(g=>n.jsx(Bt,{value:g.value,children:g.label},g.value))})]}),u.property_lien_status&&n.jsx("p",{className:"text-xs text-red-500",children:u.property_lien_status})]}),A.maxEligibleAmount>0&&n.jsxs("div",{className:"bg-gradient-to-br from-green-50 to-emerald-50 border border-green-200 rounded-lg p-3",children:[n.jsxs("p",{className:"text-xs text-gray-600",children:["×ער×ת ××××ת ר×ש×× ×ת (××× ×§×××¢: ",A.decidingAge,")"]}),n.jsx("p",{className:"text-2xl font-bold text-green-700",children:St(A.maxEl
44igibleAmount)}),n.jsxs("p",{className:"text-xs text-gray-500",children:["×¢× ",A.maxEligiblePercentage,"% ×ש××× ×× ×ס · ×פ××£ ×××ש×ר ××××£ ××××××"]})]}),n.jsx(N,{})]}):o===3?n.jsxs(Pt,{children:[n.jsxs("div",{className:"space-y-1",children:[n.jsxs(at,{className:"text-xs font-semibold text-gray-700",children:["ס×× ×תש××× ××××קש ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsxs(Mt,{value:p.payout_type,onValueChange:g=>{h({payout_type:g}),D("payout_type")},children:[n.jsx(Ot,{className:j("payout_type"),children:n.jsx(qt,{placeholder:"××ר ס××"})}),n.jsx(Ht,{children:Er.map(g=>n.jsx(Bt,{value:g.value,children:g.label},g.value))})]}),u.payout_type&&n.jsx("p",{className:"text-xs text-red-500",children:u.payout_type})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsxs(at,{className:"text-xs font-semibold text-gray-700",children:["××רת ××××××× ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsxs(Mt,{value:p.purpose,onValueChange:g=>{h({purpose:g}),D("purpose")},children:[n.jsx(Ot,{className:j("purpose"),children:n.jsx(qt,{placeholder:"××ר ××ר×"})}),n.jsx(Ht,{children:Dr.map(g=>n.jsx(Bt,{value:g.value,children:g.label},g.value))})]}),u.purpose&&n.jsx("p",{className:"text-xs text-red-500",children:u.purpose})]}),p.purpose==="other"&&n.jsx(Jn,{value:p.purpose_details,onChange:g=>h({purpose_details:g.target.value}),placeholder:"×¤×¨× ×ת ×××ר×...",rows:2,className:"text-sm rounded-lg border-gray-200 bg-gray-50 focus:bg-white resize-none"}),n.jsxs("div",{className:"space-y-1",children:[n.jsx(at,{className:"text-xs font-semibold text-gray-700",children:"ס××× ×××קש (âª)"}),n.jsx(lt,{type:"number",step:5e4,value:p.requested_amount,onChange:g=>h({requested_amount:g.target.value}),placeholder:A.maxEligibleAmount?String(A.maxEligibleAmount):"×× ××××",className:j("requested_amount")}),A.maxEligibleAmount>0&&n.jsxs("p",{className:"text-xs text-gray-500",children:["×קס×××× ××××ת ×ש×ער: ",St(A.maxEligibleAmount)]})]}),n.jsx(N,{})]}):n.jsxs(Pt,{children:[n.jsx("p",{className:"text-sm text-gray-700",children:"××× ×ª×¨×¦× ×©× ×××× ×××ª× ×ת××××? ××××¢××¥ ×××××××× ××× × ×ת×××× ××× ××¤× ×ת ×××פ×× ×××××××. ××××¢××¥ ××× ××©× ×תש××× ××× ×¢× ×©××ת ×××¢××¥ ××¢×××§× ×××× â × ××× ××× ×קר×, ×× ×× ×× ×ª×ש××."}),f?n.jsxs("div",{className:"flex items-center justify-center gap-2 py-8 text-gray-500",children:[n.jsx(Xn,{className:"w-5 h-5 animate-spin"})," ××צר ××§×©× ×××¢××ר ×תש×××..."]}):n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"space-y-2",children:[n.jsxs("button",{type:"button",onClick:()=>q("automated"),className:"w-full text-right rounded-xl border-2 border-indigo-200 hover:border-indigo-500 bg-indigo-50/50 hover:bg-indigo-50 p-3 transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Kn,{className:"w-5 h-5 text-indigo-600"}),n.jsx("span",{className:"font-semibold text-gray-900",children:"×××¢××¥ ×××××××"}),k.automated!=null&&n.jsx("span",{className:"mr-auto text-sm font-bold text-indigo-700",children:St(k.automated)})]}),n.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"××× × ×¤×× × ×××××××ת ×××פ×× ×××××××, ×× ××ת ×××¨× ××ש××× ×צע×ת ×¢× ××§××ת ××ש×× ×ª×."})]}),n.jsxs("button",{type:"button",onClick:()=>q("human"),className:"w-full text-right rounded-xl border-2 border-gray-200 hover:border-gray-400 bg-white p-3 transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Nn,{className:"w-5 h-5 text-gray-700"}),n.jsx("span",{className:"font-semibold text-gray-900",children:"×××¢××¥ ×× ×ש×"}),k.human!=null&&n.jsxs("span",{className:"mr-auto text-sm font-bold text-gray-700",children:[St(k.human)," תש××× ×¢× ×©××ת ×××¢××¥"]})]}),n.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"ש××ת ×××¢××¥ ××¢×××§× ×¢× ××××× ××ש×× ×ª× ×פ×××. ×תש××× ××× ×¢× ×©××ת ××××¢××¥ ×××× ×× ××× ××× ×קר×; ××× ×ת×××××ת ×××××× ×¢× ×¡××£ ×ת××××, ××××©× ×ת×××× ××××ר ××××."})]})]}),n.jsx("div",{className:"flex pt-1",children:n.jsxs(nt,{type:"button",variant:"outline",onClick:ae,disabled:f,className:"h-10 text-sm rounded-lg border-gray-200 text-gray-600",children:[n.jsx(fa,{className:"w-4 h-4 ml-1"})," ××ר×"]})})]})]}):null}function Br({active:e}){return n.jsx(Wn,{children:e&&n.jsx(ht.div,{className:"fixed inset-0 z-[60] flex items-center justify-center px-4",initial:{opacity:0}
44,animate:{opacity:1},exit:{opacity:0},transition:{duration:.4,ease:"easeOut"},style:{background:"radial-gradient(circle at 50% 45%, rgba(238,242,255,0.85) 0%, rgba(224,231,255,0.92) 100%)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:n.jsxs(ht.div,{className:"glass-card flex flex-col items-center gap-5 rounded-3xl px-8 py-8",initial:{scale:.6,opacity:0,y:20},animate:{scale:1,opacity:1,y:0},exit:{scale:.12,opacity:0,x:"40vw",y:"-44vh"},transition:{type:"spring",stiffness:120,damping:18,exit:{duration:1.1,ease:[.4,0,.2,1]}},children:[n.jsxs("div",{className:"relative flex items-center justify-center flex-shrink-0",style:{width:110,height:110},children:[n.jsx(ht.span,{className:"absolute inset-0 rounded-full bg-blue-400/25",animate:{scale:[1,1.25,1],opacity:[.35,0,.35]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),n.jsx(Nt,{size:"medium",variant:"default"})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("p",{className:"font-bold text-slate-700 text-base",children:"רק ר××¢, ×××× × ×× ×ת ×ש×××"}),n.jsx("span",{className:"flex items-center gap-1",children:[0,1,2].map(a=>n.jsx(ht.span,{className:"w-1.5 h-1.5 rounded-full bg-blue-500",animate:{opacity:[.2,1,.2]},transition:{duration:1.2,repeat:1/0,ease:"easeInOut",delay:a*.2}},a))})]})]})})})}function Ur(){return n.jsxs("div",{className:"fixed inset-0 -z-10 overflow-hidden bg-white","aria-hidden":"true",children:[n.jsxs("div",{className:"h-20 bg-white/90 border-b border-slate-100 flex items-center justify-between px-8",children:[n.jsx("img",{src:"https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/67d1ae8b9e8f1bef02d5736f/9c8255f9a_0C528E89-28BB-4164-97C4-4B521DBBDBB2.png",alt:"AskBina",className:"h-16 w-auto"}),n.jsx("div",{className:"hidden md:flex items-center gap-2",children:["××× ×","××××ר ××ש×","××ש××× ××","××××","×××¢××¥ ×× ×ש×"].map((e,a)=>n.jsx("span",{className:"text-sm text-slate-500 px-3 py-1.5",children:e},a))})]}),n.jsx("div",{className:"relative",style:{background:"linear-gradient(135deg, #1e40af 0%, #2563eb 45%, #3b82f6 100%)",height:"340px"},children:n.jsx("div",{className:"absolute bottom-0 left-0 right-0",children:n.jsx("svg",{viewBox:"0 0 1440 64",preserveAspectRatio:"none",className:"w-full h-16",children:n.jsx("path",{d:"M0,64 L1440,64 L1440,16 C1200,64 960,4 720,32 C480,60 240,8 0,32 Z",fill:"#ffffff"})})})}),n.jsx("div",{className:"absolute inset-0 bg-slate-900/75 backdrop-blur-sm"})]})}const Oa=({originalPrincipal:e,annualRate:a,originalTermInYears:t,remainingPrincipal:s})=>{if(!e||!a||!t||!s)return null;const o=a/100/12,y=t*12;if(o===0){const A=(e-s)/e*y;return{interestPaidRatio:0,totalInterest:0,interestPaidSoFar:0,loanPhase:"principal",monthsPaid:Math.round(A)}}const f=e*(o*Math.pow(1+o,y))/(Math.pow(1+o,y)-1),$=f*y-e;let u=e,r=0,p=0,T=0,k=0;for(;u>s&&p<y;){const D=u*o,A=f-D;r+=D,u-=A,p++,T=D,k=A}const R=$>0?r/$:0,h=T>k?"interest":"principal";return{interestPaidRatio:R,totalInterest:$.toFixed(2),interestPaidSoFar:r.toFixed(2),loanPhase:h,monthsPaid:p}};function qa(e){var s;const a=(s=e.tracks_analysis)==null?void 0:s.some(o=>{var y;return(y=o.individual_recommendation)==null?void 0:y.includes("××××ר")}),t=Gn().map((o,y)=>({...o,primary:y===0}));return a||t.push({id:"remind_me_later",label:"ת×××¨× ×× ×ש×××× ×××× ××××ר"}),t}const zr=async(e,a)=>{try{console.log(`processAndSaveDocupandaAnalysis: Calling backend for docId: ${e}, applicationId: ${a}`);const t=await De.analyzeDocupandaDocument({documentId:e,applicationId:a}),s=t.data||t;if(s.error_type==="wrong_document")throw new Error(`× ×¨×× ×©××¢××ת ×ס×× ×× ×ת××× ð ×× × ××¢×× ×ס×× "×תר×ת ×ס××××§" ×××× ×§ ש×× (×× ××ש×ר × ×××× ×ש×××, ×× ××£ ×ש××× ×××').`);const o=s.summary_recommendation||"";return console.log("â
Received analysis from backend:",s),await Te.Document.update(e,{analysis_results:s}),{analysis:s,chatResponse:o}}catch(t){throw console.error("Error processing and saving Docupanda anal
44ysis to document:",t),t}},Qt=async(e,a,t,s,o,y,f,$,u)=>{var r,p;try{const T=(r=e.find(N=>parseFloat(N.monthly_income)>0))==null?void 0:r.monthly_income,k=parseFloat(T)||parseFloat((p=s.applicationData)==null?void 0:p.monthly_income)||0,h=e.map(N=>({track_name:N.track_name||"×ש×× ×ª× ×§×××ת",balance:parseFloat(N.balance)||0,interest_rate:parseFloat(N.interest_rate)||0,remaining_term_years:parseFloat(N.remaining_term_years)||0,monthly_payment:parseFloat(N.monthly_payment)||0,repayment_fee:parseFloat(N.repayment_fee)||parseFloat(N.early_repayment_fee)||0})).filter(N=>N.balance>0&&N.interest_rate>0&&N.remaining_term_years>0);if(h.length===0){o(a,{content:"×× ×צ×××ª× ××¢×× ×ת ×× ×ª×× ×× ð ×××× ××××× ×©××××× ×ש××ת ××ר×ש××: ××ª×¨× ×ס××××§, ר×××ת ×©× ×ª×ת ×תק××¤× × ×תר×.",isLoading:!1,options:[{id:"restart_manual_input",label:"×× ×¡×ת ש××"},{id:"schedule_call_refinance",label:"ש××× ×¢× ×××¢×¥ ×× ×ש×"}],context:s}),y(!1);return}const D=h.map(N=>{if(N.monthly_payment===0&&N.balance>0&&N.interest_rate>0&&N.remaining_term_years>0){let g=er(N.balance,N.interest_rate,N.remaining_term_years);return{...N,monthly_payment:isNaN(g)||!isFinite(g)?0:g}}return N});let A=s.applicationId;if(!A){console.log("[Chat] Creating MortgageApplication for manual refinance");const N=typeof localStorage<"u"?localStorage.getItem("ref_agent_code"):null;let g=null;if(N)try{const{base44:H}=await it(async()=>{const{base44:C}=await import("./index-CcMLSBG6.js").then(S=>S.bB);return{base44:C}},__vite__mapDeps([0,1])),l=await H.entities.AgentLink.filter({link_code:N,is_active:!0});l!=null&&l[0]&&(g=l[0].agent_id)}catch{}A=(await Te.MortgageApplication.create({client_name:(t==null?void 0:t.full_name)||"",email:(t==null?void 0:t.email)||"",phone:(t==null?void 0:t.phone)||"",application_type:"refinance",status:"draft",data_source:"manual",user_id:(t==null?void 0:t.id)||"",...g&&{agent_id:g}})).id,f(H=>({...H,applicationId:A}))}console.log("[Chat] Calling analyzeManualTracks backend...");const B=await De.analyzeManualTracks({tracks:D,applicationId:A}),Y=B.data||B;if(console.log("[Chat] Backend analysis result:",Y),!Y||!Y.tracks_analysis)throw new Error("× ×ת×× ×××§×× × ×× ××××ר ת×צ××ת ×××× × ×צפ××.");const ae=Y.tracks_analysis.reduce((N,g)=>N+(g.balance||0),0),q=Y.tracks_analysis.reduce((N,g)=>N+(g.monthly_payment||0),0);if(A&&k>0)try{await Te.MortgageApplication.update(A,{monthly_income:k})}catch(N){console.error("Failed to update monthly_income:",N)}const j={...s,applicationId:A,originalTracks:D,step:"manual_data_collected",initialAnalysis:Y,applicationData:s.applicationData};o(a,{content:"×× × × ×ת×× ×¨×ש×× × ×©× ××¦× ××ש×× ×ª× ×©××:",isLoading:!1,renderManualRefinanceForm:!1,renderComponents:{summaryCardProps:{analysis:Y,onOptionSelected:$,hideButtons:!0},collapsibleTracksSectionProps:{analysis:Y}},options:[],context:j}),f(j),setTimeout(()=>{var _;const g=((_=Y.tracks_analysis)==null?void 0:_.some(H=>{var l;return(l=H.individual_recommendation)==null?void 0:l.includes("××××ר")}))?"×¢×ש×× ××× × ××××§ ×××× ××××× ××× ×ת×××:":"×¢×××× ×ש ××§×× ×שק×× ×©×× ×××× ××ת×× ×צר×××. ×× ××¢× ×××?";u&&u(g,qa(Y),!1,null,!1,!1,null,j,!1,!1,!1,Date.now()+Math.random(),null,!1)},3500)}catch(T){console.error("Error in continueManualRefinanceAnalysis:",T),o(a,{content:`×××¨×¢× ×©×××× ×× ×ת×× ×× ×ª×× ××. ×פשר ×× ×¡×ת ש×× ×× ××¤× ×ת ×ת××××. פר×× ×ש××××: ${T.message}`,isLoading:!1,options:[{id:"schedule_call_refinance",label:"ש××× ×¢× ×××¢×¥ ×× ×ש×"},{id:"restart_chat",label:"×ת××ת ש××× ××ש×"}],context:s})}finally{y(!1)}},Vr={Payment:"××£ ×תש××× ×××××××",Registration:"×ש××ת פר××× ××ש×××",Schedule:"ת×××× ×¤×××©× ×××××",CollectDocuments:"××¢××ת ×ס××××",Dashboard:"××××ר ×××ש×",Simulation:"ס××××××ר ××ש×× ×ª×",MyOffers:"××צע×ת ש××",MortgageDetails:"פר×× ××ש×× ×ª×",Auth:"×ת××ר×ת/×רש××"},Gr=({navigate:e,context:a,addMessage:t,toast:s,setIsLoading:o,getBankDisplayName:y,messages:f,updateMessage:$,setContext:u,setShowRedirectAnimation:r,setRedirectTarget:p,setShowWaitingScreen:T,setWaitingScreenMode:k,setCashOutCalculator:R,setNextAction:h,handleOptionSelected:D,redirectToAuth:A})=>async B=>{if(!B)return;const Y=B.delay||2e3,{type:ae,targetPage:q,paymentType:j,applicationId:N,bank:g}=B;switch(o(!0),ae){case"REDIRECT_TO_AUTH_FOR_PAYMENT":p("Auth"),setTimeout(async()=>{A(`${be("AuthRedirect")}?auth_completed=true`)},Y);break;case"INITIATE_PAYMENT_FLOW":if(p("Payment"),a.applicationId){const _={};a.selected_service_type&&(_.selected_service_type=a.selected_service_type),a.refinance_goal&&(_.refinance_goal=a.refinance_goal),a.selected_scenario_details&&(_.selected_scenario_details=a.selected_scenario_details);const H=a.applicationData||{};if(["monthly_income","property_value","loan_amount","client_name","email","phone","application_type","property_location","property_type","down_payment","employment_type","down_payment_percentage","monthly_expenses"].forEach(C=>{H[C]!==void 0&&(_[C]=H[C])}),Object.keys(_).length>0)try{await Te.MortgageApplication.update(a.applicationId,_)}catch(C){console.error("[Chat] â Failed to save application details:",C),s({title:"ש×××ת ש××ר×",description:"×צ××× × ×××¢××ר ×××ª× ×תש×××, ×× × ×ª×§×× × ×××¢×× ×ש××רת ×××ר×ת××.",variant:"destructive",duration:5e3})}}await K.auth.isAuthenticated()?setTimeout(()=>{r(!1);const H=a.applicationId?`&applicationId=${a.applicationId}`:"",l=`${be("Payment")}?type=${j}${H}`;e(l,{state:{paymentType:j,applicationId:a.applicationId,fromChat:!0}})},Y):(Ae.saveContextForAuth({action:"payment",targetPage:"Payment",paymentType:j,applicationId:a.applicationId,applicationData:a==null?void 0:a.applicationData,originalTracks:a==null?void 0:a.originalTracks,refinanceGoal:a.refinance_goal,selectedScenarioDetails:a.selected_scenario_details,requiresRegistration:!1,returnToChat:!1,redirectToPayment:!0}),setTimeout(async()=>{r(!1),A(`${be("AuthRedirect")}?auth_completed=true`)},Y));break;case"REDIRECT_TO_PAGE":{const _=Vr[q]||q;if(p(_),Rn(q)){t(`××¢×××¨× ×××ª× ×× ${_}... â©`,"bot"),setTimeout(()=>{r(!1),e(be(q)+(B.params||""))},Y);break}let H=!1;try{await K.auth.me()}catch{if(q!=="Registration"){const C=`${be("AuthRedirect")}?auth_completed=true`;t(`××× ××שת ×${_}, ×ש ××ת××ר ×× ××צ×ר ×ש××× ð`,"bot",[{id:"auth_register",label:"×צ×רת ×ש×××",returnTo:C},{id:"auth_login",label:"×× ××¡× ××ש×××",returnTo:C}]),Ae.saveContextForAuth({action:"redirect_to_page",redirectTo:q,applicationId:a.applicationId,returnToChat:!1,redirectToPayment:!1,returnState:{chatContext:a}}),r(!1),H=!0}}H?r(!1):(t(`××¢×××¨× ×××ª× ×× ${_}... â©`,"bot"),setTimeout(()=>{r(!1),e(be(q)+(B.params||""))},Y));break}case"SHOW_WAITING_THEN_CASH_OUT":T(!0),k(B.waitingMode||"analyzing_mortgage"),setTimeout(()=>{T(!1),r(!1);const _=a.preservedData||{};R({currentBalance:_.estimatedCurrentBalance||0,propertyValue:_.property_value||0,initialData:_}),o(!1)},Y);break;case"AUTHENTICATE_AND_UPLOAD":p("Auth");try{await K.auth.me(),r(!1),p(null);{const _=await y(g);t(`××¢×××! ×¢×ש×× ×פשר ×××¢××ת ×ת ×ס×× "×תר×ת ×ס××××§" ×${_}.`,"bot",[],!0,null,!1,!1,null,{...a,bank:g,step:"awaiting_upload"}),u(H=>({...H,bank:g}))}}catch{const H=`${be("AuthRedirect")}?auth_completed=true`;t("××× ×××ש×× ××××¢××ת ×ס××××, ×ש ××ת××ר ת×××× ð פר×× ×ת×××× × ×©×ר×.","bot",[{id:"auth_register",label:"×צ×רת ×ש×××",returnTo:H},{id:"auth_login",label:"×× ××¡× ××ש×××",returnTo:H}]),Ae.saveContextForAuth({action:"prompt_for_upload",bank:g,flow:a.flow||"refinance",returnToChat:!0,redirectToPayment:!1,returnState:{messages:f.filter(l=>!l.isLoading),currentContext:{...a,bank:g}}})}break;case"function":try{const _=await B();_&&(t(_.message,_.sender||"bot",_.options||[],_.showUpload||!1,_.formFields||null,_.isSilent||!1,_.isLoading||!1,_.renderComponents||null,_.context||a,_.renderManualRefinanceForm||!1,_.renderInteractiveSlider||!1,_.showHint||!1,Date.now(),_.nextAction||null,_.specialType||null),_.context&&u(_.context),_.nextAction&&h(_.nextAction))}catch(_){console.error("Error executing nextAction (function):",_),t("×××¨×¢× ×©×××× ××¢××××. × × ×¡× ××××ר ××תר.","bot",[],!1,null,!1,!1,null,a)}r(!1),p(null);break;default:console.warn("[Chat] â ï¸ Unknown next action type for redirect:",ae),r(!1),p(null)}o(!1)},Yr=({searchParams:e,getBankDisplayName:a,context:t,addMessage:s,updateMessage:o,setIsLoading:y,setContext:f,handleOptionSelected:$,addBotMessage:u,setMessages:r,setHasStarted:p,setShowInitialHelpText:T,setNextAction:k})=>async()=>{var D,A,B,Y,ae,q,j;if(!e.get("auth_completed"))return;const h=Ae.getContextForAuth();if(h){if(Ae.clearAuthContext(),h.action==="open_agent_application"&&h.applicationId){setTimeout(async()=>{var N;try{const g=await K.auth.me(),_=await K.entities.MortgageApplication.get(h.applicationId);if(_&&g){_.user_id||(await K.entities.MortgageApplication.update(h.applicationId,{user_id:g.id}),sessionStorage.removeItem(`active_app_check_${g.id}`));const H=h.flow||(_.application_type==="refinance"?"refinance":"new_mortgage"),l=_.application_type==="refinance"?"××××ר ×ש×× ×ª×":"×ש×× ×ª× ××ש×",C=((N=g.full_name)==null?void 0:N.split(" ")[0])||"",S=C?`ש××× ${C}! `:"ש×××! ",re={flow:H,applicationId:h.applicationId,step:"start",agentApplication:!0}
44;f(re),p(!0),T(!1),s(`${S}×ס××× ×¤×ª× ×¢×××¨× ×קשת ${l}. ×פשר ×××ש×× ××× ð `,"bot",[{id:H==="refinance"?"refinance_prompt":"new_mortgage_prompt",label:"â ×ת××ת ×ת××××",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],!1,null,!1,!1,null,re)}}catch(g){console.error("[ChatAuthRedirectHandler] Error loading agent application:",g)}},500);return}if(h.action==="submit_new_mortgage_form"&&h.formData){const N=await K.auth.me(),g=h.formData,_=((D=h.returnState)==null?void 0:D.currentContext)||t,{property_price:H,...l}=g,C={...l,property_value:H,application_type:g.application_type||"new_mortgage",email:N.email||g.email||null,client_name:g.firstName&&g.lastName?`${g.firstName} ${g.lastName}`:null,user_id:N.id},S=await K.entities.MortgageApplication.create({...C,status:"pending_payment"});try{const ye=localStorage.getItem("ref_agent_lead_id"),J=localStorage.getItem("ref_agent_code");ye&&K.entities.AgentLead.update(ye,{application_id:S.id,lead_type:"application",status:"qualified"}).catch(()=>{}),J&&K.entities.AgentLink.filter({link_code:J,is_active:!0}).then(Ce=>{Ce!=null&&Ce[0]&&K.entities.MortgageApplication.update(S.id,{agent_id:Ce[0].agent_id}).catch(()=>{})}).catch(()=>{})}catch{}const re={..._,applicationId:S.id,applicationData:C,step:"awaiting_risk_preference"};if(r(((A=h.returnState)==null?void 0:A.messages)||[]),p(!0),T(!1),f(re),_.human_advisory_mode){const ye=e.get("slot_id")||"",J=`${be("Schedule")}?confirmed=true${ye?`&slotId=${ye}`:""}&human_advisory=true`,Ce={...re,step:"data_saved_for_human_advisor"};f(Ce),s("ת××× ×¢× ×× ×ª×× ××. ש××¨×ª× ×ת פר×× ×××§×©× ××פשר ××××ר ××§××עת ×פ××ש×.","bot",[{id:"go_to_schedule_final",label:"ð ×××ר ××§××עת ×פ××ש×",primary:!0,_scheduleUrl:J}],!1,null,!1,!1,null,Ce);return}s(`ת××× ×¢× ×× ×ª×× ××! ð ס××× ××ש×× ×ª×: ${C.loan_amount?`${Number(C.loan_amount).toLocaleString("he-IL")} âª`:"× ×§××"} . 45 46××¤× × ×©××× × ×ת ×ת×××××× â ש××× ×§×¦×¨×: ×× ×ש×× ×× ××תר ××ש×× ×ª×?`,"bot",[{id:"pref_conservative",label:"ð¡ï¸ ×צ×××ת â ×××ר ×§×××¢ ×××××, ×× ×× ×קר ××תר",primary:!0},{id:"pref_moderate",label:"âï¸ ××××× â ש×××× ××× ×צ×××ת ××××ש×ת"},{id:"pref_aggressive",label:"ð¸ ××ס××× ×קס×××× â פ××ת ×סף ××××, ×× ×× ××××ר ××©×ª× ×"}],!1,null,!1,!1,null,re);return}if(h.action==="prompt_for_upload"&&h.bank){setTimeout(async()=>{var _;const N=await a(h.bank),g=((_=h.returnState)==null?void 0:_.currentContext)||t;if(h.flow==="prepayment"){let H=g.applicationId;if(!H)try{const C=await K.auth.me();H=(await K.entities.MortgageApplication.create({client_name:C.full_name||"",email:C.email||"",application_type:"refinance",is_prepayment_refinance:!0,current_bank_name:N,status:"draft",data_source:"file_upload",user_id:C.id})).id}catch(C){console.error("[ChatAuthRedirectHandler] Error creating prepayment application:",C)}const l={...g,bank:h.bank,bankDisplayName:N,flow:"prepayment",step:"prepayment_amount_selection",applicationId:H};s(`××¢×××! ð¸ ×ת××רת ××צ×××. 47 48××× ×סף ×ש ×× ×××× ×פרע×× ×${N}?`,"bot",[],!1,null,!1,!1,{prepaymentAmountSlider:{minAmount:1e4,maxAmount:3e6}},l),f(l);return}s(`××¢×××! ð ×¢×ש×× ×פשר ×××¢××ת ×ת ×ס×× "×תר×ת ×ס××××§" ×${N}.`,"bot",[],!0,null,!1,!1,null,{...g,bank:h.bank,bankDisplayName:N,step:"awaiting_upload"}),f(H=>({...H,bank:h.bank,bankDisplayName:N,step:"awaiting_upload"}))},500);return}if((B=h.returnState)!=null&&B.messages&&h.returnState.messages.length>0&&(r(h.returnState.messages),p(!0),T(!1)),(Y=h.returnState)!=null&&Y.currentContext&&f(h.returnState.currentContext),h.redirectToPayment&&h.applicationId){(ae=h.returnState)!=null&&ae.messages&&h.returnState.messages.length>0&&(r(h.returnState.messages),p(!0),T(!1)),(q=h.returnState)!=null&&q.currentContext&&f(h.returnState.currentContext),setTimeout(()=>{k({type:"INITIATE_PAYMENT_FLOW",targetPage:"Payment",paymentType:h.paymentType||"automated_consultation",applicationId:h.applicationId,delay:1e3})},500);return}if(h!=null&&h.returnToChat&&h.action==="continue_manual_refinance"&&h.tracks){const N=Date.now();s("××ש××× ×× ×ת×× ××ש×× ×ª× ×©××...","bot",[],!1,null,!1,!0,null,((j=h.returnState)==null?void 0:j.currentContext)||t,!1,!1,!1,N),y(!0),setTimeout(async()=>{var g;try{const _=await K.auth.me();await Qt(h.tracks,N,_,((g=h.returnState)==null?void 0:g.currentContext)||t,o,y,f,$,u)}
48catch(_){console.error("[Chat] Error continuing manual refinance:",_),o(N,{content:"×××¨×¢× ×©×××× ×× ×ת××. × ×¡× ×©××.",isLoading:!1}),y(!1)}},1e3)}}},ce=e=>{if(typeof e=="number")return e;if(e==null||String(e).trim()==="")return null;const a=String(e).replace(/âª/g,"").replace(/,/g,"").replace("%","").trim(),t=parseFloat(a);return isNaN(t)?null:t},Ha=e=>{if(console.log("=== Starting Hapoalim Data Extraction (v3 - Prime Detection) ==="),!e||e.length===0)return console.error("Hapoalim: Invalid or empty standardized data array received."),{tracks:[],accountHolder:null};const a=[];let t=null;return e.forEach((s,o)=>{var f,$;!t&&((f=s==null?void 0:s.data)!=null&&f.accountHolder)&&(t=s.data.accountHolder);const y=($=s==null?void 0:s.data)==null?void 0:$.loans;if(!y||!Array.isArray(y)){console.warn(`Hapoalim: No 'loans' array found in document ${o+1}. Skipping.`);return}y.forEach(u=>{var D;const r=ce(u.principal),p=ce(u.outstandingBalance);if(r===null||r<=0){console.log(`Hapoalim: Skipping loan ${u.loanNumber} due to zero or missing principal balance.`);return}const T=ce(u.earlyRepaymentFee)||0;let k=null;if(u.loanExecutionDate&&u.expectedLastPaymentDate)try{const A=new Date(u.loanExecutionDate),B=new Date(u.expectedLastPaymentDate);!isNaN(A.getTime())&&!isNaN(B.getTime())&&(k=(B.getFullYear()-A.getFullYear())*12+(B.getMonth()-A.getMonth()))}catch(A){console.error("Could not parse dates for Hapoalim loan",A)}const R=(D=u.interestRateBasis)!=null&&D.includes("P")?"פר×××":u.interestType,h={track_name:u.loanNumber||"×ס××× ×× ×××××",balance:p||r,payoff_balance:p||r,monthly_payment:ce(u.monthlyPayment),interest_rate:ce(u.nominalInterestRateAsOfThisLetter),original_principal:ce(u.originalLoanAmount),end_date:u.expectedLastPaymentDate,start_date:u.loanExecutionDate,repayment_fee:T,original_term_months:k,track_type:R,linkage_type:u.indexationBasis};a.push(h)})}),console.log(`Hapoalim extraction v3 complete. Found a total of ${a.length} tracks. Account Holder: ${t||"Unknown"}`),{tracks:a,accountHolder:t}},Ba=e=>{if(console.log("=== Starting Mizrahi Data Extraction (v33 - Robust Interest Rate) ==="),!e||e.length===0)return console.error("Mizrahi: Invalid or empty standardized data received."),{tracks:[],accountHolder:null};const a=[];let t=null;return e.forEach((s,o)=>{var $,u;!t&&(($=s==null?void 0:s.data)!=null&&$.accountHolder)&&(t=s.data.accountHolder);const y=(u=s==null?void 0:s.data)==null?void 0:u.mortgageLines;if(!y||!Array.isArray(y)){console.warn(`Mizrahi: No mortgageLines found in document ${o+1}. Skipping.`);return}const f=y.map(r=>{const p=r.interestType||r.loanPartName||"";if(p.includes("×¡× ×××")||p.includes('ס×"×')||p.includes("ס××")||p.toLowerCase().includes("total"))return null;const T=ce(r.principalBalance)||0,k=ce(r.settlementAmountForThisPart)||0,R=T;if(!p&&R<=0||R<=0)return null;const h=ce(r["ש××¢×ר ×ר×××ת"])||ce(r["ש××¢×ר ×ר×××ת ××××§ ××"])||ce(r.interestRateInThisPart)||null;let D=0;return k>0&&T>0&&k>T&&(D=k-T),{track_name:p,balance:R,monthly_payment:ce(r.monthlyChargeForThisPart),interest_rate:h,original_principal:ce(r.amountAtExecution),end_date:r.loanEndDate,start_date:r.executionDate,repayment_fee:D}}).filter(Boolean);a.push(...f),console.log(`Mizrahi: Processed standardized document ${o+1}, found ${f.length} valid tracks.`)}),console.log(`Mizrahi extraction v33 complete. Found a total of ${a.length} tracks. Account Holder: ${t||"Unknown"}`),{tracks:a,accountHolder:t}},Ua=e=>{if(console.log("=== Starting Leumi Data Extraction (v8 - Correct Fee Calculation) ==="),!e||e.length===0)return console.error("Leumi: Invalid or empty standardized data received."),{tracks:[],accountHolder:null};const a=[];let t=null;return e.forEach((s,o)=>{var f,$;!t&&((f=s==null?void 0:s.data)!=null&&f.accountHolder)&&(t=s.data.accountHolder);const y=($=s==null?void 0:s.data)==null?void 0:$.loans;if(!y||!Array.isArray(y)){console.warn(`Leumi: No 'loans' array found in document ${o+1}. Skipping.`);return}y.forEach(u=>
48{!u.subLines||u.subLines.length===0||u.subLines.forEach(r=>{const p=r.remainingBalanceForRepayment;if(!p)return;const T=ce(p.principalBalance);if(T===null||T<=0)return;let k=0;const R=ce(p.totalBalanceForRepayment);R!==null&&R>T&&(k=R-T);let h=null;if(r.issueDate&&r.endDate)try{const A=new Date(r.issueDate),B=new Date(r.endDate);!isNaN(A.getTime())&&!isNaN(B.getTime())&&(h=(B.getFullYear()-A.getFullYear())*12+(B.getMonth()-A.getMonth()))}catch(A){console.error("Could not parse dates for Leumi sub-line",A)}const D={track_name:`${u.loanNumber} (×§× ${r.subSectionNumber})`,balance:T,monthly_payment:ce(r.monthlyPayment),interest_rate:ce(r.annualInterestRate),original_principal:ce(r.amount),end_date:r.endDate,start_date:r.issueDate,repayment_fee:k,original_term_months:h,track_type:r.interestType,linkage_type:r.indexationBasis};a.push(D)})})}),console.log(`Leumi extraction v8 complete. Found a total of ${a.length} tracks. Account Holder: ${t||"Unknown"}`),{tracks:a,accountHolder:t}},Jr=e=>{if(console.log("=== Starting Jerusalem Data Extraction ==="),!e||e.length===0)return console.error("Jerusalem: Invalid or empty standardized data received."),{tracks:[],accountHolder:null};const a=[];let t=null;return e.forEach((s,o)=>{const y=(s==null?void 0:s.data)||s;!t&&(y!=null&&y.customerName)&&(t=y.customerName);const f=y==null?void 0:y.loans;if(!f||!Array.isArray(f)){console.warn(`Jerusalem: No loans array found in document ${o+1}. Skipping.`);return}const $=f.map(u=>{const r=ce(u.principalBalance);if(!r||r<=0)return null;const p=ce(u.totalPayoff);let T=0;p!==null&&p>r&&(T=p-r);const k=ce(u.currentInterestRate);if(!k||k<=0)return null;let R=null;const h=u.executionDate,D=u.endDate;if(h&&D)try{const A=new Date(h),B=new Date(D);!isNaN(A.getTime())&&!isNaN(B.getTime())&&(R=(B.getFullYear()-A.getFullYear())*12+(B.getMonth()-A.getMonth()))}catch(A){console.error("Could not parse dates for Jerusalem loan",A)}return{track_name:u.loanNumber||"×ס××× ×× ×××××",balance:r,monthly_payment:ce(u.lastPaymentAmount),interest_rate:k,original_principal:ce(u.originalAmount),end_date:D,start_date:h,repayment_fee:T,original_term_months:R,track_type:u.interestType||u.loanType,linkage_type:u.indexationMethod}}).filter(Boolean);a.push(...$),console.log(`Jerusalem: Processed doc ${o+1}, found ${$.length} valid tracks.`)}),console.log(`Jerusalem extraction complete. Found a total of ${a.length} tracks. Account Holder: ${t||"Unknown"}`),{tracks:a,accountHolder:t}},za=e=>{if(console.log("=== Starting Discount Data Extraction (v4 - New Detailed Schema) ==="),!e||e.length===0)return console.error("Discount: Invalid or empty standardized data received."),{tracks:[],accountHolder:null};const a=[];let t=null;return e.forEach((s,o)=>{var $,u;!t&&(($=s==null?void 0:s.data)!=null&&$.accountHolder)&&(t=s.data.accountHolder);const y=(u=s==null?void 0:s.data)==null?void 0:u.loans;if(!y||!Array.isArray(y)){console.warn(`Discount: No 'loans' array found in document ${o+1}. Skipping.`);return}const f=y.map(r=>{var D,A,B,Y,ae,q,j,N,g,_,H,l;const p=ce((D=r.amountDetails)==null?void 0:D.principalBalance);if(!p||p<=0)return console.log(`Discount: Skipping track ${r.loanNumber} due to zero or missing principal balance.`),null;if(p<500)return console.log(`Discount: Skipping track ${r.loanNumber} due to very small balance (âª${p}).`),null;const T=ce((A=r.interestDetails)==null?void 0:A.annualInterestRate);if(!T||T<=0)return console.log(`Discount: Skipping track ${r.loanNumber} due to zero or missing interest rate.`),null;const k=ce((B=r.amountDetails)==null?void 0:B.totalBalance);let R=0;k!==null&&k>p&&(R=k-p);let h=null;if((Y=r.dateDetails)!=null&&Y.issueDate&&((ae=r.dateDetails)!=null&&ae.lastPaymentDate))try{const C=new Date(r.dateDetails.issueDate),S=new Date(r.dateDetails.lastPaymentDate);!isNaN(C.getTime())&&!isNaN(S.getTime())&&(h=(S.getFullYear()-C.getFullYear())*12+(S.getMonth()-C.getMonth()))}catch(C){console.error("Could not parse dates for Discount track",C)}return{track_name:r.loanNumber||"×ס××× ×× ×××××",balance:p,monthly_payment:ce((q=r.amountDetails)==null?void 0:q.lastPaymentAmount),interest_rate:ce((j=r.interestDetails)==null?void 0:j.annualInterestRate),original_principal:ce((N=r.amountDetails)==null?void 0:N.originalAmount),end_date:(g=r.dateDetails)==null?void 0:g.lastPaymentDate,start_date:(_=r.dateDetails)==null?void 0:_.issueDate,repayment_fee:R,original_term_months:h,track_type:(H=r.generalDetails)==null?void 0:H.interestType,linkage_type:(l=r.interestDetails)==null?void 0:l.indexationBasis}}
48).filter(Boolean);a.push(...f),console.log(`Discount: Processed doc ${o+1}, found ${f.length} valid tracks.`)}),console.log(`Discount extraction v4 complete. Found a total of ${a.length} tracks. Account Holder: ${t||"Unknown"}`),{tracks:a,accountHolder:t}},Xr=e=>new Promise((a,t)=>{const s=new FileReader;s.readAsDataURL(e),s.onload=()=>a(s.result),s.onerror=o=>t(o)}),Kr=["completed","processed","processed.success"],Qr=async(e,a)=>{var y,f,$,u;let t=0;const s=30,o=5e3;for(;t<s;){try{const r=await a({documentId:e}),p=(f=(y=r==null?void 0:r.data)==null?void 0:y.document)==null?void 0:f.status;if(Kr.includes(p)||((u=($=r==null?void 0:r.data)==null?void 0:$.document)==null?void 0:u.localStatus)==="completed")return console.log(`[pollSingleDocument] Doc ${e} ready with status: ${p}`),e}catch(r){console.error(`Error polling for doc ${e}`,r)}t++,await new Promise(r=>setTimeout(r,o))}throw new Error(`Timeout polling for document ${e}`)},va=async(e,a,t,s,o,{checkDocumentStatus:y,updateMessage:f,addBotMessage:$,setIsLoading:u,setContext:r,setShowWaitingScreen:p,setWaitingScreenMode:T,setWaitingScreenProgress:k})=>{var h,D,A,B,Y,ae,q,j;window.isLongProcessRunning=!0,p(!0),T("analyzing_mortgage"),k(0);let R;try{const N=await Te.RefinanceSchema.filter({bank_name:a});if(N&&N.length>0)R=N[0];else throw new Error(`Schema for bank "${a}" not found.`)}catch(N){console.error("Could not fetch schema for bank:",a,N),f(t,{content:`ש××××: ×× × ×צ×× ×ª×¦××¨× ×¢××ר ×× ×§ "${a}".`,isLoading:!1}),window.isLongProcessRunning=!1,p(!1);return}try{k(10);const N=Array.from(e).map(async M=>{const w=await Xr(M);return await De.uploadToDocupanda({file:w,filename:M.name,documentType:"mortgage",documentSubtype:"loan_payoff_statement",bank:a,applicationId:s})}),g=await Promise.all(N);k(30);const _=g.map(M=>({docupandaId:M.data.data.docupandaId,recordId:M.data.data.documentId}));for(const M of _)await Qr(M.recordId,y);k(50);const H=R.schema_id,C=(await De.processMizrahiStandardization({documentIds:_.map(M=>M.recordId),schemaId:H})).data.jobId;k(60);let S="processing",re=0;for(;S==="processing"&&re<30;){const M=Math.min(88,60+re*1.2);k(M);const w=await De.checkStandardizationJobStatus({jobId:C,documentIds:_.map(v=>v.recordId)});if((h=w==null?void 0:w.data)!=null&&h.status&&(S=w.data.status),S==="processing"){re++;for(let v=0;v<10;v++)await new Promise(x=>setTimeout(x,1e3)),k(Math.min(88,M+v*.3))}}k(90);const ye=await De.getMizrahiStandardizationResult({documentIds:_.map(M=>M.recordId)});let J;switch(a){case"mizrahi":J=Ba(ye.data.results);break;case"discount":J=za(ye.data.results);break;case"leumi":J=Ua(ye.data.results);break;case"hapoalim":J=Ha(ye.data.results);break;default:J={tracks:[],accountHolder:null}}const Ce=J.tracks||J,je=J.accountHolder;if(!Ce||Ce.length===0){p(!1),f(t,{content:"×× ×צ×××ª× ××××¥ × ×ª×× ×× ×××ס××. ×××× ××××ת ש×× ×× ××× ×תר×ת ×ס××××§ ×× ×©××ס×× ×× ×ª×§××. ×× × × ×¡× ×××¢××ת ××× ××ר.",isLoading:!1,options:[{id:"retry_upload",label:"ð × ×¡× ×©××"}]}),u(!1),window.isLongProcessRunning=!1;return}const Ee=((ae=(Y=(B=(A=(D=ye.data)==null?void 0:D.results)==null?void 0:A[0])==null?void 0:B.data)==null?void 0:Y.bankName)==null?void 0:ae.toLowerCase())||"",Oe=a.toLowerCase();if(Ee&&!Ee.includes(Oe)&&!Oe.includes(Ee)){p(!1),f(t,{content:`â ï¸ ××× ×ס×× ×©× ×× ×§ "${Ee}" ××× ××רת "${a}". ×× × ××××§ ×× ×¡× ×××¢××ת ×ת ×××× ×× ×××.`,isLoading:!1,options:[{id:"retry_upload",label:"ð × ×¡× ×©××"}]}),u(!1),window.isLongProcessRunning=!1;return}if(je&&o.clientName){const M=je.toLowerCase().trim(),w=o.clientName.toLowerCase().trim();if(!M.includes(w.split(" ")[0])&&!w.includes(M.split(" ")[0])){p(!1),f(t,{content:`â ï¸ ×©× ××¢× ××ש××× ×××× ("${je}") ×× ×ª××× ×ש×× ("${o.clientName}"). ×××× ××××ת ש××¢××ת ××× ×©× ××× ××ר. ×× × ××××§ ×× ×¡× ×©××.`,isLoading:!1,options:[{id:"retry_upload",label:"ð × ×¡× ×©××"}]}),u(!1),window.isLongProcessRunning=!1;return}}k(95);const we=Ce.map(M=>{let w=null;M.original_principal>0&&M.interest_rate!==null&&M.original_term_months>0&&M.balance>=0&&(w=Oa({originalPrincipal:M.original_principal,annualRate:M.interest_rate,originalTermInYears:M.original_term_months/12,remainingPrincipal:M.balance}));let v=0;if(M.end_date){const x=new Date(M.end_date),E=new Date,ie=(x.getFullYear()-E.getFullYear())*12+(x.getMonth()-E.getMonth());v=Math.max(0,ie)}else M.original_term_months&&(v=Math.round(M.original_term_months));return{...M,stageInfo:w,remaining_months:v}});if(!o.prepaymentAmount||o.prepaymentAmount<=0){$("ס××× ×פרע×× ×× ××××ר. ×× × ×××ר ש×× ××× ××××ר ×××ר ס××× ×ª×§×£.",[{id:"prepayment_prompt",label:"×××¨× ××××רת ס×××"}]),u(!1),window.isLongProcessRunning=!1,p(!1);return}
48const te=await De.analyzePrePaymentStrategy({availableAmount:o.prepaymentAmount,tracks:we});if(k(100),!((q=te==null?void 0:te.data)!=null&&q.strategy)){const M=((j=te==null?void 0:te.data)==null?void 0:j.error)||"ש×××× ×××ש×× ×ס×ר××××ת ×פרע××";p(!1),f(t,{content:`×××¨×¢× ×©×××× ×× ×ת××: ${M}. ×פשר ×× ×¡×ת ש×× ×× ×××¢××ת ×ס×× ××ר.`,isLoading:!1,options:[{id:"retry_upload",label:"ð × ×¡× ×©××"}]}),u(!1),window.isLongProcessRunning=!1;return}const L=te.data.strategy;f(t,{content:"×× × ×××××¦× ×©×× ×פרע×× ××ש××:",isLoading:!1,renderComponents:{prepaymentRecommendation:{strategy:L,availableAmount:o.prepaymentAmount}},options:[],context:{...o,prepaymentStrategy:L,step:"prepayment_recommendation_shown"}}),r(M=>({...M,prepaymentStrategy:L,step:"prepayment_recommendation_shown"})),setTimeout(()=>p(!1),1e3)}catch(N){console.error("[Chat] Error in prepayment flow:",N),p(!1),f(t,{content:`×××¨×¢× ×©×××× ×× ×ת××: ${N.message}. ×פשר ×× ×¡×ת ש××.`,isLoading:!1,options:[]})}finally{u(!1),window.isLongProcessRunning=!1}},Zr=({context:e,messages:a,setContext:t,addMessage:s,searchParams:o,navigate:y,redirectToAuth:f})=>async $=>{try{let u=null;try{u=await K.auth.me()}catch{}if(e.flow!=="new_mortgage")return;if(!u){Ae.saveContextForAuth({action:"submit_new_mortgage_form",flow:"new_mortgage",formData:$,returnToChat:!0,redirectToPayment:!1,returnState:{messages:a.filter(h=>!h.isLoading),currentContext:e}}),f(`${be("AuthRedirect")}?auth_completed=true`);return}const{property_price:r,...p}=$,T={...p,property_value:r,application_type:$.application_type||"new_mortgage",email:u.email,client_name:$.firstName&&$.lastName?`${$.firstName} ${$.lastName}`:null,user_id:u.id,...u.maple_professional_service_allowed===!1?{selected_service_type:"self_serve"}:{}};let k=e.applicationId;k?await Te.MortgageApplication.update(k,{...T,status:"pending_payment"}):k=(await Te.MortgageApplication.create({...T,status:"pending_payment"})).id;try{const h=localStorage.getItem("ref_agent_lead_id"),D=localStorage.getItem("ref_agent_code");h&&K.entities.AgentLead.update(h,{application_id:k,lead_type:"application",status:"qualified"}).catch(()=>{}),D&&K.entities.AgentLink.filter({link_code:D,is_active:!0}).then(A=>{A&&A.length>0&&Te.MortgageApplication.update(k,{agent_id:A[0].agent_id}).catch(()=>{})}).catch(()=>{})}catch{}const R={...e,applicationId:k,applicationData:T,step:"form_submitted"};if(t(R),e.human_advisory_mode&&u.maple_professional_service_allowed!==!1){const h=await Ie.buildStandardCompletionMessage(`ת××× ×¢× ×× ×ª×× ××. ס××× ××ש×× ×ª× ××××קש ××× ${Ie.formatCurrency(T.loan_amount)} ×××××ר ×××××©× ××ת×××ª× ××× ×-${Ie.formatCurrency(T.estimated_monthly_payment)}.`,u,{...e,human_advisory_mode:!0}),D=o.get("slot_id")||"",A=`${be("Schedule")}?confirmed=true${D?`&slotId=${D}`:""}&human_advisory=true`;s(h.content,"bot",[{id:"go_to_schedule_final",label:"ð ×××ר ××§××עת ×פ××ש×",primary:!0,_scheduleUrl:A}]),t({...R,step:"data_saved_for_human_advisor"});return}s(`ת××× ×¢× ×× ×ª×× ××! ð ס××× ××ש×× ×ª×: ${Ie.formatCurrency(T.loan_amount)}. 49 50××¤× × ×©××× × ×ת ×ת×××××× â ש××× ×§×¦×¨×: 51 52**×× ×ש×× ×× ××תר ××ש×× ×ª× ×©××?**`,"bot",[{id:"pref_conservative",label:"ð¡ï¸ ×צ×××ת â ×××ר ×§×××¢ ×××××, ×× ×× ×קר ××תר",primary:!0},{id:"pref_moderate",label:"âï¸ ××××× â ש×××× ××× ×צ×××ת ××××ש×ת"},{id:"pref_aggressive",label:"ð¸ ××ס××× ×קס×××× â פ××ת ×סף ××××, ×× ×× ××××ר ××©×ª× ×"}]),t({...R,step:"awaiting_risk_preference"})}catch(u){console.error("[Chat] Error in handleFormSubmit:",u),s(`×××¨×¢× ×©×××× ××¢×××× ×××פס: ${u.message} ð ×פשר ×× ×¡×ת ש××.`,"bot")}},Wr=async e=>{var y,f,$,u,r,p,T,k;let a=0;const t=30,s=5e3,o=["completed","processed","processed.success"];for(;a<t;){try{const R=await De.checkDocumentStatus({documentId:e}),h=(f=(y=R==null?void 0:R.data)==null?void 0:y.document)==null?void 0:f.status;if(o.includes(h)||((u=($=R==null?void 0:R.data)==null?void 0:$.document)==null?void 0:u.localStatus)==="completed")return console.log(`[pollSingleDocument] Doc ${e} ready with status: ${h}`),e;if(h==="failed"||((p=(r=R==null?void 0:R.data)==null?void 0:r.document)==null?void 0:p.localStatus)==="failed"){const D=((k=(T
52=R==null?void 0:R.data)==null?void 0:T.document)==null?void 0:k.error_message)||"×¢×××× ××ס×× × ×ש×";throw new Error(D)}}catch(R){console.error(`Error polling for doc ${e}`,R)}a++,await new Promise(R=>setTimeout(R,s))}throw new Error(`Timeout polling for document ${e}`)},es=async(e,a,t,s,o,{updateMessage:y,addBotMessage:f,setIsLoading:$,setContext:u,setShowWaitingScreen:r,setWaitingScreenMode:p,setWaitingScreenProgress:T,handleCashOutSubmit:k,waitForQuestionnaire:R,onAnalysisReady:h})=>{var S,re,ye,J,Ce,je,Ee,Oe,rt,we;window.isLongProcessRunning=!0,p("analyzing_mortgage"),T(0);const D=te=>new Promise((L,M)=>{const w=new FileReader;w.readAsDataURL(te),w.onload=()=>L(w.result),w.onerror=v=>M(v)}),A={bank_name:a,display_name:Jt(a)};if(!s){y(t,{content:"ש××××: ×× × ××¦× ×××× ×קש×. ×× × ×ת×× ×ת ×ת×××× ×××ש.",isLoading:!1,options:[]}),window.isLongProcessRunning=!1,r(!1);return}let B=[];o.applicationData;let Y=null;if(["mizrahi","discount","leumi","hapoalim","jerusalem"].includes(a)){y(t,{content:`×ת×××× ×××××¥ × ×ª×× ×× ××ס××× ${A.display_name}...`});try{T(5);const te=3,L=5e3,M=Array.from(e).map(async F=>{var Xe;let Q=!1,ve=0,Le=null;for(;!Q&&ve<te;){ve++;try{const Ue=await D(F),$e=await De.uploadToDocupanda({file:Ue,filename:F.name,documentType:"mortgage_statement",bank:a,applicationId:s});if($e.error){if(Le=$e.error,(Xe=$e.error.message)!=null&&Xe.includes("Rate limit")&&ve<te){await new Promise(ut=>setTimeout(ut,L));continue}throw new Error(`Upload failed: ${$e.error.message}`)}return Q=!0,$e}catch(Ue){if(Le=Ue,ve>=te)throw Ue;await new Promise($e=>setTimeout($e,L))}}throw new Error(`Failed to upload ${F.name} after ${te} attempts. Last error: ${(Le==null?void 0:Le.message)||"Unknown error"}`)}),w=await Promise.all(M);T(20);const v=w.filter(F=>{var Q,ve;return!((ve=(Q=F.data)==null?void 0:Q.data)!=null&&ve.documentId)});if(v.length>0)throw new Error(`××¢××ת ${v.length} ×§×צ×× × ×ש××.`);const x=w.map(F=>({docupandaId:F.data.data.docupandaId,recordId:F.data.data.documentId}));for(const F of x)await Wr(F.recordId);T(35),y(t,{content:"×× ××ס×××× ×¢××××! ×עת ×× × ×©×××ת ×××ª× ×× ×ת×× ×תק×× ××¤× ××× × ××× ×§. ש×× ×× ×××¨× ×××§×...",isLoading:!0});const ie=(await De.processMizrahiStandardization({documentIds:x.map(F=>F.recordId),bank:a})).data.jobId;if(!ie)throw new Error("×× ×תק×× ×××× ×¢×××× (Job ID) ×ת×××× ×× ×ת××.");T(45);let z="processing",W=0,ue=null;for(;z==="processing";){const F=Math.min(85,45+1.3333333333333333*(W+1));T(F);const Q=await De.checkStandardizationJobStatus({jobId:ie,documentIds:x.map(ve=>ve.recordId)});if((S=Q==null?void 0:Q.data)!=null&&S.status){if(z=Q.data.status,z==="completed")ue=Q;else if(z==="failed")break}if(z==="processing"){if(W++,W>=30)break;for(let ve=0;ve<10;ve++)await new Promise(Le=>setTimeout(Le,1e3)),T(Math.min(85,F+ve*.3))}}if(z!=="completed")throw new Error("ת×××× ×××××¥ ×× ×ת×× ×× ×ª×× ×× × ××©× ×× ×× ×סת××× ××××.");T(88),y(t,{content:"×××××¥ ×× ×ת×× ×× ×ª×× ×× ××ש×× ××צ×××! ×× × ×צ××× ×ת ×ת×צ××ת ×ס×פ××ת...",isLoading:!0});const ee=await De.getMizrahiStandardizationResult({documentIds:x.map(F=>F.recordId)}),pe=Array.isArray(ee.data.results)?ee.data.results:ee.data.results?[ee.data.results]:[];await Promise.all(pe.map(F=>{const Q=x.find(ve=>ve.docupandaId===(F.docupandaId||F.documentId));return Q?Te.Document.update(Q.recordId,{standardized_results:F.data,status:"processed"}):Promise.resolve()}));try{const{analysis:F}=await zr(x[0].recordId,s);Y=F}catch(F){console.warn("Canonical document analysis was unavailable; continuing with the extracted track analysis.",F)}let O;switch(a){case"mizrahi":O=((re=Ba(ee.data.results))==null?void 0:re.tracks)||[];break;case"discount":O=((ye=za(ee.data.results))==null?void 0:ye.tracks)||[];break;case"leumi":O=((J=Ua(ee.data.results))==null?void 0:J.tracks)||[];break;case"hapoalim":O=((Ce=Ha(ee.data.results))==null?void 0:Ce.tracks)||[];break;case"jerusalem":O=((je=Jr(ee.data.results))==null?void 0:je.tracks)||[];break;default:O=[]}if(!O||O.length===0){const F=a==="leumi"||a==="hapoalim"?`×ת×××× ×¢××ר ×× ×§ ${A.display_name} ×סת××× ××צ×××, ×× ×× ×צ×××ª× ××××¥ × ×ª×× × ×ס×××××. ×× × × ×¡× ×©×× ××××ר ××תר.`:"×× ×צ×××ª× ××××¥ × ×ª×× × ×ס××××× ×××ס×××× ×©×¢××××. ×× × × ×¡× ×××¢×××ת ×ס×××× ××ר×× ×× ×¤× × ×ת××××.";throw new Error(F)}T(92),B=O.map(F=>{let Q=null;return F.original_principal>0&&F.interest_rate!==null&&F.original_term_months>0&&F.balance>=0&&(Q=Oa({originalPrincipal:F.original_principal,annualRate:F.interest_rate,originalTermInYears:F.original_term_months/12,remainingPrincipal:F.balance})),{...F,stageInfo:Q}})}catch(te){throw console.error(`Error during file processing flow (${a}):`,te),r(!1),y(t,{content:`×××¨×¢× ×©×××× ×ת×××× ×××××¥ ×× ×ת×× ×× ×ª×× ××: ${te.message}. ×פשר ×× ×¡×ת ש×× ××××ר ××תר.`,isLoading:!1,renderManualRefinanceForm:!1,options:[]}),$(!1),window.isLongProcessRunning=!1,te}}else{if(B=o.originalTracks||[],B.length===0)throw y(t,{content:`×× × ××ª× ×¦×ת, ×× ×§ ${A.display_name} ×¢×××× ×× × ×ª×× ××ער×ת ××××××××ת ××× ×× ×××× × × ×ª×× ×× ××× ×ת.`,isLoading:!1,renderManualRefinanceForm:!1,options:[]}),$(!1),window.isLongProcessRunning=!1,r(!1),new Error("×× × ×צ×× × ×ª×× × ×ס××××× ×× ×ת××.");y(t,{content:"××¢××ת ×ת ×× ×ª×× ×× ×©×××× ×...",isLoading:!0})}T(96);let ae;const q=!!((Ee=Y==null?void 0:Y.tracks_analysis)!=null&&Ee.length);if(q){const te=Y.tracks_analysis.map(L=>{const M=B.find(w=>w.track_name===L.track_name||w.track_name===L.original_track_identifier||w.track_name===L.loanNumber)||{};return{...M,...L,end_date:M.end_date,start_date:M.start_date,original_term_months:M.original_term_months,remaining_term_years:(L==null?void 0:L.remaining_term_years)??(L==null?void 0:L.remaining_years)??M.remaining_term_years,current_rate:(L==null?void 0:L.current_rate)??M.interest_rate}});ae={...Y,tracks_analysis:te}}else ae={analysis_status:"pending_quantitative_analysis",summary_recommendation:"××ס×× ××××¥ ××צ×××, ×× ×× ×ת×× ×××××ª× ××פ××¨× ××× × ×××× ×¢××××. ×× ××צ××× ××ס××× ×× ××××¦× ×¢× ××ש××ת×.",tracks_analysis:[]};const j=B.reduce((te,L)=>te+(Number(L.balance)||0),0),N=B.reduce((te,L)=>te+(Number(L.monthly_payment)||0),0);h==null||h();const g=R?await R:{},_={...o,...g,applicationData:{...o.applicationData,...g.applicationData}};if(s)try{const te=(Oe=B.find(M=>M.monthly_income>0))==null?void 0:Oe.monthly_income,L={loan_amount:j,application_type:"refinance",data_source:"file_upload",estimated_monthly_payment:N,status:"draft"};if(q){let M=Qn(ae);try{M=await Zn(s,ae)}catch(w){console.error("Failed to save full analysis to ApplicationAnalysis:",w)}L.analysis_results=M}(rt=_.applicationData)!=null&&rt.monthly_income?L.monthly_income=_.applicationData.monthly_income:te&&(L.monthly_income=te),await Te.MortgageApplication.update(s,L)}catch(te){console.error("Failed to persist refinance data:",te)}T(98);const H=!o.disclaimerShown,l={..._,applicationId:s,originalTracks:B,initialAnalysis:ae,flow:"refinance",step:"analysis_review",applicationData:_.applicationData,disclaimerShown:!0,bank:a,preservedData:_.preservedData};f(q?`×× × × ×ת×× ×¨×ש×× × ×©× ××¦× ××ש×× ×ª× ×©×× ×${A.display_name}:`:`××ס×× ×${A.display_name} ××××¥ ××צ×××. ×× ×ת×× ×××××ª× ××פ××¨× ×× ××ש××, ×××× ×× ×צ×× ××ס××× ×× ××××¦× ×©××× × ×××סס×× ×¢× ××ש×× ×××.`,[],!1,null,!1,!1,q?{summaryCardProps:{analysis:ae,hideButtons:!0},collapsibleTracksSectionProps:{analysis:ae}}:{summaryCardProps:{analysis:ae,hideButtons:!0}},l),u(l),$(!1),window.isLongProcessRunning=!1,T(100),setTimeout(()=>r(!1),1500);const C=!!_.preservedData&&((we=_.preservedData)==null?void 0:we.requested_amount)>0&&_.refinance_goal==="cash_out";q?C?setTimeout(async()=>{const te=o.preservedData||{},L=te.requested_amount||0,M=te.property_value||0,w=te.monthly_income||0,v=j+L;await k({currentBalance:j,propertyValue:M,additionalAmount:L,newTotalLoan:v,loanPurpose:"any_purpose",monthlyIncome:w,estimatedMonthlyPayment:null,estimatedRate:null,estimatedTerm:null,ptiRatio:w>0?v/w/300*100:0})},3e3):setTimeout(()=>{f("×שתס×××× ××¢××ר ×¢× ×ס×××× ××¢× ×¤×ר×× ××ס×××××, ×פשר ×××ש×× ××××רת ×××××× ××ת×××.",[{id:"review_refinance_analysis",label:"××צ×ת ×פשר×××ת ×××ש×",primary:!0,pulseAfterMs:6e3}],!1,null,!1,!1,null,l,!1,!1,!1,Date.now()+Math.random(),null,H)},12e3):setTimeout(()=>{f("×פשר ×× ×¡×ת ××פע×× ×©×× ×ת ×× ×ת×× ××××ת×, ×× ×××ש×× ×××× × ××× ×ת. ×¢× ×©×××ש×× ××ש××, ×× × ×¦×× ××¡×§× ×ª ××××ר ×× × ×ª×× × ××ס×××.",[{id:"choose_upload_document",label:"ð × ×¡× ×©××",primary:!0},{id:"manual_input_refinance",label:"â¨ï¸ ××× × ××× ×ת"}],!1,null,!1,!1,null,l)},800)},Tt=(e="medium")=>{e==="medium"?Ut({particleCount:40,spread:55,origin:{x:.5,y:.6},colors:["#3b82f6","#60a5fa","#93c5fd","#bfdbfe"],scalar:.8,gravity:1.2}):e==="big"&&(Ut({particleCount:60,angle:60,spread:55,origin:{x:0,y:.65},colors:["#3b82f6","#10b981","#f59e0b","#ec4899"]}),Ut({particleCount:60,angle:120,spread:55,origin:{x:1,y:.65},colors:["#3b82f6","#10b981","#f59e0b","#ec4899"]}))},xa=async e=>Jt(e),ts=({context:e,messages:a,isLoading:t,isUploading:s,showRedirectAnimation:o,basePrice:y,setIsLoading:f,setBasePrice:$,setCurrentApplication:u,setContext:r,setNextAction:p,setInteractiveSlider:T,setCashOutCalculator:k,setNewMortgageForm:R,setReverseMortgageFlow:
52h,setFormPropsForNewMortgage:D,setShowManualRefinanceForm:A,setShowInitialHelpText:B,setInactivityMessageCount:Y,setConsecutiveFreeTextCount:ae,addMessage:q,addBotMessage:j,updateMessage:N,clearInactivityTimers:g,handleGoToScheduleOption:_,returnToServiceOptions:H,navigate:l,redirectToAuth:C})=>async S=>{var J,Ce,je,Ee,Oe,rt,we,te,L,M;if(!S||!S.id||s||o||t)return;if(S.id==="auth_register"||S.id==="auth_login"){l(S.id==="auth_register"?In(S.returnTo):jn(S.returnTo));return}if(S.id==="back_to_service_options"){H();return}try{const{default:w}=await it(async()=>{const{default:v}=await import("./SessionTracker-Cg5flV89.js");return{default:v}},__vite__mapDeps([2,0,1]));w.track("option_clicked",{option_id:S.id,label:S.label,flow:e.flow,step:e.step})}catch(w){console.warn("SessionTracker: failed to track option click",w)}g(),Y(0),ae(0),B(!1),f(!0);let re={...e,lastOptionId:S.id},ye=null;if(e.applicationId)try{const w=await Te.MortgageApplication.get(e.applicationId);w&&(u(w),ye=w)}catch(w){console.error("[Chat] Failed to retrieve application for ID:",e.applicationId,w),u(null),ye=null}try{if(S.action&&S.action==="proceed_to_payment"){if(!ye||!ye.id){j("×צ×ערת, ×× × ×¦×¨××× ×ת פר×× ×××§×©× ××× ×××ש×× ×תש××× ð ×××× × ×ª××× ×××ש."),f(!1);return}try{await K.auth.me(),j("××¢×××¨× ×××ª× ×××£ ×תש××× ×××××××... ר××¢ ×§××! ð³",[],!1,null,!1,!1,null,re),await new Promise(v=>setTimeout(v,1500)),window.location.href=`${be("Payment")}?type=automated_consultation&applicationId=${ye.id}`}catch{Ae.saveContextForAuth({action:"payment",targetPage:"Payment",paymentType:"automated_consultation",applicationId:ye.id,requiresRegistration:!1,returnToChat:!1,redirectToPayment:!0,showRedirectingAnimation:!0,returnState:{messages:a.filter(x=>!x.isLoading),currentContext:re}}),C(`${be("AuthRedirect")}?auth_completed=true`)}f(!1);return}if(S.id==="go_to_schedule_final"){_(S),f(!1);return}if(S.id==="_show_analysis_then_service_selection"){q(S.label,"user");const v=e.initialAnalysis,x=e.selected_scenario_details,E=x?` 53 54**×תר××ש:** ${x.type==="payment"?`××§×× ×ª תש××× ×-âª${x.newMonthlyPayment}`:x.type==="term"?`×§×צ×ר תק××¤× ×-${x.newTerm} ×©× ××`:`××××ת ×ש×× ×ª× ×-âª${x.cashOutAmount}`}`:"";j(`× ××ר! ×× ×ת×× ××××××¨× ×©××${E} 55 56×¢×ש×× ×××× × ××ר ס×× ×©×ר×ת:`,[{id:"final_confirm_payment_automated_consultation",label:"××××××× ×××××× ×קצ××¢×",primary:!0},{id:"prefer_human_advisor",label:"××××××× + ×××¢×¥ ××ש×"}]),r(ie=>({...ie,step:"awaiting_service_choice"})),f(!1);return}if(S.id==="_show_analysis_choose_scenario"){q(S.label,"user"),j("×¢×ש×× ××× × ××ר ×ת ×תר××ש ××ת××× ××:",[{id:"reduce_payment_scenario",label:"ð ×××§××× ×ª×©××× ×××ש×"},{id:"shorten_period_scenario",label:"â±ï¸ ×קצר תק××¤× ××ס×××"},{id:"cash_out_scenario",label:"ð° ×××××× ×ש×× ×ª× (×§××ת ×סף)"}]),r(v=>({...v,step:"awaiting_scenario_selection"})),f(!1);return}if(S.id==="_resume_new_mortgage_process"){q(S.label,"user");const v=e.applicationData||ye,x=(v==null?void 0:v.loan_amount)||(v==null?void 0:v.requested_amount)||0,E=(v==null?void 0:v.property_value)||(v!=null&&v.loan_amount&&(v!=null&&v.down_payment)?v.loan_amount+v.down_payment:0),ie=z=>`âª${new Intl.NumberFormat("he-IL").format(Math.round(z||0))}`;j(`×××× × ×ש×× ×¢× ×× ×ª×× ×× ×©××: 57 58ð° ס××× ×ש×× ×ª×: ${ie(x)} 59ð ש××× × ×ס: ${ie(E)} 60 61×¢× ×ס×ס ×× ×ª×× ××, ×× × ××× × 3 ת×××××× ××ת×××× ××ש×ת ××××ש ×××ª× ××××¤× ××××××× ××ספר ×× ×§××. 62 63×××× × ××ר ס×× ×©×ר×ת:`,[{id:"final_confirm_payment_automated_consultation",label:"××××××× ×××××× ×קצ××¢×",primary:!0},{id:"prefer_human_advisor",label:"××××××× + ×××¢×¥ ××ש×"}]),r(z=>({...z,step:"awaiting_service_choice"})),f(!1);return}if(S.id==="_resume_refinance_bank_selection"){q(S.label,"user"),j("×××× × ××ר ×ת ××× ×§ ש×× ××× ×××ש×× ×××××§×:",[{id:"refinance_bank_selected",label:"ð¦ ×× ×§ ××ר×× ×פ××ת",value:"mizrahi"},{id:"refinance_bank_selected",label:"ð¦ ×× ×§ ×פ××¢×××",value:"hapoalim"},{id:"refinance_bank_selected",label:"ð¦ ×× ×§ ×××××",value:"leumi"},{id:"refinance_bank_selected",label:"ð¦ ×× ×§ ××סק×× ×",value:"discount"},{id:"refinance_bank_selected",label:"ð¦ ×× ×§ ×ר×ש×××",value:"jerusalem"},{id:"refinance_bank_selected",label:"ð¦ ×× ×§ ××ר",value:"bank_other"}]),r(v=>({...v,step:"select_bank"})),f(!1);return}if(S.id==="go_to_my_process"){if(q(S.label,"user"),e.applicationId){l(`${be("MyProcess")}
63?application_id=${e.applicationId}`),f(!1);return}let v=be("MyProcess");try{const x=await K.auth.me().catch(()=>null);if(x){const E=await K.entities.MortgageApplication.filter({user_id:x.id}),ie=["active","awaiting_offers","pending_final_offers","ai_review_pending"],z=E==null?void 0:E.find(ue=>ue.current_stage==="self_serve"&&ue.status==="active");z&&(v=`${be("MyProcess")}?application_id=${z.id}&tab=self_serve`);const W=E==null?void 0:E.find(ue=>ie.includes(ue.status));if((Ce=(J=W==null?void 0:W.analysis_results)==null?void 0:J.tracks_analysis)!=null&&Ce.length){const ue=W.analysis_results,ee={conservative:"ש××¨× ×",balanced:"×××××",aggressive:"××רס×××"}[W.selected_mix_type]||"",pe=ee?` 64**ת×××× ×©× ××ר:** ${ee} â `:"";j("×× × ×¡×××× ×× ×ת×× ×©××:",[],!1,null,!1,!1,{summaryCardProps:{analysis:ue,hideButtons:!0},collapsibleTracksSectionProps:{analysis:ue}}),setTimeout(()=>{j(`${pe?pe+` 65 66`:""}×¢××ר ××××ר ××××©× ×צפ××× ×ת×××××× ×××צע×ת ××× ×§××.`,[{id:"_navigate_my_process",label:"ð ×¢××ר ××××ר ×××ש×",primary:!0,_url:v}])},800),f(!1);return}}}catch{}l(v),f(!1);return}if(S.id==="_navigate_my_process"){const v=new URL(S._url||be("MyProcess"),window.location.origin);e.applicationId&&!v.searchParams.get("application_id")&&v.searchParams.set("application_id",e.applicationId),l(`${v.pathname}${v.search}${v.hash}`),f(!1);return}if((je=S.id)!=null&&je.startsWith("_select_application_")){const v=S._applicationId||S.id.replace("_select_application_","");q(S.label,"user"),f(!0);try{const x=await Te.MortgageApplication.get(v);if(!x)throw new Error("Application not found");const E=x.application_type==="refinance"?"refinance":"new_mortgage",ie={activeApplication:x,applicationId:x.id,flow:"active_process",step:"active"};if(r(z=>({...z,...ie})),["pending_payment","draft"].includes(x.status)){const z=await Aa(x.id,x),W=x.current_bank_name,ue=x.application_type,ee=ue==="refinance"||ue==="any_purpose",pe={bank:W,flow:ee?"refinance":"new_mortgage",applicationId:v,initialAnalysis:z,application_type:ue};if(r(O=>({...O,...pe})),(Ee=z==null?void 0:z.tracks_analysis)!=null&&Ee.length)if(x.selected_scenario_details){const O=x.selected_scenario_details,F=O.newMonthlyPayment||O.monthly_payment,Q=F?`×××ר ××××©× ×©× âª${F.toLocaleString("he-IL")}`:"ש×× ×× ×ª× ×× ××ש×× ×ª×",ve={...pe,step:"scenario_selected",selected_scenario_details:O,originalTracks:z.tracks_analysis,initialAnalysis:z};j(`ר×××ª× ×©×× ×ת×× ××ש×× ×תר××ש × ××ר ð¯ 67 68×× × ×¡×××× × ×ת×× ××ש×× ×ª× ×©××:`,[],!1,null,!1,!1,{summaryCardProps:{analysis:z,hideButtons:!0},collapsibleTracksSectionProps:{analysis:z}},ve),setTimeout(()=>{j(`**×תר××ש ×©× ××ר:** ${Q} 69 70××¦×¢× ×××: ×§××ת ×צע×ת ×××× ×§××. ××ש××××?`,[{id:"_resume_pending_payment_service",label:"â ××, × ×ש××",primary:!0},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"}],!1,null,!1,!1,null,ve)},800),r(Le=>({...Le,...ve,_pendingRecovery:"service",_pendingAnalysis:z,_pendingScenarioDesc:Q}))}else{const O={...pe,originalTracks:z.tracks_analysis,initialAnalysis:z,step:"data_collected",application_type:ue};j(`ר×××ª× ×©×ש × ×ת×× ×××× ð 71 72×× × ×¡×××× × ×ת×× ××ש×× ×ª× ×©××:`,[],!1,null,!1,!1,{summaryCardProps:{analysis:z,hideButtons:!0},collapsibleTracksSectionProps:{analysis:z}},O),setTimeout(()=>{j("ð¡ ×¢×ש×× ××× × ××ר ×ת ×××××× ××ת××× ××:",[{id:"_resume_pending_payment_scenario",label:"â ××ר תר××ש ××§××",primary:!0},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"}],!1,null,!1,!1,null,O)},800),r(F=>({...F,...O,_pendingRecovery:"scenario",_pendingAnalysis:z}))}else{const O=W?await xa(W):null,F=ee?O?`ת×××× ××××ר ×${O}`:"ת×××× ××××ר":"ת×××× ×ש×× ×ª× ××ש×";j(`ר×××ª× ×©×ת××ת ${F} ð 73 74×פשר ×××ש×× ××××¤× ×©×¢×¦×¨×ª?`,[{id:"_resume_pending_payment_upload",label:"â ××, × ×ש××",primary:!0,_recoveryCtx:pe,_bankDisplayName:O},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"}],!1,null,!1,!1,null,pe),r(Q=>({...Q,...pe,_pendingRecovery:"upload",_bankDisplayName:O}))}}else if(x.status==="completed")j(`×ת×××× ×סת××× ××צ××× ð 75 76×ת ×× ×××××¢ ×××ס×××× ×פשר ××צ×× ××××ר ×××ש×.`,[{id:"go_to_my_process",label:"ð ×××ר ××ש×",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}]);else if(x.selected_mix&&x.selected_scenario_details){const z=x.analysis_results,W=x.selected_scenario_details,ee={reduce_monthly_payment:"××§×× ×ª תש××× ××××©× ð",shorten_period:"×§×צ×ר תק××¤× â±ï¸",cash_out:"××××ת ×ש×× ×ª× ð°"}[x.refinance_goal]||"ש×× ×× ×ª× ×× ××ש×× ×ª×",pe={conservative:"ש××¨× ×",balanced:"×××××",aggressive:"××רס×××"}[x.selected_mix_type]||"",O=(W==null?void 0:W.newMonthlyPayment)||(W==null?void 0:W.monthly_payment),F=O?` â ×××ר ××××©× ×©× âª${Math.round(O).toLocaleStr
76ing("he-IL")}`:"";j(`×××§×©× ×©×× ×××פ×× ×¤×¢×× ð 77 78×× × ×¡×××× ×× ×ת×× ×©×××¦×¢× ×:`,[],!1,null,!1,!1,z?{summaryCardProps:{analysis:z,hideButtons:!0},collapsibleTracksSectionProps:{analysis:z}}:null,ie),setTimeout(()=>{const Q=pe?` 79**ת×××× ×©× ××ר:** ${pe} â `:"";j(`**××רת ×××××ר ×©× ××ר×:** ${ee}${F}${Q} 80 81×ת×××× ××¢×צ××× â ×פשר ××¢×§×× ××ש××× ×××.`,[{id:"_navigate_my_process",label:"ð ×¢××ר ××××ר ×××ש×",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"}])},800)}else{const z=x.analysis_results;if((Oe=z==null?void 0:z.tracks_analysis)!=null&&Oe.length){const W={...ie,initialAnalysis:z,originalTracks:z.tracks_analysis};r(ue=>({...ue,...W})),j(`×ש ת×××× ×¤×¢×× ×©××ת×× ð 82 83×× × ×¡×××× × ×ת×× ××ש×× ×ª× ×©××:`,[],!1,null,!1,!1,{summaryCardProps:{analysis:z,hideButtons:!0},collapsibleTracksSectionProps:{analysis:z}},W),setTimeout(()=>{var pe;const ee=((pe=z.tracks_analysis)==null?void 0:pe.some(O=>{var F;return(F=O.individual_recommendation)==null?void 0:F.includes("××××ר")}))?"×¢×ש×× ××× × ××××§ ×××× ××××× ××× ×ת×××:":"×¢×××× ×ש ××§×× ×שק×× ×©×× ×××× ××ת×× ×צר×××. ×× ××¢× ×××?";j(ee,qa(z),!1,null,!1,!1,null,W)},800)}else{const W=F=>F?`âª${new Intl.NumberFormat("he-IL").format(Math.round(F))}`:null,ee={active:"פע××",awaiting_offers:"××ת×× ××צע×ת ×××× ×§××",pending_final_offers:"×צע×ת ס×פ××ת ×תק×××"}[x.status]||"×××פ××",pe=x.application_type==="refinance"||x.application_type==="any_purpose";let O="";if(pe){const F=x.loan_components;if((F==null?void 0:F.length)>0)O+=` 84 85**×ס×××× ××ש×× ×ª× ××§×××××:**`,F.forEach((Q,ve)=>{const Le=Q.track_type||Q.track_name||`×ס××× ${ve+1}`,Xe=W(Q.balance||Q.amount),Ue=Q.interest_rate?`${Number(Q.interest_rate).toFixed(2)}%`:null,$e=Q.remaining_months?`${Math.round(Q.remaining_months/12)} ×©× ××`:Q.remaining_term_years?`${Q.remaining_term_years} ×©× ××`:null;O+=` 86⢠${Le}${Xe?` â ${Xe}`:""}${Ue?` | ר×××ת ${Ue}`:""}${$e?` | ${$e}`:""}`});else{const Q=x.loan_amount||x.requested_amount;Q&&(O+=` 87ð° ×תרת ×ש×× ×ª×: **${W(Q)}**`),x.current_bank_name&&(O+=` 88ð¦ ×× ×§: **${x.current_bank_name}**`)}}else{const F=x.loan_amount||x.requested_amount;F&&(O+=` 89ð° ס××× ×ש×× ×ª×: **${W(F)}**`),x.estimated_monthly_payment&&(O+=` 90ð ×××ר ××××©× ×ש×ער: **${W(x.estimated_monthly_payment)}**`),x.property_value&&(O+=` 91ð ש××× × ×ס: **${W(x.property_value)}**`),x.monthly_income&&(O+=` 92ð¼ ××× ×¡× ×××ש×ת: **${W(x.monthly_income)}**`)}j(`×ש ת×××× ${pe?"××××ר":"×ש×× ×ª× ××ש×"} פע×× ×ס×××ס: **${ee}** ð${O} 93 94××¦×¢× ××× â ×××× ×¡ ××××ר ××××©× ×צפ××× ×ת×××××× ×××צע×ת ××× ×§××.`,[{id:"_navigate_my_process",label:"ð ×¢××ר ××××ר ×××ש×",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"}])}}}catch(x){console.error("[ChatOptionHandler] Failed to load selected application:",x),j("×××¨×¢× ×©×××× ×××¢×× ×ª ×ת×××× ð ×פשר ×× ×¡×ת ש××.",[{id:"_start_new_process_choice",label:"ð ת×××× ××ש"}])}f(!1);return}if(S.id==="_start_new_process_choice"){q("ð ת×××× ××ש","user"),j("×× ×ª×¨×¦× ×עש×ת?",[{id:"new_mortgage_prompt",label:"ð ××§×ת ×ש×× ×ª×",primary:!0},{id:"refinance_prompt",label:"ð° ×שפר ×ש×× ×ª× ×§×××ת"},{id:"prepayment_advisory",label:"ð¸ ××××× ×× ×××× ×פר××¢"},{id:"reverse_mortgage_start_process",label:"ð ×ש×× ×ª× ×פ×××"}]),r({flow:"initial",step:"start",applicationId:null,analysisData:null,lastOptionId:null,selected_service_type:null,refinance_goal:null,selected_scenario_details:null}),f(!1);return}if(S.id==="_resume_pending_payment_upload"){q("â ××, × ×ש××","user");const v=e.application_type||((rt=S._recoveryCtx)==null?void 0:rt.application_type);if(v==="new_mortgage"||v==="investment"||v==="construction")try{const E=await K.entities.MortgageApplication.get(e.applicationId),ie=E.loan_amount||E.requested_amount||0,z=E.property_value||E.property_price||(E.loan_amount&&E.down_payment?E.loan_amount+E.down_payment:0);if(E&&ie){const W=await K.auth.me().catch(()=>null),ue=await Qe("automated_consultation",W),ee=await Qe("human_consultation_deposit",W),pe=Q=>`âª${new Intl.NumberFormat("he-IL").format(Math.round(Q||0))}`,O={...e,flow:"new_mortgage",step:"awaiting_payment_prompt",applicationData:{...E},_pendingRecovery:null};r(O);const F=pe(ue.finalPrice);window.isAtPricingStep=!0,sessionStorage.removeItem("exitIntentShown"),j(`××¢×××! ×צ××ª× ×ת ×××§×©× ×©×× ð 95 96ð° ס××× ×ש×× ×ª×: ${pe(ie)} 97ð ש××× × ×ס: ${pe(z)} 98 99×¢× ×ס×ס ×× ×ª×× ××, ×× × ××× × ×ª×××××× ××ת×××× ××ש×ת ×צ××¨× ××××¢×פ×ת ×©× ××ר×, ××××× ×ת ×ת×××× ××תק×××ת ××× ××× ×§××. 100 101×¢×××× ×× ×תק××× ×××× ××ת, ×ת××× ×פשר×ת ××ש××ת ××× ××צע×ת ×ש×ר×ת ××××ר ×××ש×. ×× × ××××× ×ת ×ת×××× ×¢× ××§××ת ××ש×× ×ª× ×××× ×§ ×××××. 102 103××× ×××ש××, ××¢××ת ××× **${F}**:`,[{id:"final_confirm_payment_automated_consultation",label:`×××©× ×תש××× (${F})`,primary:!0},{id:"prefer_human_advisor",label:"××××××× + ×××¢×¥ ××ש×"}],!1,null,!1,!1,null,O)}else j("××¢×××! ××× × ×ש×× ×××× ×ת פר×× ××ש×× ×ª× ×××ש×.",[{id:"new_mortgage_prompt",label:"ð ×××©× ××ש××××",primary:!0,resumeExistingProcess:!0},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"}],!1,null,!1,!1,null,{...e,step:"start",_pendingRecovery:null}),r(W=>({...W,step:"start",_pendingRecovery:null}))}catch{j("××¢×××! ××× × ×ש×× ×××× ×ת פר×× ××ש×× ×ª× ×××ש×.",[{id:"new_mortgage_prompt",label:"ð ×××©× ××ש××××",primary:!0,resumeExistingProcess:!0}],!1,null,!1,!1,null,{...e,step:"start",_pendingRecovery:null}),r(ie=>({...ie,step:"start",_pendingRecovery:null}))}else{const E=e._bankDisplayName||"";j(`××¢×××! ×פשר ×××¢××ת ×ת ×ס×× "×תר×ת ×ס××××§"${E?` ×${E}`:""}.`,[],!0,null,!1,!1,null,{...e,step:"awaiting_upload",_pendingRecovery:null}),r(ie=>({...ie,step:"awaiting_upload",_pendingRecovery:null}))}f(!1);return}if(S.id==="_resume_pending_payment_scenario"){q("â ××, ××¦× ×ת ×× ×ת××","user");const v=e._pendingAnalysis||e.initialAnalysis,x={...e,step:"data_collected",initialAnalysis:v,originalTracks:(v==null?void 0:v.tracks_analysis)||e.originalTracks||[],_pendingRecovery:null,_pendingAnalysis:null};r(x),j("×× × ×× ×ת×× ×©××! â ",[],!1,null,!1,!1,{summaryCardProps:{analysis:v,hideButtons:!0},collapsibleTracksSectionProps:{analysis:v}},x),setTimeout(()=>{const E=((v==null?void 0:v.total_savings_potential)||0)>0&&!(v!=null&&v.below_total_threshold);j("ð¡ ×¢×ש×× ××× × ××××§ ×××× ××××× ××× ×ת×××:",[{id:"reduce_payment_scenario",label:"ð ×××§××× ×ª×©××× ×××ש×"},{id:"shorten_period_scenario",label:"â±ï¸ ×קצר תק××¤× ××ס×××"},{id:"cash_out_scenario",label:"ð° ×××××× ×ש×× ×ª× (×§××ת ×סף)"}
103,E?{id:"proceed_with_savings",label:"â ×ש××ר ×¢× ×תק××¤× ××ס××× â רק ×שפר ×ת ××ª× ×××",primary:!0}:{id:"request_reminder",label:"ð ת×××¨× ×××× ×ש×××ס××× ××××"}])},1500),f(!1);return}if(S.id==="_resume_pending_payment_service"){q("â ××, × ×ש××","user");const v=e._pendingAnalysis,x=e._pendingScenarioDesc||"",E={...e,_pendingRecovery:null,_pendingAnalysis:null,_pendingScenarioDesc:null};r(E);try{const ie=await K.auth.me().catch(()=>null),z=await Qe("automated_consultation",ie),W=await Qe("human_consultation_deposit",ie),ue=z.finalPrice||0,ee=W.finalPrice||0,pe=O=>`âª${new Intl.NumberFormat("he-IL").format(Math.round(O||0))}`;window.isAtPricingStep=!0,sessionStorage.removeItem("exitIntentShown"),j(`**×תר××ש ש××רת:** ${x} 104 105×¢× ×ס×ס ×× ×ª×× ××, ×× × ××× × ×ª×××××× ××ת×××× ××ש×ת ×צ××¨× ××××¢×פ×ת ×©× ××ר×, ××××× ×ת ×ת×××× ××תק×××ת ××× ××× ×§××. 106 107×¢×××× ×× ×תק××× ×××× ××ת, ×ת××× ×פשר×ת ××ש××ת ××× ××צע×ת ×ש×ר×ת ××××ר ×××ש×. ×× × ××××× ×ת ×ת×××× ×¢× ××§××ת ××ש×× ×ª× ×××× ×§ ×××××. 108 109××× ×××ש×× ×××§×× ×ª×××××× ××צע×ת ×××× ×§××, ××¢××ת ××× **${pe(ue)}**:`,[{id:"final_confirm_payment_automated_consultation",label:`×××©× ×תש××× (${pe(ue)})`,primary:!0},{id:"prefer_human_advisor",label:"××××××× + ×××¢×¥ ××ש×"}],!1,null,!1,!1,null,E)}catch{j(`**×תר××ש ש××רת:** ${x} 110 111× ×©×ר רק ××××ר ס×× ×©×ר×ת:`,[{id:"final_confirm_payment_automated_consultation",label:"××××××× ×××××× ×קצ××¢×",primary:!0},{id:"prefer_human_advisor",label:"××××××× + ×××¢×¥ ××ש×"}],!1,null,!1,!1,null,E)}f(!1);return}if(S.id==="start_over"){Ae.clearSession(),window.location.reload();return}if(S.id==="resume_upload_flow"){q(S.label,"user");const v=e.resumeBank||e.bank,x=await xa(v);j(`××¢×××! ×פשר ×××¢××ת ש×× ×ת ×ס×× "×תר×ת ×ס××××§" ×${x}.`,[],!0,null,!1,!1,null,{...e,bank:v,step:"awaiting_upload",resumePending:!1}),r(E=>({...E,bank:v,step:"awaiting_upload",resumePending:!1})),f(!1);return}if(S.id==="resume_manual_analysis"){q(S.label,"user");const v=e.manualTracks,x=Date.now();q("××ש××× ×× ×ת×× ××ש×× ×ª× ×©××...","bot",[],!1,null,!1,!0,null,e,!1,!1,!1,x),f(!0);try{const E=await K.auth.me().catch(()=>null);await Qt(v,x,E,e,N,f,r,null,j)}catch{N(x,{content:"×××¨×¢× ×©×××× ×× ×ת×× ð ×פשר ×× ×¡×ת ש××.",isLoading:!1}),f(!1)}return}let w;switch(S.id){case"remind_me_later":{q(S.label,"user");const v=await K.auth.me().catch(()=>null),x=v==null?void 0:v.phone;x?(j(`× ××ר! ð± ×ש×× ×× ×ª×××רת ×-**${x}** 112 113×× ××ספר ×× ×××?`,[{id:"confirm_phone_for_reminder",label:"××, ×× ××ספר ×× ××× â ",primary:!0},{id:"change_phone_for_reminder",label:"××, ×× × ×¨××¦× ××©× ×ת ð"}]),r(E=>({...E,reminderPhoneConfirmation:!0,reminderCurrentPhone:x,reminderAnalysis:E.initialAnalysis}))):(j("×ש×××! ð ×× ×ספר ×××פ×× ×©××?"),r(E=>({...E,awaitingPhoneForReminder:!0,reminderAnalysis:E.initialAnalysis}))),f(!1);return}case"rate_improvement_only":case"reduce_payment_anyway":case"shorten_period_anyway":case"cash_out_anyway":q(S.label,"user"),w=await Ie.handleOptionSelected(S,re);break;case"prefer_self_serve":{q(S.label,"user");const{handlePreferSelfServe:v}=await it(async()=>{const{handlePreferSelfServe:x}=await import("./ChatManager-ph9D-sj7.js").then(E=>E.d);return{handlePreferSelfServe:x}},__vite__mapDeps([3,0,1,4,5,6,7,8,9]));w=await v(re);break}case"confirm_self_serve_payment":{q(S.label,"user");const{handleConfirmSelfServePayment:v}=await it(async()=>{const{handleConfirmSelfServePayment:x}=await import("./ChatManager-ph9D-sj7.js").then(E=>E.d);return{handleConfirmSelfServePayment:x}},__vite__mapDeps([3,0,1,4,5,6,7,8,9]));w=await v(re);break}case"explain_service_options":{q(S.label,"user");const{handleExplainServiceOptions:v}=await it(async()=>{const{handleExplainServiceOptions:x}=await import("./ChatManager-ph9D-sj7.js").then(E=>E.d);return{handleExplainServiceOptions:x}},__vite__mapDeps([3,0,1,4,5,6,7,8,9]));w=await v(re);break}case"back_to_service_options":{q(S.label,"user");const{buildServiceOptions:v}=await it(async()=>{const{buildServiceOptions:ie}=await import("./ChatManager-ph9D-sj7.js").then(z=>z.d);return{buildServiceOptions:ie}},__vite__mapDeps([3,0,1,4,5,6,7,8,9])),x=await K.auth.me().catch(()=>null);w={message:"×××¨× ×ת ××פשר×ת ××ת×××× ×××:",options:(await v(x,re)).options,context:re};break}case"prefer_human_advisor":{const v=await K.auth.me().catch(()=>null),x=await Qe("human_consultation_deposit",v);w=await Ie.handleOptionSelected(S,{...re,human_advisor_price:x});break}case"final_confirm_payment_automated_consultation":{const v=y??await Qe("automated_consultation").then(x=>($(x),x));w=await Ie.handleOptionSelected(S,{...re,selected_service_type:"automated_consultation",service_price:v});break}default:w=await Ie.handleOptionSelected(S,re);break}if(S.id==="new_mortgage_prompt"?yt("new_mortgage"):S.id==="refinance_prompt"?yt("refinance"):S.id==="prepayment_advisory"?yt("prepayment"):S.id==="reverse_mortgage_start_process"?yt("reverse_mortgage"):S.id==="reduce_payment_scenario"?(Lt("reduce_payment",(we=e.initialAnalysis)==null?void 0:we.estimated_monthly_savings),Tt("medium")):S.id==="shorten_period_scenario"?(Lt("shorten_period",(te=e.initialAnalysis)==null?void 0:te.estimated_monthly_savings),Tt("medium")):S.id==="cash_out_scenario"?(Lt("cash_out",0),Tt("medium")):S.id==="final_confirm_payment_automated_consultation"?(da("automated"),Tt("big")):S.id==="prefer_human_advisor"&&da("human"),(L=w==null?void 0:w.context)!=null&&L.bank&&w.context.bank!==e.bank&&Fn(w.context.bank),f(!1),w){const v=["final_confirm_payment_automated_consultation","prefer_human_advisor"];(M=w.options)!=null&&M.some(x=>v.includes(x.id))&&(window.isAtPricingStep=!0,sessionStorage.removeItem("exitIntentShown"),window.dispatchEvent(new Event("mousemove"))),w.nextAction?(q(w.message,"bot",w.options||[],w.showUpload||!1,w.formFields||null,w.isSilent||!1,w.isLoading||!1,w.renderComponents||null,w.context||re,w.renderManualRefinanceForm||!1,w.renderInteractiveSlider||!1,!1,Date.now()+Math.random(),w.nextAction,w.specialType||null,w.showDisclaimer||!1),p(w.nextAction)):(w.renderComponents&&(w.renderComponents.interactiveSlider!==void 0&&T(w.renderComponents.interactiveSlider||null),w.renderComponents.cashOutCalculator!==void 0&&k(w.renderComponents.cashOutCalculator||null),w.renderComponents.newMortgageForm!==void 0&&R(w.renderComponents.newMortgageForm||null),w.renderComponents.reverseMortgageFlow!==void 0&&h&&h(w.renderComponents.reverseMortgageFlow||null),w.renderComponents.formProps&&D(w.renderComponents.formProps)),w.renderManualRefinanceForm&&A(!0),q(w.message,"bot",w.options||[],w.showUpload||!1,w.formFields||null,!1,!1,w.renderComponents||null,w.context||re,w.renderManualRefinanceForm||!1,w.renderInteractiveSlider||!1,!1,Date.now()+Math.random(),w.nextAction||null,w.specialType||null,w.showDisclaimer||!1)),w.context&&r(w.context)}else q("×× × ××ª× ×¦×ת, ×××¨×¢× ×©×××× ×××ª× ×¦×¤××× ××× ×צ×××ª× ××¢×× ×ת ×××××¨× ð ×פשר ×× ×¡×ת ש××.","bot",[],!1,null,!1,!1,null,re)}catch(w){console.error("Error handling option:",w),f(!1),q("ס××××, ×××¨×¢× ×©×××× ð ×פשר ×× ×¡×ת ש××.","bot",[{id:"retry",label:"× ×ס××× × ×סף"}],!1,null,!1,!1,null,re)}},as=()=>{try{const e=sessionStorage.getItem("bina_landing_calculator_data");if(!e)return null;const a=JSON.parse(e);return sessionStorage.removeItem("bina_landing_calculator_data"),a}catch(e){return console.error("[ChatInitializer] Failed to parse calculator data:",e),null}},Va=(e,a=null)=>{const t=o=>`âª${new Intl.NumberFormat("he-IL").format(Math.round(o||0))}`;e&&(Dn(e),yt(e));const s=` 114 115ð _×××××¢ ×©× ×סר ×ש××× × ×©×ר ××××¤× ×××××× ×××©× 90 ××× ××ש×ש ×× ×רק ×ת×××× ××ש×× ×ª× ×©××._`;return e==="new_mortgage"?a?{message:`××¢×××! ð ר×××ª× ×©××ר ××ש××ª× ×ת ××××ר ×××××©× ××ש×ער: 116 117**ס××× ×ש×× ×ª×:** ${t(a.loanAmount)} 118**×××ר ×××ש×:** ${t(a.monthlyPayment)} 119 120ר×צ×× ×©× ×ª××× ×ת ×ת×××× ×¢× ×× ×ª×× ×× ××××?${s}`,options:[{id:"new_mortgage_prompt",label:"ð × ×ª××× ×¢× ×× ×ª×× ××",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}
120],context:{flow:"new_mortgage",step:"calculator_import",calculatorData:a}}:{message:`××¢×××! ð ××× ××× ×ת ××¦×¢× ××××קת ×¢××ר×, ×× × ×¦×¨××× ××× ×¤×¨××× ×¢× ×× ×ס ××¢× ××××××× ××××קשת.${s}`,options:[{id:"new_mortgage_prompt",label:"ð × ×ª××× â פר×× ×× ×ס",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],context:{flow:"new_mortgage",step:"start"}}:e==="affordability_explorer"?{message:"××××£! ð ×××× × ××××§ ×¢× ×××× ×××ר ×××¨× ×פשר ××§× ×ת â ××¤× ×××× ×¡×, ×××× ×עצ×× ×תקרת ××××××. ×פשר ×ש××§ ×¢× ××ספר×× ××× ×צ'×× ð¡",options:[],renderComponents:{buyingCapacityCard:{targetPrice:2e6,label:"××××קת ××××ת ××§× ××× ×©××× (××× ×¡×, ××× ×¢×¦×× ×תקרת ×××××)"}},context:{flow:"affordability_explorer",step:"calculator_opened"}}:e==="refinance"?{message:`××¢×××! ð ××× ×× ×ª× ×ת ×××××ת ×××××ר ש××, ×× × ×¦×¨××× ×¤×¨××× ×¢× ××ש×× ×ª× ××§×××ת. 121 122×ת ×ס×× "×תר×ת ×ס××××§" ×××× ×§ ×פשר ×××¢××ת, ×× ××××× ×ת ×פר××× ××× ×ת.${s}`,options:[{id:"refinance_prompt",label:"ð¦ × ×ª××× â ×××רת ×× ×§",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],context:{flow:"refinance",step:"start"}}:e==="reverse_mortgage"?{message:"×פשר ×××××§ ××× ×פשר×××ת ××ש×× ×ª× ×פ×××, ××××× ×ת ××ª× ××× ×××§×× ××××¢ ××¤× × ×©×××××××.",options:[{id:"reverse_mortgage",label:"×××קת ×ש×× ×ª× ×פ×××",primary:!0},{id:"mortgage_questions",label:"×ש ×× ×©×××"}],context:{flow:"initial",step:"start"}}:e==="debt_consolidation"?{message:`××¢×××! × ×¢×©× ×¡×ר ×××××××ת ×× ××××§ ×× ××××× ×ת×× ×ש×× ×ª× ×××× ××ת×××. × ××× ×× ×ת ×××§×× ××××ש×ת ××× ×ת ××¢××ת ×××××ת ××××¨× ×××.${s}`,options:[{id:"debt_consolidation_start",label:"×××קת ××××× ××××××ת",primary:!0},{id:"mortgage_questions",label:"×ש ×× ×©×××"}],context:{flow:"debt_consolidation",step:"start",debt_consolidation:!0}}:e==="prepayment"?{message:`××¢×××! ð¸ ××× ×× ×ª× ×××× ×ס××××× ×××× ×פר××¢, × ×¦××¨× ×ת ×ס×× "×תר×ת ×ס××××§" ×××× ×§.${s}`,options:[{id:"prepayment_advisory",label:"ð¸ × ×ª××× â פ×רע×× ×××§××",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],context:{flow:"prepayment",step:"start"}}:e==="investment"?{message:`××¢×××! ð¢ × ×ס ×××©×§×¢× ××רש ת×× ×× ×¤×× × ×¡× ×§×¤×× × ××תר ×ר××שת ×××¨× ××××ר××. 123 124×× × ××× × ×× ×ª×××× ×©×ת××× ××שק××¢×× (×××ש ××תר, ×¢× ×פשר×ת ×פ×רע×× ×××§×× ×שת×××ר).${s}`,options:[{id:"new_mortgage_prompt",label:"ð × ×ª××× â פר×× ×× ×ס",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],context:{flow:"new_mortgage",step:"start",property_purpose:"investment"}}:e==="self_build"?{message:`××¢×××! ð¨ ×× ××× ×¢×¦××ת ××× ×¤×¨×××§× ××ר×× ×©××רש ××××× ×¦×××. 125 126×× × ××××× ×ת×× ×ש××× ××× ××× ×××××× ×©××ש×× ×ª× ×ª×××ת ×ת×ר×× ×× ×××.${s}`,options:[{id:"new_mortgage_prompt",label:"ð × ×ª××× â פר×× ×פר×××§×",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],context:{flow:"new_mortgage",step:"start",property_purpose:"self_build"}}:e==="upgrade"?{message:`××¢×××! ðï¸ ×©×ר×× ×××¨× ×ר×× ×× ×××× ×©×ª× ×¢×¡×§××ת ×××§××× â ××××¨× ×ר××ש×. 127 128×× × ×ת×× × ×ת ×××ש×ר ×פ×× × ×¡× ×××××× ×©×× ×ª×©××× ××תר ×××.${s}`,options:[{id:"new_mortgage_prompt",label:"ð × ×ª××× â פר×× ×ר××ש×",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],context:{flow:"new_mortgage",step:"start",property_purpose:"upgrade"}}:null};function ns(e,a){if(e.get("source")!=="retell_voice")return!1;const t=e.get("flow"),s=tr(t);if(!t&&!s)return!1;const o=Va(t,null)||s&&{message:"×פשר ××ת××× ×ש××× ×¢× ×ש×× ×ª×, ×××¢××ר ××צ×× ×ת ××××©× ××ת×××.",options:[{id:"mortgage_questions",label:"×ש ×× ×©×××"}],context:{flow:"initial",step:"start"}};if(!o)return!1;s&&(o.message=`×ש××× ×××פ×× ×ת ××רת×: ${s.label}. 129 130${o.message}`,o.context={...o.context,voice_intent:s.intent}),a.addMessage(o.message,"bot",o.options,!1,null,!1,!1,o.renderComponents||null,o.context),a.setContext(o.context),a.setHasStarted(!0),a.setShowInitialHelpText(!1);const y=new URL(window.location.href);return y.searchParams.delete("flow"),window.history.replaceState({},"",y.toString()),a.setShowWaitingScreen(!1),a.setIsInitializing(!1),a.setIsInitialized(!0),!0}const rs=e=>
130new Intl.NumberFormat("he-IL").format(Math.round(e||0)),Je=e=>`${rs(e)} âª`,At=e=>{var t,s;const a=((t=e==null?void 0:e.firstName)==null?void 0:t.trim())||((s=e==null?void 0:e.full_name)==null?void 0:s.trim().split(/\s+/)[0])||"";return a?`â¨${a}â©`:""};function ho(){const e=En(),a=Ln(),[t]=Mn(),s=t.get("auth_completed")==="true",[o,y]=m.useState([]),[f,$]=m.useState(""),[u,r]=m.useState(!1),[p,T]=m.useState(!1),[k,R]=m.useState(null),[h,D]=m.useState(null),[A,B]=m.useState(!1),[Y,ae]=m.useState(!1),[q,j]=m.useState({}),[N,g]=m.useState(null),[_,H]=m.useState(null),[l,C]=m.useState({flow:"initial",step:"start",history:[],applicationId:null,analysisData:null,lastOptionId:null,selected_service_type:null,refinance_goal:null,selected_scenario_details:null}),[S,re]=m.useState(!1),[ye,J]=m.useState(!1),[Ce,je]=m.useState(0),[Ee,Oe]=m.useState(0),[rt,we]=m.useState(!1),[te,L]=m.useState(!1),[M,w]=m.useState("loading"),[v,x]=m.useState(0),[E,ie]=m.useState(!1),[z,W]=m.useState(null),[ue,ee]=m.useState(!0),[pe,O]=m.useState(!1),[F,Q]=m.useState(null),[ve,Le]=m.useState(!1),Xe=m.useRef(null),Ue=m.useRef(null),$e=m.useRef(null),ut=m.useRef(null),It=m.useRef(null),Zt=m.useRef(null),wt=m.useRef(null),Wt=m.useRef(!1),ea=m.useRef(!1),st=m.useRef(null),jt=m.useRef(null),{toast:pt}=On();m.useEffect(()=>{(async()=>{try{const b=await Qe("automated_consultation");Q(b)}catch(b){console.error("Failed to fetch base price:",b)}})();const d=()=>{if(wt.current){const b=wt.current.getBoundingClientRect().top,P=16;wt.current.style.height=`${window.innerHeight-b-P}px`}};return requestAnimationFrame(d),window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[]);const I=m.useCallback((i,d,b=[],P=!1,V=null,c=!1,Z=!1,G=null,fe=null,Fe=!1,ze=!1,Be=!1,Ke=Date.now()+Math.random(),tt=null,Ve=null,mt=!1)=>{const Ne={id:Ke,content:i,sender:d,timestamp:new Date,options:b,showUpload:P,formFields:V,isSilent:c,isLoading:Z,renderComponents:G,renderManualRefinanceForm:Fe,renderInteractiveSlider:ze,showHint:Be,actionProcessed:!1,nextAction:tt,specialType:Ve,context:fe,showDisclaimer:mt};y(Ge=>{const Ye=[...Ge],dt=Ye.findIndex(xt=>xt.isLoading);return dt!==-1&&Ye.splice(dt,1),Ye.push(Ne),Ye}),fe&&C(Ge=>({...Ge,...fe}))},[]),ge=m.useCallback((i,d=[],b=!1,P=null,V=!1,c=!1,Z=null,G=null,fe=!1,Fe=!1,ze=!1,Be=Date.now()+Math.random(),Ke=null,tt=!1)=>{I(i,"bot",d,b,P,V,c,Z,G,fe,Fe,ze,Be,null,Ke,tt)},[I]),Ze=m.useCallback(i=>{ea.current||(ea.current=!0,I("××× ×ש××ר ×ת ×ת×××× ××××ש×× ×××××§ ××××ª× × ×§×××, ×ש ××××× ×¡ ××ש××× ×× ××צ×ר ×ש××× ××ש.","bot",[{id:"auth_register",label:"×צ×רת ×ש×××",returnTo:i},{id:"auth_login",label:"×× ××¡× ××ש×××",returnTo:i}],!1,null,!1,!1,null,l))},[I,l]),ke=m.useCallback((i,d)=>{y(b=>b.map(P=>P.id===i?{...P,...d}:P))},[]),We=m.useCallback(()=>{ut.current&&clearTimeout(ut.current),It.current&&clearTimeout(It.current)},[]),Ft=m.useCallback(()=>{We();const i=o[o.length-1],d=(i==null?void 0:i.sender)==="bot"&&(i.formFields||i.renderComponents||i.renderManualRefinanceForm||i.renderInteractiveSlider),b=o.some(c=>c.isLoading),P=(l==null?void 0:l.step)==="awaiting_payment_prompt",V=(l==null?void 0:l.flow)&&!["initial","general_question"].includes(l.flow)&&!P;window.isLongProcessRunning||u||b||d||V||E||(ut.current=setTimeout(()=>{const c=o.some(G=>G.isLoading||G.formFields||G.renderComponents||G.renderManualRefinanceForm||G.renderInteractiveSlider),Z=(l==null?void 0:l.flow)&&!["initial","general_question"].includes(l.flow);Ee<1&&o.length>1&&!u&&!window.isLongProcessRunning&&!c&&!Z&&!E?(I("×××, ×× × ×¨××× ×©×× ××××ª× ×¤×¢×××ת ××ר ××× ×× ð¤ ×פשר ××¢××ר?","bot",[],!1,null,!1,!1,null,l),Oe(G=>G+1),It.current=setTimeout(()=>{I("× ×¨×× ×©××× ×ª××××. ×× × ××× ××× ×¢×ª ð¬ ×פשר ××××ר ×× ×עש×ת:","bot",[{id:"new_mortgage_prompt",label:"×ש×× ×ª× ××ש×"},{id:"refinance_prompt",label:"××××ר ×ש×× ×ª×"},{id:"ask_question",label:"ש×××ת ×××××ת ×¢× ×ש×× ×ª××ת"}],!1,null,!1,!1,null,l)},6e4)):(We(),Ft())},9e4))},[o,u,Ee,We,I,l,E]),et=m.useCallback(async i=>Jt(i),[]),ta=m.useCallback(async()=>{var fe,Fe,ze,Be,Ke,tt,Ve,mt,Ne,Ge,Ye,dt,xt;if(ee(!0),t.get("auth_completed")){let se=!1;try{se=!!sessionStorage.getItem("reverse_mortgage_pending")}catch{}if(se){ae(!0),we(!0),J(!1),setTimeout(()=>{L(!1),ee(!1),O(!0)},300);return}}if(t.get("auth_completed")){const se=Ae.getContextForAuth();if(se&&se.action!=="open_agent_application"){we(!0),J(!1),L(!1),ee(!1),O(!0);return}}const i=t.get("human_advisory"),d=t.get("mortgage_type");if(i==="true"){const se={flow:d==="refinance"?"refinance":"new_mortgage",step:"start",history:[],applicationId:null,human_advisory_mode:!0,selected_service_type:"human"};C(se),we(!0),J(!1),I(d==="refinance"?`××¢×××! ð ××× ×©××××¢×¥ ××××¢ ×××× ×פ××ש×, × ×ס××£ פר××× ×¢× ××ש×× ×ª× ××§×××ת. 131 132×ת ×ס×× "×תר×ת ×ס××××§" ×××× ×§ ×פשר ×××¢××ת, ×× ××××× ×ת ×פר××× ××× ×ת.`:"××¢×××! ð ××× ×©××××¢×¥ ××××¢ ×××× ×פ××ש×, × ×ס××£ פר××× ×¢× ×× ×ס ××¢× ××××××× ××××קשת.","bot",d==="refinance"?[{id:"refinance_prompt",label:"ð¦ × ×ª××× â ×××רת ×× ×§",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}]:[{id:"new_mortgage_prompt",label:"ð × ×ª××× â פר×× ×× ×ס",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],!1,null,!1,!1,null,se),setTimeout(()=>{L(!1),ee(!1),O(!0)},1800);return}if(ns(t,{addMessage:I,setContext:C,setHasStarted:we,setShowInitialHelpText:J,setShowWaitingScreen:L,setIsInitializing:ee,setIsInitialized:O}))return;const b=t.get("applicationId"),P=t.get("flow");if(P==="self_serve_advisory"&&b){const se=new URL(window.location);se.searchParams.delete("applicationId"),se.searchParams.delete("flow"),window.history.replaceState({},"",se.toString());let _e=!1,oe=null;try{const X=await K.entities.MortgageApplication.get(b);if(X!=null&&X.proposal_id){const me=await K.entities.MortgageMix.filter({proposal_id:X.proposal_id});me!=null&&me.length&&(oe=me.reduce((de,le)=>Math.min(de,le.monthly_payment||1/0),1/0),isFinite(oe)||(oe=null))}const U=await K.entities.Document.filter({application_id:b,document_type:"mortgage",document_subtype:"bank_offer",status:"processed"});_e=((U==null?void 0:U.length)||0)>0}catch(X){console.error("[Chat] self_serve_advisory context load error:",X)}
132const Se={flow:"self_serve_advisory",applicationId:b,step:"advisory"},ne=oe?` 133 134××ש××ª× ×¢×××¨× ×ª×××××× â ×××× ×××תר ××××ר ××××©× ×©× **âª${Math.round(oe).toLocaleString("he-IL")}**.`:"",Re=_e?` 135 136ר×××ª× ×©××ר ××¢××ת ××¦×¢× ×××× ×§ â ×ש×× ××¢××ר ××××× ×××ª× ××××××§ ×× ×פשר ×שפר.`:"";C(Se),we(!0),J(!1),I(`×××! ð ×× × ××× ××× ××¢××ר ×× ××××× ×ת ×ת×××× ×©×× ×××××× ×צע×ת ×××× ×§.${ne}${Re} 137 138××× ×פשר ××¢××ר?`,"bot",[{id:"mortgage_questions",label:"ð ××××× ×ת ×ת×××× ×©××",primary:!0},{id:"mortgage_questions",label:"ð¦ ××××× ××¦×¢× ×©×§××××ª× ×××× ×§"},{id:"mortgage_questions",label:'ð¬ ××פ×× ×××"× ××× ××× ×§'},{id:"mortgage_questions",label:"ð° ×¢××××ת × ×¡×ª×¨×ת ש×××× ×××××§"}],!1,null,!1,!1,null,Se),setTimeout(()=>{L(!1),ee(!1),O(!0)},1800);return}if(b){const se=new URL(window.location);se.searchParams.delete("applicationId"),se.searchParams.delete("flow"),window.history.replaceState({},"",se.toString());let _e=null;try{_e=await K.auth.me()}catch{}if(!_e){Ae.saveContextForAuth({action:"open_agent_application",applicationId:b,flow:P||"new_mortgage",returnToChat:!0,redirectToPayment:!1}),setTimeout(()=>{L(!1),ee(!1),O(!0)},500),window.location.href=Ta(`${be("AuthRedirect")}?auth_completed=true`);return}try{const oe=await K.entities.MortgageApplication.get(b);if(oe){oe.user_id||(await K.entities.MortgageApplication.update(b,{user_id:_e.id}),sessionStorage.removeItem(`active_app_check_${_e.id}`));const Se=P||(oe.application_type==="refinance"?"refinance":"new_mortgage"),ne=oe.application_type==="refinance"?"××××ר ×ש×× ×ª×":"×ש×× ×ª× ××ש×",Re=At(_e),X=Re?`ש××× ${Re}! `:"ש×××! ",U={flow:Se,applicationId:b,step:"start",agentApplication:!0};C(U),we(!0),J(!1),I(`${X}×ס××× ×¤×ª× ×¢×××¨× ×קשת ${ne}. ×פשר ××ת××× ð `,"bot",[{id:Se==="refinance"?"refinance_prompt":"new_mortgage_prompt",label:"â × ×ª×××",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],!1,null,!1,!1,null,U),setTimeout(()=>{L(!1),ee(!1),O(!0)},1800);return}}catch(oe){console.error("[Chat] Error loading agent application:",oe)}}const V=["active","awaiting_offers","pending_final_offers","completed","pending_payment","ai_review_pending","draft"];let c=null,Z=null;try{if(Z=await K.auth.me(),Z){const se=`active_app_check_${Z.id}`,_e=sessionStorage.getItem(se),oe=_e&&Date.now()-JSON.parse(_e).ts<300*1e3;if(!(!oe||oe&&((fe=JSON.parse(_e).app)==null?void 0:fe.status)==="ai_review_pending"))c=JSON.parse(_e).app;else{const Re=(await Te.MortgageApplication.filter({user_id:Z.id})||[]).sort((me,de)=>new Date(de.created_date||0)-new Date(me.created_date||0)),X=Re.filter(me=>V.includes(me.status)),U=Re.slice(0,3);if(U.length>1){const me=he=>he.application_type==="refinance"?"ð ××××ר ×ש×× ×ª×":he.application_type==="new_mortgage"?"ð ×ש×× ×ª× ××ש×":he.application_type==="investment"?"ð ×ש×× ×ª× ××שקע×":"ð¦ ת×××× ×ש×× ×ª×",de=he=>he.status==="active"?"פע××":he.status==="awaiting_offers"?"××ת×× ××צע×ת":he.status==="pending_final_offers"?"×צע×ת ס×פ××ת":he.status==="completed"?"××ש××":he.status==="ai_review_pending"?"×××××§×":he.status==="pending_payment"?"××ת×× ×תש×××":(he.status==="draft","××¨× ×ª×©×××"),le=At(Z),Pe=le?`××× ${le}! `:"×××! ",xe=U.map(he=>({id:`_select_application_${he.id}`,label:`${me(he)} â ${de(he)} (${new Date(he.created_date).toLocaleDateString("he-IL")})`,_applicationId:he.id}));xe.push({id:"_navigate_my_process",label:"ð ×× ×ת××××××",_url:`${be("MyProcess")}?tab=history`}),xe.push({id:"_start_new_process_choice",label:"ð ת×××× ××ש"}),I(`${Pe}×ש ×× ××× ×ª×××××× ×¤×ª×××× ð 139 140××××× ×ª×¨×¦× ××ת××§× ×¢×ש××?`,"bot",xe,!1,null,!1,!1,null,{}),we(!0),J(!1),setTimeout(()=>{L(!1),ee(!1),O(!0)},1800);return}c=X[0]||null,(c==null?void 0:c.status)!=="ai_review_pending"&&sessionStorage.setItem(se,JSON.stringify({app:c,ts:Date.now()}))}}}catch{}if(c){Ae.clearSession();const se=At(Z),_e=se?`××× ${se}! `:"×××! ";let oe,Se;if(["pending_payment","draft"].includes(c.status)){const ne=await Aa(c.id,c),Re=c.current_bank_name,X=c.id,U=c.application_type,de={bank:Re,flow:U==="refinance"||U==="any_purpose"?"refinance":"new_mortgage",applicationId:X,initialAnalysis:ne,application_type:U};if(C(le=>({...le,...de})),we(!0),J(!1),(Fe=ne==null?void 0:ne.tracks_analysis)!=null&&Fe.length)if(c.selected_scenario_details){const le=c.selected_scenario_details,Pe=le.newMonthlyPayment||le.monthly_payment||le.monthlyPayment,xe=Pe?le.type==="payment"?`××§×× ×ª תש××× ××××©× ×-âª${Pe.toLocaleStr
140ing("he-IL")}`:`×§×צ×ר תק××¤× ×¢× ×××ר âª${Pe.toLocaleString("he-IL")}`:"ש×× ×× ×ª× ×× ××ש×× ×ª×",he={...de,step:"scenario_selected",selected_scenario_details:le,originalTracks:ne.tracks_analysis,initialAnalysis:ne};I(`${_e}ר×××ª× ×©×× ×ת×× ××ש×× ×תר××ש × ××ר ð¯ 141 142×× × ×¡×××× × ×ת×× ××ש×× ×ª× ×©××:`,"bot",[],!1,null,!1,!1,{summaryCardProps:{analysis:ne,hideButtons:!0},collapsibleTracksSectionProps:{analysis:ne}},he),setTimeout(()=>{I(`**×תר××ש ×©× ××ר:** ${xe} 143 144××¦×¢× ×××: ×§××ת ×צע×ת ×××× ×§××. ××ש××××?`,"bot",[{id:"_resume_pending_payment_service",label:"â ××, × ×ש××",primary:!0},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],!1,null,!1,!1,null,he)},800),C(He=>({...He,...he,_pendingRecovery:"service",_pendingAnalysis:ne,_pendingScenarioDesc:xe}))}else{const le={...de,originalTracks:ne.tracks_analysis,initialAnalysis:ne,step:"data_collected",application_type:U};I(`${_e}ר×××ª× ×©×ש × ×ת×× ×××× ð 145 146×× × ×¡×××× × ×ת×× ××ש×× ×ª× ×©××:`,"bot",[],!1,null,!1,!1,{summaryCardProps:{analysis:ne,hideButtons:!0},collapsibleTracksSectionProps:{analysis:ne}},le),setTimeout(()=>{I("ð¡ ×¢×ש×× ××× × ××ר ×ת ×××××× ××ת××× ××:","bot",[{id:"_resume_pending_payment_scenario",label:"â ××ר תר××ש ××§××",primary:!0},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],!1,null,!1,!1,null,le)},800),C(Pe=>({...Pe,...le,_pendingRecovery:"scenario",_pendingAnalysis:ne}))}else{const le=Re?await et(Re):null,Pe=U==="refinance"||U==="any_purpose"?le?`ת×××× ××××ר ×${le}`:"ת×××× ××××ר":"ת×××× ×ש×× ×ª× ××ש×";I(`${_e}ר×××ª× ×©×ת××ת ${Pe} ð 147 148×פשר ×××ש×× ××××¤× ×©×¢×¦×¨×ª?`,"bot",[{id:"_resume_pending_payment_upload",label:"â ××, × ×ש××",primary:!0,_recoveryCtx:de,_bankDisplayName:le},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],!1,null,!1,!1,null,{...de}),C(xe=>({...xe,...de,_pendingRecovery:"upload",_bankDisplayName:le}))}setTimeout(()=>{L(!1),ee(!1),O(!0)},1800);return}else if(c.status==="completed")oe=`${_e}×ת×××× ×סת××× ××צ××× ð 149 150×ת ×× ×××××¢, ××ס×××× ×××צע×ת ×פשר ××צ×× ××××ר ×××ש×. ××× ×פשר ××¢××ר?`,Se=[{id:"go_to_my_process",label:"ð ×××ר ××ש×",primary:!0},{id:"refinance_prompt",label:"ð° × ×ת×× ×ש×× ×ª× × ×ספת"},{id:"contact_support",label:"ð¬ ×¤× ××× ×צ××ת"},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],I(oe,"bot",Se),C(ne=>({...ne,activeApplication:c,applicationId:c.id,flow:"active_process"}));else{if(c.status==="ai_review_pending"&&((Be=(ze=c.analysis_results)==null?void 0:ze.tracks_analysis)!=null&&Be.length)&&!c.selected_scenario_details){const X=c.analysis_results,U=c.application_type,de={bank:c.current_bank_name,flow:U==="refinance"?"refinance":"new_mortgage",applicationId:c.id,initialAnalysis:X,originalTracks:X.tracks_analysis,step:"data_collected",application_type:U};I(`${_e}ר×××ª× ×©×ש × ×ת×× ×××× ð 151 152×× × ×¡×××× × ×ת×× ××ש×× ×ª× ×©××:`,"bot",[],!1,null,!1,!1,{summaryCardProps:{analysis:X,hideButtons:!0},collapsibleTracksSectionProps:{analysis:X}},de),setTimeout(()=>{I("ð¡ ×¢×ש×× ××× × ××ר ×ת ×××××× ××ת××× ××:","bot",[{id:"_resume_pending_payment_scenario",label:"â ××ר תר××ש ××§××",primary:!0},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"}],!1,null,!1,!1,null,de)},800),C(le=>({...le,...de,_pendingRecovery:"scenario",_pendingAnalysis:X})),J(!1),we(!0),setTimeout(()=>{L(!1),ee(!1),O(!0)},1800);return}const ne={activeApplication:c,applicationId:c.id,flow:"active_process",step:"active"};if(C(X=>({...X,...ne})),c.selected_mix&&c.selected_scenario_details){const X=c.analysis_results,U=c.selected_scenario_details,de={reduce_monthly_payment:"××§×× ×ª תש××× ××××©× ð",shorten_period:"×§×צ×ר תק××¤× â±ï¸",cash_out:"××××ת ×ש×× ×ª× ð°"}[c.refinance_goal]||"ש×× ×× ×ª× ×× ××ש×× ×ª×",le={conservative:"ש××¨× ×",balanced:"×××××",aggressive:"××רס×××"}[c.selected_mix_type]||"",Pe=(U==null?void 0:U.newMonthlyPayment)||(U==null?void 0:U.monthly_payment),xe=Pe?` â ×××ר ××××©× ×©× âª${Math.round(Pe).toLocaleStr
152ing("he-IL")}`:"";I(`${_e}×××§×©× ×©×× ×××פ×× ×¤×¢×× ð 153 154×× × ×¡×××× ×× ×ת×× ×©×××¦×¢× ×:`,"bot",[],!1,null,!1,!1,X?{summaryCardProps:{analysis:X,hideButtons:!0},collapsibleTracksSectionProps:{analysis:X}}:null,ne),setTimeout(()=>{const he=le?` 155**ת×××× ×©× ××ר:** ${le} â `:"";ge(`**××רת ×××××ר ×©× ××ר×:** ${de}${xe}${he} 156 157×ת×××× ××¢×צ××× â ×פשר ××¢×§×× ××ש××× ×××.`,[{id:"_navigate_my_process",label:"ð ×¢××ר ××××ר ×××ש×",primary:!0},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"},{id:"contact_support",label:"ð¬ ×¤× ××× ×צ××ת"},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"}])},800)}else{const X=c.analysis_results;if((Ke=X==null?void 0:X.tracks_analysis)!=null&&Ke.length){const U={...ne,initialAnalysis:X,originalTracks:X.tracks_analysis};C(me=>({...me,...U})),I(`${_e}×ש ת×××× ×¤×¢×× ×©××ת×× ð 158 159×× × ×¡×××× × ×ת×× ××ש×× ×ª× ×©××:`,"bot",[],!1,null,!1,!1,{summaryCardProps:{analysis:X,hideButtons:!0},collapsibleTracksSectionProps:{analysis:X}},U),setTimeout(()=>{var Pe;const me=(Pe=X.tracks_analysis)==null?void 0:Pe.some(xe=>{var he;return(he=xe.individual_recommendation)==null?void 0:he.includes("××××ר")}),de=me?"×¢×ש×× ××× × ××××§ ×××× ××××× ××× ×ת×××:":"×¢×××× ×ש ××§×× ×שק×× ×©×× ×××× ××ת×× ×צר×××. ×× ××¢× ×××?",le=[{id:"reduce_payment_scenario",label:"×××§××× ×ª×©××× ×××ש×",primary:!0},{id:"shorten_period_scenario",label:"××ס×× ×תש××× ××××× (×§×צ×ר תק×פ×)"},{id:"cash_out_scenario",label:"×××××× ×ש×× ×ª× (××§×× ×סף)"},...me?[]:[{id:"remind_me_later",label:"ת×××¨× ×× ×ש×××× ×××× ××××ר"}]];I(de,"bot",le,!1,null,!1,!1,null,U)},800)}else{const U=He=>He?`âª${new Intl.NumberFormat("he-IL").format(Math.round(He))}`:null,de={active:"פע××",awaiting_offers:"××ת×× ××צע×ת ×××× ×§××",pending_final_offers:"×צע×ת ס×פ××ת ×תק×××"}[c.status]||"×××פ××",Pe=!(c.application_type==="refinance"||c.application_type==="any_purpose");let xe="";if(Pe){const He=c.loan_amount||c.requested_amount;He&&(xe+=` 160ð° ס××× ×ש×× ×ª×: **${U(He)}**`),c.estimated_monthly_payment&&(xe+=` 161ð ×××ר ××××©× ×ש×ער: **${U(c.estimated_monthly_payment)}**`),c.property_value&&(xe+=` 162ð ש××× × ×ס: **${U(c.property_value)}**`),c.monthly_income&&(xe+=` 163ð¼ ××× ×¡× ×××ש×ת: **${U(c.monthly_income)}**`)}else{const He=c.loan_components;if((He==null?void 0:He.length)>0)xe+=` 164 165**×ס×××× ××ש×× ×ª× ××§×××××:**`,He.forEach((Me,pn)=>{const mn=Me.track_type||Me.track_name||`×ס××× ${pn+1}`,ca=U(Me.balance||Me.amount),ua=Me.interest_rate?`${Number(Me.interest_rate).toFixed(2)}%`:null,pa=Me.remaining_months?`${Math.round(Me.remaining_months/12)} ×©× ××`:Me.remaining_term_years?`${Me.remaining_term_years} ×©× ××`:null;xe+=` 166⢠${mn}${ca?` â ${ca}`:""}${ua?` | ר×××ת ${ua}`:""}${pa?` | ${pa}`:""}`});else{const Me=c.loan_amount||c.requested_amount;Me&&(xe+=` 167ð° ×תרת ×ש×× ×ª×: **${U(Me)}**`),c.current_bank_name&&(xe+=` 168ð¦ ×× ×§: **${c.current_bank_name}**`)}}I(`${_e}×ש ת×××× ${Pe?"×ש×× ×ª× ××ש×":"××××ר"} פע×× ×ס×××ס: **${de}** ð${xe} 169 170××¦×¢× ××× â ×××× ×¡ ××××ר ××××©× ×צפ××× ×ת×××××× ×××צע×ת ××× ×§××.`,"bot",[{id:"_navigate_my_process",label:"ð ×¢××ר ××××ר ×××ש×",primary:!0,_url:be("MyProcess")},{id:"mortgage_questions",label:"â ×ש ×× ×©×××"},{id:"_start_new_process_choice",label:"ð ת×××× ××ש"}])}}}J(!1),we(!0),setTimeout(()=>{L(!1),ee(!1),O(!0)},1800);return}const G=Ae.getLastSession();if(G&&G.messages&&G.messages.length>0){sessionStorage.getItem("bina_chat_visit_counted")||(localStorage.setItem("bina_chat_return_count",String(Number(localStorage.getItem("bina_chat_return_count")||0)+1)),sessionStorage.setItem("bina_chat_visit_counted","true"));const se=(G.messages||[]).filter(ne=>!ne.isLoading),_e=se.length>0&&["awaiting_upload","initiating_auth","auth_required_for_upload"].includes((tt=G.context)==null?void 0:tt.step);if((G.was_interrupted||_e)&&((Ve=G.context)!=null&&Ve.applicationId)){const ne=G.context.applicationId,Re=G.context.bank;y(se),C(G.context),we(!0),J(!1);try{const X=await Te.MortgageApplication.get(ne);if(((Ne=(mt=X==null?void 0:X.analysis_results)==null?void 0:mt.tracks_analysis)==null?void 0:Ne.length)>0){const U=X.analysis_results,me={...G.context,initialAnalysis:U,originalTracks:U.tracks_analysis,flow:"refinance",step:"data_collected"};C(me),ge("ר×××ª× ×©×צ×ת ×××צע â ×× ×ת×× ××ר ××ש×× â ×× × ×ת×צ××ת:",[],!1,null,!1,!1,{summaryCardProps:{analysis:U,hideButtons:!0},collapsibleTracksSectionProps:{analysis:U}},me),setTimeout(()=>{const de=(U.total_savings_potential||0)>0;ge("ð¡ ×¢×ש×× ××× × ××××§ ×××× ××××× ××× ×ת×××:",[{id:"reduce_payment_scenario",label:"ð ×××§××× ×ª×©××× ×××ש×"},{id:"shorten_period_scenario",label:"â±ï¸ ×קצר תק××¤× ××ס×××"},{id:"cash_out_scenario",label:"ð° ×××××× ×ש×× ×ª× (×§××ת ×סף)"}
170,de?{id:"proceed_with_savings",label:"â ××ש××× ×¢× ××ס××× ×××",primary:!0}:{id:"request_reminder",label:"ð ת×××¨× ×× ×ש×שת×× ××××ר"}])},1500)}else if(X!=null&&X.documents_request_sent_date){const U=X.application_type||((Ge=G.context)==null?void 0:Ge.application_type),me=U==="new_mortgage"||U==="investment"||U==="construction";ge(me?`ר×××ª× ×©×צ×ת ×××צע ð ×××××¢ ××¢××× ×רקע. 171 172××ש××××?`:"ר×××ª× ×©×צ×ת ×××צע ð ××ס×× ×תק×× ×××¢××× ×רקע.",me?[{id:"new_mortgage_prompt",label:"ð ××ש××× ××ש××××",primary:!0},{id:"start_over",label:"ðï¸ ×ת×× ×××ש"}]:[{id:"resume_upload_flow",label:"ð ×¨×¢× × ×××××§",primary:!0},{id:"manual_refinance_entry",label:"âï¸ ××× × ×ª×× ×× ××× ×ת"},{id:"start_over",label:"ðï¸ ×ת×× ×××ש"}]),C(de=>({...de,resumePending:!0,resumeBank:Re,resumeApplicationId:ne,application_type:U}))}else{const U=X.application_type||((Ye=G.context)==null?void 0:Ye.application_type),me=U==="new_mortgage"||U==="investment"||U==="construction";ge(me?`ר×××ª× ×©×צ×ת ×××צע ת×××× ×ש×× ×ª× ×××©× ð 173 174×פשר ×××ש×× ××××¤× ×©×¢×¦×¨× ×?`:`ר×××ª× ×©×צ×ת ×××צע ת×××× ×××××ר ð 175 176×פשר ×××ש×× ××××¤× ×©×¢×¦×¨× ×?`,me?[{id:"new_mortgage_prompt",label:"ð ××ש××× ××ש××××",primary:!0},{id:"start_over",label:"ð ×ת×× ×××ש"}]:[{id:"resume_upload_flow",label:"â ××, ××ש×××",primary:!0},{id:"start_over",label:"ð ×ת×× ×××ש"}]),C(de=>({...de,resumePending:!0,resumeBank:Re,resumeApplicationId:ne,application_type:U}))}}catch(X){console.error("[Chat] Error checking DB for interrupted session:",X),y(se.length?se:[])}setTimeout(()=>{L(!1),ee(!1),O(!0)},1800);return}if(G.was_interrupted&&((dt=G.context)!=null&&dt.manualTracks)){y(se),C(G.context),we(!0),J(!1),ge("ר×××ª× ×©×צ×ת ×××צע × ×ת×× ××× × ð ××ש××××?",[{id:"resume_manual_analysis",label:"â ××, ××ש××××",primary:!0},{id:"start_over",label:"ð ×ת×× ×××ש"}]),setTimeout(()=>{L(!1),ee(!1),O(!0)},1800);return}if((G.lastUpdated?(Date.now()-new Date(G.lastUpdated).getTime())/(1e3*3600):0)>4&&(Z==null?void 0:Z.full_name)){const ne=At(Z);y([{id:`welcome_back_${Date.now()}`,content:`×ר×××× ×ש×××, ${ne}! ð ××ש×××× ××××¤× ×©×¢×¦×¨× ×.`,sender:"bot",timestamp:new Date,options:[],isSilent:!1,isLoading:!1},...se])}else y(se);G.context&&C(G.context),J(!1),we(!0)}else{const se=t.get("flow"),_e=as(),oe=Va(se,_e);if(oe)I(oe.message,"bot",oe.options,!1,null,!1,!1,oe.renderComponents||null,oe.context),C(Se=>({...Se,...oe.context}));else{const Se=` 177 178ð _×××××¢ ×©× ×סר ×ש××× × ×©×ר ××××¤× ×××××× ×××©× 90 ××× ××ש×ש ×× ×רק ×ת×××× ××ש×× ×ª×._`,ne=[`ð ×××, ×× × ××× × â ××¢××רת ××××××××ת ×××ש×ת ש××× ××ש×× ×ª××ת. 179 180×פשר ××ת×××¢×¥ ×××ª× ×××¢× ×¢× ×× × ××©× ×©×§×©×ר ××ש×× ×ª××ת, ×× ×ª× ×פשר×××ת ×××תק×× ×××××××ת. ××××צ×ת ש×× ×¢××ר×ת ××§×¨× ×קצ××¢×ת ×©× ×צ××ת; ×× ×ª×¨×¦× ×©××ת ×¢×××§ ××ש×ת, ×פשר ××××ר ×× ×××. 181 182פש×× ×ת×× ×× ×××× ×ת ×ש××× ×©×××, ×× ×××¨× ×××× ××× ×ש××× ×©××× ×ª× ×××:${Se}`,`⨠ש×××! ×× × ××× × â ×-AI ××××©× ×©××× ××ש×× ×ª××ת. 183 184×× × ××××× ××¢× ×ת ×¢× ×©×××ת, ×ס×××¢ ×××× ×ª × ×ª×× ×× ××××××× ×ת×× ××ס××× ××××××× ××× â ×ש×× ×ª× ××ש×, ××××ר, ×××ר××, ר××××ת ××ס×××××. ××××צ×ת ש×× ×¢××ר×ת ××§×¨× ×קצ××¢×ת, ×××©×ª×¨×¦× ×פשר ×× ××××ר ××××× ×××©× ×©× ×××××. 185 186×ת×× ×× ×××פש××ת ×× ××¢× ××× ×ת××, ×× ×××¨× × ××©× ××רש××× ×©××× ×ª×:${Se}`,`ð° ש××× ×©××ª× ×××! ×× × ××× × â ×××¨× ××××××××ת ××××× ××××× ××× ×× ×ש×× ×ª×. 187 188×פשר ×ש××× ×××ª× ×××¢× ×× ××ר, ××תק×× ××§×¦× ×©××× ×¢× ×××צ×ת ×××§×¨× ×קצ××¢×ת, ××× ×ª×××¨× â ×××ס××£ ×× ×××¢××¥ ×××©× ×©× ×××××. 189 190פש×× ×ת×× ×× ×ת ×ש××× ××××, ×× ×××¨× ×××× ××× ×ש××× ×©××× ×ª× ×××:${Se}`];I(ne[Math.floor(Math.random()*ne.length)],"bot",[{id:"new_mortgage_prompt",label:"ð ××§×ת ×ש×× ×ª×",primary:!0},{id:"open_buying_capacity_calculator",label:"ð ×××××§ ×¢× ×××× ×××ר ×פשר ××§× ×ת ××ר×"},{id:"refinance_prompt",label:"ð° ×שפר ×ש×× ×ª× ×§×××ת"},{id:"prepayment_advisory",label:"ð¸ ××××× ×× ×××× ×פר××¢"},{id:"mortgage_questions",label:"â ×ש××× ×©××× ×¢× ×ש×× ×ª×"},{id:"contact_support",label:"ð¬ ××¤× ×ת ×צ××ת"}]),J(!0),qn(document.referrer||"direct"),ha.track("chat_opened",{source_page:d
190ocument.referrer||"direct",device_type:window.innerWidth<768?"mobile":"desktop",flow:((xt=oe==null?void 0:oe.context)==null?void 0:xt.flow)||null})}if(we(!0),se){const Se=new URL(window.location);Se.searchParams.delete("flow"),window.history.replaceState({},"",Se.toString())}}setTimeout(()=>{L(!1),ee(!1),O(!0)},1800)},[I,t,et]),Ga=m.useCallback(async()=>{try{const d=[];for(let b=0;b<sessionStorage.length;b++){const P=sessionStorage.key(b);P&&P.startsWith("active_app_check_")&&d.push(P)}d.forEach(b=>sessionStorage.removeItem(b))}catch{}Ae.clearSession()?(pt({title:"×ש××× × ×קת×",description:"×ת××××× ×©××× ××ש×."}),window.location.reload()):pt({title:"ש×××× ×× ××§×× ×ש×××",description:"×× × ×¨×¢× × ×ת ××¢××× ×× ×¡× ×©××.",variant:"destructive"})},[pt]),Ya=async(i,d,b)=>{if(!i||i.length===0){I("×× ×תק××× ×ס×××× ð ×פשר ×× ×¡×ת ש××.","bot",[],!1,null,!1,!1,null,l);return}re(!0),J(!1),jt.current=null,Vn(l.flow||"refinance"),ha.track("document_upload_started",{flow:l.flow,bank:l.bank});const P=Date.now(),V={...l,applicationId:b,step:"refinance_questionnaire"},c=new Promise(Z=>{st.current={resolve:Z,applicationId:b,analysisReady:!1}});I("××ס×× ×תק××. ×× × ×××קת ×ת ××ס×××××, ×ר××××ת ××¢×××ת ×פ×רע×× ××× ×ª× ×× ×ש××§.","bot",[],!1,null,!1,!1,null,V,!1,!1,!1,P),I("×××× ×©×× × ×× ×ª×ת ×ת ××ס××, ×× ××× ×ש×× ××× ××ש×× ××××××ר?","bot",Yn(),!1,null,!1,!1,{refinancePreferencesStep:{step:"goal"}},V),C(V),re(!1),Ka(i,d,P,b,c,()=>{st.current&&(st.current.analysisReady=!0)}).catch(()=>{st.current&&(st.current.failed=!0),L(!1),re(!1),ke(P,{content:"×× ×צ××× × ××ש××× ×ת ×¢×××× ××ס××. ×פשר ×× ×¡×ת ××¢××× ×××רת ×× ××¢××ר ×××× × ××× ×ת.",isLoading:!1,options:[{id:"choose_upload_document",label:"ð ××¢××× ×××רת",primary:!0},{id:"manual_input_refinance",label:"â¨ï¸ ××× × ××× ×ת"}],renderComponents:null})})};m.useCallback((i,d=!1)=>{const b=d?" × ×¡× ×©××.":"";I(`××× ××ת×××, ×פשר ×××¢××ת ×ת ×ס×× "×תר×ת ×ס××××§" ${i?`×${i}`:""}.${b}`,"bot",[],!0,null,!1,!1,null,{...l,step:"awaiting_upload"}),J(!1)},[l,I]);const Ja=async i=>{var V;if(i&&i.preventDefault&&i.preventDefault(),!f.trim()||u||S||E)return;We(),Oe(0);const d=f.trim();if(l.awaitingPhoneForReminder){I(d,"user"),$(""),r(!0);try{const c=await K.auth.me().catch(()=>null),Z=l.reminderAnalysis||l.initialAnalysis,G=(Z==null?void 0:Z.estimated_monthly_savings)||0;await Te.RefinanceReminder.create({user_id:(c==null?void 0:c.id)||null,phone:d,email:(c==null?void 0:c.email)||null,application_id:l.applicationId,original_analysis:Z,original_savings_potential:G,current_savings_potential:G,status:"active",next_check_date:new Date(Date.now()+720*60*60*1e3).toISOString()}),zn(),ge("××¢×××! ð ×ת×××רת × ×©××¨× ××צ×××. ×××××§ ×ת ×ש××§ ××××¤× ×§×××¢, ××ש×××× ×××× ××××ר â ×ש×× ××××¢×.",[{id:"mortgage_questions",label:"â ש×××ת × ×ספ×ת"}]),C(fe=>({...fe,awaitingPhoneForReminder:!1,reminderAnalysis:null,step:"reminder_saved"}))}catch{ge("×××¨×¢× ×©×××× ×ש××רת ×ת×××רת ð ×פשר ×× ×¡×ת ש×× ×× ××¤× ×ת ×ת××××.")}r(!1);return}let b=!1;const P=o.slice().reverse().find(c=>c.sender==="bot");if(P&&P.options&&P.options.length>0){const c=Ce+1;je(c),c>=2&&(b=!0)}else je(0);I(d,"user",[],!1,null,!1,!1,null,l),$(""),r(!0),J(!1);try{const c=await Ie.processUserMessage(d,l);if(r(!1),c){const Z=b&&c.options&&c.options.length>0,G=["final_confirm_payment_automated_consultation","prefer_human_advisor","×××©× ×תש×××"];(V=c.options)!=null&&V.some(fe=>G.includes(fe.id)||G.some(Fe=>{var ze;return(ze=fe.label)==null?void 0:ze.includes(Fe)}))&&(window.isAtPricingStep=!0),I(c.message,c.sender||"bot",c.options||[],c.showUpload||!1,c.formFields||null,!1,c.isLoading||!1,c.renderComponents||null,c.context,!1,c.renderInteractiveSlider||!1,Z,Date.now(),c.nextAction,null,c.showDisclaimer||!1),Z&&je(0)}}catch(c){console.error("Error processing user message:",c),r(!1),I("×××¨×¢× ×©×××× ××¢×××× ×××××¢×. ×פשר ×× ×¡×ת ש×× ×× ××××ר ××ת ×××פשר×××ת ××××ת:","bot",[{id:"new_mortgage_prompt",label:"×ת××ת ת×××× ×ש×× ×ª× ××ש×",primary:!0},{id:"refinance_prompt",label:"×××קת ×××××ת ××××ר"}],!1,null,!1,!1,null,l)}},Xa=()=>{var i;return(i=Ue.current)==null?void 0:i.click()},aa=m.useCallback(()=>{y(i=>{const d=i.map(P=>{var V;return(V=P.renderComponents)==null?void 0:V.servicePaths}).lastIndexOf(!0);if(d===-1)return i;const b=i.slice(0,d).map(P=>{var V;return(V=P.options)==null?void 0:V.some(c=>c.id==="read_service_payment_details")}).lastIndexOf(!0);return i.filter((P,V)=>V!==d).map((P,V)=>V===b?{...P,id:`${P.id}-restored-${Date.now()}`}:P)})},[]),qe=m.useCallback(ts({context:l,messages:o,isLoading:u,isUploading:S,showRedirectAnimation:E,basePrice:F,setIsLoading:r,setBasePrice:Q,setCurrentApplication:g,setContext:C,setNextAction:H,setInteractiveSlider:R,setCashOutCalculator:D,setNewMortgageForm:B,setReverseMortgageFlow:ae,setFormPropsForNewM
190ortgage:j,setShowManualRefinanceForm:T,setShowInitialHelpText:J,setInactivityMessageCount:Oe,setConsecutiveFreeTextCount:je,addMessage:I,addBotMessage:ge,updateMessage:ke,clearInactivityTimers:We,handleGoToScheduleOption:i=>{ge("××¢××ר ×××ª× ×××£ ×§××עת ×פ××ש×... ð "),setTimeout(()=>a(i._scheduleUrl||be("Schedule")),1500)},returnToServiceOptions:aa,navigate:a,redirectToAuth:Ze}),[l,o,u,S,E,F,I,ge,ke,We,aa,a,Ze]),Ka=async(i,d,b,P,V,c)=>{if(l.flow==="prepayment"){if(!l.prepaymentAmount){ke(b,{content:"××× ×סף ×ש ×× ×××× ×פרע××?",isLoading:!1,renderComponents:{prepaymentAmountSlider:{minAmount:1e4,maxAmount:3e6}},options:[],context:{...l,bank:d,step:"prepayment_amount_selection"}}),C(Z=>({...Z,bank:d,step:"prepayment_amount_selection",_pendingFiles:i})),r(!1);return}await Qa(i,d,b,P);return}await es(i,d,b,P,l,{updateMessage:ke,addBotMessage:ge,setIsLoading:r,setContext:C,setShowWaitingScreen:L,setWaitingScreenMode:w,setWaitingScreenProgress:x,handleCashOutSubmit:Dt,waitForQuestionnaire:V,onAnalysisReady:c})},Qa=(i,d,b,P)=>va(i,d,b,P,l,{checkDocumentStatus:De.checkDocumentStatus,updateMessage:ke,addBotMessage:ge,setIsLoading:r,setContext:C,setShowWaitingScreen:L,setWaitingScreenMode:w,setWaitingScreenProgress:x}),Za=async i=>{i.preventDefault();const d=i.target.files;if(!d||d.length===0||E)return;const b=t.get("bank"),P=b||l.bank;if(!P){I("×××¨×¢× ×©××××. ×× ×××× ××× ×§ ×¢×××¨× ×¦×¨×× ××¢×× ×ת ××ס×××× ð¦ ×פשר ××ת××× ×ת ×ת×××× ×××ש.","bot",[],!1,null,!1,!1,null,l);return}let V=l.applicationId;if(!V){let c=null;try{c=await K.auth.me()}catch{}if(!c){Ae.saveContextForAuth({action:"prompt_for_upload",bank:P,bankDisplayName:l.bankDisplayName||P,flow:l.flow||"refinance",returnToChat:!0,redirectToPayment:!1,returnState:{context:l}}),Ze(`${be("AuthRedirect")}?auth_completed=true`);return}try{V=(await Te.MortgageApplication.create({client_name:c.full_name||"",email:c.email||"",phone:c.phone||"",application_type:"refinance",status:"draft",data_source:"file_upload",user_id:c.id,...l.monthly_income>0&&{monthly_income:l.monthly_income},current_bank_name:P||null})).id,C(G=>({...G,applicationId:V}))}catch(Z){console.error("[Chat] Error creating MortgageApplication:",Z),I("×××¨×¢× ×©×××× ××צ×רת ×××§×©× ð ×פשר ×× ×¡×ת ש××.","bot",[],!1,null,!1,!1,null,l);return}}try{await Ya(d,P,V)}catch(c){console.error("[Chat] Critical error during file upload flow:",c),r(!1),re(!1),window.isLongProcessRunning&&(window.isLongProcessRunning=!1),I("×××¨×¢× ×©×××× ×××ª× ×¦×¤××× ×ת×××× ××¢××ת ××§×צ×× ð ×פשר ×× ×¡×ת ש××.","bot",[],!1,null,!1,!1,null,l)}if(b){const c=new URL(window.location);c.searchParams.delete("action"),c.searchParams.delete("bank"),c.searchParams.delete("is_new_user"),window.history.replaceState({},"",c.toString())}i.target.value=null},na=m.useCallback((i,d=[])=>{var G;if((G=st.current)!=null&&G.analysisReady)return!1;const b=["risk_preference","liquidity","co_borrower"].find(fe=>!d.includes(fe));if(!b)return!1;const P={risk_preference:"×××× ×©××××××¥ ×¢×××× ×תק××, ×× ×ש×× ××× ××תר ×ת×××× ×××ש?",liquidity:`××× ×¦×¤×× ××××× ×¡ ××× ×¡××× ×ש××¢××ª× ××©× ×× ×קר×××ת? 191_(×§×¨× ×שת×××ת, ×ר×ש×, ××× ×ס ×× ×××רת × ×ס)_`,co_borrower:"××× ×××××ר ×××צע ×× ×¢× ××/×ת ××× ××××××?"},V={risk_preference:[["conservative","ð¡ï¸ ×צ×××ת ×ש××× ××"],["moderate","âï¸ ××××× ××× ×צ×××ת ×××ס×××"],["aggressive","ð ×××ש×ת ×××ס××× ×ר××"]],liquidity:[["yes","â ××, ×ס××ר×ת ×××××"],["maybe","ð¤ ××××, ×× ××××××"],["no","â ×× ×¦×¤××"]],co_borrower:[[!1,"××, ×××××ר ×¢× ×©×× ××××"],[!0,"××, ×× ××/×ת ××× ×××××"]]},c={...i,step:`refinance_enrichment_${b}`,refinanceEnrichmentSteps:d},Z=Date.now()+Math.random();return jt.current=Z,C(c),I(P[b],"bot",V[b].map(([fe,Fe])=>({id:`refinance_enrichment_${b}`,label:Fe,value:fe,refinancePreferenceStep:b}
191)),!1,null,!1,!1,null,c,!1,!1,!1,Z),!0},[I]),Wa=async({step:i,value:d},b)=>{const P=st.current;if(!P)return;const V=P.applicationId||l.applicationId,c={...l.refinancePreferences||{}},Z={reduce_payment:"reduce_monthly_payment",shorten_period:"reduce_total_cost",cash_out:"cash_out"},G={reduce_payment:"××פ××ת ×ת ××××ר ××××ש×",shorten_period:"××ס×× ××¢××ת ×××××ת",cash_out:"××§×× ×¡××× × ×סף ××× ×ס"},fe={},Fe={income:`××× ×¡× ×××ש×ת × ×× ×©× ×שק ×××ת: ${Je(d)}`,other_loans:d?"×ש ××××××ת × ×ספ×ת פת×××ת.":"××× ××××××ת × ×ספ×ת פת×××ת.",other_loans_payment:`×××ר ××××©× ×¢× ××××××ת × ×ספ×ת: ${Je(d)}`,risk_preference:{conservative:"××¢××¤× ×ת×××× ×צ××.",moderate:"××¢××¤× ×××××× ××× ×צ×××ת ×××ס×××.",aggressive:"××¢××¤× ××××ש×ת ××××ת ××ס××× ×ר××."}[d],liquidity:{yes:"צפ×× ×¡××× ×ש××¢××ª× ××©× ×× ×קר×××ת.",maybe:"××ת×× ×©×××× ×¡ ס××× ×ש××¢××ª× ××©× ×× ×קר×××ת.",n
191o:"×× ×¦×¤×× ×¡××× ×ש××¢××ª× ××©× ×× ×קר×××ת."}[d],co_borrower:d?"×××××ר ×××צע ×× ×¢× ××/×ת ××× ××××××.":"×××××ר ×××צע ×¢× ×©× ×××× ××××.",property_value:`ש××× × ×ס ×ש×ער: ${Je(d)}`,requested_amount:`ס××× × ×סף ×××קש: ${Je(d)}`};if(i==="goal")c.intent=d,fe.client_goal=Z[d]||"stability";else{c[i]=d;const Ne={income:"monthly_income",other_loans:"existing_loans",other_loans_payment:"existing_loans_monthly_payment",risk_preference:"client_risk_preference",liquidity:"future_liquidity_expectation",co_borrower:"has_spouse_as_borrower",property_value:"property_value",requested_amount:"requested_amount"};fe[Ne[i]]=d}try{await Te.MortgageApplication.update(V,fe),ke(b,{renderComponents:null})}catch(Ne){throw console.error("[Chat] Failed to save refinance preference:",Ne),Ne}if(I(i==="goal"?`××××¨× ×©× ××ר×: ${G[d]}.`:Fe[i],"user"),["risk_preference","liquidity","co_borrower"].includes(i)){jt.current=null;const Ne=[...l.refinanceEnrichmentSteps||[],i],Ge={...l,refinancePreferences:c,refinanceEnrichmentSteps:Ne};if(na(Ge,Ne))return;
191const Ye={...P.questionnaireContext||Ge,refinancePreferences:c,refinanceEnrichmentSteps:Ne};C(Ye),P.resolve({...Ye,applicationId:V}),P.analysisReady||(w("analyzing_mortgage"),L(!0));return}const Be=i==="goal"?"income":i==="income"?"other_loans":i==="other_loans"&&d?"other_loans_payment":i==="other_loans"&&c.intent==="cash_out"||i==="other_loans_payment"&&c.intent==="cash_out"?"property_value":i==="property_value"?"requested_amount":null;if(Be){const Ne={...l,step:`refinance_questionnaire_${Be}`,refinancePreferences:c};C(Ne),I({income:"××× ××ת××× ×ת ×תר××ש×× ×××××ת ××××ר, ××× ×××× ×¡× ××××ש×ת × ×× ×©× ×שק ×××ת?",other_loans:"××× ×ש ××× ××××××ת פת×××ת × ×ספ×ת, ××¢×ר ××ש×× ×ª× ×©×× × ×× ×ª×ת?",other_loans_payment:"××× ××ª× ××××ר×× ××× ××× ×××ש ×¢× ×××××××ת ×× ×ספ×ת?",property_value:"××× ×©××× ×× ×ס ××ש×ער?",requested_amount:"××× ×סף × ×סף ×ª×¨×¦× ××§××?"}[Be],"bot",[],!1,null,!1,!1,{refinancePreferencesStep:{step:Be}},Ne);return}const Ke=c.other_loans?Number(c.other_loans_payment||0):0,tt={...l.applicationData,monthly_income:c.income,existing_loans:!!c.other_loans,existing_loans_monthly_payment:Ke,disposable_monthly_income:Math.max(0,Number(c.income||0)-Ke),...c.property_value?{property_value:c.property_value}:{},...c.requested_amount?{requested_amount:c.requested_amount}:{}},Ve={...l,step:"refinance_questionnaire_complete",refinance_intent:c.intent,refinancePreferences:c,applicationData:tt};if(C(Ve),P.failed){I("×× ×צ××× × ××ש××× ×ת ×¢×××× ××ס××. ×פשר ×× ×¡×ת ש×× ×× ××¢××ר ×××× × ××× ×ת.","bot",[{id:"choose_upload_document",label:"ð ××¢××× ×××רת",primary:!0},{id:"manual_input_refinance",label:"â¨ï¸ ××× × ××× ×ת"}],!1,null,!1,!1,null,Ve);return}
191P.questionnaireContext=Ve,!na(Ve)&&(P.resolve({...Ve,applicationId:V}),P.analysisReady||(w("analyzing_mortgage"),L(!0)))},ra=async i=>{var Z;if(!i||i.length===0){I("×× ×××× × × ×ª×× ×× ð ×פשר ×××× ×ת ×××פס ש××.","bot",[],!1,null,!1,!1,null,l);return}T(!1);const d=(Z=i.find(G=>parseFloat(G.monthly_income)>0))==null?void 0:Z.monthly_income,b=d?{...l,applicationData:{...l.applicationData,monthly_income:parseFloat(d)}}:l;d&&C(b);const P=Date.now();I("××¢××ת × ×ª×× ××...","bot",[],!1,null,!1,!0,null,b,!1,!1,!1,P),r(!0),J(!1);let V=!1,c=null;try{c=await K.auth.me(),V=!0}catch{}if(!V){Ae.saveContextForAuth({action:"continue_manual_refinance",flow:"refinance",returnToChat:!0,redirectToPayment:!1,tracks:i,returnState:{messages:o.filter(G=>!G.isLoading),currentContext:{...b,manualTracks:i,step:"manual_refinance_pending_auth"}}}),Ze(`${be("AuthRedirect")}?auth_completed=true`);return}await Qt(i,P,c,b,ke,r,C,qe,ge)},sa=async i=>{r(!0),R(null),D(null),I(`××רת×: ${i.type==="term"?`×קצר תק××¤× â ×××ר ××××©× ×©× ${Je(i.newM
191onthlyPayment)}`:`×××§××× ×ª×©××× ××××©× ×-${Je(i.newMonthlyPayment)}`}`,"user");const d=await Ie.handleScenarioProceed(i,l);d?(I(d.message,"bot",d.options||[],!1,null,!1,!1,null,d.context||l,!1,!1,!1,Date.now()+Math.random(),null,null,!1),d.context&&C(d.context)):I("×××¨×¢× ×©×××× ××¢×××× ×××××¨× ð ×פשר ×× ×¡×ת ש××.","bot",[],!1,null,!1,!1,null,l),r(!1)},en=async i=>{if(i){r(!0);try{const d=await K.auth.me().catch(()=>null),b=l.reminderAnalysis||l.initialAnalysis,P=(b==null?void 0:b.estimated_monthly_savings)||0;await K.entities.RefinanceReminder.create({user_id:(d==null?void 0:d.id)||null,phone:i,email:(d==null?void 0:d.email)||null,application_id:l.applicationId,original_analysis:b,original_savings_potential:P,current_savings_potential:P,status:"active",next_check_date:new Date(Date.now()+720*60*60*1e3).toISOString()}),ge("××¢×××! ð ×ת×××רת × ×©××¨× ××צ×××. ×××××§ ××¢×× ×××ש ×× ×ש ש×פ×ר ××ª× ×× ×ש××§.",[{id:"mortgage_questions",label:"â ש×××ת × ×ספ×ת"}]),C(V=>({...V,awaitingPhoneForReminder:!1,reminderPhoneConfirmation:!1,reminderCurrentPhone:null,reminderAnalysis:null,step:"reminder_saved"}))}catch{ge("×××¨×¢× ×©×××× ×ש××רת ×ת×××רת ð ×פשר ×× ×¡×ת ש×× ×× ××¤× ×ת ×ת××××.")}finally{r(!1)}}},tn=async i=>{var b;if(!i||i<=0)return;const d=l.bankDisplayName||l.bank;if(I(`×××¨×ª× ×¡××× ×©× ${Je(i)} ×פרע××`,"user"),((b=l._pendingFiles)==null?void 0:b.length)>0){const P={...l,prepaymentAmount:i,step:"awaiting_prepayment_document",_pendingFiles:null};C(P);const V=Date.now();I("××ס×××× ×תק×××! ð ×××צת ×ת ×× ×ª×× ××...","bot",[],!1,null,!1,!0,null,P,!1,!1,!1,V),r(!0),await va(l._pendingFiles,l.bank,V,l.applicationId,P,{checkDocumentStatus:De.checkDocumentStatus,updateMessage:ke,addBotMessage:ge,setIsLoading:r,setContext:C,setShowWaitingScreen:L,setWaitingScreenMode:w,setWaitingScreenProgress:x});return}ge(`××¢×××! רש××ª× ${Je(i)} ×פרע××. 192 193×עת צר×× ×ת ×ס×× "×תר×ת ×ס××××§" ×${d} ××× ×× ×ª× ×××× ×ס××××× ×××× ×פר××¢.`,[],!0,null,!1,!1,null,{...l,prepaymentAmount:i,step:"awaiting_prepayment_document"}),C(P=>({...P,prepaymentAmount:i,step:"awaiting_prepayment_document"}))},Dt=async i=>{if(!i)return;D(null);const d=Date.now();I(`××× ×ª פר××× ×××××ת ×ש×× ×ª×: ס××× × ×סף ${Je(i.additionalAmount)}, ס×"× ×ש×× ×ª× ×××©× ${Je(i.newTotalLoan)}`,"user"),C(b=>({...b,refinance_goal:"cash_out",selected_scenario_details:i})),I("××שרת ×ת ××××ר×...","bot",[],!1,null,!1,!0,null,l,!1,!1,!1,d),r(!0),J(!1);try{const b=await Ie.handleCashOutSubmission(i,{...l,refinance_goal:"cash_out",selected_scenario_details:i});r(!1),b.nextAction?H(b.nextAction):ke(d,{content:b.message,sender:"bot",options:b.options||[],isLoading:!1,renderComponents:b.renderComponents||null,context:b.context}),b.context&&C(b.context)}catch(b){console.error("Error handling cash out submission:",b),r(!1),ke(d,{content:`×××¨×¢× ×©×××× ××¢×××× ××קש×: ${b.message} ð`,isLoading:!1})}},an=async i=>{I("×ש ×ש×× ×ª× ×§×××ת ×¢× ×× ×ס.","user",[],!1,null,!0,!1,null,l),J(!1),r(!0);try{let d=l.applicationId;const b=await K.auth.me().catch(()=>null);d?await Te.MortgageApplication.update(d,{...i,application_type:"new_mortgage"}):d=(await Te.MortgageApplication.create({...i,client_name:(b==null?void 0:b.full_name)||"",email:(b==null?void 0:b.email)||"",phone:(b==null?void 0:b.phone)||"",application_type:"new_mortgage",status:"draft",user_id:(b==null?void 0:b.id)||""})).id;const P=await Ie.handleConvertNewMortgageToCashOutRefinance({...l,applicationId:d,applicationData:i});P&&(I(P.message,"bot",P.options||[],!1,null,!1,!1,null,P.context),P.context&&C(P.context))}catch(d){console.error("[Chat] Error in conversion:",d),I("×××¨×¢× ×©××××. × ×¡× ×©××.","bot")}finally{r(!1)}},nn=m.useCallback(async i=>{r(!0);try{const d=await Ie.handlePrepaymentRefinanceProceed(i,l);d&&(I(d.message,"bot",d.options||[],!1,null,!1,!1,null,d.context,!1,!1,!1,Date.now()+Math.random()),d.context&&C(d.context))}catch{ge("×××¨×¢× ×©×××× ð × ×¡× ×©×× ×× ×¤× × ×ת××××.")}finally{r(!1)}},[l,I,ge]),rn=m.useCallback(async()=>{await qe({id:"prepayment_deep_check"})},[qe]),sn=m.useCallback(async()=>{await qe({id:"prepayment_not_interested"})},[qe]),on=m.useCallback(async()=>{await qe({id:"prepayment_request_reminder"})},[qe]),ln=m.useCallback(async i=>{r(!0);try{const d=await Ie.handlePrepaymentDetailsSubmit(i,l);d&&(I(d.message,"bot",d.options||[],!1,null,!1,!1,null,d.context),d.delayedMessage&&setTimeout(()=>{ge(d.delayedMessage.message,d.delayedMessage.options||[])},d.delayedMessage.delay||3e3),d.context&&C(d.context))}catch{ge("×××¨×¢× ×©×××× ð × ×¡× ×©××.")}finally{r(!1)}},[l,I,ge]),oa=m.useCallback(Zr({context:l,messages:o,setContext:C,addMessage:I,searchParams:t,navigate:a,redirectToAuth:Ze}),[l,o,C,I,t,a,Ze]),vt=m.useCallback(()=>
193{if(!$e.current)return;const{scrollTop:i,scrollHeight:d,clientHeight:b}=$e.current;Le(d-i-b>50)},[]);m.useEffect(()=>{const i=$e.current;if(i)return i.addEventListener("scroll",vt),setTimeout(vt,500),()=>i.removeEventListener("scroll",vt)},[vt]);const cn=m.useCallback((i="smooth")=>{var d;(d=Xe.current)==null||d.scrollIntoView({behavior:i,block:"end"})},[]);m.useEffect(()=>(o.length>0&&(Ae.saveSession({messages:o,context:l}),(o.length>1||o.length===1&&o[0].sender==="user")&&J(!1),setTimeout(()=>{var i;(i=Xe.current)==null||i.scrollIntoView({behavior:"smooth",block:"end"})},50)),Ft(),()=>We()),[o,l,Ft,We]),m.useEffect(()=>{ta(),typeof window.isLongProcessRunning>"u"&&(window.isLongProcessRunning=!1),typeof window.isAtPricingStep>"u"&&(window.isAtPricingStep=!1)},[ta]),m.useEffect(()=>{const i=new Set(["awaiting_form_submission","awaiting_upload","initiating_auth","auth_required_for_upload","payment_selection","term_selection","scenario_selected","awaiting_risk_preference","awaiting_service_choice","awaiting_payment_prompt","payment_initiated","active"]),d=o.some(b=>{var P,V,c;return b.showUpload||b.renderManualRefinanceForm||((P=b.renderComponents)==null?void 0:P.newMortgageForm)||((V=b.renderComponents)==null?void 0:V.incomeInputField)||((c=b.renderComponents)==null?void 0:c.refinancePreferencesStep)});return window.binaChatCallbackBlocked=!!(l.applicationId||l.bank||i.has(l.step)||l.flow==="active_process"||d),()=>{window.binaChatCallbackBlocked=!1}},[l.applicationId,l.bank,l.flow,l.step,o]);const[Et,un]=m.useState(!1);m.useEffect(()=>{const i=setTimeout(()=>un(!0),1400);return()=>clearTimeout(i)},[]),m.useEffect(()=>{var i;ue||!Et||typeof window<"u"&&window.innerWidth>=768&&((i=Zt.current)==null||i.focus())},[ue,Et]);const ia=m.useCallback(Yr({searchParams:t,getBankDisplayName:et,context:l,addMessage:I,updateMessage:ke,setIsLoading:r,setContext:C,handleOptionSelected:qe,addBotMessage:ge,setMessages:y,setHasStarted:we,setShowInitialHelpText:J,setNextAction:H}),[t,et,l,I,ke,r,C,qe,ge,H]);m.useEffect(()=>{const i=async()=>{var V;const d=t.get("help"),b=t.get("action"),P=t.get("bank");if(o.length>0&&!((V=e.state)!=null&&V.processedUrlParams))if(d){r(!0),J(!1);try{const c=await Ie.handleHelpRequest(d);I(c.message,"bot",c.options||[],!1,null,!1,!1,null,c.context||l)}catch(c){console.error("Error handling help request from URL:",c)}finally{r(!1)}t.delete("help"),window.history.replaceState({},"",`${window.location.pathname}?${t.toString()}`)}else b==="prompt_for_upload"&&P&&(async()=>{try{if(!await K.auth.me())return;const G=await et(P);I(`××¢×××! ×¢×ש×× ×פשר ×××¢××ת ×ת ×ס×× "×תר×ת ×ס××××§" ×${G}.`,"bot",[],!0,null,!1,!1,null,{...l,bank:P,step:"awaiting_upload"}),C(Fe=>({...Fe,bank:P,step:"awaiting_upload"})),J(!1);const fe=new URL(window.location);fe.searchParams.delete("action"),fe.searchParams.delete("bank"),fe.searchParams.delete("is_new_user"),fe.searchParams.delete("auth_completed"),window.history.replaceState({},"",fe.toString())}catch{I("×××¨×¢× ×©×××× ×××¢×× ×ª ×× ×ª×× ××. ×× × × ×¡× ×©××.","bot",[{id:"refinance_prompt",label:"×ת×× ××××ר"}],!1,null,!1,!1,null,l)}})()};setTimeout(async()=>{Wt.current||(Wt.current=!0,await ia()),i()},200)},[o,I,et,C,r,e.state,l,J,ke,ia,t]);const la=m.useCallback(Gr({navigate:a,context:l,addMessage:I,toast:pt,setIsLoading:r,getBankDisplayName:et,messages:o,updateMessage:ke,setContext:C,setShowRedirectAnimation:ie,setRedirectTarget:W,setShowWaitingScreen:L,setWaitingScreenMode:w,setCashOutCalculator:D,setNextAction:H,handleOptionSelected:qe,redirectToAuth:Ze}),[a,l,I,pt,r,et,o,ke,C,qe,Ze]);return m.useEffect(()=>{_&&(la(_),H(null))},[_,la]),E?n.jsx(_a,{mode:"redirecting",targetPage:z}):n.jsxs(pr,{children:[n.jsx(Ur,{}),n.jsxs("div",{ref:wt,className:"relative z-10 flex flex-col font-sans max-w-3xl w-full mx-auto my-4 rounded-3xl overflow-hidden ring-1 ring-white/50 bg-white",style:{boxShadow:"0 40px 90px -15px rgba(15,23,42,0.65), 0 0 60px -10px rgba(59,130,246,0.35)"},dir:"rtl",children:[n.jsxs("header",{className:"flex items-center justify-between px-4 py-3 chat-v2-header flex-shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ht.div,{layoutId:"bina-hero",className:"chat-v2-avatar-wrap",transition:{type:"spring",stiffness:260,damping:26},children:n.jsx(Nt,{size:"small",variant:"default"})}),n.jsxs("div",{className:"leading-tight",children:[n.jsx("p",{className:"font-bold text-slate-800 text-sm",children:"××× ×"}),n.jsx("p",{className:"text-[11px] text-emerald-600",children:"â ××××רת"})]})]}),n.jsx("div",{className:"flex items-center gap-1",children:n.jsxs(Ir,{children:[n.jsxs(zt,{children:[n.jsx(Vt,{asChild:!0,children:n.jsx(nt,{variant:"ghost",size:"icon",onClick:()=>window.dispatchEvent(new CustomEvent("bina:open-consent-preferences")),children:n.jsx(Hn,{className:"h-4 w-4 text-gray-600"})})}),n.jsx(kt,{children:n.jsx("p",{children:"×××ר×ת פר×××ת ××¢××××ת"})})]}),n.jsxs(zt,{children:[n.jsx(Vt,{asChild:!0,children:n.jsx(nt,{variant:"ghost",size:"icon",onClick:Ga,children:n.jsx(ar,{className:"h-5 w-5 text-gray-600"})})}),n.jsx(kt,{children:n.jsx("p",{children:"×××קת ×ש××× ××ת××× ×××ש"})})]}),n.jsxs(zt,{children:[n.jsx(Vt,{asChild:!0,children:n.jsx(nt,{variant:"ghost",size:"icon",onClick:()=>a(be("Landing")),children:n.jsx(Bn,{className:"h-5 w-5 text-gray-600"})})}),n.jsx(kt,{children:n.jsx("p",{children:"×××¨× ×××£ ×××ת"})})]})]})})]}),n.jsx("div",{className:`flex-1 overflow-y-auto chat-v2-scroll chat-v2-body chat-v2-frame ${S?"chat-v2-frame-uploading":""}`,ref:$e,children:n.jsxs("div",{className:"p-4 space-y-4",children:[o.map(i=>n.jsx(ft,{message:i,onOptionSelected:qe,onSubmitForm:oa,onManualRefinanceSubmit:ra,onOpenFileUpload:Xa,onScenarioProceed:sa,onCashOutSubmit:Dt,onSuggestRefinance:an,onPhoneInputSubmit:en,onPrepaymentAmountSubmit:tn,onPrepaymentRefinanceProceed:nn,onPrepaymentRequestReminder:on,onPrepaymentDeepCheck:rn,onPrepaymentNotInterested:sn,onPrepaymentDetailsSubmit:ln,onRefinancePreferencesSubmit:Wa},i.id)),u&&n.jsxs("div",{className:"flex items-end gap-2 animate-enter-left",children:[n.jsx("div",{className:"chat-v2-avatar-wrap flex-shrink-0",children:n.jsx(Nt,{size:"tiny",variant:"chat"})}),n.jsx("div",{className:"max-w-lg chat-v2-bubble-bot",children:n.jsx(Un,{className:"p-4 bg-transparent border-none",children:n.jsx(jr,{})})})]}),p&&n.jsx(ft,{message:{id:"manual-refinance-form-bubble",sender:"bot",content:"×פשר ×××× ×ת פר×× ××ס×××××:",renderManualRefinanceForm:!0,timestamp:new Date,isSilent:!0},onManualRefinanceSubmit:ra,isManualFormActive:!0},"manual-refinance-form"),k&&n.jsx(ft,{message:{id:"interactive-slider-bubble",sender:"bot",content:k.message||"× ××××§ ×ת ××פשר×××ת:",renderInteractiveSlider:!0,interactiveSliderProps:k,timestamp:new Date,isSilent:!0},onScenarioProceed:sa,isInteractiveSliderActive:!0},"interactive-slider-bubble"),h&&n.jsx(ft,{message:{id:"cash-out-calculator-bubble",sender:"bot",content:"×× ××ס×××× ×¢××××! ×עת ×× × ×©×××ת ×××ª× ×× ×ת×× ×תק×× ××¤× ××× × ××× ×§. ש×× ×× ×××¨× ×××§×...",renderComponents:{cashOutCalculatorProps:{...h,initialData:h.initialData}},timestamp:new Date,isSilent:!0},onCashOutSubmit:Dt,isCashOutCalculatorActive:!0},"cash-out-calculator-bubble"),A&&n.jsx(ft,{message:{id:"new-mortgage-form-bubble",sender:"bot",content:"×פשר ×××× ×ת פר×× ×קשת ××ש×× ×ª×:",renderComponents:{newMortgageForm:!0,formProps:q},timestamp:new Date,isSilent:!0},onSubmitForm:oa,isNewMortgageFormActive:!0},"new-mortgage-form-bubble"),Y&&n.jsx(Hr,{isOpen:!0,onClose:()=>ae(!1),source:"chat"}),n.jsx("div",{ref:Xe})]})}),ve&&n.jsxs("button",{onClick:()=>cn("smooth"),className:"chat-v2-primary-btn fixed bottom-32 right-6 z-50 text-white rounded-full p-4 shadow-xl transition-all hover:scale-110","aria-label":"×××× ×ת×ת×ת",style:{animation:"gentle-bounce 2s ease-in-out infinite"},children:[n.jsx(sr,{className:"h-6 w-6"}),n.jsx("style",{dangerouslySetInnerHTML:{__html:"@keyframes gentle-bounce { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }"}})]}),n.jsx("div",{className:"chat-v2-input-bar p-4 flex-shrink-0",children:n.jsxs("div",{className:"max-w-3xl mx-auto",children:[ye&&n.jsx("div",{className:"text-center text-sm text-gray-500 mb-4 animate-fade-in",children:"×פשר ×ש××× ×××ª× ×× ××ר ×¢× ×ש×× ×ª××ת ×× ××ת××× ×ª××××."}),n.jsxs("form",{onSubmit:Ja,className:"flex items-center gap-2",children:[n.jsx(lt,{ref:Zt,type:"text",placeholder:"×פשר ×ש××× ×××ª× ×× ××ר...",value:f,onChange:i=>$(i.target.value),className:"flex-1 chat-v2-input rounded-xl",disabled:u||o.some(i=>i.formFields||i.renderManualRefinanceForm||i.renderInteractiveSlider||i.renderComponents&&(i.renderComponents.interactiveSlider||i.renderComponents.cashOutCalculator||i.renderComponents.cashOutCalculatorProps||i.renderComponents.newMortgageForm||i.renderComponents.prepaymentAmountSlider||i.renderComponents.prepaymentDetailsForm||i.renderComponents.incomeInputField||i.renderComponents.refinancePreferencesForm||i.renderComponents.phoneInputField))||p||k||h||A||E}),n.jsx(nt,{type:"submit",size:"icon",className:"chat-v2-primary-btn",disabled:u||!f.trim()||o.some(i=>i.formFields||i.renderManualRefinanceForm||i.renderInteractiveSlider||i.renderComponents&&(i.renderComponents.interactiveSlider||i.renderComponents.cashOutCalculator||i.renderComponents.cashOutCalculatorProps||i.renderComponents.newMortgageForm||i.renderComponents.prepaymentAmountSlider||i.renderComponents.prepaymentDetailsForm||i.renderComponents.incomeInputField||i.renderComponents.refinancePreferencesForm||i.renderComponents.phoneInputField))||p||k||h||A||E,children:n.jsx(nr,{className:"h-5 w-5"})})]})]})}),n.jsx(Br,{active:!s&&(ue||!Et)}),n.jsx("input",{ref:Ue,type:"file",className:"hidden",accept:".pdf,.jpg,.jpeg,.png",onCh
193ange:Za,multiple:!0}),te&&n.jsx(_a,{mode:M,showProgress:M==="analyzing_mortgage",progress:v,onComplete:()=>L(!1)})]})]})}export{ho as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.