PageSourceSearch

https://askbina.ai/assets/Chat-BlbG12_k.js

js askbina.ai collected 2026-10-05 13:00:03 UTC 161,661 bytes, 193 lines download raw bytes

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.