1import{u as De,j as e,S as oe,a as Be,r,f as z,fl as Te,z as v,h as J,fm as Pe,B as ue,fn as _e,y as Ue,de as Oe,fo as He,U as ze,aY as Ge,l as Ke,fp as We,fq as Re,fr as qe,M as H,n as F,x as Le}from"./index-BvNIJ_c2.js";import{T as Ye}from"./Typeahead-yJkIRLml.js";import"./Anchor-C0wshJja.js";import"./index-DqV4P4K8.js";import{L as Ve}from"./index-Dd_NvOz0.js";import{x as Je}from"./index-IEJD0KmR.js";import{G as Ee,H as Qe,I as Ae}from"./index-Laxbxmnr.js";import{u as Xe,W as Ze}from"./WebGuide-BIxIKBbg.js";import{O as et,T as tt}from"./OverlayTrigger-BK7PUync.js";import{B as st}from"./NavbarContext-C9kG8e2O.js";import{R as nt}from"./Row-Bj__9rZq.js";import"./floating-ui.dom-R3fyi12P.js";import"./assertThisInitialized-B9jnkVVz.js";import"./index-o7Cpnlg6.js";import"./useRootClose-CVG0q7Ag.js";import"./profile1-DX-Es6KB.js";import"./navigationConfig-DMPz6vwn.js";import"./NavIcon-CE0lX41N.js";import"./Image-y3xwkAif.js";import"./Tab-B5OAj-R1.js";import"./Nav-Tj50dJFm.js";import"./CardHeaderContext-CfKayEkG.js";import"./useAiChatStore-DgcBp8ir.js";const at="https://ewq-ferrier.s3.eu-north-1.amazonaws.com/",rt=t=>t?/^https?:\/\//i.test(t)?t:`${at}${t}`:"",it=(t,i)=>{if(!t)return"";const u=new Date(t);if(Number.isNaN(u.getTime()))return"";const x=new Date-u,g=Math.floor(x/1e3),N=Math.floor(g/60),M=Math.floor(N/60),O=Math.floor(M/24);return g<60?"nu":N<60?`${N} min`:M<24?`${M} h`:O<7?`${O} d`:u.toLocaleDateString(i,{month:"short",day:"numeric"})},ot=(t,i=60)=>t?t.length<=i?t:t.slice(0,i).trimEnd()+"â¦":"",lt=({conversations:t,selectedKey:i,onSelect:u,loading:p,emptyTitle:x,emptyText:g})=>{const{t:N,i18n:M}=De(),O=M.language||"sv-SE";return p?e.jsxs("div",{className:"conversation-list-loading",children:[e.jsx(oe,{animation:"border",size:"sm",variant:"primary"}),e.jsx("span",{children:N("inbox.loadingConversations")||"Laddar dialoger..."})]}):t.length?e.jsx("ul",{className:"conversation-list",children:t.map(j=>{var L,_,Z,y,E,G;const h=`${j.partnerId}-${j.partnerRole}`,Q=i===h,B=((L=j.partner)==null?void 0:L.name)||N("inbox.unknown")||"Okänd",ae=((_=j.lastMessage)==null?void 0:_.content)||((Z=j.lastMessage)==null?void 0:Z.subject)||"",R=((y=j.lastMessage)==null?void 0:y.isSentByUser)?`${N("inbox.youPrefix")||"Du"}: `:"",T=j.unreadCount||0,P=B.split(/\s+/).map(ee=>ee[0]).join("").slice(0,2).toUpperCase();return e.jsxs("li",{className:`conversation-item ${Q?"selected":""} ${T>0?"has-unread":""}`,onClick:()=>u(j),children:[e.jsx("div",{className:"conversation-avatar",children:(E=j.partner)!=null&&E.profileImage?e.jsx("img",{src:rt(j.partner.profileImage),alt:B}):e.jsx("span",{className:"conversation-avatar-initials",children:P||"?"})}),e.jsxs("div",{className:"conversation-body",children:[e.jsxs("div",{className:"conversation-row-top",children:[e.jsx("span",{className:"conversation-name",children:B}),e.jsx("span",{className:"conversation-time",children:it((G=j.lastMessage)==null?void 0:G.createdAt,O)})]}),e.jsxs("div",{className:"conversation-row-bottom",children:[e.jsxs("span",{className:"conversation-preview",children:[R,ot(ae,60)]}),T>0&&e.jsx("span",{className:"conversation-unread-badge",children:T})]})]})]},h)})}):e.jsxs("div",{className:"conversation-list-empty",children:[e.jsx("i",{className:"bi bi-chat-dots conversation-list-empty-icon"}),e.jsx("h6",{children:x}),e.jsx("p",{children:g})]})},$e={open_invoice:t=>`/invoice-view/${t}`,open_booking:t=>`/booking-details/${t}`,open_animal:t=>`/animal-details/${t}`,open_customer:t=>`/customer-details/${t}`,open_journal:t=>`/journal-details/${t}`,open_animal_import:()=>"/animal-management"},ct=80,dt="https://ewq-ferrier.s3.eu-north-1.amazonaws.com/",ut=t=>t?/^https?:\/\//i.test(t)?t:`${dt}${t}`:"",mt=(t,i)=>{if(!t)return"";const u=new Date(t);if(Number.isNaN(u.getTime()))return"";const p=new Date;return u.toDateString()===p.toDateString()?u.toLocaleTimeString(i,{hour:"2-digit",minute:"2-digit"}):u.toLocaleString(i,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})},ht=(t,i)=>{if(!t)return"";const u=new Date(t);if(Number.isNaN(u.getTime()))return"";const p=new Date,x=new Date(p.getFullYear(),p.getMonth(),p.getDate()),g=new Date(x);g.setDate(x.getDate()-1);const N=new Date(u.getFullYear(),u.getMonth(),u.getDate());return N.getTime()===x.getTime()?"Idag":N.getTime()===g.getTime()?"IgÃ¥r":u.toLocaleDateString(i,{weekday:"long",month:"short",day:"numeric",year:N.getFullYear()!==x.getFullYear()?"numeric":void 0})},pt=({userId:t,userRole:i,partnerId:u,partnerRole:p,partner:x,onMessageSent:g,onClose:N,showBackButton:M,targetMessageId:O,onTargetMessageHandled:j})=>{const{t:h,i18n:Q}=De(),B=Be(),ae=Q.language||"sv-SE",[X,R]=r.useState([]),[T,P]=r.useState(!1),[L,_]=r.useState(null),[Z,y]=r.useState(!0),[E,G]=r.useState(!1),[ee,b]=r.useState(""),[K,pe]=r.useState(!1),[W,me]=r.useState(null),U=r.useRef(null),D=r.useRef(null),re=r.useRef(!1),le=`${u}-${p}`,te=r.useRef(null),ce=r.useRef(0),se=r.useRef(0),A=r.useRef(!1),w=r.useCallback(async()=>{var n,d,a,f;y(!0);try{const{data:o}=await z.get(Te.endPoint(t,u,p));if(o!=null&&o.status){const l=((n=o.result)==null?void 0:n.messages)||[];R(l),P(!!((d=o.result)!=null&&d.hasMore)),_(((a=o.result)==null?void 0:a.nextBefore)||null)}}catch(o){if(((f=o==null?void 0:o.response)==null?void 0:f.status)===404){R([]),P(!1);return}console.error("Failed to load conversation:",o),v.error(J(o))}finally{y(!1)}},[t,u,p]),$=r.useCallback(async()=>{var n;try{await z.patch(Pe.endPoint(),{userId:t,partnerId:u,partnerRole:p}),window.dispatchEvent(new Event("notification-read")),g==null||g({markReadOnly:!0})}catch(d){if(((n=d==null?void 0:d.response)==null?void 0:n.status)===404)return;console.error("Failed to mark conversation as read:",d)}},[t,u,p,g]);r.useEffect(()=>{!t||!u||!p||te.current!==le&&(te.current=le,w(),$())},[t,u,p,le,w,$]),r.useEffect(()=>{if(!u||!p)return;const n=()=>{document.visibilityState==="visible"&&(w(),$())};
1return document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[u,p,w,$]),r.useEffect(()=>{if(!u||!p)return;const n=async d=>{const a=d.detail||{};if(String(a.senderId)===String(u)&&Number(a.senderRole)===Number(p)&&a.messageId)try{const{data:f}=await z.get(_e.endPoint(a.messageId)),o=f==null?void 0:f.result;if(!(f!=null&&f.status)||!(o!=null&&o._id))return;R(l=>l.some(k=>String(k._id)===String(o._id))?l:[...l,o]),requestAnimationFrame(()=>{const l=U.current;l&&(l.scrollTop=l.scrollHeight)}),$(),window.dispatchEvent(new CustomEvent("chat-conversation-updated",{detail:{partnerId:u,partnerRole:p,content:o.content||"",subject:o.subject||"",createdAt:o.createdAt,isSentByUser:!1}}))}catch(f){console.error("Failed to fetch arrived chat message:",f),w(),$()}};return window.addEventListener("chat-message-arrived",n),()=>window.removeEventListener("chat-message-arrived",n)},[u,p,w,$]),r.useEffect(()=>{if(Z)return;const n=U.current;if(!(!n||A.current)){if(O){const d=n.querySelector(`[data-message-id="${O}"]`);if(d){d.scrollIntoView({behavior:"smooth",block:"center"}),d.classList.add("chat-bubble-row-highlight"),setTimeout(()=>{d.classList.remove("chat-bubble-row-highlight")},2e3),j==null||j();return}}n.scrollTop=n.scrollHeight}},[Z,X.length,O,j]),r.useEffect(()=>{if(!A.current)return;const n=U.current;if(n){const a=n.scrollHeight-ce.current;n.scrollTop=se.current+a}A.current=!1},[X]);const ie=r.useCallback(async()=>{var d,a,f,o;if(E||!T||!L)return;const n=U.current;n&&(ce.current=n.scrollHeight,se.current=n.scrollTop),A.current=!0,G(!0);try{const{data:l}=await z.get(Te.endPoint(t,u,p,L));if(l!=null&&l.status){const k=((d=l.result)==null?void 0:d.messages)||[];R(S=>[...k,...S]),P(!!((a=l.result)!=null&&a.hasMore)),_(((f=l.result)==null?void 0:f.nextBefore)||null)}}catch(l){if(((o=l==null?void 0:l.response)==null?void 0:o.status)===404){P(!1);return}console.error("Failed to load older messages:",l),v.error(J(l)),A.current=!1}finally{G(!1)}},[t,u,p,L,T,E]),fe=r.useCallback(n=>{n.target.scrollTop<ct&&T&&!E&&ie()},[T,E,ie]),be=async()=>{const n=ee.trim();if(!n||K)return;const d=h("inbox.subjectFallback")||"Meddelande",a=`tmp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,f={_id:a,_tempId:a,senderId:t,senderRole:i||1,receiverId:u,receiverRole:p,subject:d,content:n,isRead:!1,createdAt:new Date().toISOString(),isSentByUser:!0,isPending:!0};R(o=>[...o,f]),b(""),requestAnimationFrame(()=>{const o=U.current;o&&(o.scrollTop=o.scrollHeight)}),pe(!0);try{const{data:o}=await z.post(Oe.endPoint(),{senderId:t,senderUserRole:i||1,receiverId:u,receiverUserRole:p,subject:d,content:n});if(o!=null&&o.status){const l=o.result;R(k=>k.map(S=>S._tempId===a?{...S,_id:(l==null?void 0:l._id)||S._id,createdAt:(l==null?void 0:l.createdAt)||S.createdAt,isPending:!1,_tempId:void 0}:S)),g==null||g({created:l})}else R(l=>l.filter(k=>k._tempId!==a)),b(n),v.error((o==null?void 0:o.message)||J())}catch(o){console.error("Failed to send message:",o),R(l=>l.filter(k=>k._tempId!==a)),b(n),v.error(J(o))}finally{pe(!1)}},Se=r.useCallback(n=>{if(!(n!=null&&n.type)||!(n!=null&&n.entityId))return;const d=$e[n.type];d&&B(d(n.entityId))},[B]),Ne=n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),be())},he=async n=>{if(!n)return;const d=h("inbox.confirmDeleteMessage")||"Vill du ta bort detta meddelande?";if(window.confirm(d))try{const{data:a}=await z.delete(He.endPoint(n));a!=null&&a.status?(R(f=>f.filter(o=>o._id!==n)),v.success(h("inbox.messageDeleted")||"Meddelandet togs bort"),g==null||g({deleted:!0})):v.error((a==null?void 0:a.message)||J())}catch(a){console.error("Failed to delete message:",a),v.error(J(a))}},xe=async n=>{var d;if(n)try{if((d=navigator.clipboard)!=null&&d.writeText)await navigator.clipboard.writeText(n);else{const a=document.createElement("textarea");a.value=n,a.style.position="fixed",a.style.opacity="0",document.body.appendChild(a),a.select(),document.execCommand("copy"),document.body.removeChild(a)}v.success(h("inbox.messageCopied")||"Meddelandet kopierat")}catch(a){console.error("Failed to copy message:",a),v.error(J(a))}},ge=r.useCallback((n,d,a)=>
1{if(!(n!=null&&n._id))return;const f=200,o=96,l=Math.min(d,window.innerWidth-f-8),k=Math.min(a,window.innerHeight-o-8);me({messageId:n._id,content:n.content||"",x:Math.max(8,l),y:Math.max(8,k)})},[]),q=r.useCallback(()=>me(null),[]);r.useEffect(()=>{if(!W)return;const n=f=>{var o,l;(l=(o=f.target).closest)!=null&&l.call(o,".chat-bubble-context-menu")||q()},d=f=>{f.key==="Escape"&&q()};document.addEventListener("mousedown",n),document.addEventListener("touchstart",n),document.addEventListener("keydown",d);const a=U.current;return a==null||a.addEventListener("scroll",q,{passive:!0}),()=>{document.removeEventListener("mousedown",n),document.removeEventListener("touchstart",n),document.removeEventListener("keydown",d),a==null||a.removeEventListener("scroll",q)}},[W,q]);const ye=(n,d)=>{var l;re.current=!1;const a=((l=n.touches)==null?void 0:l[0])||n,f=a.clientX,o=a.clientY;D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{re.current=!0,ge(d,f,o)},500)},Y=()=>{D.current&&(clearTimeout(D.current),D.current=null)},ve=(n,d)=>{n.preventDefault(),Y(),ge(d,n.clientX,n.clientY)},de=(x==null?void 0:x.name)||h("inbox.unknown")||"Okänd",je=de.split(/\s+/).map(n=>n[0]).join("").slice(0,2).toUpperCase(),ke=()=>{let n=null,d=null;return X.map(a=>{const f=a.createdAt?new Date(a.createdAt).toDateString():"",o=f!==n;n=f;const l=a.isSentByUser,k=!!a.subject&&!!a.content&&a.subject!==a.content&&a.subject!==d;return d=a.subject||d,e.jsxs(Ue.Fragment,{children:[o&&e.jsx("div",{className:"chat-day-divider",children:e.jsx("span",{children:ht(a.createdAt,ae)})}),e.jsx("div",{className:`chat-bubble-row ${l?"from-me":"from-them"}`,"data-message-id":a._id,onContextMenu:S=>ve(S,a),onTouchStart:S=>ye(S,a),onTouchEnd:Y,onTouchMove:Y,onTouchCancel:Y,onMouseDown:S=>{S.button===0&&ye(S,a)},onMouseUp:Y,onMouseLeave:Y,children:e.jsxs("div",{className:"chat-bubble",children:[k&&e.jsx("div",{className:"chat-bubble-subject",children:a.subject}),e.jsx("div",{className:"chat-bubble-content",children:a.content}),a.action&&$e[a.action.type]&&e.jsx("div",{className:"chat-bubble-action",children:e.jsx(ue,{size:"sm",variant:"outline-primary",onClick:()=>Se(a.action),children:a.action.label})}),e.jsxs("div",{className:"chat-bubble-time",children:[mt(a.createdAt,ae),l&&e.jsx("i",{className:`bi ${a.isPending?"bi-clock-history":a.isRead?"bi-check2-all":"bi-check2"} chat-bubble-status`})]})]})})]},a._id)})};return e.jsxs("div",{className:"conversation-thread",children:[e.jsxs("div",{className:"conversation-thread-header",children:[M&&e.jsx("button",{type:"button",className:"conversation-thread-back",onClick:N,"aria-label":h("CommonText.Back")||"Tillbaka",children:e.jsx("i",{className:"bi bi-arrow-left"})}),e.jsx("div",{className:"conversation-thread-avatar",children:x!=null&&x.profileImage?e.jsx("img",{src:ut(x.profileImage),alt:de}):e.jsx("span",{children:je||"?"})}),e.jsxs("div",{className:"conversation-thread-title",children:[e.jsx("h6",{children:de}),(x==null?void 0:x.email)&&e.jsx("small",{children:x.email})]})]}),e.jsx("div",{className:"conversation-thread-body",ref:U,onScroll:fe,children:Z?e.jsx("div",{className:"chat-loading",children:e.jsx(oe,{animation:"border",size:"sm",variant:"primary"})}):e.jsxs(e.Fragment,{children:[E&&e.jsxs("div",{className:"chat-loading-older",children:[e.jsx(oe,{animation:"border",size:"sm",variant:"primary"}),e.jsx("span",{children:h("inbox.loadingOlder")||"Laddar äldre meddelanden..."})]}),!T&&X.length>0&&e.jsx("div",{className:"chat-start-marker",children:h("inbox.startOfConversation")||"Början av dialogen"}),X.length===0?e.jsxs("div",{className:"chat-empty-state",children:[e.jsx("i",{className:"bi bi-chat-square-text"}),e.jsx("p",{children:h("inbox.noMessagesInConversation")||"Inga meddelanden ännu. Skriv det första!"})]}):ke()]})}),e.jsxs("div",{className:"conversation-thread-input",children:[e.jsx("textarea",{value:ee,onChange:n=>b(n.target.value),onKeyDown:Ne,placeholder:h("inbox.typeReply")||"Skriv ett meddelande...",rows:1,disabled:K}),e.jsx(ue,{variant:"primary",onClick:be,disabled:!ee.trim()||K,className:"conversation-thread-send",children:K?e.jsx(oe,{animation:"border",size:"sm"}):e.jsx("i",{className:"bi bi-send-fill"})})]}),W&&e.jsxs("div",{className:"chat-bubble-context-menu",style:{to
1p:W.y,left:W.x},role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:"chat-bubble-context-menu-item",onClick:()=>{xe(W.content),q()},children:[e.jsx("i",{className:"bi bi-files"}),e.jsx("span",{children:h("inbox.copy")||"Kopiera"})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"chat-bubble-context-menu-item danger",onClick:()=>{const n=W.messageId;q(),he(n)},children:[e.jsx("i",{className:"bi bi-trash"}),e.jsx("span",{children:h("inbox.deleteMessage")||"Ta bort"})]})]})]})},Fe=t=>{if(!t)return"";const i=new Date(t);if(Number.isNaN(i.getTime()))return"";const u=i.getTimezoneOffset()*6e4;return new Date(i.getTime()-u).toISOString().slice(0,16)},_t=()=>{const{t}=De(),{user:i}=ze(),{isMobile:u}=Ge(),p=Ke(),x=Be(),g=Xe("inbox"),[N,M]=r.useState([]),[O,j]=r.useState(!0),[h,Q]=r.useState(null),[B,ae]=r.useState(""),[X,R]=r.useState(null),T=r.useRef(!1),[P,L]=r.useState(!1),[_,Z]=r.useState([]),[y,E]=r.useState({recipientId:"",subject:"",content:""}),[G,ee]=r.useState(!1),[b,K]=r.useState(()=>({...Ee})),[pe,W]=r.useState(()=>({...Ee})),[me,U]=r.useState(!1),[D,re]=r.useState(!1),[le,te]=r.useState(!1),[ce,se]=r.useState(!1),A=r.useRef(!1);r.useEffect(()=>{const s=P||ce;s&&!A.current&&(window.history.pushState({inboxModal:!0},""),A.current=!0),!s&&A.current&&(A.current=!1,window.history.back())},[P,ce]),r.useEffect(()=>{const s=()=>{A.current&&(A.current=!1,L(!1),se(!1))};return window.addEventListener("popstate",s),()=>window.removeEventListener("popstate",s)},[]);const w=r.useCallback(async()=>{var s,c;if(i!=null&&i.id){j(!0);try{const{data:m}=await z.get(We.endPoint(i.id,1,100,B));m!=null&&m.status&&M(((s=m.result)==null?void 0:s.conversations)||[])}catch(m){if(((c=m==null?void 0:m.response)==null?void 0:c.status)===404){M([]);return}console.error("Failed to fetch conversations:",m),v.error(J(m))}finally{j(!1)}}},[i==null?void 0:i.id,B]);r.useEffect(()=>{w()},[w]),r.useEffect(()=>{if(!(i!=null&&i.id)||T.current)return;const c=new URLSearchParams(p.search).get("messageId");c&&(T.current=!0,(async()=>{var m;try{const{data:C}=await z.get(_e.endPoint(c));if(!(C!=null&&C.status)||!C.result)return;const I=C.result,V=((m=I.senderId)==null?void 0:m.toString())===i.id.toString(),ne=V?I.receiverId:I.senderId,we=V?I.receiverRole:I.senderRole;if(!ne||!we)return;Q({partnerId:ne.toString(),partnerRole:we,partner:null}),R(c),x(p.pathname,{replace:!0})}catch(C){console.error("Failed to resolve message deeplink:",C)}})())},[i==null?void 0:i.id,p.search,p.pathname,x]),r.useEffect(()=>{const s=()=>w();return window.addEventListener("new-notification",s),()=>window.removeEventListener("new-notification",s)},[w]),r.useEffect(()=>{const s=c=>{const m=c.detail||{},C=String(m.partnerId||""),I=Number(m.partnerRole);!C||!I||M(V=>{var Ie;const ne=V.findIndex(Me=>String(Me.partnerId)===C&&Number(Me.partnerRole)===I);if(ne===-1)return V;const we={...V[ne],lastMessage:{...V[ne].lastMessage||{},_id:m.messageId||((Ie=V[ne].lastMessage)==null?void 0:Ie._id),content:m.content||"",subject:m.subject||"",createdAt:m.createdAt||new Date().toISOString(),isSentByUser:!!m.isSentByUser,isRead:!0}},Ce=[...V];return Ce.splice(ne,1),Ce.unshift(we),Ce})};return window.addEventListener("chat-conversation-updated",s),()=>window.removeEventListener("chat-conversation-updated",s)},[]);const $=r.useRef(w);r.useEffect(()=>{$.current=w},[w]),r.useEffect(()=>{const s=Re.getState().setInboxOpen;s(document.visibilityState==="visible");const c=()=>{var C;const m=document.visibilityState==="visible";s(m),m&&((C=$.current)==null||C.call($))};return document.addEventListener("visibilitychange",c),()=>{document.removeEventListener("visibilitychange",c),Re.getState().clear()}},[]),r.useEffect(()=>{const s=h?qe(h.partnerRole,h.partnerId):null;Re.getState().setOpenChatKey(s)},[h]);const ie=r.useCallback(s=>{const c={...Ee,...s};K(c),W({...c}),te(!1)},[]),fe=r.useCallback(async()=>{if(i!=null&&i.id){U(!0);try{const s=await Qe(i.id);ie(s)}catch(s){console.error("Failed to fetch auto reply settings:",s),v.error(t("autoReply.loadError")||"Kunde inte ladda autosvar.")}finally{U(!1)}}},[i==null?void 0:i.id,ie,t]);r.useEffect(()=>{fe()},[fe]);const be=async()=>{try{const{data:s}=await z.get(`/customers/list?page=1&limit=1000&ferrierId=${i==null?void 0:i.id}`);if(s!=null&&s.status){const c=(s.result.customers||[]).filter(m=>m.appUserId);Z(c)}}catch(s){console.error("Failed to fetch customers:",s)}},Se=()=>{be(),E({recipientId:"",subject:"",content:""}),L(!0)},Ne=async()=>
1{if(!y.recipientId||!y.subject.trim()||!y.content.trim()){v.error(t("inbox.fillRequiredFields")||"Fyll i alla obligatoriska fält");return}ee(!0);try{const{data:s}=await z.post(Oe.endPoint(),{senderId:i==null?void 0:i.id,senderUserRole:1,receiverId:y.recipientId,receiverUserRole:5,subject:y.subject,content:y.content});s!=null&&s.status&&(L(!1),E({recipientId:"",subject:"",content:""}),await w(),Q({partnerId:y.recipientId,partnerRole:5,partner:_.find(c=>c.appUserId===y.recipientId)?{name:`${_.find(c=>c.appUserId===y.recipientId).firstName||""} ${_.find(c=>c.appUserId===y.recipientId).lastName||""}`.trim()}:null}),v.success(t("inbox.messageSent")||"Meddelande skickat!"))}catch(s){console.error("Failed to send message:",s),v.error(J(s))}finally{ee(!1)}},he=(s,c)=>{K(m=>({...m,[s]:c})),te(!0)},xe=(s,c)=>{he(s,c?new Date(c).toISOString():"")},ge=async s=>{const c={...b,isEnabled:s};if(s&&!b.message.trim()&&(c.message=t("autoReply.fallbackMessage")||"Hej! Jag är på semester just nu och svarar så snart jag är tillbaka."),K(c),!!(i!=null&&i.id)){re(!0);try{const m=await Ae(i.id,c);ie(m),window.dispatchEvent(new Event("autoreply-updated")),v.success(t("autoReply.saveSuccess")||"Autosvar uppdaterat."),te(!1)}catch(m){console.error("Failed to save auto reply settings:",m),v.error(t("autoReply.saveError")||"Det gick inte att spara autosvaret."),te(!0)}finally{re(!1)}}},q=()=>{K({...pe}),te(!1)},ye=async()=>{if(i!=null&&i.id){if(b.isEnabled&&!b.message.trim()){v.error(t("autoReply.validationMessage")||"Skriv ett autosvar innan du aktiverar funktionen.");return}if(b.startDate&&b.endDate&&new Date(b.startDate)>new Date(b.endDate)){v.error(t("autoReply.validationDate")||"Slutdatum måste vara efter startdatum.");return}re(!0);try{const s=await Ae(i.id,b);ie(s),window.dispatchEvent(new Event("autoreply-updated")),v.success(t("autoReply.saveSuccess")||"Autosvar uppdaterat.")}catch(s){console.error("Failed to save auto reply settings:",s),v.error(t("autoReply.saveError")||"Det gick inte att spara autosvaret.")}finally{re(!1)}}},Y=s=>{if(!s)return null;const c=new Date(s);return Number.isNaN(c.getTime())?null:c},ve=Y(b.startDate),de=Y(b.endDate),je=new Date,ke=(!ve||ve<=je)&&(!de||je<=de),n=b.isEnabled&&ke,d=s=>{Q(s)},a=()=>{Q(null)},f=r.useCallback(({markReadOnly:s}={})=>{if(s&&h){const c=String(h.partnerId),m=Number(h.partnerRole);M(C=>C.map(I=>String(I.partnerId)===c&&Number(I.partnerRole)===m?{...I,unreadCount:0}:I));return}w()},[w,h]),o=!!h,l=u&&!o,k=u&&o,S=h?`${h.partnerId}-${h.partnerRole}`:null;return e.jsxs(Ve,{pageTitle:t("Sidebar.Inbox")||"Inkorg",onRestartTour:g.startManually,children:[g.shouldShow&&e.jsx(Ze,{steps:g.steps,onComplete:g.complete,onSkip:g.skip}),(!u||l)&&e.jsxs("div",{className:"admin-top",children:[e.jsx("div",{className:"at-left",children:e.jsxs("div",{className:"inline-search-wrapper","data-guide":"inbox-search",children:[e.jsx("i",{className:"bi bi-search inline-search-icon"}),e.jsx("input",{type:"text",className:"inline-search-input",placeholder:t("inbox.searchPlaceholder")||"Sök meddelanden...",value:B,onChange:s=>ae(s.target.value)}),B&&e.jsx("button",{className:"inline-search-clear",onClick:()=>ae(""),type:"button",children:e.jsx("i",{className:"bi bi-x-circle"})})]})}),e.jsxs("div",{className:"at-right",children:[e.jsx(et,{placement:"top",overlay:e.jsxs(tt,{children:[t("autoReply.title")||"Autosvar",n?` (${t("autoReply.statusBadgeActive")||"Aktiv"})`:""]}),children:e.jsxs("button",{className:`btn-filter-icon ${n?"auto-reply-active":""}`,onClick:()=>se(!0),disabled:me,"data-guide":"inbox-auto-reply",children:[e.jsx("i",{className:"bi bi-reply-all"}),n&&e.jsx("span",{className:"filter-badge auto-reply-active-badge"})]})}),e.jsx("button",{className:"fab-create-invoice",onClick:Se,title:t("inbox.newMessage")||"Nytt meddelande","data-guide":"inbox-compose",children:e.jsx("i",{className:"bi bi-plus-lg"})})]})]}),e.jsxs("div",{className:"inbox-layout",children:[(!u||l)&&e.jsx("div",{className:"inbox-sidebar","data-guide":"inbox-list",children:e.jsx(lt,{conversations:N,selectedKey:S,onSelect:d,loading:O,emptyTitle:t("CommonText.NoMessagesYet")||"Inga meddelanden än",emptyText:t("CommonText.StartByComposingMessage")||"Börja med att skriva ditt första meddelande"})}),(!u||k)&&e.jsx("div",{className:"inbox-main",children:h?e.jsx(pt,{userId:i==null?void 0:i.id,userRole:1,partnerId:h.partnerId,partnerRole:h.partnerRole,partner:h.partner,onMessageSent:f,onClose:a,showBackButton:u,targetMessageId:X,onTargetMessageHandled:()=>R(null)}):e.jsxs("div",{className:"conversation-thread-placeholder",children:[e.jsx("i",{className:"bi bi-chat-square-dots"}),e.jsx("h5",{children:t("inbox.selectConversation")||"Välj en dialog"}),e.jsx("p",{children:t("inbox.selectConversationHint")||"Välj en dialog frå
1n listan för att läsa och svara."})]})})]}),e.jsxs(H,{show:P,onHide:()=>L(!1),size:"lg",children:[e.jsx(H.Header,{closeButton:!0,style:{backgroundColor:"#f8f9fa"},children:e.jsx(H.Title,{style:{fontSize:"18px",color:"#2c372c"},children:t("inbox.newMessage")||"Nytt meddelande"})}),e.jsx(H.Body,{children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"20px"},children:[e.jsxs("div",{children:[e.jsxs("label",{style:{display:"block",marginBottom:"8px",fontWeight:"500",color:"#2c372c"},children:[t("inbox.recipient")||"Mottagare"," ",e.jsx("span",{style:{color:"red"},children:"*"})]}),e.jsx(Ye,{id:"inbox-recipient-select",options:_.map(s=>{const c=`${s.firstName||""}${s.lastName?" "+s.lastName:""}`.trim(),m=s.email?`${c} (${s.email})`:c;return{id:s.appUserId,label:m,customer:s}}),labelKey:"label",inputProps:{autoComplete:"off"},selected:y.recipientId?_.filter(s=>s.appUserId===y.recipientId).map(s=>{const c=`${s.firstName||""}${s.lastName?" "+s.lastName:""}`.trim(),m=s.email?`${c} (${s.email})`:c;return{id:s.appUserId,label:m,customer:s}}):[],onChange:s=>{E(c=>{var m;return{...c,recipientId:((m=s==null?void 0:s[0])==null?void 0:m.id)||""}})},placeholder:t("inbox.selectCustomer")||"Välj kund...",emptyLabel:t("inbox.noCustomersFound")||"Inga kunder hittades"}),e.jsx("small",{style:{color:"#6c757d",display:"block",marginTop:"4px"},children:t("inbox.onlyAppLinkedCustomers")||"Endast kunder med kundapp-konto visas"})]}),e.jsxs("div",{children:[e.jsxs("label",{style:{display:"block",marginBottom:"8px",fontWeight:"500",color:"#2c372c"},children:[t("inbox.subject")||"Ãmne"," ",e.jsx("span",{style:{color:"red"},children:"*"})]}),e.jsx("input",{type:"text",className:"form-control",value:y.subject||"",onChange:s=>E(c=>({...c,subject:s.target.value})),placeholder:t("inbox.subjectPlaceholder")||"Skriv ämnesraden..."})]}),e.jsxs("div",{children:[e.jsxs("label",{style:{display:"block",marginBottom:"8px",fontWeight:"500",color:"#2c372c"},children:[t("inbox.message")||"Meddelande"," ",e.jsx("span",{style:{color:"red"},children:"*"})]}),e.jsx("textarea",{className:"form-control",rows:8,value:y.content||"",onChange:s=>E(c=>({...c,content:s.target.value})),placeholder:t("inbox.messagePlaceholder")||"Skriv ditt meddelande här..."})]})]})}),e.jsxs(H.Footer,{children:[e.jsx(ue,{variant:"secondary",onClick:()=>L(!1),disabled:G,children:t("commonButton.Cancel")||"Avbryt"}),e.jsxs(ue,{variant:"success",onClick:Ne,disabled:!y.recipientId||!y.subject.trim()||!y.content.trim()||G,children:[G?e.jsx(oe,{animation:"border",size:"sm",className:"me-2"}):e.jsx(Je,{style:{marginRight:"5px"}}),t("inbox.sendMessage")||"Skicka meddelande"]})]})]}),e.jsxs(H,{show:ce,onHide:()=>se(!1),size:"lg",children:[e.jsx(H.Header,{closeButton:!0,style:{backgroundColor:"#f8f9fa"},children:e.jsxs(H.Title,{style:{fontSize:"18px",color:"#2c372c"},children:[e.jsx("i",{className:"bi bi-reply-all me-2"}),t("autoReply.title")||"Autosvar"]})}),e.jsx(H.Body,{children:me?e.jsxs("div",{className:"text-center py-4",children:[e.jsx(oe,{animation:"border",variant:"primary"}),e.jsx("p",{className:"mt-2 text-muted",children:t("autoReply.loading")||"Laddar..."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"d-flex justify-content-between align-items-center mb-4 pb-3 border-bottom",children:[e.jsx("div",{children:e.jsx("p",{className:"text-muted mb-0",style:{fontSize:"14px"},children:t("autoReply.subtitle")||"Skicka ett automatiskt svar när hästägare kontaktar dig."})}),e.jsxs("div",{className:"d-flex align-items-center gap-3",children:[b.isEnabled&&e.jsx(st,{bg:n?"success":"secondary",children:n?t("autoReply.statusBadgeActive")||"Aktiv":t("autoReply.statusBadgeInactive")||"Schemalagd"}),e.jsx(F.Check,{type:"switch",id:"auto-reply-modal-toggle",checked:b.isEnabled,onChange:s=>ge(s.target.checked),disabled:D,label:""})]})]}),b.isEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs(F.Group,{className:"mb-3",children:[e.jsx(F.Label,{children:t("autoReply.messageLabel")||"Ditt autosvar"}),e.jsx(F.Control,{as:"textarea",rows:4,value:b.message||"",onChange:s=>he("message",s.target.value),placeholder:t("autoReply.messagePlaceholder")||"Hej! Jag är pÃ¥ semester ...",disabled:D})]}),e.jsxs(nt,{className:"mb-3",children:[e.jsx(Le,{md:6,children:e.jsxs(F.Group,{children:[e.jsx(F.Label,{children:t("autoReply.startDateLabel")||"Startdatum"}),e.jsx(F.Control,{type:"datetime-local",value:Fe(b.startDate),onChange:s=>xe("startDate",s.target.value),disabled:D})]})}),e.jsx(Le,{md:6,children:e.jsxs(F.Group,{children:[e.jsx(F.Label,{children:t("autoReply.endDateLabel")||"Slutdatum"}),e.jsx(F.Control,{type:"datetime-local",value:Fe(b.endDate),onChange:s=>xe("endDate",s.target.value),disabled:D}),e.jsx(F.Text,{muted:!0,children:t("autoReply.windowHelper")||"Lämna tomt för att gälla tills vidare."})]})})]}),e.jsx(F.Check,{type:"checkbox",id:"auto-reply-once-modal",className:"mb-3",label:t("autoReply.sendOnceLabel")||"Skicka bara ett autosvar per hästägare",checked:b.sendOncePerSender,onCh
1ange:s=>he("sendOncePerSender",s.target.checked),disabled:D}),b.message&&e.jsxs("div",{style:{backgroundColor:"#f8f9fa",borderRadius:"8px",padding:"12px 16px",borderLeft:"4px solid #2c372c"},children:[e.jsx("small",{className:"text-muted d-block mb-1",children:t("autoReply.previewLabel")||"Förhandsvisning"}),e.jsx("p",{className:"mb-0",style:{whiteSpace:"pre-wrap"},children:b.message})]})]})]})}),e.jsxs(H.Footer,{children:[e.jsx(ue,{variant:"secondary",onClick:()=>{q(),se(!1)},children:t("commonButton.Cancel")||"Avbryt"}),e.jsx(ue,{className:"form-action-btn-primary",onClick:async()=>{await ye(),le||se(!1)},disabled:D||!le,children:D?e.jsxs(e.Fragment,{children:[e.jsx(oe,{animation:"border",size:"sm",className:"me-2"}),t("autoReply.saving")||"Sparar..."]}):t("commonButton.Save")||"Spara"})]})]})]})};export{_t 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.