PageSourceSearch

https://app.proptonomy.ai/assets/ContactEditModal-CabJIu_o.js

js proptonomy.ai collected 2026-10-05 14:32:03 UTC 169,148 bytes, 5 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/nativeVoiceAdapter-D1b8DW-N.js","assets/nativeCall-COgr6g3i.js","assets/rolldown-runtime-C0FnF6B9.js","assets/errorHandling-DsD3b-ed.js","assets/dist-CACrOlUe.js","assets/react-C21x__mS.js","assets/dist-Dhrj-3P3.js","assets/platform-BdYn0vmB.js","assets/emitter-DbHDsTGB.js","assets/softphoneLog-BTvrcEbV.js","assets/telnyxAdapter-BjdAlG1q.js","assets/twilioAdapter-CRrADMWa.js","assets/tslib.es6-CHdXbnTP.js"])))=>i.map(i=>d[i]);
2import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{t}from"./react-C21x__mS.js";import{n,t as r}from"./preload-helper-CYQMH_Gl.js";import{m as i,n as a,p as o}from"./chunk-OB3PAWPO-yTawzNiH.js";import{t as s}from"./createLucideIcon-C84aaOyl.js";import{t as c}from"./activity-DpNR0IXi.js";import{n as l,r as u,t as d}from"./phone-forwarded-BjHhD6Pg.js";import{t as f}from"./arrow-right-CcIIe6Nj.js";import{t as p}from"./building-complex-KGjrp6oP.js";import{$t as m,An as h,At as g,Bn as _,Bt as v,Dn as y,En as b,Hn as x,Ht as S,In as C,Jt as w,Ln as T,Lt as E,Mn as D,Pn as O,Qt as k,Rn as A,Rt as j,Sn as M,Tn as N,Tr as P,Vn as ee,Wt as F,Zt as I,c as te,cn as ne,en as re,fr as ie,h as ae,in as oe,jn as se,jt as ce,kn as L,l as R,m as z,o as le,on as B,qn as V,qt as ue,s as de,sn as fe,vn as pe,wn as me,wr as he,yr as ge,zt as _e}from"./ui-D9SHXhOv.js";import{t as ve}from"./chevron-up-Dn71Nt7l.js";import{n as ye,t as be}from"./chunk-JXT5O7F3-DtS3BkK0.js";import{t as xe}from"./circle-DIFWLnx3.js";import{t as Se}from"./ellipsis-Dpl-xZZv.js";import{t as Ce}from"./hash-D_CiG05s.js";import{t as we}from"./link-BQ_zyO86.js";import{t as Te}from"./mail-BE4sxOk1.js";import{t as Ee}from"./message-circle-Bx59EOKK.js";import{t as De}from"./message-square-s9kY8w7D.js";import{a as Oe,c as ke,i as H,n as Ae,r as je,s as Me}from"./phoneFormat-D3H38Jpe.js";import{t as Ne}from"./pause-CeTbLgGZ.js";import{t as U}from"./pencil-DIrtBRpg.js";import{t as Pe}from"./phone-BZCu58_O.js";import{t as Fe}from"./play-Cf5N4Sn-.js";import{t as Ie}from"./plus-B-mja-vO.js";import{t as W}from"./save-BcE4JNG8.js";import{t as Le}from"./shield-alert-B3swHnKk.js";import{t as G}from"./trash-CNLtSgO2.js";import{t as Re}from"./upload-CG3bpgk8.js";import{t as ze}from"./user-plus-C-zlnwhp.js";import{t as K}from"./user-x-CR20H0fu.js";import{t as Be}from"./users-BRJyexy6.js";import{t as Ve}from"./jsx-runtime-BdxMnOeJ.js";import{et as He}from"./chunk-BGEKJ4Q5-uEOfRNrw.js";import{i as q}from"./dist-CACrOlUe.js";import{F as J,t as Y,w as Ue}from"./useQuery-DGBNsgop.js";import{t as We}from"./useInfiniteQuery-CLmkIL-9.js";import{t as X}from"./useMutation-CiPQDxyA.js";import{$i as Ge,Af as Ke,Bs as qe,Cf as Je,Cs as Ye,Df as Xe,Ef as Ze,Fs as Qe,If as $e,In as et,Jr as tt,Qi as nt,Qr as rt,Rf as it,Sf as at,Vs as ot,Xi as st,Xr as ct,Yr as lt,_f as ut,ad as dt,bf as ft,cd as pt,ea as mt,ed as ht,eg as gt,ei as _t,gf as vt,hf as yt,ia as bt,kf as xt,ld as St,na as Ct,no as wt,oa as Tt,od as Et,q as Dt,qr as Ot,sd as kt,tg as At,ud as jt,vf as Mt,wf as Nt,ws as Pt,xf as Ft,yf as It,zf as Lt}from"./sdk.gen-D4QOengS.js";import"./api-gen-U2FehJ-o.js";import{c as Rt,s as zt}from"./errorHandling-DsD3b-ed.js";import{s as Bt}from"./useProperties-DFloC7Zp.js";import{n as Vt,r as Ht,t as Ut}from"./platform-BdYn0vmB.js";import{r as Wt}from"./auth-DZEnhR-8.js";import{D as Gt,E as Kt,O as qt,S as Jt,T as Yt,a as Xt,b as Zt,d as Qt,f as $t,h as en,l as tn,m as nn,o as rn,p as an,r as on,s as sn,t as cn,u as ln,v as un,x as dn,y as fn}from"./nativeCall-COgr6g3i.js";import{a as pn,i as mn,l as hn,n as gn,o as _n,s as vn}from"./useAuth-BDINV9q2.js";import{c as yn,f as bn,g as xn,i as Sn,l as Cn,r as wn,s as Tn,t as En,u as Dn}from"./useOrganizations-BxzUXOsO.js";import{n as On}from"./useOrganizations-BIM3qCCr.js";import{t as kn}from"./useDebounce-DtM4W2lJ.js";import{a as An,r as jn,t as Mn}from"./useSignalR-D226W8ro.js";import{n as Nn}from"./useInboxes-B8h3QR6M.js";import{a as Pn}from"./phone-shared-B1hA0ZmJ.js";import{n as Fn,r as In,t as Ln}from"./usePhoneDevice-DfDwKcJL.js";import{t as Rn}from"./Timestamp-CTVWtV6v.js";import{n as zn}from"./notificationPreferences-Ck0VJ_VN.js";import{n as Bn}
2from"./softphoneLog-BTvrcEbV.js";import{t as Vn}from"./reloadGuard-C7kcZpky.js";import{a as Hn,d as Un,f as Wn,h as Gn,i as Kn,l as qn,m as Jn,n as Yn,o as Xn,p as Zn,s as Qn,t as $n,u as er}from"./useContacts-CHTvUqFH.js";import{t as tr}from"./OrgRoleSelect-_b6NsKOl.js";import{t as nr}from"./usePartners-C7knFY3a.js";import{t as rr}from"./useExternalIntegrations-zc1Zt3du.js";var ir={name:`captions`,size:24,node:[[`rect`,{width:`18`,height:`14`,x:`3`,y:`5`,rx:`2`,ry:`2`,key:`12ruh7`}],[`path`,{d:`M7 15h4M15 15h2M7 11h2M13 11h4`,key:`1ueiar`}]],aliases:[`subtitles`]};ir.node;var ar=s(ir),or={name:`grid-3x3`,size:24,node:[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M3 9h18`,key:`1pudct`}],[`path`,{d:`M3 15h18`,key:`5xshup`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`M15 3v18`,key:`14nvp0`}]],aliases:[`grid`,`grid-3-x-3`]};or.node;var sr=s(or),cr={name:`headphones`,size:24,node:[[`path`,{d:`M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3`,key:`1xhozi`}]]};cr.node;var lr=s(cr),ur={name:`merge`,size:24,node:[[`path`,{d:`m8 6 4-4 4 4`,key:`ybng9g`}],[`path`,{d:`M12 2v10.3a4 4 0 0 1-1.172 2.872L4 22`,key:`1hyw0i`}],[`path`,{d:`m20 22-5-5`,key:`1m27yz`}]]};ur.node;var dr=s(ur),fr={name:`mic-off`,size:24,node:[[`path`,{d:`M12 19v3`,key:`npa21l`}],[`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`,key:`1gzdoj`}],[`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`,key:`cqa7eg`}],[`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`,key:`16hl24`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`,key:`r2i35w`}]]};fr.node;var pr=s(fr),mr={name:`phone-incoming`,size:24,node:[[`path`,{d:`M16 2v6h6`,key:`1mfrl5`}],[`path`,{d:`m22 2-6 6`,key:`6f0sa0`}],[`path`,{d:`M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384`,key:`9njp5v`}]]};mr.node;var hr=s(mr),gr={name:`phone-off`,size:24,node:[[`path`,{d:`M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272`,key:`1wngk7`}],[`path`,{d:`M22 2 2 22`,key:`y4kqgn`}],[`path`,{d:`M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473`,key:`10hv5p`}]]};gr.node;var _r=s(gr),vr={name:`sticky-note`,size:24,node:[[`path`,{d:`M21 9a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2z`,key:`1dfntj`}],[`path`,{d:`M15 3v5a1 1 0 0 0 1 1h5`,key:`6s6qgf`}]]};vr.node;var yr=s(vr),br={name:`volume-2`,size:24,node:[[`path`,{d:`M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z`,key:`uqj9uw`}],[`path`,{d:`M16 9a5 5 0 0 1 0 6`,key:`1q6k2b`}],[`path`,{d:`M19.364 18.364a9 9 0 0 0 0-12.728`,key:`ijwkga`}]]};br.node;var xr=s(br),Sr={name:`volume-x`,size:24,node:[[`path`,{d:`M11 4.702a.7.7 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.7.7 0 0 0 11 19.298z`,key:`1p7khw`}],[`path`,{d:`m16.5 14.5 5-5`,key:`cul3yw`}],[`path`,{d:`m16.5 9.5 5 5`,key:`1akey5`}]]};Sr.node;var Cr=s(Sr),Z=e(t(),1);n();var Q=Ve(),wr=new Set([`hybel`,`finn`,`guesty`,`hostaway`,`airbnb`,`booking`,`homeaway`,`vrbo`,`uplisting`,`lodgify`,`krossbooking`]);function Tr(e,t){return!e||!t||!wr.has(t)?!1:/^\d{3,}$/.test(e.trim())}var Er=/^([^\s@+]+)\+bncb[a-z0-9_-]*@([^\s@]+)$/i;function Dr(e){let t=Er.exec(e.trim());return t?`${t[1]}@${t[2]}`:e}function Or(e){return typeof e.isGroupChat==`boolean`?e.isGroupChat:!!(e.subject?.toLowerCase().includes(`group`)||(e.participants?.length??0)>=3)}function kr(e){return Or(e)?e.chatTitle||e.subject||e.from||`Unknown`:Tr(e.from,e.source)?e.subject?.trim()||e.from||`Unknown`:e.from||e.subject||`Unknown`}function Ar(e){let t=kr(e);if(Or(e))return t;let n=e.subject?.trim();return!n||n===t?t:n.toLowerCase().startsWith(t.toLowerCase())?n:`${t} — ${n}`}function jr(e){if(!Or(e)){let t=e.subject?.trim();return!t||t===kr(e)?null:t}let t=(e.participants??[]).map(e=>e.contact?.displayName?.split(` `)[0]||e.contact?.email).filter(
2Boolean);if(t.length===0)return e.subject||`No members yet`;let n=t.slice(0,5).join(`, `);return t.length>5?`${n} +${t.length-5} more`:n}function Mr(e){if(e.subject?.trim())return e.subject.trim();if(e.chatTitle?.trim())return e.chatTitle.trim();let t=e.participants?.find(e=>e.contact)?.contact;return[t?.firstName,t?.lastName].filter(Boolean).join(` `).trim()||t?.email||`Conversation`}function Nr(e){return e?e.replace(/<\/?[a-zA-Z][^>]*>/g,` `).replace(/&nbsp;/g,` `).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#0?39;/g,`'`).replace(/\s+/g,` `).trim():``}function Pr(e){return e?.ownsProperties||e?.organizationRole===`PropertyOwner`?`owner`:e?.organizationRole===`Admin`||e?.organizationRole===`Member`||e?.organizationRole===`MemberReadOnly`||e?.organizationRole===`StaffCoordinator`||e?.organizationRole===`StaffMember`||e?.organizationRole===`InboxAgent`||e?.partnerOrganizationId?`ops`:`guest`}function Fr(e,t){return Lr(Ir(e),t)}function Ir(e){if(e.chatRole===`Internal`||e.chatRole===`Admin`)return`ops`;let t=(e.participants??[]).map(e=>Pr(e.contact));return t.includes(`owner`)?`owner`:t.includes(`guest`)?`guest`:t.includes(`ops`)?`ops`:`guest`}function Lr(e,t){return!t||t.length!==1?e:t[0].toLowerCase()}var Rr={guest:{label:`Guest`,pill:`bg-[var(--status-info-fg)]/10 text-[var(--status-info-fg)]`,activeTab:`bg-[var(--status-info-fg)] text-white`,border:``},owner:{label:`Owner`,pill:`bg-primary/10 text-primary`,activeTab:`bg-primary text-primary-foreground`,border:`border-l-primary`},ops:{label:`Ops`,pill:`bg-secondary-600/10 text-secondary-600`,activeTab:`bg-secondary-600 text-secondary-50`,border:`border-l-secondary-600`}},zr=[`guest`,`owner`,`ops`];function Br(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase().replace(/[^a-z0-9]/g,``);if(t.includes(`airbnb`))return`airbnb`;if(t.includes(`krossbooking`))return`krossbooking`;if(t.includes(`booking`))return`booking`;if(t.includes(`hybel`))return`hybel`;if(t.includes(`guesty`))return`guesty`;if(t.includes(`hostaway`))return`hostaway`;if(t.includes(`telegram`))return`telegram`;if(t.includes(`whatsapp`))return`whatsapp`;if(t.includes(`slack`))return`slack`;if(t.startsWith(`line`))return`line`;if(t.includes(`homeaway`))return`homeaway`;if(t.includes(`vrbo`))return`vrbo`;if(t.includes(`uplisting`))return`uplisting`;if(t.includes(`lodgify`))return`lodgify`;if(t.includes(`internalnote`))return`internalnote`;if(t.includes(`inapp`))return`inapp`;if(t.includes(`email`))return`email`;if(t===`sms`)return`sms`;if(t.includes(`phone`))return`phone`;if(t.includes(`finn`))return`finn`}var $={all:[`conversations`],lists:()=>[...$.all,`list`],list:e=>[...$.lists(),e],details:()=>[...$.all,`detail`],detail:e=>[...$.details(),e],messages:e=>[...$.detail(e),`messages`],readHistory:e=>[...$.detail(e),`read-history`],assistantThread:(e,t)=>[...$.all,`assistant-thread`,e??null,t??null]},Vr=15,Hr=200;function Ur(e){let t=Br(e);if(t)return t;switch(e){case`Email`:return`email`;case`SMS`:return`sms`;case`Phone`:return`phone`;case`Guesty`:return`guesty`;case`Hostaway`:return`hostaway`;case`HybelNo`:return`hybel`;case`Telegram`:return`telegram`;case`Slack`:return`slack`;case`Line`:return`line`;case`InApp`:return`inapp`;case`InternalNote`:return`internalnote`;default:return`email`}}function Wr(e){return e.externalIntegrations?.map(e=>Br(e.externalIntegrationName)).find(e=>!!e)}var Gr=new Set([`airbnb`,`booking`,`whatsapp`,`telegram`,`homeaway`,`vrbo`,`uplisting`,`lodgify`,`line`,`sms`,`email`,`phone`]);function Kr(e){if(e.channel){let t=Ur(e.channel);return Gr.has(t)?t:Wr(e)??t}let t=e.messages?.[e.messages.length-1],n=e.messages?.[0],r=e.messages?.find(e=>e.direction===`Inbound`),i=Ur(r?.type||t?.type||n?.type);return Gr.has(i)?i:Wr(e)??i}function qr(e){let t=e.unreadCount||0,n=(e.subject||``).toLowerCase();return n.includes(`urgent`)||n.includes(`akutt`)||n.includes(`emergency`)||n.includes(`vannlekkasje`)||t>3?`high`:t===0?`low`:`medium`}function Jr(e){let t=(e.subject||``).toLowerCase();return t.includes(`book`)||t.includes(`reserv`)||t.includes(`check-in`)||t.includes(`innsjekk`)?`booking`:t.includes(`maintenance`)||t.includes(`repair`)||t.includes(`leak`)?`maintenance`:t.includes(`complain`)||t.includes(`complaint`)||t.includes(`problem`)||t.includes(`noise`)?`complaint`:t.includes(`inquiry`)||t.includes(`question`)||t.includes(`interest`)?`inquiry`:`general`}function Yr(e){if(!e)return`Unknown time`;let t=new Date,n=new Date(e),r=t.getTime()-n.getTime(),i=Math.floor(r/6e4),a=Math.floor(r/36e5),o=Math.floor(r/864e5);return i<1?`Just now`:i<60?`${i} min ago`:a<24?`${a}h ago`:o===1?`Yesterday`:o<7?`${o} days ago`:n.toLocaleDateString(`en-US`)}function Xr(e){let t={};for(let n of e)n.id&&(t[n.id]=n.allowedAudiences);return t}function Zr(e,t){let n=e,r=e.messages?.[e.messages.length-1],i=e.messages?.[0],a=e.messages?.find(e=>e.direction===`Inbound`),o=Wr(e)??Ur(e.channel||a?.type||r?.type||i?.type),s=qr(e),c=Jr(e),l=e.participants?.map(e=>
2e.contact?.displayName||e.contact?.email).filter(Boolean)?.[0],u=e.messages?.find(e=>e.direction===`Inbound`),d=e=>Tr(e,o)?void 0:e??void 0,f=Dr(l||u?.fromContact?.displayName||u?.fromContact?.email||d(u?.senderIdentifier)||r?.fromContact?.displayName||r?.fromContact?.email||d(r?.senderIdentifier)||e.subject||u?.senderIdentifier||r?.senderIdentifier||`Unknown`),p=Nr(r?.content||r?.htmlContent||``)||e.subject||`No content`,m=e.assignedUserName??void 0,h=e.unreadCount||0;return{...e,id:e.id??``,subject:e.subject??null,organizationId:e.organizationId??``,propertyId:n.propertyId??null,leaseId:n.leaseId??null,lastMessageAt:e.lastMessageAt??null,unreadCount:h,isArchived:e.isArchived||!1,source:o,channelSource:Kr(e),priority:s,category:c,from:f,preview:p.substring(0,200),timestamp:Yr(e.lastMessageAt??null),unread:e.isUnread===!0,assignedAgent:m,audience:Fr(e,e.inboxId?t?.[e.inboxId]:void 0)}}function Qr(e,t){return t?e.filter(e=>{if(t.searchString){let n=t.searchString.toLowerCase();if(!(e.from.toLowerCase().includes(n)||(e.subject||``).toLowerCase().includes(n)||e.preview.toLowerCase().includes(n)))return!1}return!(t.source&&t.source!==`all`&&e.source!==t.source||t.priority&&t.priority!==`all`&&e.priority!==t.priority||t.category&&t.category!==`all`&&e.category!==t.category||t.unread!==void 0&&e.unread!==t.unread)}):e}function $r(e,t){let n=kn(t,Hr),r=t!==null&&!!e,{inboxes:i}=Nn(e??void 0),a=(0,Z.useMemo)(()=>Xr(i),[i]),{data:o,isLoading:s}=Y({queryKey:[...$.all,`mention-search`,e??null,n??``],enabled:r,placeholderData:Ue,staleTime:6e4,queryFn:async({signal:t})=>{let r=await Ot({signal:t,query:{organizationIds:[e],searchString:n||void 0,includeArchived:!1,page:1,pageSize:Vr}});if(r.error)throw Error(JSON.stringify(r.error));return(r.data??[]).map(e=>Zr(e,a)).map(e=>({id:e.id,label:kr(e),description:[e.audience,e.source].filter(Boolean).join(` · `)||void 0}))}});return{items:r?o??[]:[],isLoading:r&&s}}function ei(e){let{selectedOrganizationId:t}=On(),n=e?.pageSize||25,r=e?.organizationIds??(t?[t]:[]),{inboxes:i}=Nn(t??void 0),a=(0,Z.useMemo)(()=>Xr(i),[i]),o=We({queryKey:[...$.list(e),e?.organizationIds?null:t],queryFn:async({pageParam:t=1,signal:i})=>{if(r.length===0)return[];let a=await Ot({signal:i,query:{organizationIds:r,includeArchived:e?.includeArchived,isArchived:e?.isArchived,searchString:e?.searchString,inboxId:e?.inboxId,propertyIds:e?.propertyIds,pageSize:n,page:t,leaseStatus:e?.leaseStatus||void 0,stayStatus:e?.stayStatus||void 0,leaseStartFrom:e?.leaseStartFrom||void 0,leaseStartTo:e?.leaseStartTo||void 0,minMessages:e?.minMessages||void 0,minGuestMessages:e?.minGuestMessages||void 0,minHostMessages:e?.minHostMessages||void 0,isEscalated:e?.isEscalated,audience:e?.audience||void 0,assignment:e?.assignment||void 0,includeInternalAssistantChats:e?.includeInternalAssistantChats||void 0,isRead:e?.unread===void 0?void 0:!e.unread,sort:e?.sort||void 0}});if(a.error)throw Error(JSON.stringify(a.error));return a.data??[]},initialPageParam:1,getNextPageParam:(e,t,r)=>{if(!(e.length<n))return r+1},enabled:r.length>0,staleTime:3e4}),s=Qr((o.data?.pages.flat()??[]).map(e=>Zr(e,a)),e);return{conversations:s,totalCount:s.length,loading:o.isLoading,error:o.error,refetch:o.refetch,hasNextPage:o.hasNextPage??!1,isFetchingNextPage:o.isFetchingNextPage,fetchNextPage:o.fetchNextPage}}function ti(e){let{selectedOrganizationId:t}=On(),n=e?.organizationIds??(t?[t]:[]);return Y({queryKey:[...$.list({...e,audience:void 0,sort:void 0}),e?.organizationIds?null:t,`audience-counts`],enabled:n.length>0,staleTime:3e4,queryFn:async({signal:t})=>{let r=await lt({signal:t,query:{organizationIds:n,includeArchived:e?.includeArchived,isArchived:e?.isArchived,searchString:e?.searchString,inboxId:e?.inboxId,propertyIds:e?.propertyIds,leaseStatus:e?.leaseStatus||void 0,stayStatus:e?.stayStatus||void 0,leaseStartFrom:e?.leaseStartFrom||void 0,leaseStartTo:e?.leaseStartTo||void 0,minMessages:e?.minMessages||void 0,minGuestMessages:e?.minGuestMessages||void 0,minHostMessages:e?.minHostMessages||void 0,isEscalated:e?.isEscalated,assignment:e?.assignment||void 0,includeInternalAssistantChats:e?.includeInternalAssistantChats||void 0,isRead:e?.unread===void 0?void 0:!e.unread}});if(r.error)throw Error(JSON.stringify(r.error));return r.data??{all:0,guest:0,owner:0,ops:0}}})}function ni(e,t){let{inboxes:n}=Nn(t?.[0]),r=(0,Z.useMemo)(()=>Xr(n),[n]),i=Y({queryKey:$.detail(e??``),queryFn:async({signal:t})=>{if(!e)throw Error(`Conversation ID is required`);let n=await ct({path:{conversationId:e},signal:t});if(n.error)throw Error(JSON.stringify(n.error));let i=n.data;return Zr(i,r)},enabled:!!e&&(t===void 0||t.length>0),staleTime:3e4}),a=i.data!==void 0&&t!==void 0&&(!i.data.organizationId||!t.includes(i.data.organizationId));return{conversation:a?void 0:i.data,outOfWorkScopeOrganizationId:a?i.data?.organizationId??void 0:void 0,loading:i.isLoading,error:i.error,refetch:i.refetch}}var ri=100,ii=50;function ai(e){let t=We({queryKey:$.messages(e??``),initialPageParam:0,queryFn:async({pageParam:t,signal:n})=>{if(!e)throw Error(`Conversation ID is required`);let r=await rt({path:{conversationId:e},query:{skip:t,maxNum:t===0?ri:ii},signal:n});if(r.error)throw Error(JSON.stringify(r.error));return r.data||[]},getNextPageParam:(e,t)=>{let n=t.length===1?ri:ii;if(!(e.length<n))return t.flat().length},enabled:!!e,staleTime:3e4});return{messages:(0,Z.useMemo)(()=>[...t.data?.pages??[]].reverse().flat(),[t.data?.pages]),loading:t.isLoading,error:t.error,refetch:t.refetch,fetchOlderMessages:t.fetchNextPage,hasOlderMessages:t.hasNextPage??!1,isFetchingOlder:t.isFetchingNextPage}}function oi(){let e=J();return X({mutationFn:async({conversationId:e,source:t=`opened`,notify:n=!1})=>{let r=await pt({path:{conversationId:e},query:{source:t},meta:n?{successToastMsg:`Marked as read`,errorToastMsg:`Could not mark as read`}:{successToast:!1,errorToast:!1}});if(r.error)throw Error(JSON.stringify(r.error));return r.data},onSuccess:(t,{conversationId:n})=>{si(e,n,t)}})}function si(e,t,n){n&&e.setQueryData($.detail(t),e=>e&&{...e,isUnread:n.isUnread,unread:n.isUnread===!0,lastReadAt:n.lastReadAt,lastReadByUserId:n.lastReadByUserId,lastReadByUserName:n.lastReadByUserName}
2),e.invalidateQueries({queryKey:$.lists()}),e.invalidateQueries({queryKey:$.detail(t)}),e.invalidateQueries({queryKey:$.readHistory(t)})}function ci(){let e=J();return X({mutationFn:async e=>{let t=await St({path:{conversationId:e},meta:{successToastMsg:`Marked as unread`,errorToastMsg:`Could not mark as unread`}});if(t.error)throw Error(JSON.stringify(t.error));return t.data},onSuccess:(t,n)=>{si(e,n,t)}})}function li(e,t=!0){return Y({queryKey:$.readHistory(e??``),enabled:!!e&&t,staleTime:3e4,queryFn:async({signal:t})=>{let n=await _t({signal:t,path:{conversationId:e},meta:{successToast:!1}});if(n.error)throw Error(JSON.stringify(n.error));return n.data??[]}})}function ui(){let e=J();return X({mutationFn:async e=>{let t=await dt({body:{organizationId:e.organizationId||null,subject:e.subject||null,propertyId:e.propertyId||null,leaseId:e.leaseId||null,inboxId:e.inboxId||null,externalReservationId:e.externalReservationId||null,contactIds:e.contactIds||null,tags:e.tags||null,forceNew:e.forceNew??!1,assistantScopeKey:e.assistantScopeKey||null,isInternalAssistantThread:e.isInternalAssistantThread??!1},meta:{successToastMsg:e.assistantScopeKey?void 0:`New conversation created`,errorToastMsg:`Could not create conversation`}});if(t.error){let e=typeof t.error==`string`?t.error:t.error.message||`Unknown error`;throw Error(e)}return t.data},onSuccess:()=>{e.invalidateQueries({queryKey:$.lists()})}})}function di(e,t){return Y({queryKey:$.assistantThread(e,t),queryFn:async()=>{if(!e||!t)return null;let n=await tt({query:{organizationId:e,assistantScopeKey:t}});if(n.error)throw Error(`Could not resolve the assistant thread`);return n.data?.conversationId??null},enabled:!!(e&&t),staleTime:0})}function fi(e){let t=J();return X({mutationFn:async t=>{if(!e)throw Error(`Conversation is required`);let n=await kt({path:{conversationId:e},query:{force:t}});if(n.error){let e=n.error;throw Error(e?.assignedUserName?`Already assigned to ${e.assignedUserName}`:`Could not assign conversation`)}return n.data},onSuccess:()=>{e&&(t.invalidateQueries({queryKey:$.detail(e)}),t.invalidateQueries({queryKey:$.lists()}),t.invalidateQueries({queryKey:An.all}))}})}function pi(e){let t=J();return X({mutationFn:async({userId:t,displayName:n})=>{if(!e)throw Error(`Conversation is required`);let r=await Et({path:{conversationId:e},body:{userId:t},meta:{successToastMsg:t?`Assigned to ${n?.trim()||`a teammate`}`:`Unassigned — back in the team's queue`,errorToastMsg:`Could not change the assignment`}});if(r.error)throw Error(JSON.stringify(r.error));return r.data},onSuccess:()=>{e&&(t.invalidateQueries({queryKey:$.detail(e)}),t.invalidateQueries({queryKey:$.lists()}),t.invalidateQueries({queryKey:An.all}))}})}function mi(){let e=J();return X({mutationFn:async({conversationId:e,isAiEnabled:t})=>{let n=await Pt({path:{conversationId:e},body:{isAiEnabled:t},meta:{successToast:!1,errorToastMsg:`Could not update AI setting`}});if(n.error){let e=typeof n.error==`string`?n.error:n.error.message||`Unknown error`;throw Error(e)}return n.data},onSuccess:(t,n)=>{e.invalidateQueries({queryKey:$.detail(n.conversationId)}),e.invalidateQueries({queryKey:$.messages(n.conversationId)}),e.invalidateQueries({queryKey:$.lists()}),Rt(n.isAiEnabled?`AI agent enabled for this conversation`:`AI agent disabled for this conversation`)},onError:e=>{zt(e,`Could not update AI setting`)}})}function hi(){let e=J();return X({mutationFn:async({conversationId:e,replyPolicyOverride:t})=>{let n=await Pt({path:{conversationId:e},body:{updateReplyPolicyOverride:!0,replyPolicyOverride:t??void 0},meta:{successToast:!1,errorToastMsg:`Could not update reply policy`}});if(n.error){let e=typeof n.error==`string`?n.error:n.error.message||`Unknown error`;throw Error(e)}return n.data},onSuccess:(t,n)=>{e.invalidateQueries({queryKey:$.detail(n.conversationId)}),e.invalidateQueries({queryKey:$.messages(n.conversationId)}),e.invalidateQueries({queryKey:$.lists()}),Rt(`Conversation reply policy updated`)},onError:e=>{zt(e,`Could not update reply policy`)}})}function gi(){let e=J();return X({mutationFn:async({conversationId:e,notes:t})=>{let n=await Pt({path:{conversationId:e},body:{updateNotes:!0,notes:t??void 0},meta:{successToast:!1,errorToastMsg:`Could not save conversation note`}});if(n.error){let e=typeof n.error==`string`?n.error:n.error.message||`Unknown error`;throw Error(e)}return n.data},onSuccess:(t,n)=>
2{e.invalidateQueries({queryKey:$.detail(n.conversationId)}),e.invalidateQueries({queryKey:$.messages(n.conversationId)}),Rt(`Conversation note saved`)},onError:e=>{zt(e,`Could not save conversation note`)}})}function _i(){let e=J();return X({mutationFn:async({conversationId:e,sentiment:t})=>{let n=await Pt({path:{conversationId:e},body:{updateSentiment:!0,sentiment:t},meta:{successToast:!1,errorToastMsg:`Could not update sentiment`}});if(n.error){let e=typeof n.error==`string`?n.error:n.error.message||`Unknown error`;throw Error(e)}return n.data},onSuccess:(t,n)=>{e.invalidateQueries({queryKey:$.detail(n.conversationId)}),e.invalidateQueries({queryKey:$.lists()}),Rt(`Sentiment set to ${n.sentiment.toLowerCase()}`)},onError:e=>{zt(e,`Could not update sentiment`)}})}function vi(){let e=J();return X({mutationFn:async({conversationId:e,isArchived:t})=>{let n=await Pt({path:{conversationId:e},body:{isArchived:t},meta:{successToast:!1,errorToastMsg:t?`Could not archive conversation`:`Could not restore conversation`}});if(n.error){let e=typeof n.error==`string`?n.error:n.error.message||`Unknown error`;throw Error(e)}return n.data},onSuccess:(t,n)=>{e.invalidateQueries({queryKey:$.detail(n.conversationId)}),e.invalidateQueries({queryKey:$.messages(n.conversationId)}),e.invalidateQueries({queryKey:$.lists()}),Rt(n.isArchived?`Conversation archived`:`Conversation restored`)},onError:(e,t)=>{zt(e,t.isArchived?`Could not archive conversation`:`Could not restore conversation`)}})}function yi(){let e=J();return X({mutationFn:async({sourceConversationId:e,targetConversationId:t})=>{let n=await jt({path:{conversationId:e},body:{targetConversationId:t},meta:{successToast:!1,errorToastMsg:`Could not merge conversation`}});if(n.error){let e=typeof n.error==`string`?n.error:n.error.message||`Unknown error`;throw Error(e)}return n.data},onSuccess:(t,n)=>{e.invalidateQueries({queryKey:$.detail(n.sourceConversationId)}),e.invalidateQueries({queryKey:$.detail(n.targetConversationId)}),e.invalidateQueries({queryKey:$.messages(n.targetConversationId)}),e.invalidateQueries({queryKey:$.lists()}),Rt(`Conversation merged`)},onError:e=>{zt(e,`Could not merge conversation`)}})}function bi(){let e=J();return X({mutationFn:async({conversationId:e,enabled:t,language:n})=>{let r=await Pt({path:{conversationId:e},body:{updateAutomaticallyTranslateToLanguage:!0,automaticallyTranslateToLanguage:t?n??`English`:null},meta:{successToast:!1,errorToastMsg:`Could not update auto-translation setting`}});if(r.error){let e=typeof r.error==`string`?r.error:r.error.message||`Unknown error`;throw Error(e)}return r.data},onSuccess:(t,n)=>{e.invalidateQueries({queryKey:$.detail(n.conversationId)}),e.invalidateQueries({queryKey:$.lists()}),Rt(n.enabled?`Conversation auto-translation enabled (${n.language??`English`})`:`Conversation auto-translation disabled`)},onError:e=>{zt(e,`Could not update auto-translation setting`)}})}function xi(){let e=J();return X({mutationFn:async({conversationId:e,language:t})=>{let n=await Pt({path:{conversationId:e},body:{updateComposeLanguage:!0,composeLanguage:t},meta:{successToast:!1,errorToastMsg:`Could not update the AI writing language`}});if(n.error){let e=typeof n.error==`string`?n.error:n.error.message||`Unknown error`;throw Error(e)}return n.data},onSuccess:(t,n)=>{e.invalidateQueries({queryKey:$.detail(n.conversationId)}),e.invalidateQueries({queryKey:$.lists()}),Rt(n.language?`Proptonomy now writes in ${n.language} in this conversation`:`Proptonomy now mirrors whoever writes in this conversation`)},onError:e=>{zt(e,`Could not update the AI writing language`)}})}function Si(){let e=J();return X({mutationFn:async({conversationId:e,translateMessages:t,nativeLanguages:n})=>{let r=await Pt({path:{conversationId:e},body:{updateTranslateMessages:t!==void 0,translateMessages:t??null,updateNativeLanguages:n!==void 0,nativeLanguages:n??null},meta:{successToast:!1,errorToast:!1}});if(r.error){let e=r.error,t=typeof e==`string`?e:e.detail||e.title||e.message||`Unknown error`;throw Error(t)}return r.data},onSuccess:(t,n)=>{e.invalidateQueries({queryKey:$.detail(n.conversationId)}
2),e.invalidateQueries({queryKey:$.lists()}),n.translateMessages!==void 0&&Rt(n.translateMessages?`Every message in this chat is now relayed into the group's languages`:`Message relay turned off for this chat`)},onError:e=>{zt(e,`Could not update the translation relay`)}})}function Ci(){let e=J();return X({mutationFn:async({conversation:e,role:t})=>{let n=e.chatId,r=e.chatIntegrationId??void 0,i=e.organizationId||void 0;if(!n)throw Error(`This conversation is not a connected chat`);let a=e.externalIntegrations?.find(e=>e.externalIntegrationId===r)?.type,o={successToast:!1,errorToast:!1},s;switch(a){case`WhatsApp`:s=await ot({path:{chatId:n},query:{organizationId:i},body:{role:t},meta:o});break;case`Telegram`:s=await qe({path:{chatId:n},query:{organizationId:i},body:{role:t},meta:o});break;case`Line`:s=await Ye({path:{chatId:n},query:{organizationId:i},body:{role:t},meta:o});break;case`Slack`:s=await Qe({path:{channelId:n},query:{integrationId:r},body:{role:t},meta:o});break;default:throw Error(`Changing the chat role is not supported for this channel (${a??`unknown`}).`)}if(s.error)throw Error(typeof s.error==`string`?s.error:`Could not update chat role`)},onSuccess:(t,n)=>{e.invalidateQueries({queryKey:$.detail(n.conversation.id)}
2),e.invalidateQueries({queryKey:$.lists()}),Rt(`Chat role updated`)},onError:e=>{zt(e,`Could not update chat role`)}})}function wi({call:e,organizationId:t,clientIdentity:n,onChanged:r,presentation:i=`toolbar`}){let[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(!1),[_,b]=(0,Z.useState)(``),x=e.participants?.some(e=>e.role===`Guest`&&!e.leftAt&&e.isOnHold)??!1,S=e.participants?.some(e=>e.role===`Transferee`&&!e.leftAt&&!!e.mediaJoinedAt)??!1,w=e.isRecordingPaused??!1,E=!!(e.recordCalls||e.transcribeCalls),D=!E&&!!e.streamLiveAudio,O=e.participants?.filter(e=>e.role===`Added`||e.role===`Transferee`&&!e.leftAt).length??0,A=e=>{e&&r?.(e)},j=X({mutationFn:async n=>{let r=await It({path:{id:e.id},query:{organizationId:t},body:{hold:n}});if(r.error)throw Error(Pn(r.error,`Could not put the call on hold`));return r.data},onSuccess:(e,t)=>{A(e),q.success(t?`On hold`:`Back on the call`)},onError:e=>q.error(e.message)}),N=X({mutationFn:async n=>{let r=await at({path:{id:e.id},query:{organizationId:t},body:{paused:n}});if(r.error)throw Error(Pn(r.error,`Could not change the recording`));return r.data},onSuccess:(e,t)=>{A(e),q.success(D?`Live transcription has stopped for the rest of this call.`:t?`Recording paused. Live transcription has stopped for this call.`:`Recording again. Live transcription returns on the next call.`)},onError:e=>q.error(e.message)}),P=X({mutationFn:async n=>{let r=await Ft({path:{id:e.id},query:{organizationId:t},body:{e164:n}});if(r.error)throw Error(Pn(r.error,`Could not add them to the call`));return r.data},onSuccess:e=>{A(e),b(``),g(!1),q.success(`Ringing them into the call`)},onError:e=>q.error(e.message)}),ee=X({mutationFn:async r=>{let i=await Ze({path:{id:e.id},query:{organizationId:t},body:{toE164:r,warm:!0,fromClientIdentity:n??void 0}});if(i.error)throw Error(Pn(i.error,`Could not start the transfer`));return i.data},onSuccess:e=>{A(e),c(!0),q.success(`Ringing them now — stay on to introduce the call`)},onError:e=>q.error(e.message)}),F=X({mutationFn:async()=>{let r=await Xe({path:{id:e.id},query:{organizationId:t},body:{clientIdentity:n??``}});if(r.error)throw Error(Pn(r.error,`Could not hand the call over`));return r.data},onSuccess:e=>{A(e),p(!1),q.success(`Handed over`)},onError:e=>q.error(e.message)});return e.canControl?(0,Q.jsxs)(`div`,{className:i===`more`?`flex flex-col items-stretch gap-3`:`flex shrink-0 items-center gap-1`,children:[i!==`hold`&&(E||D)&&(0,Q.jsx)(M,{content:D?`Live transcription stops for the rest of this call. Previously saved audio and text remain.`:w?`Resume carrier recording. Live transcription returns on the next call.`:`Pause recording. Live transcription will stop for the rest of this call.`,placement:`top`,children:(0,Q.jsx)(`span`,{className:`inline-flex`,children:(0,Q.jsx)(C,{"aria-pressed":w,icon:w?xe:Ne,isDisabled:D&&w,isLoading:N.isPending,"aria-label":D?w?`Live transcription stopped`:`Stop live transcription`:w?`Start recording again`:`Pause recording`,size:i===`toolbar`?`sm`:`lg`,variant:w?`tertiary`:`ghost`,onPress:()=>w?N.mutate(!1):o(!0),children:D?w?`Live transcription stopped`:`Stop live transcription`:w?`Start recording again`:`Pause recording`})})}),i!==`more`&&(0,Q.jsx)(M,{content:x?`Take off hold`:`Put on hold`,placement:`top`,children:(0,Q.jsxs)(C,{className:`min-w-0 flex-col gap-1 px-2 text-[length:var(--text-caption)] text-foreground`,"aria-pressed":x,isLoading:j.isPending,"aria-label":x?`Resume`:`Hold`,size:i===`toolbar`?`sm`:`lg`,variant:x?`tertiary`:`ghost`,onPress:()=>j.mutate(!x),children:[x?(0,Q.jsx)(Fe,{size:20,strokeWidth:1.5}):(0,Q.jsx)(Ne,{size:20,strokeWidth:1.5}),x?`Resume`:`Hold`]})}),i!==`hold`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(k,{isOpen:h,placement:`top`,onOpenChange:g,children:[(0,Q.jsx)(m,{children:(0,Q.jsx)(C,{icon:ze,"aria-label":`Add someone to this call`,size:i===`toolbar`?`sm`:`lg`,variant:h||O>0?`tertiary`:`ghost`,children:`Add participant`})}),(0,Q.jsx)(re,{className:`w-80 p-3`,children:(0,Q.jsxs)(`div`,{className:`flex w-full flex-col gap-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(y,{className:`font-semibold`,variant:`footnote`,children:`Add someone`}),(0,Q.jsx)(y,{tone:`muted`,variant:`caption`,children:O>0?`${O===1?`One extra person is`:`${O} extra people are`} already on this call.`:`They join the call. Nobody leaves.`})]}),(0,Q.jsx)(v,{description:`A colleague, a plumber, an owner — any number.`,label:`Number to add`,placeholder:`+47 400 91 097`,type:`tel`,value:_,onValueChange:b}),(0,Q.jsx)(T,{children:(0,Q.jsxs)(C,{isDisabled:_.trim().length<6,isLoading:P.isPending,size:i===`toolbar`?`sm`:`lg`,variant:`primary`,onPress:()=>P.mutate(_.trim()),children:[`Ring `,H(_.trim())||`them`,` in`]})})]})})]}),(0,Q.jsxs)(k,{isOpen:f,placement:`top`,onOpenChange:p,children:[(0,Q.jsx)(m,{children:(0,Q.jsx)(C,{icon:d,"aria-label":`Transfer this call`,size:i===`toolbar`?`sm`:`lg`,variant:f||S?`tertiary`:`ghost`,children:`Transfer call`})}),(0,Q.jsx)(re,{className:`w-80 p-3`,children:(0,Q.jsxs)(`div`,{className:`flex w-full flex-col gap-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(y,{variant:`footnote`,className:`font-semibold`,children:`Transfer`}),(0,Q.jsx)(y,{tone:`muted`,variant:`caption`,children:`They join the call with you. Introduce them, then hand over.`})]}),S||s?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(B,{intent:S?`success`:`info`,title:S?`Recipient answered`:`Transfer pending`,children:S?`Introduce the caller before completing the transfer.`:`Waiting for the recipient to answer. Stay on the call.`}),(0,Q.jsx)(T,{children:(0,Q.jsx)(C,{isDisabled:!S,isLoading:F.isPending,size:i===`toolbar`?`sm`:`lg`,variant:`primary`,onPress:()=>F.mutate(),children:`Hand over and leave`})})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(v,{description:`A colleague's mobile, a supplier, anyone.`,label:`Number to transfer to`,placeholder:`+47 400 91 097`,type:`tel`,value:l,onValueChange:u}),(0,Q.jsx)(T,{children:(0,Q.jsxs)(C,{isDisabled:l.trim().length<6,isLoading:ee.isPending,size:i===`toolbar`?`sm`:`lg`,variant:`primary`,onPress:()=>ee.mutate(l.trim()),children:[`Call `,H(l.trim())||`them`]})})]})]})})]})]}),(0,Q.jsx)(me,{isOpen:a,onClose:()=>o(!1),onConfirm:async()=>{await N.mutateAsync(!0)}
2,title:D?`Stop live transcription?`:`Pause recording?`,description:`Live transcription will stop for the rest of this call, even if recording resumes. Previously saved audio and text remain.`,confirmLabel:D?`Stop live transcription`:`Pause recording`})]}):null}var Ti=[[`1`,`2`,`3`],[`4`,`5`,`6`],[`7`,`8`,`9`],[`*`,`0`,`#`]],Ei=/^[0-9*#]$/;function Di({callId:e,organizationId:t,serverCanSend:n,sessionId:r,unavailableReason:i,labelled:a=!1}){let{sendDigits:o,sendNativeDigits:s}=In(),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),f=(0,Z.useRef)(Promise.resolve()),p=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let e=new AbortController;return p.current=e,f.current=Promise.resolve(),d(``),()=>e.abort()},[e,t,r,n,i]);let h=(0,Z.useCallback)(r=>{let a=p.current;if(a&&!a.signal.aborted){if(n===null||i){q.error(i||`The keypad is not ready yet`);return}if(s){f.current=f.current.then(async()=>{if(!a.signal.aborted)try{let e=await s(r);if(a.signal.aborted)return;e?d(e=>(e+r).slice(-32)):q.error(`That key was not confirmed. Check the call before sending it again.`)}catch{a.signal.aborted||q.error(`That key was not confirmed. Check the call before sending it again.`)}});return}if(n){if(!e||!t){q.error(`The keypad is not ready yet`);return}f.current=f.current.then(async()=>{if(!a.signal.aborted)try{let n=await ut({signal:a.signal,path:{id:e},query:{organizationId:t},body:{digits:r}});if(a.signal.aborted)return;if(n.error){q.error(Pn(n.error,`Could not send that key`));return}d(e=>(e+r).slice(-32))}catch{a.signal.aborted||q.error(`Could not send that key`)}});return}if(o(r)){d(e=>(e+r).slice(-32));return}q.error(`Keys cannot be sent on this call`)}},[e,t,o,s,n,i]);return(0,Z.useEffect)(()=>{if(!c)return;let e=e=>{if(e.metaKey||e.ctrlKey||e.altKey||!Ei.test(e.key)||e.repeat||e.isComposing||e.defaultPrevented)return;let t=e.target;t instanceof Element&&t.closest(`input, textarea, select, [contenteditable]:not([contenteditable='false']), [role='textbox']`)||(e.preventDefault(),h(e.key))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c,h]),(0,Q.jsxs)(k,{isOpen:c,placement:`top`,onOpenChange:l,children:[(0,Q.jsx)(m,{children:a?(0,Q.jsxs)(C,{type:`button`,size:`lg`,variant:c?`tertiary`:`ghost`,className:`min-w-0 flex-1 flex-col gap-1 px-2 text-[length:var(--text-caption)] text-foreground`,children:[(0,Q.jsx)(sr,{size:20,strokeWidth:1.5}),`Keypad`]}):(0,Q.jsx)(A,{icon:sr,label:`Keypad`,size:`sm`,variant:c?`tertiary`:`ghost`})}),(0,Q.jsx)(re,{className:`w-64 p-3`,children:(0,Q.jsxs)(`div`,{className:`flex w-full flex-col gap-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(y,{className:`font-semibold`,variant:`footnote`,children:`Keypad`}),(0,Q.jsx)(y,{tone:`muted`,variant:`caption`,children:i||(n===null?`Waiting for call details…`:`Each key is sent as you press it. You can type 0-9, * and # too.`)})]}),(0,Q.jsxs)(y,{className:`min-h-6 truncate text-right font-mono tabular-nums`,"data-testid":`keypad-sent`,variant:`body`,children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:`Keys sent: `}),u||`—`]}),(0,Q.jsx)(`span`,{"aria-live":`polite`,className:`sr-only`,children:u.slice(-1)}),(0,Q.jsx)(`div`,{className:`grid grid-cols-3 gap-2`,children:Ti.flat().map(e=>(0,Q.jsx)(C,{isDisabled:n===null||!!i,className:`h-touch`,size:`sm`,variant:`secondary`,onPress:()=>h(e),children:e},e))})]})})]})}var Oi=new Set,ki=!1;function Ai(){if(ki||typeof window>`u`||window.RTCPeerConnection===void 0)return;ki=!0;let e=window.RTCPeerConnection;function t(...t){let n=new e(...t);return Oi.add(new WeakRef(n)),n}t.prototype=e.prototype,Object.setPrototypeOf(t,e),window.RTCPeerConnection=t}function ji(e){let t=null,n=!1,r=n=>{n!==t&&(t=n,e(n))},i=()=>{if(typeof navigator<`u`&&navigator.onLine===!1){r(`reconnecting`);return}let e=Ni()??Mi();if(!e){n&&r(`closed`);return}switch(n=!0,e.connectionState){case`connected`:r(`connected`);break;case`disconnected`:r(`reconnecting`);break;case`failed`:r(`lost`)}},a=setInterval(i,1e3);return i(),()=>clearInterval(a)}function Mi(){let e=null;for(let t of[...Oi]){let n=t.deref();if(!n){Oi.delete(t);continue}n.connectionState!==`closed`&&(e=n)}return e}function Ni(){let e=null;for(let t of[...Oi]){let n=t.deref();if(!n){Oi.delete(t);continue}n.connectionState===`connected`&&(e=n)}return e}function Pi(e,t,n){if(e===null&&t===null&&n===null)return null;let r=(e??0)+(t??0)*2+10,i=r<160?93.2-r/40:93.2-(r-120)/10;if(i-=(n??0)*2.5,i<0)return 1;if(i>100)return 4.5;let a=1+.035*i+i*(i-60)*(100-i)*7e-6;return Math.round(Math.min(4.5,Math.max(1,a))*10)/10}async function Fi(){let e=Ni();if(!e)return null;let t;try{t=await e.getStats()}catch{return null}let n=null,r=null,i=null,a=null,o=null,s=new Map;
2return t.forEach(e=>{let t=e;if(t.type===`codec`&&typeof t.mimeType==`string`){s.set(t.id,t.mimeType.replace(/^audio\//i,``));return}if(t.type===`inbound-rtp`&&t.kind===`audio`){typeof t.jitter==`number`&&(r=Math.round(t.jitter*1e3*10)/10),typeof t.audioLevel==`number`&&(o=t.audioLevel);let e=typeof t.packetsLost==`number`?t.packetsLost:0,n=e+(typeof t.packetsReceived==`number`?t.packetsReceived:0);n>0&&(i=Math.round(e/n*1e3)/10),typeof t.codecId==`string`&&(a=s.get(t.codecId)??a);return}if(t.type===`candidate-pair`&&t.state===`succeeded`&&t.nominated){typeof t.currentRoundTripTime==`number`&&(n=Math.round(t.currentRoundTripTime*1e3));return}t.type===`remote-inbound-rtp`&&n===null&&typeof t.roundTripTime==`number`&&(n=Math.round(t.roundTripTime*1e3))}),a===null&&s.size>0&&(a=[...s.values()][0]??null),{rttMs:n,jitterMs:r,packetLossPercent:i,codec:a,audioLevel:o,mos:Pi(n,r,i)}}function Ii(e){return e===null?{label:`Measuring`,intent:`warning`}:e>=4?{label:`Good`,intent:`success`}:e>=3.1?{label:`Fair`,intent:`warning`}:{label:`Poor`,intent:`danger`}}var Li=2e3;function Ri({isConnected:e}){let[t,n]=(0,Z.useState)(null);if((0,Z.useEffect)(()=>{if(!e){n(null);return}let t=!1,r=async()=>{let e=await Fi();t||n(e)};r();let i=setInterval(()=>void r(),Li);return()=>{t=!0,clearInterval(i)}},[e]),!e||!t)return null;let{label:r,intent:i}=Ii(t.mos),a=i===`success`?`bg-success-500`:i===`warning`?`bg-warning-500`:`bg-danger-500`;return(0,Q.jsx)(M,{content:(0,Q.jsxs)(`div`,{className:`max-w-[15rem] space-y-1 py-1`,children:[(0,Q.jsxs)(y,{className:`font-semibold`,variant:`caption`,children:[`Line quality: `,r]}),(0,Q.jsxs)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5`,children:[(0,Q.jsx)(zi,{label:`Score`,value:t.mos===null?`—`:`${t.mos.toFixed(1)} of 5`}),(0,Q.jsx)(zi,{label:`Round trip`,value:t.rttMs===null?`—`:`${t.rttMs} ms`}),(0,Q.jsx)(zi,{label:`Jitter`,value:t.jitterMs===null?`—`:`${t.jitterMs} ms`}),(0,Q.jsx)(zi,{label:`Packet loss`,value:t.packetLossPercent===null?`—`:`${t.packetLossPercent}%`}),(0,Q.jsx)(zi,{label:`Codec`,value:t.codec??`—`})]}),(0,Q.jsx)(y,{className:`pt-1`,tone:`muted`,variant:`caption`,children:`The score is an estimate from latency, jitter and loss — good for telling a bad line from a good one, not for quoting at a carrier.`})]}),placement:`top`,children:(0,Q.jsxs)(`span`,{className:`inline-flex shrink-0 items-center gap-1`,"aria-label":`Line quality: ${r}`,children:[(0,Q.jsx)(c,{"aria-hidden":!0,className:`text-default-400`,size:13}),(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`h-1.5 w-1.5 rounded-full ${a}`})]})})}function zi({label:e,value:t}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dt`,{className:`text-caption text-default-400`,children:e}),(0,Q.jsx)(`dd`,{className:`text-caption tabular-nums`,children:t})]})}var Bi=new Set([`Completed`,`NoAnswer`,`Busy`,`Failed`,`Cancelled`]);function Vi(e){return!!e&&Bi.has(e)}function Hi(e,t){return Vi(e.status)&&!!t&&e.callId===t}function Ui(e,t,n){return n?e.some(e=>!e.callId||e.callId===n):t?e.some(e=>!e.counterpartMasked||e.counterpartMasked===t):e.length>0}function Wi({label:e,icon:t,devices:n,selectedDeviceId:r,onSelect:i,labelled:a=!1}){return n.length===0?null:(0,Q.jsxs)(le,{classNames:{content:F},placement:`top-end`,children:[(0,Q.jsx)(de,{children:a?(0,Q.jsx)(C,{type:`button`,icon:t,size:`lg`,variant:`ghost`,children:e}):(0,Q.jsx)(A,{icon:t,label:e,size:`sm`,variant:`ghost`})}),(0,Q.jsx)(te,{"aria-label":e,itemClasses:S,children:n.map(e=>(0,Q.jsx)(R,{startContent:(0,Q.jsx)(P,{size:16,className:e.deviceId===r?`opacity-100`:`opacity-0`}),onPress:()=>i(e.deviceId),children:e.label},e.deviceId))})]})}var Gi={loading:`Loading live transcription settings…`,live:`Waiting for speech… Text arrives in short segments.`,off:`Live transcription is off for this call.`,stopped:`Live transcription stopped for this call. Earlier text is kept; resuming recording will not restart live text.`,unavailable:`Live text may be delayed. Your call can continue.`,ended:`Call ended. The final transcript will appear in the conversation.`};function Ki({text:e,status:t,compact:n=!1}){let[r,i]=(0,Z.useState)(!0),[a,o]=(0,Z.useState)(!0),s=(0,Z.useRef)(null),c=(0,Z.useRef)(0),l=e.split(`
3`).map(e=>
3e.trim()).filter(Boolean),u=l.at(-1),d=l.slice(0,-1);return(0,Z.useLayoutEffect)(()=>{let e=s.current;e&&r&&!n&&(e.scrollTop=a?e.scrollHeight:c.current)},[e,r,a,n]),(0,Q.jsxs)(`section`,{className:`min-w-0 space-y-3`,"aria-label":`Live call transcript`,children:[!n&&(0,Q.jsx)(oe,{label:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-2 text-foreground`,children:[(0,Q.jsx)(ar,{"aria-hidden":!0,size:20,strokeWidth:1.5}),`Live transcript`]}),trailing:r?`Fold`:`Show`,isOpen:r,onOpenChange:i,size:`lg`,indentContent:!1,children:d.length>0&&(0,Q.jsx)(`div`,{ref:s,role:`region`,"aria-label":`Earlier transcript`,tabIndex:0,className:`h-28 overflow-y-auto overscroll-contain rounded-medium pr-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus`,onScroll:e=>{let t=e.currentTarget;c.current=t.scrollTop,o(t.scrollHeight-t.clientHeight-t.scrollTop<24)},children:(0,Q.jsx)(`div`,{className:`space-y-3`,children:d.map((e,t)=>(0,Q.jsx)(y,{as:`p`,variant:`body`,className:`break-words`,children:e},`${t}-${e}`))})})}),u&&(0,Q.jsxs)(`div`,{className:`min-w-0 space-y-1`,"data-testid":`latest-transcript-line`,children:[(0,Q.jsx)(y,{as:`p`,variant:`caption`,tone:`subtle`,children:t===`live`?`Latest`:`Last captured`}),(0,Q.jsx)(y,{as:`p`,variant:n?`footnote`:`body`,className:`max-h-24 overflow-y-auto break-words`,children:u})]}),(t!==`live`||!u)&&(0,Q.jsx)(y,{as:`p`,variant:`caption`,tone:`subtle`,children:Gi[t]}),!n&&r&&d.length>0&&(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(y,{as:`p`,variant:`caption`,tone:`subtle`,children:a?t===`live`?`Following live · scroll up for earlier text`:`Scroll up for earlier text`:`Reading earlier · latest speech stays visible`}),!a&&(0,Q.jsx)(C,{type:`button`,variant:`ghost`,size:`lg`,fullWidth:!0,onPress:()=>o(!0),children:`Jump to latest`})]})]})}function qi(e,t){let[n,r]=(0,Z.useState)(null);Mn({organizationIds:t?[t]:[],organizationTopics:[`phone`],subscribeConversationId:e?.conversationId,autoInvalidateQueries:!1,onCallLiveTranscript:(0,Z.useCallback)(n=>{t&&n.organizationId===t&&e?.id&&n.callId===e.id&&r(e=>e?.callId===n.callId&&e.organizationId===n.organizationId&&e.chunkIndex>n.chunkIndex?e:n)},[t,e?.id])});let i=e?.liveTranscriptText??``,a=n?.callId===e?.id&&n?.organizationId===t?n:null;return a&&a.text.length>=i.length?a.text:i}function Ji(){let e=In(),{activeCall:t}=e,{selectedOrganizationId:n}=Dn(),r=t?.organizationId,i=!!r&&r===n,{data:a,refetch:o,isError:s}=Y({queryKey:jn.current(r,t?.callId,t?.legId,t?.sessionId),queryFn:async({signal:e})=>{if(!r||!i||!t?.callId&&!t?.legId)return null;let n=await nt({signal:e,query:{organizationId:r,callId:t.callId??void 0,legSid:t.callId?void 0:t.legId??void 0}});if(n.error)throw Error(`Could not load call details`);return n.data??null},enabled:i&&!!(t?.callId||t?.legId),refetchInterval:4e3,retry:!1}),c=qi(i?a:null,i?r:void 0);return t?(0,Q.jsx)(Yi,{phone:e,detailsUnavailable:s,transcript:c,call:i?a:null,ownsCall:i,onChanged:()=>void o()},`${r}:${t.sessionId??t.callId??t.startedAt}`):null}function Yi({phone:e,call:t,ownsCall:n,onChanged:r,detailsUnavailable:i=!1,transcript:o=t?.liveTranscriptText??``}){let{activeCall:s,transport:c,isMuted:u,setMuted:d,hangup:f,stepIn:p,identity:m}=e,[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(!1),[S,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(!1);if((0,Z.useEffect)(()=>{(t?.isRecordingPaused||t?.isLiveTranscriptionStopped)&&O(!0)},[t?.isRecordingPaused,t?.isLiveTranscriptionStopped]),!s)return null;let k=s.organizationId,A=s.role===`listener`||s.role===`whisper`,j=!s.isConnecting&&c===`connected`,M=t?.participants?.some(e=>e.role===`Guest`&&!e.leftAt&&e.isOnHold),N=s.displayName?.trim()||H(s.counterpart)||s.masked,P=s.isConnecting?`Connecting…`:c===`connected`?M?`Caller on hold`:s.role===`listener`?`Listening in`:s.role===`whisper`?`Whispering to colleague`:`Connected`:`Reconnecting…`,F=n&&j&&t?.status===`InProgress`?t.conferenceName?t.canControl?!0:null:!1:null,I=!!(t?.recordCalls||t?.transcribeCalls),te=t?.participants?.filter(e=>!e.leftAt)??[],ne=!n||i?`unavailable`:t?Vi(t.status)?`ended`:t.isRecordingPaused||t.isLiveTranscriptionStopped||D?`stopped`:t.streamLiveAudio?j?`live`:`unavailable`:`off`:`loading`,re=s.isConnecting?`Cancel connection`:A?`Leave call`:`End call`,ie=async()=>{x(!0);try{await f(t?.id??s.callId??void 0)}catch(e){q.error(e instanceof Error?e.message:`Could not end the call`)}finally{x(!1)}},ae=(0,Q.jsx)(C,{type:`button`,size:`lg`,className:`shrink-0`,variant:A||s.isConnecting?`secondary`:`danger`,isLoading:b,onPress:()=>{!A&&!s.isConnecting&&te.filter(e=>e.role!==`Guest`).length>1?E(!0):ie()},children:re});return(0,Q.jsxs)(`section`,{"aria-label":`Call in progress`,className:Xi,children:[(0,Q.jsx)(z,{level:`raised`,padding:`md`,radiu
3s:`large`,className:`max-h-[calc(100dvh-6rem)] overflow-y-auto shadow-sm`,children:(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(ee,{intent:!j||M?`warning`:`success`,label:P}),(0,Q.jsx)(y,{as:`span`,variant:`caption`,tone:`subtle`,className:`flex-1`,children:P}),!s.isConnecting&&(0,Q.jsx)(y,{as:`span`,variant:`caption`,tone:`subtle`,className:`font-mono`,tabular:!0,children:je(s.durationSeconds)}),(0,Q.jsx)(C,{type:`button`,variant:`ghost`,size:`lg`,className:`min-w-0 px-2`,icon:h?ve:he,"aria-expanded":!h,"aria-label":h?`Expand call panel`:`Collapse call panel`,onPress:()=>g(!h),children:h?`Expand`:`Collapse`})]}),(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[(0,Q.jsx)(y,{as:`p`,variant:h?`footnote`:`headline`,className:`break-words font-semibold`,children:N}),!h&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(y,{as:`p`,variant:`caption`,tone:`subtle`,children:[s.direction===`inbound`?`Calling from`:`Calling`,` `,H(s.counterpart)||s.masked]}),t?.phoneNumberE164&&(0,Q.jsxs)(y,{as:`p`,variant:`footnote`,children:[s.direction===`inbound`?`Receiving line`:`Your line`,` `,H(t.phoneNumberE164)]}),s.isWhatsApp&&(0,Q.jsx)(y,{as:`p`,variant:`caption`,tone:`subtle`,children:`WhatsApp call`})]})]}),!h&&(0,Q.jsxs)(Q.Fragment,{children:[s.isConnecting&&(0,Q.jsx)(y,{as:`p`,variant:`footnote`,tone:`subtle`,children:`Connecting your audio. You are not connected yet.`}),!n&&(0,Q.jsx)(y,{as:`p`,variant:`footnote`,tone:`subtle`,children:`Return to this call’s workspace to use conference controls and live text.`}),A&&(0,Q.jsx)(y,{as:`p`,variant:`footnote`,tone:`subtle`,children:s.role===`listener`?`Nobody can hear you. Join the conversation when you want to speak.`:`Only your colleague can hear you.`}),M&&(0,Q.jsx)(y,{as:`p`,variant:`footnote`,tone:`subtle`,children:`The caller hears hold music. Resume to continue.`}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 border-t border-divider pt-4`,children:[I&&(0,Q.jsx)(y,{as:`span`,variant:`caption`,tone:`subtle`,children:t?.isRecordingPaused?`Recording paused`:`Recording`}),te.length>0&&(0,Q.jsxs)(y,{as:`span`,variant:`caption`,tone:`subtle`,children:[te.length,` participants`]}),(0,Q.jsx)(Ri,{isConnected:j})]})]}),(0,Q.jsx)(Ki,{text:o,status:ne,compact:h}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t border-divider pt-3`,children:[s.role!==`listener`&&(0,Q.jsxs)(C,{type:`button`,variant:u?`tertiary`:`ghost`,size:`lg`,className:`min-w-0 flex-1 flex-col gap-1 px-2 text-[length:var(--text-caption)] text-foreground`,"aria-pressed":u,isDisabled:!j,onPress:()=>d(!u),children:[(0,Q.jsx)(`span`,{children:u?(0,Q.jsx)(pr,{size:20,strokeWidth:1.5}):(0,Q.jsx)(ke,{size:20,strokeWidth:1.5})}),u?`Unmute`:`Mute`]}),!h&&!A&&(0,Q.jsxs)(Q.Fragment,{children:[t&&k&&n&&j&&(0,Q.jsx)(wi,{call:t,organizationId:k,clientIdentity:m,onChanged:r,presentation:`hold`}),(0,Q.jsx)(Di,{callId:t?.id??null,organizationId:k??null,serverCanSend:F,sessionId:s.sessionId,labelled:!0,unavailableReason:t?.conferenceName&&t.provider===`Telnyx`?`Keypad is unavailable for this provider’s conference calls.`:void 0})]}),!h&&(0,Q.jsxs)(C,{type:`button`,size:`lg`,variant:_?`tertiary`:`ghost`,className:`min-w-0 flex-1 flex-col gap-1 px-2 text-[length:var(--text-caption)] text-foreground`,"aria-expanded":_,onPress:()=>v(!_),children:[(0,Q.jsx)(Se,{size:20,strokeWidth:1.5}),`More`]}),ae]}),!h&&s.role===`listener`&&t?.canControl&&t.id&&j&&(0,Q.jsx)(C,{type:`button`,variant:`primary`,size:`lg`,fullWidth:!0,icon:Be,isLoading:S,onPress:async()=>{w(!0);try{await p(t.id)}catch(e){q.error(e instanceof Error?e.message:`Could not join`)}finally{w(!1)}},children:`Join conversation`}),!h&&_&&(0,Q.jsxs)(`div`,{className:`space-y-3 border-t border-divider pt-4`,children:[!A&&t&&k&&n&&j&&(0,Q.jsx)(wi,{call:t,organizationId:k,clientIdentity:m,onChanged:e=>{e.isRecordingPaused&&O(!0),r(e)},presentation:`more`}),(0,Q.jsx)(oe,{label:`Audio settings`,size:`lg`,indentContent:!1,children:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(Wi,{devices:e.inputDevices,icon:ke,label:`Choose a microphone`,selectedDeviceId:e.selectedInputDeviceId,onSelect:t=>void e.setInputDevice(t),labelled:!0}),e.isOutputSelectionSupported&&(0,Q.jsx)(Wi,{devices:e.outputDevices,icon:xr,label:`Choose a speaker`,selectedDeviceId:e.selectedOutputDeviceId,onSelect:t=>void e.setOutputDevice(t),labelled:!0}),e.isSpeakerAvailable&&(0,Q.jsx)(C,{type:`button`,variant:`secondary`,icon:e.isSpeakerOn?xr:Cr,"aria-pressed":e.isSpeakerOn,onPress:()=>e.setSpeakerOn(!e.isSpeakerOn),children:e.isSpeakerOn?`Turn off speaker`:`Speaker`})]})}),te.length>0&&(0,Q.jsx)(oe,{label:`Participants · ${te.length}`,size:`lg`,indentContent:!1,children:(0,Q.jsx)(`div`,{className:`space-y-2`,children:te.map(e=>(0,Q.jsxs)(y,{as:`p`,variant:`footnote`,children:[e.displayName||e.role||`Participant`,e.isMuted?` · muted`:``,e.isOnHold?` · on hold`:``]},e.id??e.providerCallSid))})})]}),!h&&s.conversationId&&(0,Q.jsx)(C,{type:`button`,as:a,to:`/inbox?conversationId=${s.conversationId}`,size:`lg`,fullWidth:!0,variant:`ghost`,icon:l,children:`Open conversation`})]})}),(0,Q.jsx)(me,{isOpen:T,onClose:()=>E(!1),onConfirm:ie,title:`End call for everyone?`,description:`The caller and all participants will be disconnected.`,confirmLabel:`End call for everyone`})]})}var Xi=`fixed inset-x-3 bottom-[calc(var(--mobile-bottomnav-total-h,3.5rem)+0.75rem)] z-drawer sm:inset-x-auto sm:right-4 sm:w-[27rem] lg:bottom-4`,Zi=`fixed inset-x-3 bottom-[calc(var(--mobile-bottomnav-total-h,3.5rem)+0.75rem)] z-toast sm:inset-x-auto sm:right-4 sm:w-[27rem] lg:bottom-4`;function Qi(){let{answeredElsewhere:e,dismissAnsweredElsewhere:t}=In();if(!e)return null;let{answeredByName:n,conversationId:r}=e,i=n?.trim()||`a colleague`,o=(0,Q.jsxs)(z,{level:`raised`,padding:`md`,radiu
3s:`large`,className:`shadow-sm`,children:[(0,Q.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,Q.jsx)(hr,{"aria-hidden":!0,className:`h-3.5 w-3.5 shrink-0 text-default-500`}),(0,Q.jsx)(b,{className:`text-default-500`,children:`Call answered`})]}),(0,Q.jsxs)(y,{as:`p`,variant:`body`,className:`text-foreground`,lines:2,children:[`Answered by `,i]}),r&&(0,Q.jsxs)(`span`,{className:`mt-2 inline-flex items-center gap-1 text-caption text-default-500`,children:[`Open the conversation`,(0,Q.jsx)(f,{"aria-hidden":!0,className:`h-3 w-3`})]})]});return r?(0,Q.jsx)(`section`,{"aria-label":`Call answered`,"aria-live":`polite`,className:Zi,children:(0,Q.jsx)(a,{className:`block rounded-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus focus-visible:ring-offset-2`,to:`/inbox?conversationId=${r}`,onClick:t,children:o})}):(0,Q.jsx)(`section`,{"aria-label":`Call answered`,"aria-live":`polite`,className:Zi,children:o})}function $i(){let{incoming:e,answer:t,reject:n}=In();if(!e)return(0,Q.jsx)(Qi,{});let r=e.contactName?.trim()||(e.from?H(e.from):e.isEnriched?`Unknown caller`:`Identifying caller…`),i=!!e.contactName?.trim();return(0,Q.jsx)(`section`,{"aria-label":`Incoming call`,"aria-live":`assertive`,className:Zi,children:(0,Q.jsxs)(z,{level:`raised`,padding:`md`,radius:`large`,className:`shadow-sm`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Q.jsxs)(`span`,{className:`relative flex h-2 w-2 shrink-0`,"aria-hidden":!0,children:[(0,Q.jsx)(`span`,{className:`absolute inline-flex h-full w-full animate-ping rounded-full bg-success opacity-75`}),(0,Q.jsx)(`span`,{className:`relative inline-flex h-2 w-2 rounded-full bg-success`})]}),(0,Q.jsx)(b,{className:`text-default-500`,children:`Incoming call`})]}),(0,Q.jsx)(y,{as:`p`,variant:`headline`,className:`text-foreground`,lines:1,children:r}),(0,Q.jsxs)(`div`,{className:`mt-1 space-y-0.5`,children:[i&&(0,Q.jsxs)(y,{as:`p`,variant:`footnote`,className:`text-default-500`,tabular:!0,children:[`From `,H(e.from)||`Number unavailable`]}),e.receivingNumber&&(0,Q.jsxs)(y,{as:`p`,variant:`footnote`,className:`text-default-500`,tabular:!0,children:[`To `,H(e.receivingNumber)]}),!e.isEnriched&&e.from&&(0,Q.jsx)(y,{as:`p`,variant:`footnote`,className:`text-default-500`,children:`Looking up caller…`}),e.propertyName&&(0,Q.jsx)(y,{as:`p`,variant:`footnote`,className:`text-default-500`,lines:1,children:e.propertyName}),e.checkIn&&(0,Q.jsxs)(y,{as:`p`,variant:`footnote`,className:`text-default-500`,children:[(0,Q.jsx)(Rn,{value:e.checkIn,showClock:!1}),e.checkOut?(0,Q.jsxs)(Q.Fragment,{children:[` – `,(0,Q.jsx)(Rn,{value:e.checkOut,showClock:!1})]}):null]}),e.isStaffOrPartner&&(0,Q.jsx)(y,{as:`p`,variant:`footnote`,className:`text-default-500`,children:`Colleague or partner`})]}),(0,Q.jsxs)(T,{align:`between`,className:`mt-4 flex-nowrap [&>*]:flex-1`,children:[(0,Q.jsx)(C,{fullWidth:!0,size:`lg`,variant:`secondary`,onPress:()=>void n(),children:`Decline`}),(0,Q.jsx)(C,{fullWidth:!0,icon:Pe,size:`lg`,variant:`primary`,onPress:()=>void t(),children:`Answer`})]}),(0,Q.jsx)(y,{as:`p`,variant:`caption`,tone:`subtle`,className:`mt-3`,children:`Declines your offer. Other staff can still answer.`})]})})}function ea(e){if(e.hasActiveCall)return{canDial:!1,title:`You are already on a call`,detail:null,action:null};let t=e.status===`ready`||e.status===`ringing`||e.status===`in-call`;return e.isEnabled&&e.isLeaderTab&&t?null:e.canRing?e.isEnabled?e.isLeaderTab?e.status===`error`?{canDial:!0,title:`Phone reconnecting`,detail:null,action:{kind:`retry`,label:`Try again`}}:{canDial:!0,title:`Phone connecting`,detail:null,action:null}:{canDial:!0,title:`Calls ring in another tab`,detail:`Calling from this tab moves them here`,action:{kind:`take-over`,label:`Take calls here`}}:{canDial:!1,title:`Turn on Take calls here to dial`,detail:null,action:{kind:`turn-on`,label:`Take calls here`}}:{canDial:!1,title:`This organization has no number to call from`,detail:null,action:null}}var ta=`proptonomy-softphone-call-alerts-asked`,na=`/favicons/android-chrome-192x192.png`;function ra(){return typeof window>`u`||window.Notification===void 0?`unsupported`:window.Notification.permission}function ia(){try{return localStorage.getItem(ta)===`true`}catch{return!1}}function aa(){try{localStorage.setItem(ta,`true`)}catch{}}async function oa(){if(ra()===`unsupported`)return`unsupported`;aa();try{return await window.Notification.requestPermission()??ra()}catch{return ra()}}function sa(){ra()!=="default"||ia()||oa()}function ca(){let[e,t]=(0,Z.useState)(ra);return(0,Z.useEffect)(()=>
3{if(ra()===`unsupported`||!navigator.permissions?.query)return;let e=null,n=!1,r=()=>t(ra());return navigator.permissions.query({name:`notifications`}).then(t=>{n||(e=t,e.addEventListener(`change`,r),r())}).catch(()=>{}),()=>{n=!0,e?.removeEventListener(`change`,r)}},[]),{permission:e,request:(0,Z.useCallback)(async()=>{t(await oa())},[])}}function la(e){let t=e.contactName?.trim()||(e.from?H(e.from):``),n=[e.propertyName?.trim(),e.receivingNumber?`To ${H(e.receivingNumber)}`:null].filter(Boolean);return{title:t?`Incoming call from ${t}`:`Incoming call`,body:[n.join(` · `),`Click to switch to Proptonomy and answer.`].filter(Boolean).join(`
4`),tag:e.callId?`call-${e.callId}`:`softphone-incoming-call`}}function ua(){return document.visibilityState===`visible`&&document.hasFocus()}function da(){return ra()===`granted`&&zn().calls}function fa(e){try{let t=new window.Notification(e.title,{body:e.body,tag:e.tag,icon:na,requireInteraction:!0});return t.onclick=e=>{e.preventDefault(),window.focus(),t.close()},t}catch(e){return Bn(`Could not show the incoming call notification`,e),null}}function pa(e){let t=e?la(e):null,n=(0,Z.useRef)(t);n.current=t;let r=(0,Z.useRef)(null),i=(0,Z.useRef)(null),a=t!==null,o=t?`${t.tag}\n${t.title}\n${t.body}`:null;(0,Z.useEffect)(()=>{if(!a)return;let e=()=>{r.current?.notification.close(),r.current=null},t=()=>{let t=n.current;if(!t||ua()||!da()){e();return}let i=`${t.tag}\n${t.title}\n${t.body}`;if(r.current?.key===i)return;r.current&&r.current.tag!==t.tag&&e();let a=fa(t);r.current=a?{notification:a,tag:t.tag,key:i}:null};return i.current=t,t(),document.addEventListener(`visibilitychange`,t),window.addEventListener(`focus`,t),window.addEventListener(`blur`,t),()=>{document.removeEventListener(`visibilitychange`,t),window.removeEventListener(`focus`,t),window.removeEventListener(`blur`,t),i.current=null,e()}},[a]),(0,Z.useEffect)(()=>{o&&i.current?.()},[o])}function ma(e){return e===`true`?`on`:e===`false`?`off`:`unset`}function ha(e){if(!e||typeof window>`u`)return`unset`;try{return ma(window.localStorage.getItem(Fn(e)))}catch{return`unset`}}function ga(e,t){try{window.localStorage.setItem(Fn(e),t===`on`?`true`:`false`)}catch{}}function _a({preference:e,ownsActiveNumber:t}){return e===`unset`&&t}function va(e,t){return t?e.filter(e=>e.assignedContactId===t):[]}function ya(e){if(e.isDismissed||!e.isSettled||e.ringable.length===0)return null;let t=e.isEnabled&&e.status===`error`;if(e.isEnabled&&!t||!e.isEnabled&&e.isPreferred)return null;if(e.own.length>0)return{audience:`owner`,numbers:e.own.map(e=>e.e164),failed:t};let n=e.ringable.filter(e=>!e.assignedContactId);return n.length===0?null:{audience:`team`,numbers:n.map(e=>e.e164),failed:t}}function ba(e){let t=e.map(e=>H(e));return t.length<=1?t[0]??``:t.length===2?`${t[0]} and ${t[1]}`:`${t[0]} and ${t.length-1} other numbers`}function xa(e,t){let n=t.isNativeApp?`app`:`browser`,r=ba(e.numbers),i=e.audience===`owner`?`Calls to your ${e.numbers.length===1?`number`:`numbers`} ${r} can ring here`:`Calls to ${r} can ring in this ${n}`,a=e.failed?`Try again`:`Take calls here`;return t.microphoneDenied?{title:i,body:t.isNativeApp?`Your microphone is blocked, so callers would not hear you. Allow it for Proptonomy in your phone's Settings, then take calls here.`:`Your microphone is blocked, so callers would not hear you. Allow it for this site from the icon next to the address bar, then take calls here.`,intent:`warning`,actionLabel:a}:e.failed?{title:i,body:t.error?`This ${n} could not connect: ${t.error}`:`This ${n} could not connect.`,intent:`warning`,actionLabel:a}:{title:i,body:`Turn it on to answer and make calls from this ${n}.`,intent:`info`,actionLabel:a}}function Sa(e){return`proptonomy.softphone.prompt-dismissed.${e}`}function Ca(e){if(!e||typeof window>`u`)return!1;try{return window.sessionStorage.getItem(Sa(e))===`true`}catch{return!1}}function wa(e){try{window.sessionStorage.setItem(Sa(e),`true`)}catch{}}function Ta(){let{isGlobalAdmin:e}=gn(),{selectedOrganizationId:t}=Dn(),n=Cn(t),r=Sn(t),i=wn(t),a=r===`Admin`||r===`Member`||r===`StaffCoordinator`||e(),o=Y({queryKey:[`phoneNumbers`,`voice-capable`,t??`none`],queryFn:async({signal:e})=>t?((await bt({signal:e,query:{organizationId:t}}
4)).data??[]).filter(e=>e.voiceCapable&&e.status===`Active`).map(e=>({e164:e.e164??``,friendlyName:e.friendlyName??null,assignedContactId:e.assignedContactId??null})).filter(e=>e.e164.length>0):[],enabled:a&&!!t,staleTime:6e5,retry:!1}),s=(0,Z.useMemo)(()=>a?o.data??[]:[],[a,o.data]);return{numbers:s,own:(0,Z.useMemo)(()=>va(s,i),[s,i]),isSettled:!t||!n.isPending&&(!a||!o.isPending)}}function Ea(){return Ta().numbers}function Da(e){let[t,n]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{if(!e){n(null);return}let t=!1,r=()=>{en().then(e=>{t||n(e)})},i=()=>{document.visibilityState===`visible`&&r()};return r(),document.addEventListener(`visibilitychange`,i),()=>{t=!0,document.removeEventListener(`visibilitychange`,i)}},[e]),{permissions:t,openFullScreenIntentSettings:(0,Z.useCallback)(()=>{ln()},[])}}function Oa(e){switch(e){case`connecting`:return{label:`Connecting…`,intent:`warning`,pulse:!0};case`ready`:return{label:`Taking calls here`,intent:`success`,pulse:!1};case`ringing`:return{label:`Ringing`,intent:`success`,pulse:!0};case`in-call`:return{label:`On a call`,intent:`primary`,pulse:!0};case`error`:return{label:`Phone reconnecting`,intent:`danger`,pulse:!1};default:return{label:`Calls off here`,intent:`neutral`,pulse:!1}}}var ka=[{value:`native`,label:`Native`},{value:`off`,label:`WebView`}];function Aa({iconOnly:e=!1}){let{selectedOrganizationId:t}=Dn(),n=Sn(t),{isGlobalAdmin:r}=gn(),i=n===`Admin`||n===`Member`||n===`StaffCoordinator`||r(),{status:a,isEnabled:o,isPreferred:s,isLeaderTab:c,error:l,microphone:u,enable:d,disable:f,inputDevices:p,outputDevices:m,isOutputSelectionSupported:h,selectedInputDeviceId:g,selectedOutputDeviceId:_,setInputDevice:v,setOutputDevice:y,takeCallsHere:b}=In(),[x,S]=(0,Z.useState)(!1),w=ca(),T=Ea(),{permissions:E,openFullScreenIntentSettings:D}=Da(o);if(!i||T.length===0)return null;let O=T.map(e=>e.friendlyName?`${e.e164} (${e.friendlyName})`:e.e164).join(`
5`),k=o,A=o&&!c,j=o?ea({isEnabled:o,isLeaderTab:c,status:a,hasActiveCall:!1,canRing:!0}):null,N=j?.action&&j.action.kind!==`turn-on`?j.action:null,P=o&&!A&&a!==`error`&&u===`denied`,F=A&&j?{label:j.title,intent:`neutral`,pulse:!1}:P?{label:`Microphone blocked`,intent:`danger`,pulse:!1}:Oa(o&&a===`off`?`connecting`:a),I=a===`error`?l??`Could not register this browser`:P?`Calls ring here, but nobody will hear you. Allow the microphone in your browser or app settings.`:A&&j?.detail?j.detail:!o&&s?`Turn back on for this browser`:o?T.length===1?`Calls to ${T[0].e164} ring here`:`Calls to ${T.length} numbers ring here`:`Ring this browser`,te=async()=>{S(!0);try{await b()}catch(e){q.error(e instanceof Error?e.message:`Could not move calls to this tab`)}finally{S(!1)}},ne=async e=>{try{e?await d():await f()}catch{q.error(`Couldn’t change where your calls ring`)}};return e?(0,Q.jsx)(M,{content:`${F.label} — ${I}\n${O}`,placement:`right`,children:(0,Q.jsx)(`button`,{"aria-label":`Take calls in this browser: ${F.label}. Toggle`,"aria-pressed":k,className:`mx-auto flex h-10 w-10 items-center justify-center rounded-medium transition-colors hover:bg-default-100/70`,type:`button`,onClick:()=>void ne(!k),children:(0,Q.jsx)(ee,{intent:F.intent,pulse:F.pulse})})}):(0,Q.jsx)(M,{content:`Rings here:\n${O}`,placement:`right`,children:(0,Q.jsxs)(`div`,{className:`rounded-lg px-2 py-1.5`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(ee,{className:`shrink-0`,intent:F.intent,pulse:F.pulse}),(0,Q.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(`span`,{className:`block truncate text-xs text-default-600`,children:F.label}),(0,Q.jsx)(`span`,{className:`block truncate text-[10px] text-default-400`,children:I})]}),(0,Q.jsx)(ue,{"aria-label":`Take calls in this browser`,className:`shrink-0`,isDisabled:o&&a===`connecting`,isSelected:k,size:`sm`,onValueChange:e=>void ne(e)})]}),N&&(0,Q.jsx)(`div`,{className:`mt-1.5 pl-4`,children:(0,Q.jsx)(C,{icon:Pe,isLoading:x,size:`sm`,variant:`secondary`,onPress:()=>void te(),children:N.label})}),o&&(0,Q.jsxs)(`div`,{className:`mt-1 flex items-center gap-1 pl-4`,children:[(0,Q.jsx)(Wi,{devices:p,icon:ke,label:`Choose a microphone`,selectedDeviceId:g,onSelect:e=>void v(e)}),h&&(0,Q.jsx)(Wi,{devices:m,icon:xr,label:`Choose a speaker`,selectedDeviceId:_,onSelect:e=>void y(e)})]}),o&&E&&!E.notifications&&(0,Q.jsx)(`p`,{className:`mt-1 pl-4 text-[10px] text-warning-600`,children:`Notifications are off, so calls only ring while the app is open.`}),o&&E?.notifications&&!E.fullScreenIntent&&(0,Q.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 pl-4`,children:[(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 text-[10px] text-warning-600`,children:`Calls show as a small banner when the phone is locked.`}),(0,Q.jsx)(C,{size:`sm`,variant:`ghost`,onPress:D,children:`Allow full screen`})]}),o&&w.permission==="default"&&(0,Q.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 pl-4`,children:[(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 text-[10px] text-default-400`,children:`Backgroun
5d calls show no alert.`}),(0,Q.jsx)(C,{size:`sm`,variant:`ghost`,onPress:()=>void w.request(),children:`Allow alerts`})]}),o&&Vt()&&(0,Q.jsx)(`div`,{className:`mt-1.5 pl-4`,children:(0,Q.jsx)(ae,{fullWidth:!0,label:`Native call screen`,options:ka,size:`sm`,value:Qt(),onChange:e=>{qt(e),window.location.reload()}})})]})})}var ja=6e4;function Ma(e){let t=e.filter(e=>e.covered).length;return e.length===0?{tone:`uncovered`,headline:`No number to take calls on`}:t===e.length?{tone:`covered`,headline:e.length===1?`Calls are covered`:`All ${e.length} lines are covered`}:t===0?{tone:`uncovered`,headline:e.length===1?`Nobody is taking calls`:`Nobody is taking calls on ${e.length} lines`}:{tone:`partial`,headline:`${t} of ${e.length} lines are covered`}}function Na(e){if(e.covered&&(e.browsersRinging??0)>0){let t=e.browsersRinging??0;return t===1?`rings 1 browser`:`rings ${t} browsers`}return e.covered&&e.forwardE164||e.forwardE164?`forwards to ${H(e.forwardE164)}`:`goes to voicemail`}function Pa({organizationId:e,className:t}){let{data:n}=Y({queryKey:[`phoneCoverage`,e??`none`],queryFn:async({signal:t})=>e?(await Tt({signal:t,query:{organizationId:e}})).data??[]:[],enabled:!!e,refetchInterval:ja,staleTime:ja,retry:!1}),r=n??[];if(!n||r.length===0)return null;let{tone:i,headline:a}=Ma(r);return(0,Q.jsx)(z,{className:t,level:`sunken`,padding:`sm`,radius:`medium`,children:(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(ee,{intent:i===`covered`?`success`:i===`partial`?`warning`:`danger`,label:void 0}),(0,Q.jsx)(y,{as:`p`,className:`font-medium`,variant:`body`,children:a})]}),(0,Q.jsx)(`div`,{className:`flex flex-col gap-0.5 pl-4`,children:r.map(e=>(0,Q.jsxs)(y,{as:`p`,title:e.trace??void 0,tone:`muted`,variant:`caption`,children:[H(e.e164??``),e.friendlyName?` (${e.friendlyName})`:``,` `,Na(e)]},e.phoneNumberId??e.e164))}),(0,Q.jsxs)(y,{as:`p`,className:`pl-4`,tone:`subtle`,variant:`footnote`,children:[`As of `,r[0]?.localTime??`now`]}),(0,Q.jsx)(`div`,{className:`mt-1 border-t border-default-200/60 pt-1`,children:(0,Q.jsx)(Aa,{})})]})})}var Fa=18e5;function Ia(){let[e,t]=(0,Z.useState)(null),{selectedOrganizationId:n}=Dn(),{isRegistered:r,isEnabled:i,activeCall:s,incoming:c,declinedCallIds:l,rejoin:u,listenIn:d}=In(),f=new URLSearchParams(o().search).get(`conversationId`),p=!!n&&!s&&!c,{data:m=[],refetch:h}=Y({queryKey:[...jn.all,`reconnectable`,n??`none`],queryFn:async({signal:e})=>n?(await mt({signal:e,query:{organizationId:n}})).data??[]:[],enabled:p,refetchInterval:e=>(e.state.data?.length??0)>0?4e3:6e4,retry:!1}),{data:g=[]}=Y({queryKey:[...jn.all,`live`,`bar`,n??`none`],queryFn:async({signal:e})=>n?(await Ge({signal:e,query:{organizationId:n}})).data??[]:[],enabled:p,refetchInterval:e=>(e.state.data?.length??0)>0?8e3:6e4,retry:!1}),_=m[0]??null,v=Date.now()-Fa,b=g.find(e=>e.callId!==_?.id&&!l?.has(e.callId??``)&&(!e.startedAt||new Date(e.startedAt).getTime()>v))??null,x=X({mutationFn:async()=>{_?.id&&await u(_.id)},onSuccess:async()=>{q.success(`Rejoining`),await h()},onError:e=>q.error(e instanceof Error?e.message:`Could not rejoin the call`)}),S=X({mutationFn:async()=>{b?.callId&&await d(b.callId,`Listen`)},onError:e=>q.error(e instanceof Error?e.message:`Could not join the call`)}),w=X({mutationFn:async()=>{b?.callId&&await d(b.callId,`Barge`)},onError:e=>q.error(e instanceof Error?e.message:`Could not join the call`)}),E=X({mutationFn:async e=>{if(!n)return;let t=await Mt({path:{id:e},query:{organizationId:n}});if(t.error)throw Error(String(t.error))},onSuccess:async()=>{q.success(`Call ended`),await h()},onError:e=>q.error(e instanceof Error?e.message:`Could not end the call`)}),D=(0,Q.jsx)(me,{isOpen:!!e,onClose:()=>t(null),onConfirm:async()=>{e&&await E.mutateAsync(e)},title:`End call for everyone?`,description:`The caller and all participants will be disconnected.`,confirmLabel:`End call for everyone`});if(s||c)return null;if(_){let e=_.direction===`Outbound`?_.toE164:_.fromE164;return(0,Q.jsxs)(La,{intent:`warning`,label:`A call is waiting for you`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Q.jsxs)(y,{as:`p`,className:`font-semibold`,lines:1,variant:`footnote`,children:[H(e??``)||`A caller`,` is still on the line`]}),(0,Q.jsx)(y,{as:`span`,tone:`subtle`,variant:`caption`,children:`They are on hold. Rejoin before the line closes.`})]}),(0,Q.jsxs)(T,{children:[(0,Q.jsx)(oe,{label:`More actions`,size:`lg`,indentContent:!1,children:(0,Q.jsx)(C,{icon:_r,isLoading:E.isPending,size:`sm`,variant:`danger`,onPress:()=>_.id&&t(_.id),children:`Hang up`})}),(0,Q.jsx)(C,{icon:hr,isDisabled:!r&&!i,isLoading:x.isPending,variant:`primary`,onPress:()=>x.mutate(),children:r||i?`Rejoin`:`Turn calls on first`})]}),D]})}return!b||b.conversationId&&b.conversationId===f?null:(0,Q.jsxs)(La,{intent:`neutral`,label:b.answeredAt?`A call is in progress`:`A caller is waiting for an answer`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Q.jsxs)(y,{as:`p`,className:`font-semibold`,lines:1,variant:`footnote`,children:[b.contactName||b.counterpartMasked||`A caller`,b.answeredByName?` · ${b.answeredByName}`:``]}),(0,Q.jsxs)(y,{as:`span`,tabular:!0,tone:`subtle`,variant:`caption`,children:[b.answeredAt?je(b.elapsedSeconds??0):`Waiting for someone to answer`,b.numberE164?` · ${H(b.numberE164)}`:``]})]}),(0,Q.jsxs)(T,{children:[b.conversationId&&(0,Q.jsx)(C,{as:a,size:`sm`,to:`/inbox?conversationId=${b.conversationId}`,variant:`ghost`,children:`Open thread`}),(0,Q.jsx)(oe,{label:`More actions`,size:`lg`,indentContent:!1,children:(0,Q.jsx)(C,{icon:_r,isLoading:E.isPending,size:`sm`,variant:`danger`,onPress:()=>b.callId&&t(b.callId),children:`Hang up`})}),b.answeredAt&&(0,Q.jsx)(C,{icon:lr,isDisabled:!r&&!i,isLoading:S.isPending,size:`sm`,variant:`ghost`,onPress:()=>S.mutate(),children:r||i?`Listen in`:`Turn calls on first`}),(0,Q.jsx)(C,{icon:Be,isDisabled:!r&&!i,isLoading:w.isPending,size:`sm`,variant:`primary`,onPress:()=>w.mutate(),children:b.answeredAt?`Join call`:`Take call`})]}),D]})}function La({intent:e,label:t,children:n}){return(0,Q.jsx)(`section`,{"aria-label":t,className:`fixed inset-x-3 bottom-[calc(var(--mobile-bottomnav-total-h,3.5rem)+0.75rem)] z-drawer sm:inset-x-auto sm:right-4 sm:w-[27rem] lg:bottom-4`,children:(0,Q.jsx)(z,{className:e===`warning`?`border border-warning-300 shadow-sm`:`border border-divider shadow-sm`,level:`raised`,padding:`none`,radius:`large`,children:(0,Q.jsxs)(`div`,{className:`flex items-start gap-2 p-3`,children:[(0,Q.jsx)(`span`,{"aria-hidden":!0,
5className:`mt-1.5 h-2 w-2 shrink-0 animate-pulse rounded-full ${e===`warning`?`bg-warning-500`:`bg-success-500`}`}),(0,Q.jsx)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-2`,children:n})]})})})}async function Ra(e){if(tn(e)===`native-sdk`){let{createNativeVoiceAdapter:e}=await r(async()=>{let{createNativeVoiceAdapter:e}=await import(`./nativeVoiceAdapter-D1b8DW-N.js`);return{createNativeVoiceAdapter:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]));return e()}if(e===`Telnyx`){let{createTelnyxAdapter:e}=await r(async()=>{let{createTelnyxAdapter:e}=await import(`./telnyxAdapter-BjdAlG1q.js`);return{createTelnyxAdapter:e}},__vite__mapDeps([10,9,8]));return e()}let{createTwilioAdapter:t}=await r(async()=>{let{createTwilioAdapter:e}=await import(`./twilioAdapter-CRrADMWa.js`);return{createTwilioAdapter:e}},__vite__mapDeps([11,2,12,9,8]));return t()}var za=4e3,Ba=za*3,Va=600,Ha=2e3,Ua=()=>typeof document>`u`||document.visibilityState===`visible`,Wa=()=>typeof document<`u`&&document.hasFocus();function Ga({channelName:e,onCh
5ange:t,isVisible:n=Ua,isFocused:r=Wa}){let i=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,a=Date.now(),o=0,s=n()?null:Date.now(),c=!1,l=!1,u=!1,d=!1,f=!1,p=!1,m=null,h=null,g=null,_=null,v=null,y=null,b=null,x=null;function S(e){c!==e&&(c=e,t(e))}if(typeof BroadcastChannel>`u`)return S(!0),{get isLeader(){return c},release(){S(!1)},claim(){return S(!0),Promise.resolve(!0)},setBusy(){}};let C=new BroadcastChannel(e),w=e=>{try{C.postMessage(e)}catch{}};function T(){let e=n();return e?s=null:s??=Date.now(),e}function E(){let e=T(),t=e&&r();d=u,f=t,w({kind:`lead`,id:i,since:a,priority:o,visible:e,hiddenSince:s,busy:u,active:t})}function D(){l||b||(b=setTimeout(()=>{b=null,!(l||c)&&(S(!0),E(),y??=setInterval(E,za))},Va),w({kind:`claim`,id:i,since:a,priority:o}))}function O(){l||c||(b&&=(clearTimeout(b),null),x&&=(clearTimeout(x),null),S(!0),E(),y??=setInterval(E,za))}function k(){y&&=(clearInterval(y),null),S(!1)}function A(){x&&clearTimeout(x),x=setTimeout(()=>{x=null,!l&&!c&&D()},Ba)}function j(e){let t=e.priority??0;return t===o?e.since===a?e.id<i:e.since<a:t>o}function M(){l||c||_||!v||!n()||v.visible!==!1||v.busy||v.hiddenSince==null||Date.now()-v.hiddenSince<1e4||ee()}function N(){l||c||_||!v||m===null||n()&&r()&&(Date.now()-m<2e3||v.busy===!1&&(v.active||ee()))}function P(){if(!l){if(c&&(n()&&r())!==f&&E(),!n()||!r()){m=null,h&&=(clearTimeout(h),null);return}m===null&&(m=Date.now(),h=setTimeout(()=>{h=null,N()},Ha))}}function ee(){if(l)return Promise.resolve(!1);if(c)return Promise.resolve(!0);if(_)return _;let e=!1,t=()=>{},n=new Promise(e=>{t=e});_=n;let r=r=>{e||(e=!0,g=null,_===n&&(_=null),t(r))};return g=()=>r(!1),setTimeout(()=>{if(!e){if(l){r(!1);return}o=Date.now(),O(),r(!0)}},Va),w({kind:`yield`,id:i}),n}C.onmessage=e=>{let t=e.data;if(!l&&t&&t.id!==i){if(t.kind===`lead`){if(c){if(!j(t)){E();return}k()}b&&=(clearTimeout(b),null),A(),v=t,M(),N();return}if(t.kind===`claim`){if(c){E();return}b&&j(t)&&(clearTimeout(b),b=null,A());return}if(t.kind===`yield`){if(!c)return;if(u){w({kind:`busy`,id:i}),E();return}k(),A();return}if(t.kind===`busy`){g?.();return}t.kind===`resign`&&(v=null,D())}};let F=()=>{c&&w({kind:`resign`,id:i})};window.addEventListener(`pagehide`,F);let I=()=>{T(),P(),c?E():M()};return document.addEventListener(`visibilitychange`,I),window.addEventListener(`focus`,P),window.addEventListener(`blur`,P),D(),P(),{get isLeader(){return c},setBusy(e){u=e,c&&!p&&(p=!0,queueMicrotask(()=>{p=!1,!l&&c&&u!==d&&E()}))},claim:ee,release(){l||(l=!0,c&&w({kind:`resign`,id:i}),k(),b&&clearTimeout(b),x&&clearTimeout(x),h&&clearTimeout(h),window.removeEventListener(`pagehide`,F),window.removeEventListener(`focus`,P),window.removeEventListener(`blur`,P),document.removeEventListener(`visibilitychange`,I),C.close())}}}var Ka=5e3;async function qa(){try{let e=await navigator.permissions?.query({name:`microphone`});if(e?.state===`granted`||e?.state===`denied`||e?.state===`prompt`)return e.state}catch{}try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`);return e.length===0?`unknown`:e.some(e=>e.label)?`granted`:`prompt`}catch(e){return Bn(`Could not read the microphone permission state`,e),`unknown`}}async function Ja(e,t){let n=navigator.mediaDevices.getUserMedia({audio:!0}).then(e=>{for(let t of e.getTracks())t.stop();return`granted`}).catch(e=>(Bn(`Microphone permission was refused`,e),`denied`)),r=new Promise(t=>{setTimeout(()=>t(`unknown`),e)}),i=await Promise.race([n,r]);return i===`unknown`&&t&&n.then(t),i}async function Ya(e=Ka,t){let n=await qa();return n===`granted`||n===`denied`?n:Ja(e,t)}function Xa(e){if(!e||!/^tel:/i.test(e))return null;let t=e.slice(4);try{t=decodeURIComponent(t)}catch{}let n=t.split(`;`)[0].replace(/[\s().-]/g,``);return Oe(n)?n:null}var Za=`Turn on “Take calls here” (Phone page or the sidebar) to call through Proptonomy, so the call is recorded and shows your company number.`,Qa=`Calling is still connecting on this phone. Try again in a moment.`,$a=`Calling through Proptonomy is unavailable right now, so this call will not be recorded.`,eo=2e3;function to(e){let t=!1,n=0;return r=>{if(r.defaultPrevented||r.button!==0||r.metaKey||r.ctrlKey||r.shiftKey||r.altKey)return;let i=r.target;if(!(i instanceof Element))return;let a=i.closest(`a[href]`)?.getAttribute(`href`)??null;if(!a||!/^tel:/i.test(a))return;let o=e(),s=Xa(a);if((o.canPlaceCall||!o.isNative&&o.isEnabled)&&s){if(r.preventDefault(),t||Date.now()<n)return;t=!0;let e=()=>{t=!1,n=Date.now()+eo};try{Promise.resolve(o.placeCall({to:s})).catch(()=>{}).finally(e)}catch{e()}return}if(o.isNative&&o.hasProptonomyCalling&&s){if(o.isEnabled&&o.status===`error`){q($a);return}r.preventDefault(),q(o.isEnabled?Qa:Za)}}}function no(){let e=In(),t=Ea(),n=(0,Z.useRef)(null);return n.current={canPlaceCall:e.isRegistered,isEnabled:e.isEnabled,status:e.status,isNative:Ht
5(),hasProptonomyCalling:t.length>0,placeCall:e.placeCall},(0,Z.useEffect)(()=>{let e=to(()=>n.current);return document.addEventListener(`click`,e,{capture:!0}),()=>document.removeEventListener(`click`,e,{capture:!0})},[]),null}var ro=5e3,io=2e4,ao=`Proptonomy can only call numbers that include a country code. Call this one from the Phone page.`,oo=`Calling through Proptonomy is unavailable right now, so the call was not placed. Try again in a moment.`;function so(e){let t=e.trim().replace(/[\s ().-]/g,``);return Oe(t)?t:null}function co(e,t,n){let r=so(e);if(!r)return{kind:`tell`,message:ao};if(t.canPlaceCall)return{kind:`place`,to:r};if(t.isEnabled&&t.status===`error`)return{kind:`tell`,message:oo};let i=t.isEnabled?io:ro;return n<i?{kind:`wait`,forMs:i-n}:{kind:`tell`,message:t.isEnabled?Qa:Za}}function lo({read:e,place:t,tell:n,now:r=Date.now}){let i=null,a,o=()=>{if(clearTimeout(a),a=void 0,!i)return;let s=co(i.handle,e(),r()-i.since);if(s.kind===`wait`){a=setTimeout(o,s.forMs);return}if(i=null,s.kind===`tell`){n(s.message);return}try{Promise.resolve(t({to:s.to})).catch(()=>{})}catch{}};return{receive(e){i={handle:e,since:r()},o()},evaluate:o,dispose(){clearTimeout(a),i=null}}}function uo(){let e=In(),t=(0,Z.useRef)(null);t.current={canPlaceCall:e.isRegistered,isEnabled:e.isEnabled,status:e.status,placeCall:e.placeCall};let n=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let e=lo({read:()=>t.current,place:e=>t.current?.placeCall(e),tell:e=>q(e)});n.current=e;let r=!1,i=()=>{Jt().then(t=>{t&&!r&&e.receive(t.handle)})};i();let a;return Gt(i).then(e=>{r?e():a=e}),()=>{r=!0,a?.(),e.dispose(),n.current=null}},[]),(0,Z.useEffect)(()=>{n.current?.evaluate()},[e.isRegistered,e.isEnabled,e.status]),null}var fo=50,po=10,mo=5e3,ho=15e3;function go(...e){for(let t of e){if(typeof t!=`string`)continue;let e=t.trim().replace(/\s+/g,`-`);if(e!==`next`&&/^[A-Za-z0-9_.:-]{1,80}$/.test(e))return e}}function _o(e){return e.slice(0,500).replace(/(?:https?|wss?):\/\/\S+|\b(?:Bearer\s+\S+|(?:token|password|secret|authorization)["']?\s*[:=]\s*["']?[^\s,;]+)|\b(?:org_|client:|sip:)\S+|[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}|\b[A-Za-z0-9_-]{24,}(?:\.[A-Za-z0-9_-]+)*\b|\+?\d[\d ()-]{6,}\d/gi,`[redacted]`).replace(/[\r\n\t]/g,` `).slice(0,500)}function vo(e){try{if(typeof e==`string`)return{errorMessage:_o(e)};if(!e||typeof e!=`object`)return{};let{code:t,message:n}=e;return{errorCode:typeof t==`number`||typeof t==`string`?String(t).slice(0,64):void 0,errorMessage:typeof n==`string`?_o(n):void 0}}catch{return{}}}function yo(e,t){try{return bo(e,t)}catch{return{record:(e,t)=>{},flush:async()=>{},dispose:()=>{}}}}function bo(e,t){let n=crypto.randomUUID(),r=go(window.env?.APP_BUILD_DATE,void 0,void 0),i=0,a=0,o=[],s,c=!1,l=!1;function u(){o.length<=fo||(a=Math.min(1e6,a+o.length-fo),o=o.slice(-50))}function d(e=mo){l||s||!o.length||(s=setTimeout(()=>{s=void 0,f()},e))}async function f(){try{await p()}catch{}}async function p(){if(c||!o.length||!navigator.onLine)return;s&&clearTimeout(s),s=void 0,c=!0;let t=o.splice(0,po),i=a;a=0;let f=!1;try{let a=await $e({client:At(gt.getConfig()),headers:{Authorization:`Bearer ${Wt()??``}`},body:{organizationId:e,clientSessionId:n,events:t,droppedEvents:i,clientVersion:r},keepalive:!0,signal:AbortSignal.timeout(5e3),meta:{toast:!1}});f=!a.response||a.response.status>=500||a.response.status===429}catch{f=!0}finally{c=!1,f&&!l&&(o.unshift(...t),a=Math.min(1e6,a+i),u()),d(f?ho:mo)}}function m(e,n={}){if(!l)try{let r=t();o.push({event:e,occurredAt:new Date().toISOString(),sequence:++i,provider:r.provider,appState:r.appState,isLeader:r.isLeader,hasActiveCall:r.hasActiveCall,tokenRemainingSeconds:r.tokenRemainingSeconds,isVisible:document.visibilityState===`visible`,isOnline:navigator.onLine,region:n.region?.slice(0,32),sdkState:n.sdkState?.slice(0,32),reason:n.reason?.slice(0,32),errorCode:n.errorCode?.slice(0,64),errorMessage:n.errorMessage?_o(n.errorMessage):void 0,httpStatus:n.httpStatus,elapsedMilliseconds:n.elapsedMilliseconds}),u(),d()}catch{}}function h(){m(`EnvironmentChanged`),f()}function g(){f()}return window.addEventListener(`online`,h),window.addEventListener(`offline`,h),document.addEventListener(`visibilitychange`,h),window.addEventListener(`pagehide`,g),{record:m,flush:f,dispose(){l=!0,s&&clearTimeout(s),s=void 0,window.removeEventListener(`online`,h),window.removeEventListener(`offline`,h),document.removeEventListener(`visibilitychange`,h),window.removeEventListener(`pagehide`,g),f()}}}function xo(e,t){if(e){let t=e.direction===`outbound`?`outgoing`:`incoming`;return{key:`${t}:${e.counterpart}`,kind:t,handle:e.counterpart,displayName:e.displayName,connected:!e.isConnecting}}return t?{key:`incoming:${t.from}
5`,kind:`incoming`,handle:t.from,displayName:t.contactName,connected:!1}:null}var So=2e4,Co=45e3,wo=55e3;function To(){let e=globalThis.crypto;return e&&typeof e.randomUUID==`function`?e.randomUUID():`call-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Eo(){return typeof document>`u`||document.visibilityState===`visible`}function Do({activeCall:e,incoming:t,isMuted:n,provider:r,onAnswer:i,onEnd:a,onSetMuted:o}){let s=(0,Z.useRef)({onAnswer:i,onEnd:a,onSetMuted:o});s.current={onAnswer:i,onEnd:a,onSetMuted:o};let c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(void 0),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(0),h=tn(r),g=h===`native-sdk`,_=cn()&&!g,v=_&&h===`ring-only`,y=(0,Z.useRef)(Promise.resolve()),b=(0,Z.useCallback)(e=>{y.current=y.current.then(e,e).catch(e=>{Bn(`Native call bridge step failed`,e)})},[]),x=(0,Z.useMemo)(()=>xo(e,t),[e,t]),S=(0,Z.useRef)(x);S.current=x;let C=(0,Z.useCallback)(e=>{clearTimeout(u.current),u.current=setTimeout(()=>m(e=>e+1),e)},[]),w=(0,Z.useCallback)(async e=>{c.current=null,clearTimeout(u.current),await rn(e.callId,`remote`),s.current.onAnswer(e.pushed??null)},[]),T=(0,Z.useCallback)(async e=>{if(Eo()){await w(e);return}e.awaitingForeground=!0,e.pushGraceUntil=Date.now()+wo,C(wo)},[C,w]),E=(0,Z.useCallback)(async e=>{let t=c.current;if(t&&t.callId!==e.callId){if(t.connected){await rn(e.callId,`busy`);return}await rn(t.callId,`remote`)}let n=S.current,r=n?.kind===`incoming`,i=e.answered===!0||l.current===e.callId;l.current=null;let a=i?Co:So,o={key:r&&n?n.key:`incoming:${e.handle??e.callId}`,callId:e.callId,connected:!1,osEnded:!1,pushed:e,pushGraceUntil:r?void 0:Date.now()+a};if(c.current=o,v){if(r){c.current=null,await rn(e.callId,`remote`);return}C(a),i&&await T(o);return}r||C(a),i&&s.current.onAnswer(r?null:e)},[C,T,v]);(0,Z.useEffect)(()=>{if(!_)return;let e=!1,t=null,n=null,i=async()=>{let t=await dn();!e&&t&&await E(t)};b(async()=>{await Xt(on(r)),await sn(`failed`),await i()});function a(e){let t=c.current;if(!t||e.callId&&e.callId!==t.callId){e.action===`answer`&&e.callId&&(l.current=e.callId);return}switch(e.action){case`answer`:{if(v){b(()=>T(t));break}let e=t.pushGraceUntil!==void 0;e&&(t.pushGraceUntil=Date.now()+Co,C(Co)),s.current.onAnswer(e?t.pushed??null:null);break}case`end`:t.osEnded=!0,s.current.onEnd();break;case`failed`:t.osEnded=!0;break;case`mute`:s.current.onSetMuted(!0);break;case`unmute`:s.current.onSetMuted(!1);break;case`routeChanged`:e.route&&f(e.route===`speaker`)}}Yt(a).then(n=>{e?n():t=n}),Kt(()=>{e||b(i)}).then(t=>{e?t():n=t});function o(){if(!v||!Eo())return;let e=c.current;e?.awaitingForeground&&b(async()=>{c.current===e&&await w(e)})}return typeof document<`u`&&document.addEventListener(`visibilitychange`,o),()=>{e=!0,t?.(),n?.(),typeof document<`u`&&document.removeEventListener(`visibilitychange`,o),clearTimeout(u.current),c.current=null,sn(`ended`)}},[_,v,r,b,E,C,T,w]),(0,Z.useEffect)(()=>{_&&b(async()=>{let e=c.current;if(!x){if(!e||e.pushGraceUntil!==void 0&&e.pushGraceUntil>Date.now())return;c.current=null,await rn(e.callId,e.pushGraceUntil===void 0?`remote`:`unanswered`);return}if(v){if(!e)return;c.current=null,clearTimeout(u.current),await rn(e.callId,`remote`);return}if(e&&e.key!==x.key&&(e.pushGraceUntil!==void 0&&x.kind===`incoming`?e.key=x.key:(c.current=null,await rn(e.callId,`remote`),e=null)),!e?.osEnded){if(e&&e.pushGraceUntil!==void 0&&(e.pushGraceUntil=void 0,clearTimeout(u.current)),!e){let t=To();e={key:x.key,callId:t,connected:!1,osEnded:!1},c.current=e,x.kind===`outgoing`?await Zt({callId:t,handle:x.handle,displayName:x.displayName??void 0}):await nn({callId:t,handle:x.handle,displayName:x.displayName??void 0})}x.connected&&!e.connected&&!e.osEnded&&(e.connected=!0,await an(e.callId))}})},[_,v,x,b,p]),(0,Z.useEffect)(()=>{_&&!v&&b(async()=>{let e=c.current;e&&!e.osEnded&&await un(e.callId,n)})},[_,v,n,b]);let D=x?.key??null;(0,Z.useEffect)(()=>{_&&!v&&D&&(f(!1),b(()=>fn(`earpiece`)))},[_,v,D,b]);let O=(0,Z.useCallback)(e=>{v||(f(e),b(()=>fn(e?`speaker`:`earpiece`)))},[v,b]);(0,Z.useEffect)(()=>{g&&b(()=>Xt(on(r)))},[g,r,b]),(0,Z.useEffect)(()=>{g&&D&&(f(!1),b(()=>fn(`earpiece`)))},[g,D,b]);let k=(0,Z.useCallback)(e=>{b(async()=>{let t=c.current;t&&t.callId===e&&(c.current=null,clearTimeout(u.current),await rn(e,`failed`))})},[b]);return(0,Z.useMemo)(()=>({isAvailable:g||_&&!v,isOn:d,setOn:O,abandonPushedCall:k}),[g,_,v,d,O,k])}var Oo=new Set([`Admin`,`Member`,`StaffCoordinator`,`MemberReadOnly`,`InboxAgent`]);function ko(e,t){let n=[];for(let r of e??[]){let e=r.id;if(e&&e!==t&&!n.includes(e)&&r.currentUserRole&&Oo.has(r.currentUserRole)&&(n.push(e),n.length>=10))break}return n}function Ao(e){return ha(e)===`on`}var jo=[`voip`,`call`];function Mo({userId:e,organizationId:t,isEnabled:n,isAwaitingDefault:r=!1,otherOrganizationIds:i}){let a=[...i??[]].sort().join(`,`),o=!n&&r;(0,Z.useEffect)(()=>
5{if(!e)return;if(Ut()){let e=()=>{pn(`call`)&&vn(`call`)};return e(),window.addEventListener(`online`,e),()=>window.removeEventListener(`online`,e)}if(!n){if(!t||Ao(t)||o)return;let e=()=>{for(let e of jo)pn(e)&&vn(e)};return e(),window.addEventListener(`online`,e),()=>window.removeEventListener(`online`,e)}let r=window.env?.APP_BUILD??void 0,i=!1,s,c=new Set,l=t?[t,...a.split(`,`).filter(e=>e&&e!==t)]:[],u=Vt()?mn(async e=>{if(await _n(e,`ios`,r,`voip`)&&!i)for(let t of l){if(i)return;let n=`${e}|${t}`;c.has(n)||(c.add(n),await hn(t,e)||c.delete(n))}}):null;if(u)return u.then(e=>{i?e():s=e}),()=>{i=!0,s?.()}},[e,t,n,a,o])}var No=6e4,Po=12e4,Fo=[2e3,4e3,8e3,15e3],Io=3e4,Lo=1e4,Ro=15e3;function zo(e){let t=e?.joinNativeCall;return t?(e,n,r)=>t(e,n,r):null}function Bo(e){let t=e.registrations;return t?.length?t:void 0}function Vo(e,t){return{organizationId:t,edges:e.edges,registrations:Bo(e)}}function Ho(e){return Bo(e)?.map(e=>e.region)??[]}function Uo(e){return{callId:e.callId,organizationId:e.organizationId,offerId:e.offerId,admissionGeneration:e.admissionGeneration,from:e.handle,masked:Me(e.handle),contactId:null,contactName:e.displayName,conversationId:e.conversationId,propertyId:null,propertyName:null,checkIn:null,checkOut:null,isStaffOrPartner:!1,isEnriched:!1}}function Wo(e){switch(e){case`Listen`:return`listener`;case`Whisper`:return`whisper`;case`Barge`:return`barge`;default:return`operator`}}var Go=3e4,Ko=1e4,qo=2,Jo=3e3,Yo=8e3;async function Xo(e){let t=await Ya(Ka,e);return t===`unknown`&&Bn(`Microphone permission did not resolve in time; enabling the softphone without it`),t}var Zo=`Your microphone is blocked, so nobody would hear you. Allow it in your browser or app settings, then call again.`;function Qo({children:e}){let{user:t}=gn(),{selectedOrganizationId:n,organizations:r}=Dn(),i=J(),[a,o]=(0,Z.useState)(()=>ha(n)),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(`connected`),p=(0,Z.useRef)(null),[m,h]=(0,Z.useState)(`off`),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(`unknown`),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(()=>new Set),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(!1),[M,N]=(0,Z.useState)(null),[P,ee]=(0,Z.useState)([]),[F,I]=(0,Z.useState)([]),[te,ne]=(0,Z.useState)(!1),[re,ie]=(0,Z.useState)(null),[ae,oe]=(0,Z.useState)(null),[se,ce]=(0,Z.useState)(()=>Date.now()),L=(0,Z.useRef)(null),R=(0,Z.useRef)(null),z=(0,Z.useRef)(null),le=(0,Z.useRef)(null),B=(0,Z.useRef)(null),V=(0,Z.useRef)(null),ue=(0,Z.useRef)(null),de=(0,Z.useRef)(0),fe=(0,Z.useRef)(null),pe=(0,Z.useRef)(!1),me=(0,Z.useRef)(null),he=(0,Z.useRef)([]),[ge,_e]=(0,Z.useState)(0),[ve,ye]=(0,Z.useState)(null),be=(0,Z.useRef)(null),xe=(0,Z.useRef)(0),Se=(0,Z.useRef)([]),Ce=(0,Z.useRef)(null),[we,Te]=(0,Z.useState)(null),Ee=(0,Z.useCallback)(e=>{Ce.current=e,Te(e)},[]),De=(0,Z.useRef)(null),Oe=(0,Z.useRef)(!1),ke=(0,Z.useRef)(!1),H=(0,Z.useRef)(`off`),Ae=(0,Z.useRef)({forToken:null,attempt:0}),je=(0,Z.useRef)(!1),Ne=(0,Z.useRef)(null);B.current=w,V.current=O,Oe.current=s;let[U,Pe]=(0,Z.useState)(n??null),Fe=(0,Z.useRef)(U);Fe.current=U,(0,Z.useEffect)(()=>{!w&&!O&&!we&&Pe(n??null)},[n,w,O,we]);let Ie=(0,Z.useCallback)(e=>{let t={...e,sessionId:crypto.randomUUID(),startedAt:Date.now(),isConnecting:!0};return V.current=t,k(t),h(`in-call`),t.sessionId},[]),W=(0,Z.useCallback)(e=>!e||V.current?.sessionId!==e||!V.current.isConnecting?!1:(Ne.current===e&&(Ne.current=null),de.current=0,fe.current=null,ue.current=null,V.current=null,k(null),h(`ready`),!0),[]),Le=(0,Z.useCallback)((e,t)=>{if(!e||!t||V.current?.sessionId!==e)return;let n=V.current;if(t.organizationId&&t.organizationId!==n.organizationId||t.id&&n.callId&&t.id!==n.callId)return;let r=n.counterpart||(t.direction===`Outbound`?t.toE164:t.fromE164)||``,i={...n,callId:n.callId??t.id,counterpart:r,masked:n.masked||Me(r),conversationId:n.conversationId??t.conversationId??null};V.current=i;let a=fe.current;a?.sessionId===e&&i.callId&&(fe.current=null,a.adapter===L.current&&(a.callId===i.callId&&(!a.organizationId||a.organizationId===i.organizationId)?a.adapter?.answer():a.adapter?.reject())),k(t=>t?.sessionId===e?{...t,callId:i.callId,counterpart:i.counterpart,masked:i.masked,conversationId:i.conversationId}:t)},[]),G=m===`ready`||m===`ringing`||m===`in-call`;ke.current=G,H.current=m;let Re=(0,Z.useRef)(null),ze=(0,Z.useRef)({appState:m,isLeader:l});ze.current={appState:m,isLeader:l};let K=(0,Z.useCallback)((...e)=>{try{Re.current?.record(...e)}catch{}},[]);(0,Z.useEffect)(()=>
5{if(!O?.isConnecting||!de.current)return;let e=O.sessionId;if(!e)return;let t=de.current,n=window.setTimeout(()=>{V.current?.sessionId===e&&V.current.isConnecting&&W(e)&&(K(`SelfLegTimeout`),L.current?.hangup(),q.error(`The call could not be connected`))},Math.max(0,t-Date.now()));return()=>window.clearTimeout(n)},[O?.sessionId,O?.isConnecting,W,K]),(0,Z.useEffect)(()=>{if(!U||!t?.sub)return;let e=yo(U,()=>{let e=Date.parse(le.current??``);return{...ze.current,provider:z.current??void 0,hasActiveCall:!!V.current,tokenRemainingSeconds:Number.isFinite(e)?Math.max(-86400,Math.min(86400,Math.floor((e-Date.now())/1e3))):void 0}});return Re.current=e,()=>{e.dispose(),Re.current===e&&(Re.current=null)}},[U,t?.sub]),(0,Z.useEffect)(()=>{K(`AppStateChanged`,{reason:s?`enabled`:`disabled`})},[m,l,s,U,t?.sub,K]),(0,Z.useEffect)(()=>{K(`MicrophoneResult`,{reason:v})},[v,U,t?.sub,K]);let Be=Ta(),Ve=Be.own.length>0,He=a===`on`||_a({preference:a,ownsActiveNumber:Ve}),Y=(0,Z.useMemo)(()=>ko(r,U),[r,U]);Mo({userId:t?.sub??null,organizationId:U,isEnabled:s,isAwaitingDefault:a===`unset`&&(!Be.isSettled||Ve),otherOrganizationIds:Y});let Ue=[t?.firstName,t?.lastName].filter(Boolean).join(` `).trim()||t?.email||`an operator`;(0,Z.useEffect)(()=>{let e=ha(U);o(e),e===`on`&&U&&c(!0)},[U]),(0,Z.useEffect)(()=>{U&&Ve&&_a({preference:ha(U),ownsActiveNumber:Ve})&&c(!0)},[U,Ve]),(0,Z.useEffect)(()=>{if(!s)return;let e=()=>void Xo(y).then(y);return window.addEventListener(`pointerdown`,e,{once:!0}),window.addEventListener(`keydown`,e,{once:!0}),()=>{window.removeEventListener(`pointerdown`,e),window.removeEventListener(`keydown`,e)}},[s]);let We=(0,Z.useCallback)(async()=>{let e=L.current;if(!e)return;let t=await e.listDevices();ee(t.inputs),I(t.outputs),ne(t.isOutputSelectionSupported)},[]),X=(0,Z.useCallback)(async(e,t,n)=>{let r=t,a=t=>{if(Fe.current!==e)return;let i={...r,...t};B.current===r&&(B.current=i,T(i));let a=V.current;if(n&&a?.legId===n&&a.organizationId===e){let e={...a,callId:i.callId??a.callId,counterpart:i.from,masked:i.masked,displayName:i.contactName,conversationId:i.conversationId};V.current=e,k(e)}r=i};try{if(r.callId||n){let t=(await nt({query:{organizationId:e,callId:r.callId,legSid:r.callId?void 0:n??void 0}})).data;if(t?.id&&t.organizationId===e&&(!r.callId||t.id===r.callId)){let e=(t.direction===`Outbound`?t.toE164:t.fromE164)??``;a({callId:t.id,from:e,masked:Me(e),receivingNumber:t.phoneNumberE164??(t.direction===`Inbound`?t.toE164:null),conversationId:t.conversationId??null})}}if(!/^\+[1-9]\d{5,14}$/.test(r.from)){a({isEnriched:!0});return}let t=r.from,o=await i.fetchQuery({queryKey:jn.lookup(e,t),queryFn:async()=>(await Ct({query:{organizationId:e,e164:t}})).data??null,staleTime:3e5});a({isEnriched:!0,contactId:o?.contactId??null,contactName:o?.contactName??r.contactName,conversationId:r.conversationId??o?.conversationId??null,propertyId:o?.propertyId??null,propertyName:o?.propertyName??null,checkIn:o?.checkIn??null,checkOut:o?.checkOut??null,isStaffOrPartner:o?.isStaffOrPartner??!1})}catch{a({isEnriched:!0})}},[i]),qe=(0,Z.useCallback)(async e=>{let t=tn()===`native-sdk`?await $t():void 0,n=e=>tn(e)===`native-sdk`?t:`browser-offers-v1`,r=t=>Lt({body:{organizationId:e,callingProtocolVersion:+!!t,callingProtocolCapability:t},meta:{toast:!1}}),i=t=>{let n=t?.dialIdentity||t?.identity;n&&Dt({path:{identity:n},query:{organizationId:e},meta:{toast:!1}}).catch(()=>{})},a=n(z.current),o=await r(a);if(!o.error&&o.data?.token&&n(o.data.provider)!==a){a=n(o.data.provider);let e=o.data;try{o=await r(a)}catch(t){throw i(e),t}(o.data?.dialIdentity||o.data?.identity)!==(e.dialIdentity||e.identity)&&i(e)}if(o.error||!o.data?.token||n(o.data.provider)!==a)throw i(o.data),K(`TokenRefreshFailed`,{reason:`token-request`,httpStatus:o.response?.status}),Error(typeof o.error==`string`?o.error:`This organization has no voice-capable number`);return o.data},[K]),Ye=(0,Z.useCallback)((e,t,n=!1)=>{let r=Dt({path:{identity:t},query:{organizationId:e},meta:{toast:!1},...n?{keepalive:!0}:{}});n||r.then(()=>i.invalidateQueries({queryKey:[`phoneCoverage`]}))},[i]),Xe=(0,Z.useCallback)(async()=>{let e=L.current;if(e&&U&&me.current!==e){if(V.current||B.current){K(`TokenRefreshDeferred`,{reason:`active-call`}),pe.current=!0;return}me.current=e,K(`TokenRefreshStarted`);try{let t=await qe(U),n=t.dialIdentity||t.identity,r=()=>{n&&n!==R.current&&Ye(U,n)};if(L.current!==e){r();return}if(V.current||B.current){pe.current=!0,r();return}let i=R.current,a=t.dialIdentity||t.identity;if(a&&a!==i){if(await e.register(t.token??``,Vo(t,U)),L.current!==e){e.destroy(),r();return}he.current=Ho(t),R.current=a,C(a),i&&Ye(U,i)}else if(await e.updateToken(t.token??``,Vo(t,U)),L.current!==e)return;if(L.current!==e)return;le.current=t.expiresAt??null,K(`TokenRefreshSucceeded`),_(null)}catch(t){if(L.current!==e)return;K(`TokenRefreshFailed`,vo(t)),Bn(`Could not refresh the token`,t);let n=Ae.current,r=le.current;n.forToken!==r&&(n.forToken=r,n.attempt=0);let i=Fo[Math.min(n.attempt,Fo.length-1)];n.attempt+=1,Date.now()+i<Date.parse(r??``)&&(clearTimeout(n.timer),n.timer=setTimeout(()=>{L.current===e&&Xe()},i))}finally{me.current===e&&(me.current=null)}}},[U,qe,Ye,K]);(0,Z.useEffect)(()=>
5{if(!s||!U){u(!1);return}let e=Ga({channelName:`proptonomy-softphone-${U}`,onChange:u});return p.current=e,()=>{e.release(),p.current=null,u(!1)}},[s,U]),(0,Z.useEffect)(()=>{if(!s||!l||!U)return;Ai();let e=!1,t=null,n=null;return(async()=>{K(`RegistrationStarted`),h(`connecting`),_(null);try{let r=await qe(U);if(e)return;if(t=await Ra(r.provider??`Twilio`),e){t.destroy();return}t.setTokenExpiry?.(r.expiresAt??void 0),L.current=t,z.current=r.provider??`Twilio`;let a=r.dialIdentity||r.identity||null;R.current=a,n=a,le.current=r.expiresAt??null,x(r.provider??`Twilio`),C(a),t.on(`diagnostic`,t=>{e||K(t.event,{region:t.region,sdkState:t.sdkState,...vo(t)})}),t.on(`registered`,()=>{_(null),h(e=>e===`ringing`||e===`in-call`?e:`ready`),We()}),t.on(`incoming`,e=>{let n=Ce.current;if(n&&Date.now()<n.until&&(!e.parameters.callId||e.parameters.callId===n.callId)&&(!e.parameters.organizationId||e.parameters.organizationId===n.organizationId)&&(!n.offerId||e.parameters.offerId===n.offerId&&e.parameters.admissionGeneration===n.admissionGeneration)){Ee(null);let e=Uo(n);B.current=e,N(null),T(e),t?.answer(),X(U,e,t?.currentLegId?.());return}let r=V.current;if(r&&Date.now()<de.current){let n=e.parameters.callId&&r.callId&&e.parameters.callId!==r.callId,i=e.parameters.organizationId&&e.parameters.organizationId!==r.organizationId;if(!n&&!i){if(e.parameters.callId&&!r.callId){fe.current={sessionId:r.sessionId,callId:e.parameters.callId,organizationId:e.parameters.organizationId,adapter:t};return}Le(r.sessionId,{id:e.parameters.callId||void 0}),t?.answer();return}W(r.sessionId)}let i={callId:e.parameters.callId||void 0,organizationId:e.parameters.organizationId||U,declineOfferId:e.parameters.declineOfferId,offerId:e.parameters.offerId,admissionGeneration:e.parameters.admissionGeneration,purpose:e.parameters.callPurpose===`join`?`join`:e.parameters.callPurpose===`answer`?`answer`:void 0,from:``,masked:Me(e.from||e.parameters.From),contactId:null,contactName:e.parameters.callerName??null,conversationId:null,propertyId:null,propertyName:e.parameters.propertyName??null,checkIn:null,checkOut:null,isStaffOrPartner:!1,isEnriched:!1};B.current=i,N(null),T(i),h(`ringing`),p.current?.setBusy(!0),X(U,i,t?.currentLegId?.())});let o=(e,n)=>{n||(de.current=0);let r=B.current;B.current=null,T(null),h(`in-call`);let i=V.current,a=i?{...i,legId:t?.currentLegId?.()??null,isConnecting:n,startedAt:Date.now()}:{sessionId:crypto.randomUUID(),callId:r?.callId??null,organizationId:r?.organizationId??U,legId:t?.currentLegId?.()??null,role:Wo(ue.current),direction:e.direction,counterpart:r?.from??``,masked:r?.masked??Me(r?.from),displayName:r?.contactName??null,conversationId:r?.conversationId??null,isConnecting:n,startedAt:Date.now()};ue.current=null,V.current=a,k(a)};if(t.on(`bound`,e=>{if(L.current!==t)return;let n=V.current;if(!n)return;let r={...n,callId:e.callId,organizationId:e.organizationId,legId:e.legId};V.current=r,k(r)}),t.on(`answering`,e=>o(e,!0)),t.on(`accepted`,e=>o(e,!1)),t.on(`disconnected`,e=>{let t=fe.current;if(t&&e.callId===t.callId&&!V.current?.callId){fe.current=null;return}let n=V.current;e.callId&&n?.callId&&e.callId!==n.callId||e.organizationId&&n?.organizationId&&e.organizationId!==n.organizationId||(fe.current=null,K(`CallDisconnected`),de.current=0,ue.current=null,B.current=null,V.current=null,T(null),k(null),j(!1),h(e=>e===`off`||e===`error`?e:`ready`),i.invalidateQueries({queryKey:jn.all}),pe.current&&(pe.current=!1,Xe()))}),t.on(`tokenWillExpire`,()=>{Xe()}),t.on(`error`,e=>{K(`SdkError`,{reason:`adapter`,...vo(e)}),_(e.message),h(e=>e===`in-call`||e===`ringing`?e:`error`)}),await t.register(r.token??``,Vo(r,U)),he.current=Ho(r),e)return;h(`ready`),await We()}catch(t){if(e)return;K(`RegistrationFailed`,vo(t));let n=t instanceof Error?t.message:`Could not start the softphone`;_(n),h(`error`)}})(),()=>{e=!0;let r=t,i=R.current??n;L.current=null,de.current=0,V.current=null,R.current=null,z.current=null,le.current=null,T(null),k(null),C(null),h(`off`),i&&Ye(U,i),r?.unregister().finally(()=>r?.destroy())}},[s,l,U,ge,qe,We,X,Ye,Xe,i,Ee,K]),(0,Z.useEffect)(()=>
5{if(G){xe.current===0&&(xe.current=Date.now());let e=Se.current;Se.current=[];for(let t of e)t(!0);return}if(xe.current=0,m===`error`){let e=Se.current;Se.current=[];for(let t of e)t(!1)}},[G,m]);let Ze=(0,Z.useCallback)(e=>new Promise(t=>{let n,r=e=>{clearTimeout(n),t(e)};n=setTimeout(()=>{Se.current=Se.current.filter(e=>e!==r),t(!1)},e),Se.current.push(r)}),[]);(0,Z.useEffect)(()=>{if(!ve)return;if(ve!==U){ye(null);return}if(!U||O||w)return;ye(null);let e=be.current;if(e?.organizationId===U&&Date.now()-e.at<6e4){_(`Reconnect using Take calls here.`),h(`error`);return}be.current={organizationId:U,at:Date.now()},_e(e=>e+1)},[ve,U,O,w]),(0,Z.useEffect)(()=>{if(!G||!S||!U||tn(z.current)===`native-sdk`)return;let e=!1,t=!1,n=async(n=!1)=>{if(document.visibilityState===`visible`)try{let r=await it({body:{organizationId:U,identity:S,provider:z.current??void 0,regions:he.current},meta:{toast:!1}});if(t)return;r.response?.status===409&&ye(U),r.error||r.response&&!r.response.ok?(e=!0,K(`HeartbeatFailed`,{httpStatus:r.response?.status})):e&&(e=!1,K(`HeartbeatRecovered`)),n&&await i.invalidateQueries({queryKey:[`phoneCoverage`]})}catch(t){e=!0,K(`HeartbeatFailed`,vo(t))}},r=()=>void n(!0);n(!0);let a=setInterval(()=>void n(),No);return document.addEventListener(`visibilitychange`,r),()=>{t=!0,clearInterval(a),document.removeEventListener(`visibilitychange`,r)}},[G,S,U,i,K]),(0,Z.useEffect)(()=>{if(!S||!U)return;let e=()=>Ye(U,S,!0);return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[S,U,Ye]),(0,Z.useEffect)(()=>{if(!s||!l)return;let e=()=>{if(document.visibilityState!==`visible`)return;if(H.current===`error`){V.current||_e(e=>e+1);return}if(!ke.current)return;let e=le.current?Date.parse(le.current):NaN;(Number.isNaN(e)||e-Date.now()<Po)&&Xe()};return document.addEventListener(`visibilitychange`,e),window.addEventListener(`online`,e),()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`online`,e)}},[s,l,Xe]),(0,Z.useEffect)(()=>{if(!G||navigator.mediaDevices===void 0)return;let e=()=>void We();return navigator.mediaDevices.addEventListener(`devicechange`,e),()=>navigator.mediaDevices.removeEventListener(`devicechange`,e)},[G,We]),(0,Z.useEffect)(()=>{if(!O){f(`connected`);return}return ji(f)},[O,w,we]),(0,Z.useEffect)(()=>(p.current?.setBusy(!!(O||w||we)),()=>p.current?.setBusy(!1)),[O,w,we]),(0,Z.useEffect)(()=>{if(O)return Vn(`phone-call`,`You are on a call. Leaving this page will end it.`)},[!!O]),(0,Z.useEffect)(()=>{if(!O||O.isConnecting)return;ce(Date.now());let e=setInterval(()=>ce(Date.now()),1e3);return()=>clearInterval(e)},[O,w,we]),(0,Z.useEffect)(()=>{if(!O||d!==`closed`)return;let e=window.setTimeout(()=>{k(null),j(!1),h(e=>e===`off`||e===`error`?e:`ready`),i.invalidateQueries({queryKey:jn.all})},Jo);return()=>window.clearTimeout(e)},[O,d,i]),(0,Z.useEffect)(()=>{if(!O||O.isConnecting)return;let e=O.organizationId??U;if(!e)return;let t=O,n=!1,r=0,a=!1,o=null,s=async()=>{if(a)return;a=!0;let s=new AbortController;o=s;let c;try{let a=await Promise.race([Ge({query:{organizationId:e},signal:s.signal}),new Promise((e,t)=>{c=setTimeout(()=>{s.abort(),t(Error(`Call reconciliation timed out`))},15e3)})]);if(n||V.current!==t)return;if(a.error||a.response?.ok===!1||!Array.isArray(a.data)){r=0;return}if(Ui(a.data,t.masked)){r=0;return}if(r+=1,r<qo)return;k(null),V.current=null,j(!1),h(e=>e===`off`||e===`error`?e:`ready`),L.current?.forgetStaleCall?.(),q(`That call has ended`),i.invalidateQueries({queryKey:jn.all})}catch{r=0}finally{clearTimeout(c),o=null,a=!1}},c=setInterval(()=>void s(),Ko);return()=>{n=!0,o?.abort(),clearInterval(c)}},[O,U,i]);let Qe=(0,Z.useCallback)(e=>{let t=B.current,n=V.current;n&&e.organizationId===n.organizationId&&Hi(e,n.callId)&&(V.current=null,k(null),h(e=>e===`off`||e===`error`?e:`ready`),j(!1),L.current?.forgetStaleCall?.(),pe.current&&(pe.current=!1,Xe()));let r=!!t&&e.organizationId===(t?.organizationId??U)&&(t?.callId?e.callId===t.callId:!e.counterpartMasked||!t?.masked||e.counterpartMasked===t.masked),a=r&&Vi(e.status);a&&(B.current=null,T(null),L.current?.reject(),h(e=>e===`ringing`?`ready`:e)),r&&!a&&t?.purpose!==`join`&&(e.hasAnsweredParticipant===!0||e.hasAnsweredParticipant===void 0&&t?.purpose!==`answer`)&&e.direction===`Inbound`&&e.status!==`Ringing`&&(B.current=null,T(null),L.current?.reject(),N({answeredByName:e.answeredByName??null,conversationId:e.conversationId??t?.conversationId??null}),h(e=>e===`ringing`?`ready`:e)),i.invalidateQueries({queryKey:jn.all})},[i,U,Xe]);Mn({organizationIds:[U,w?.organizationId,O?.organizationId].filter(e=>!!e),organizationTopics:[`phone`],keepAliveWhileHidden:!!(w||O),onCallChanged:Qe,autoInvalidateQueries:!1}),(0,Z.useEffect)(()=>
5{if(!M)return;let e=setTimeout(()=>N(null),Yo);return()=>clearTimeout(e)},[M]);let $e=(0,Z.useCallback)(()=>N(null),[]);pa(w);let et=(0,Z.useCallback)(async()=>{U&&(y(await Xo(y)),sa(),ga(U,`on`),o(`on`),_(null),c(!0))},[U]),tt=(0,Z.useCallback)(async()=>{if(!s){await et();return}if(m===`error`&&l){_(null),_e(e=>e+1);return}if(!(await p.current?.claim()??!1))throw Error(`Another tab is on a call. It keeps the phone until that call ends.`)},[s,et,m,l]),rt=(0,Z.useCallback)(async()=>{if(je.current)return!1;je.current=!0;try{let e=Ze(Ro);try{await tt()}catch(e){return K(`OutboundBlocked`,{reason:`take-over-refused`}),q.error(e instanceof Error?e.message:`Could not move calls to this tab`),!1}let t=await e?R.current:null,n=L.current;return Fe.current===U?!t||!U?(K(`OutboundBlocked`,{reason:`take-over-timeout`}),q.error(`The phone could not connect in this tab. Try again in a moment.`),!1):(tn(z.current)!==`native-sdk`&&await it({body:{organizationId:U,identity:t,provider:z.current??void 0,regions:he.current},meta:{toast:!1}}).catch(()=>void 0),Fe.current===U&&L.current===n&&R.current===t):!1}finally{je.current=!1}},[tt,Ze,U,K]),at=(0,Z.useCallback)(async(e,t=`Listen`)=>{if(!ke.current&&Oe.current&&U&&!V.current&&!B.current&&!await rt())throw Error(`Could not connect the phone in this tab`);if(Fe.current!==U)return;if(zo(L.current))throw Error(`Listen, whisper and barge are not available with native calling yet`);if(!U||!R.current){q.error(`Turn on “Take calls here” before joining a call`);return}if(V.current||B.current)return;de.current=Date.now()+Go;let n=Ie({intent:`join`,callId:e,organizationId:U,role:Wo(t),direction:`inbound`,counterpart:``,masked:``,displayName:null,conversationId:null});try{let r=await ft({path:{id:e},query:{organizationId:U},body:{clientIdentity:R.current,mode:t},meta:{toast:!1}});if(r.error)throw Error(String(r.error));Le(n,r.data)}catch(e){W(n)&&q.error(e instanceof Error?e.message:`Could not join the call`)}},[U,rt,Ie,W,Le]),ot=(0,Z.useCallback)(async e=>{if(!U||!R.current){q.error(`Turn on “Take calls here” before joining a call`);return}let t=await Nt({path:{id:e},query:{organizationId:U},body:{clientIdentity:R.current}});if(t.error)throw Error(String(t.error));k(e=>e&&{...e,role:`barge`}),q.success(`You are in the conversation`)},[U]),st=(0,Z.useCallback)(async e=>{if(!ke.current&&Oe.current&&U&&!V.current&&!B.current&&!await rt())throw Error(`Could not connect the phone in this tab`);if(Fe.current!==U)return;let t=L.current,n=zo(t);if(!U||!R.current){q.error(`Turn on “Take calls here” before rejoining`);return}if(V.current||B.current)return;de.current=Date.now()+Go;let r=Ie({callId:e,organizationId:U,role:`operator`,direction:`inbound`,counterpart:``,masked:``,displayName:null,conversationId:null});n&&(Ne.current=r??null);try{let i=await Je({path:{id:e},query:{organizationId:U},body:{clientIdentity:R.current}});if(i.error)throw Error(String(i.error));if(V.current?.sessionId!==r||Fe.current!==U||L.current!==t)return;if(n){let t=i.data?.nativeOffer;if(i.data?.callingProtocolVersion!==0&&(!t?.offerId||!t.commandId||!t.admissionGeneration))throw Error(`The call did not return a current native reconnect offer`);Le(r,i.data),Ne.current=null,await n(e,`operator`,t??void 0)}else Le(r,i.data)}catch(e){if(W(r))throw e instanceof Error?e:Error(`Could not rejoin the call`)}},[U,rt,Ie,W,Le]),ct=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{G&&U&&R.current&&!O&&(ct.current||(ct.current=!0,(async()=>{try{let e=((await mt({query:{organizationId:U}})).data??[])[0];if(!e?.id)return;await st(e.id),q.success(`Back on your call`)}catch{}})()))},[G,U,O,st]);let lt=(0,Z.useCallback)(async()=>{U&&(ga(U,`off`),o(`off`)),c(!1),h(`off`),_(null)},[U]),ut=(0,Z.useCallback)(async()=>{await L.current?.answer()},[]),dt=(0,Z.useCallback)(async e=>{if(B.current){let t=B.current;(!t.callId||t.callId===e.callId)&&(!t.organizationId||!e.organizationId||t.organizationId===e.organizationId)&&(String(e.callingProtocolVersion)!==`1`||t.offerId===e.offerId&&t.admissionGeneration===String(e.admissionGeneration))&&await L.current?.answer();return}let t=t=>{Ee(null),q.error(t),De.current?.abandonPushedCall(e.callId)};if(!U){t(`Sign in to take this call`);return}if(e.organizationId&&e.organizationId!==U){t(`This call belongs to another organization — switch to it in the app to answer`);return}if(String(e.callingProtocolVersion)===`1`&&(!e.offerId||!Number.isInteger(Number(e.admissionGeneration))||Number(e.admissionGeneration)<=0)){t(`This call offer is incomplete; wait for a new incoming call`);return}Ee({offerId:String(e.callingProtocolVersion)===`1`?e.offerId:void 0,admissionGeneration:String(e.callingProtocolVersion)===`1`?String(e.admissionGeneration):void 0,callId:e.callId,organizationId:U,handle:e.handle??``,displayName:e.displayName??null,conversationId:e.conversationId??null,until:Date.now()+Io});let n=ke.current&&Date.now()-xe.current<Lo;n||(Oe.current?_e(e=>e+1):c(!0));let r=n||await Ze(Ro);if(Ce.current?.callId!==e.callId)return;let i=R.current;if(!r||!i){t(`Could not connect the phone in time`);return}try{await it({body:{organizationId:U,identity:i,provider:z.current??void 0,regions:he.current},meta:{toast:!1}});let t=await yt({path:{id:e.callId},query:{organizationId:U},body:{clientIdentity:i,...String(e.callingProtocolVersion)===`1`?{offerId:e.offerId,admissionGeneration:Number(e.admissionGeneration)}:{}}
5});if(t.error)throw Error(String(t.error))}catch(e){t(e instanceof Error?e.message:`Could not take the call`)}},[U,Ze,Ee]),pt=(0,Z.useCallback)(async()=>{let e=B.current;if(!e)return;if(B.current=null,T(t=>t===e?null:t),e.callId){let t=e.callId;D(e=>new Set([...e,t].slice(-100)))}h(e=>e===`ringing`?`ready`:e);let t=L.current,n=e.callId&&e.organizationId&&e.declineOfferId&&e.purpose!==`join`?vt({path:{id:e.callId},query:{organizationId:e.organizationId},body:{offerId:e.declineOfferId},meta:{toast:!1}}).then(e=>{if(e.error)throw Error(`Decline could not be recorded`)}).catch(()=>{q.error(`Ringing dismissed here. The caller may keep waiting until the call times out.`)}):Promise.resolve();await Promise.all([t?.reject(),n])},[]),ht=(0,Z.useCallback)(async e=>{let t=V.current;if(!t||e&&t.callId&&e!==t.callId)return;let n=t.callId??e,r=t?.organizationId??U,i=L.current;if(i?.ownsCallCommands){if(Ne.current===t.sessionId){Ne.current=null,W(t.sessionId);return}await i.hangup(),W(t.sessionId);return}let a=V.current?.role,o=a===`listener`||a===`whisper`||t.isConnecting&&t.intent===`join`,s=o?null:i?.currentLegId?.()??null;if(t.isConnecting&&W(t.sessionId)&&i?.hangup(),r&&!o&&(n||s))try{let e=s?await xt({path:{legSid:s},query:{organizationId:r}}):null;if(n&&(!e||e.response?.status===204)&&(e=await Mt({path:{id:n},query:{organizationId:r}})),e?.error)throw Error(String(e.error))}catch{q.error(`The call could not be ended for the caller. They may stay on the line for up to a minute.`)}L.current===i&&V.current?.sessionId===t.sessionId&&await i?.hangup()},[U,W]),gt=(0,Z.useCallback)(async()=>{let e=V.current;if(!e)return;let t=L.current,n=t?.currentLegId?.(),r=t?.hangup();if(!t?.ownsCallCommands&&e.organizationId&&e.role!==`listener`&&e.role!==`whisper`)try{n?await xt({path:{legSid:n},query:{organizationId:e.organizationId}}):e.callId&&(e.role===void 0||e.role===`operator`||e.role===`barge`)&&await Mt({path:{id:e.callId},query:{organizationId:e.organizationId}})}catch{q.error(`The caller may still be connected. Server cleanup will retry.`)}await r},[]),_t=(0,Z.useCallback)(e=>{L.current?.mute(e),j(e)},[]),bt=(0,Z.useCallback)(async e=>L.current?.sendNativeDigits?.(e)??!1,[]),St=(0,Z.useCallback)(e=>L.current?.sendDigits?.(e)??!1,[]),wt=(0,Z.useCallback)(async e=>{await L.current?.setInputDevice(e),ie(e)},[]),Tt=(0,Z.useCallback)(async e=>{await L.current?.setOutputDevice(e),oe(e)},[]),Et=(0,Z.useCallback)(async e=>{if(K(`OutboundRequested`),!ke.current&&Oe.current&&U&&!V.current&&!await rt())return null;let t=L.current;if(!t||!ke.current||!U)return K(`OutboundBlocked`,{reason:`not-ready`}),q.error(`Turn on “Take calls here” before placing a call`),null;if(V.current||B.current||Ce.current)return K(`OutboundBlocked`,{reason:`active-call`}),q.error(`You are already on a call`),null;if(tn(z.current)!==`native-sdk`){let e=await Ya(Ka,y);if(y(e),e===`denied`)return K(`OutboundBlocked`,{reason:`microphone-denied`}),q.error(Zo),null}if(Fe.current!==U||L.current!==t||V.current||B.current)return null;tn(z.current)!==`native-sdk`&&(de.current=Date.now()+Go);let n=Ie({organizationId:U,direction:`outbound`,counterpart:e.to,masked:Me(e.to),displayName:e.displayName??null,conversationId:e.conversationId??null,isWhatsApp:e.viaWhatsApp===!0});if(tn(z.current)===`native-sdk`)try{return await t.connect({to:e.to,params:{...e.conversationId?{ConversationId:e.conversationId}:{},...e.phoneNumberId?{PhoneNumberId:e.phoneNumberId}:{},...e.viaWhatsApp?{ViaWhatsApp:`true`}:{},...e.agentContactId?{AgentContactId:e.agentContactId}:{},AgentName:e.agentName??Ue}}),null}catch(e){return K(`OutboundFailed`,vo(e)),W(n)&&q.error(e instanceof Error?e.message:`Could not place the call`),null}de.current=Date.now()+Go;try{let t=await Ke({body:{organizationId:U,to:e.to,clientIdentity:R.current??``,conversationId:e.conversationId,contactId:e.agentContactId,phoneNumberId:e.phoneNumberId,agentName:e.agentName??Ue,...e.viaWhatsApp?{viaWhatsApp:!0}:{}}});if(t.error)throw K(`OutboundFailed`,{reason:`api`,httpStatus:t.response?.status}),Error(String(t.error));return K(`OutboundAccepted`,{reason:`api`}),Le(n,t.data),t.data??null}catch(e){if(K(`OutboundFailed`,vo(e)),W(n)){let t=e instanceof Error?e.message:`Could not place the call`;q.error(t)}return null}},[rt,Ue,U,K,Ie,W,Le]),Ot=Do({activeCall:O,incoming:w,isMuted:A,provider:b,onAnswer:e=>void(e?dt(e):ut()),onEnd:()=>{Ee(null),B.current?pt():gt()},onSetMuted:_t});De.current=Ot;let kt=(0,Z.useMemo)(()=>O?{...O,durationSeconds:O.isConnecting?0:Math.max(0,Math.floor((se-O.startedAt)/1e3))}:null,[O,se]),At=(0,Z.useMemo)(()=>({status:m,microphone:v,isEnabled:s,isPreferred:He,isLeaderTab:l,isRegistered:G,identity:S,provider:b,error:g,incoming:w,declinedCallIds:E,answeredElsewhere:M,dismissAnsweredElsewhere:$e,activeCall:kt,isMuted:A,inputDevices:P,outputDevices:F,isOutputSelectionSupported:te,isSpeakerAvailable:Ot.isAvailable,isSpeakerOn:Ot.isOn,setSpeakerOn:Ot.setOn,selectedInputDeviceId:re,selectedOutputDeviceId:ae,enable:et,disable:lt,answer:ut,reject:pt,hangup:
5ht,setMuted:_t,sendDigits:St,sendNativeDigits:tn(z.current)===`native-sdk`?bt:void 0,setInputDevice:wt,setOutputDevice:Tt,placeCall:Et,listenIn:at,stepIn:ot,takeCallsHere:tt,rejoin:st,transport:d}),[m,v,s,He,l,G,S,b,g,w,E,M,$e,kt,A,P,F,te,Ot,re,ae,et,lt,ut,pt,ht,_t,St,bt,wt,Tt,Et,at,ot,tt,st,d]);return(0,Q.jsxs)(Ln.Provider,{value:At,children:[(0,Q.jsx)(no,{}),(0,Q.jsx)(uo,{}),e]})}function $o({name:e,avatarUrl:t,initials:n,avatarIcon:r,title:i,titleTone:o=`default`,subtitle:s,subtitleTone:c=`muted`,badges:l,footer:u,meta:d,to:f,isSelected:p=!1,action:m}){let h=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(x,{className:`shrink-0`,fallbackIcon:r,initials:n,name:e,size:`md`,src:t}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col gap-0.5 border-b border-divider py-3`,children:[(0,Q.jsxs)(`span`,{className:`flex min-w-0 items-baseline gap-2`,children:[(0,Q.jsx)(y,{as:`span`,className:`min-w-0 flex-1 truncate`,tone:o,variant:`body`,children:i}),l?(0,Q.jsx)(`span`,{className:`flex shrink-0 items-center gap-1`,children:l}):null,d?(0,Q.jsx)(y,{as:`span`,className:`shrink-0 whitespace-nowrap`,tone:`subtle`,variant:`caption`,children:d}):null]}),s?(0,Q.jsx)(y,{as:`span`,className:`truncate`,tone:c,variant:`caption`,children:s}):null,u?(0,Q.jsx)(`span`,{className:`flex flex-wrap items-center gap-1 pt-0.5`,children:u}):null]})]});return(0,Q.jsxs)(`li`,{className:`flex items-center gap-3`,children:[f?(0,Q.jsx)(a,{"aria-current":p?`true`:void 0,className:He(`flex min-w-0 flex-1 items-center gap-3 rounded-medium transition-colors`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus focus-visible:ring-offset-2`,p?`bg-primary-100`:`hover:bg-default-50`),to:f,children:h}):(0,Q.jsx)(`div`,{className:`flex min-w-0 flex-1 items-center gap-3`,children:h}),m?(0,Q.jsx)(`span`,{className:`shrink-0`,children:m}):null]})}function es({label:e,onCall:t,isDisabled:n}){return(0,Q.jsx)(`button`,{"aria-label":e,className:He(`grid h-touch w-touch place-items-center rounded-full border`,`transition-colors duration-instant`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus focus-visible:ring-offset-2`,n?`cursor-not-allowed border-divider text-default-300`:`border-secondary-200 text-secondary hover:bg-secondary-50 active:scale-[0.98]`),disabled:n,onClick:t,type:`button`,children:(0,Q.jsx)(Pe,{"aria-hidden":`true`,className:`h-4 w-4`})})}function ts({label:e,icon:t,to:n,onPress:r,isDisabled:i,disabledReason:o,isLoading:s=!1}){let c=He(`grid h-touch w-touch place-items-center rounded-full border`,`transition-colors duration-instant`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus focus-visible:ring-offset-2`,i?`cursor-not-allowed border-divider text-default-300`:`border-secondary-200 text-secondary hover:bg-secondary-50 active:scale-[0.98]`,s&&`cursor-progress`),l=s?(0,Q.jsx)(ge,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}):(0,Q.jsx)(t,{"aria-hidden":`true`,className:`h-4 w-4`});return(0,Q.jsxs)(`span`,{className:`flex w-16 flex-col items-center gap-1`,children:[n&&!i&&!s?(0,Q.jsx)(a,{"aria-label":e,className:c,to:n,children:l}):(0,Q.jsx)(`button`,{"aria-busy":s||void 0,"aria-label":i&&o?`${e}. ${o}`:e,className:c,disabled:i||s,onClick:r,type:`button`,children:l}),(0,Q.jsx)(y,{as:`span`,className:`text-center`,tone:i?`subtle`:`muted`,variant:`caption`,children:e})]})}function ns({direction:e,missed:t}){return(0,Q.jsx)(e===`Outbound`?l:u,{"aria-hidden":`true`,className:He(`inline-block h-3 w-3 shrink-0 align-[-0.1em]`,t?`text-danger`:`text-default-400`)})}function rs({children:e,id:t}){return(0,Q.jsx)(`li`,{className:`sticky top-0 z-10 scroll-mt-4 bg-background pb-1 pt-4`,id:t,children:(0,Q.jsx)(y,{as:`h2`,className:`text-default-400`,variant:`eyebrow`,children:e})})}var is=/\/phone(\/|$)/;function as({className:e}){let{pathname:t}=o(),{selectedOrganizationId:n}=Dn(),{status:r,isEnabled:i,isPreferred:a,error:s,microphone:c,takeCallsHere:l}=In(),u=Ta(),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(`unknown`),_=ya({status:r,isEnabled:i,isPreferred:a,ringable:u.numbers,own:u.own,isSettled:u.isSettled,isDismissed:!n||d===n||Ca(n)}),v=_!==null&&!is.test(t);if((0,Z.useEffect)(()=>
5{if(!v)return;let e=!1;return qa().then(t=>{e||g(t)}),()=>{e=!0}},[v]),!v||!_||!n)return null;let y=xa(_,{microphoneDenied:c===`unknown`?h===`denied`:c===`denied`,error:s,isNativeApp:Ht()}),b=async()=>{m(!0);try{await l()}catch(e){q.error(e instanceof Error?e.message:`Could not turn on calls here`)}finally{m(!1)}};return(0,Q.jsx)(`div`,{className:He(`shrink-0 px-4 pt-3`,e),children:(0,Q.jsx)(B,{icon:Pe,intent:y.intent,title:y.title,children:(0,Q.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Q.jsx)(`p`,{children:y.body}),(0,Q.jsxs)(T,{className:`shrink-0`,children:[(0,Q.jsx)(C,{className:`max-sm:min-h-touch`,size:`sm`,variant:`ghost`,onPress:()=>{wa(n),f(n)},children:`Not now`}),(0,Q.jsx)(C,{className:`max-sm:min-h-touch`,icon:Pe,isLoading:p,size:`sm`,variant:`secondary`,onPress:()=>void b(),children:y.actionLabel})]})]})})})}function os(e,t=200){return Y({queryKey:[...jn.list(e),t],enabled:!!e,queryFn:async({signal:n})=>{let r=await st({signal:n,query:{organizationId:e??void 0,limit:t}});if(r.error)throw Error(JSON.stringify(r.error));return r.data??[]},staleTime:3e4})}var ss=[...`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``),`Æ`,`Ø`,`Å`,`#`];function cs(e){return!e.firstName&&!e.lastName&&!e.email&&!e.phone}function ls(e){return cs(e)?`Unnamed contact`:e.displayName||`Unnamed contact`}function us(e){let t=e.lastName?.trim(),n=e.firstName?.trim();return t?`${t} ${n??``}`.trim():(e.displayName??``).trim()}function ds(e){if(cs(e))return`#`;let t=us(e).charAt(0).toLocaleUpperCase();return ss.includes(t)?t:`#`}function fs(e){let t=new Map;for(let n of e){let e=ds(n),r=t.get(e);r?r.push(n):t.set(e,[n])}let n=[];for(let e of ss){let r=t.get(e);r&&r.length!==0&&(r.sort((e,t)=>us(e).toLocaleUpperCase().localeCompare(us(t).toLocaleUpperCase())),n.push({letter:e,contacts:r}))}return n}function ps(e){return`contact-band-${e===`#`?`hash`:e}`}var ms=30,hs=8;function gs(){return(0,Q.jsx)(_,{icon:Be,intent:`accent`,size:`sm`,children:`Group`})}function _s({contact:e}){if(cs(e))return(0,Q.jsx)(`span`,{className:`italic`,children:ls(e)});let t=e.firstName?.trim(),n=e.lastName?.trim();return!n&&Oe(e.displayName)?(0,Q.jsx)(`span`,{className:`font-semibold tabular-nums`,children:H(e.displayName)}):n?(0,Q.jsxs)(Q.Fragment,{children:[t?`${t} `:``,(0,Q.jsx)(`span`,{className:`font-semibold`,children:n})]}):(0,Q.jsx)(`span`,{className:`font-semibold`,children:ls(e)})}function vs(e){if(e.isGroup)return e.partnerOrganizationName??null;let t=[];return e.email&&t.push((0,Q.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-1`,children:[(0,Q.jsx)(Te,{"aria-hidden":`true`,className:`h-3 w-3 shrink-0 text-default-400`}),(0,Q.jsx)(`span`,{className:`truncate`,children:e.email})]},`email`)),e.phone&&t.push((0,Q.jsxs)(`span`,{className:`inline-flex shrink-0 items-center gap-1`,children:[(0,Q.jsx)(Pe,{"aria-hidden":`true`,className:`h-3 w-3 shrink-0 text-default-400`}),(0,Q.jsx)(`span`,{className:`tabular-nums`,children:H(e.phone)||e.phone})]},`phone`)),e.partnerOrganizationName&&t.push((0,Q.jsx)(`span`,{className:`truncate`,children:e.partnerOrganizationName},`partner`)),t.length===0?null:(0,Q.jsx)(`span`,{className:`flex min-w-0 items-center gap-3`,children:t})}function ys(e){return(e??``).split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>(0,Q.jsx)(_,{intent:`primary`,size:`sm`,children:e},e))}
5function bs({book:e,me:t,onCall:n,canCall:r=!1,contactPath:i,selectedContactId:a,showGuests:o,onShowGuestsChange:s,rowMenu:c}){let l=fs(e.contacts),u=new Set(l.map(e=>e.letter)),d=(0,Z.useRef)(null),[f,p]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{let e=d.current;if(!e)return;let t=new IntersectionObserver(e=>p(e[0]?.isIntersecting??!1),{rootMargin:`400px`});return t.observe(e),()=>t.disconnect()},[]);let{hasNextPage:m,isFetchingNextPage:h,fetchNextPage:g,contacts:v,isLoading:b,pagesLoaded:x,isSearch:S}=e,C=v.length<ms,w=C&&x>=hs;(0,Z.useEffect)(()=>{if(!(!m||h||b)){if(C){x<hs&&g();return}f&&g()}},[m,h,b,f,C,x,g]);let T=e=>{let t=Oe(e.phone)&&!e.isGroup,o=ls(e),s=t&&n?(0,Q.jsx)(es,{isDisabled:!r,label:r?`Call ${o}`:`Turn on calls in this browser to ring out`,onCall:()=>n(e)}):null,l=c?.(e)??null,u=[];e.isGroup&&u.push((0,Q.jsx)(gs,{},`group`)),e.duplicateCount&&u.push((0,Q.jsxs)(_,{intent:`warning`,size:`sm`,children:[e.duplicateCount+1,` copies`]},`copies`));let d=ys(e.tags),f=vs(e);return(0,Q.jsx)($o,{action:s||l?(0,Q.jsxs)(`span`,{className:`flex items-center gap-1`,children:[s,l]}):null,avatarIcon:e.isGroup?Be:void 0,avatarUrl:e.avatarUrl,badges:u.length>0?u:void 0,footer:d.length>0?d:void 0,initials:Oe(e.displayName)?Ae(e.displayName):void 0,isSelected:!!e.id&&e.id===a,name:o,subtitle:f,title:(0,Q.jsx)(_s,{contact:e}),to:i(e)},e.id)};return(0,Q.jsxs)(`div`,{className:`flex flex-col`,children:[(0,Q.jsx)(`div`,{className:`border-b border-divider pb-3`,children:S?(0,Q.jsx)(y,{as:`p`,tone:`subtle`,variant:`caption`,children:`Search covers every contact, guests and leads included.`}):(0,Q.jsx)(j,{description:o?`Guests, leads and everyone else`:`Staff, owners and partners only`,isSelected:o,label:`Show everyone`,onValueChange:s,size:`sm`})}),(0,Q.jsxs)(`div`,{className:`flex items-start gap-1`,children:[(0,Q.jsxs)(`ul`,{className:`flex min-w-0 flex-1 flex-col`,children:[t&&!S?(0,Q.jsx)($o,{name:t.name,subtitle:t.detail,title:t.name}):null,e.isLoading?(0,Q.jsx)(`li`,{className:`py-6`,children:(0,Q.jsx)(fe,{rows:8,withHeader:!0})}):null,!e.isLoading&&e.contacts.length===0?(0,Q.jsx)(`li`,{className:`py-6`,children:(0,Q.jsx)(ne,{description:S?`No contact matches that name, email, number or tag.`:o?`Guests, owners, partners and colleagues appear here once they are in this organization's contacts.`:`Every contact loaded so far is a guest. Turn on Show guests to see them.`,icon:Be,size:`inline`,title:S?`No matches`:`No contacts to show`})}):null,S?e.contacts.map(T):null,S?null:l.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`ul`,{className:`flex flex-col`,children:[(0,Q.jsx)(rs,{id:ps(e.letter),children:e.letter}),e.contacts.map(T)]})},e.letter)),(0,Q.jsx)(`li`,{"aria-hidden":`true`,className:`py-4`,ref:d,children:e.isFetchingNextPage?(0,Q.jsx)(fe,{rows:2}):null}),w&&!e.isFetchingNextPage&&!S?(0,Q.jsx)(`li`,{className:`pb-4`,children:(0,Q.jsx)(B,{intent:`info`,children:`Most of this book is guests. Turn on Show guests, or search for the person you want.`})}):null,!e.hasNextPage&&!e.isLoading&&e.contacts.length>0?(0,Q.jsx)(`li`,{className:`pb-4`,children:(0,Q.jsx)(y,{as:`p`,className:`text-center`,tone:`subtle`,variant:`caption`,children:S?`${e.contacts.length} of ${e.total}${e.totalIsExact?``:`+`} matches`:e.total>0?`End of the book · ${e.total} contacts`:`End of the book`})}):null]}),S?null:(0,Q.jsx)(`nav`,{"aria-label":`Jump to letter`,className:`sticky top-1/2 flex w-5 shrink-0 -translate-y-1/2 flex-col items-center gap-px`,children:ss.map(e=>{let t=u.has(e);return(0,Q.jsx)(`a`,{"aria-disabled":!t,className:He(`px-1 text-[10px] font-semibold leading-[1.1] tracking-tight`,`rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus`,t?`text-primary hover:text-primary-600`:`pointer-events-none text-default-300`),href:t?`#${ps(e)}`:void 0,children:e},e)})})]})]})}function xs({isOpen:e,onClose:t,channel:n,contact:r,conversationId:i,organizationId:a,onSaved:o}){let s=J(),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{e&&l(``)},[e]);let f=n===`Phone`?`call`:`SMS`,p=r?.displayName||r?.fullName||`contact`,m=r?.phone?`${n===`Phone`?`tel`:`sms`}:${r.phone}`:void 0;async function g(){if(!r?.id&&!i)return;let e=c.trim();if(!e){q.error(`Add a note before saving.`);return}d(!0);try{let c=i,l=a??r?.organizationId??void 0;if(!c){if(!r?.id)throw Error(`Could not open a conversation for this contact`);let e=await dt({body:{organizationId:r.organizationId??null,contactIds:[r.id],matchByContact:!0,forceNew:!1}});if(e.error)throw Error(JSON.stringify(e.error));let t=e.data;c=t?.id,l=t?.organizationId??l}if(!c)throw Error(`Could not open a conversation for this contact`);
5let u=await ht({body:{organizationId:l,conversationId:c,type:`InternalNote`,content:`${n===`Phone`?`📞 Phone call`:`💬 SMS`} — ${e}`},meta:{successToastMsg:`Note saved to conversation`,errorToastMsg:`Could not save note`}});if(u.error)throw Error(JSON.stringify(u.error));await s.invalidateQueries({queryKey:$.lists()}),await s.invalidateQueries({queryKey:$.messages(c)}),o?.(c),t()}catch(e){q.error(e instanceof Error?e.message:`Could not save note`)}finally{d(!1)}}return(0,Q.jsx)(L,{isOpen:e,onClose:u?void 0:t,size:`lg`,children:(0,Q.jsxs)(D,{children:[(0,Q.jsxs)(h,{className:`flex items-center gap-2`,children:[n===`Phone`?(0,Q.jsx)(Pe,{size:18,className:`text-primary`}):(0,Q.jsx)(De,{size:18,className:`text-primary`}),(0,Q.jsxs)(`span`,{children:[`Log `,f,` with `,p]})]}),(0,Q.jsx)(O,{className:`space-y-3`,children:(0,Q.jsx)(V,{label:`What did you talk about?`,placeholder:`Summary of the conversation…`,value:c,minRows:4,onChange:e=>l(e.target.value)})}),(0,Q.jsxs)(se,{className:`justify-between`,children:[m?(0,Q.jsx)(be,{as:`a`,href:m,variant:`flat`,startContent:n===`Phone`?(0,Q.jsx)(Pe,{size:16}):(0,Q.jsx)(De,{size:16}),children:n===`Phone`?`Start call`:`Start SMS`}):(0,Q.jsx)(`span`,{}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(be,{variant:`light`,onPress:t,isDisabled:u,children:`Cancel`}),(0,Q.jsx)(be,{color:`primary`,startContent:(0,Q.jsx)(yr,{size:16}),onPress:g,isLoading:u,children:`Save as internal note`})]})]})]})})}var Ss=[{value:`Guest`,label:`Guest`},{value:`PropertyOwner`,label:`Property owner`},{value:`Partner`,label:`Partner`}];function Cs({aiSimulated:e,personaId:t,onAiSimulatedChange:n,onPersonaIdChange:r}){let[i,a]=(0,Z.useState)(`Guest`),{data:o=[],isLoading:s}=Y({queryKey:[`simulation-personas`,i],enabled:e&&!!i,queryFn:async()=>{let{data:e}=await wt({query:i?{contactType:i}:void 0,throwOnError:!0});return e??[]}});return(0,Z.useEffect)(()=>{!e&&t!==null&&r(null)},[e,t,r]),(0,Z.useEffect)(()=>{e&&t&&o.length>0&&!o.some(e=>e.personaId===t)&&r(null)},[e,t,o,r]),(0,Q.jsxs)(`div`,{className:`space-y-3 rounded-md border border-divider p-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`text-sm font-medium`,children:`AI-simulated`}),(0,Q.jsx)(`div`,{className:`text-xs text-default-500`,children:`Replies in this contact's chats will be generated by a code-defined persona. Cannot be changed after the contact is created.`})]}),(0,Q.jsx)(ue,{isSelected:e,onValueChange:n,"aria-label":`AI-simulated`})]}),e&&(0,Q.jsx)(w,{label:`Persona type`,selectedKeys:[i],onSelectionChange:e=>{let t=Array.from(e)[0]?.toString();t&&(a(t),r(null))},children:Ss.map(e=>(0,Q.jsx)(I,{children:e.label},e.value))}),e&&(0,Q.jsx)(w,{label:`Persona`,placeholder:i?s?`Loading…`:o.length===0?`No personas for ${i}`:`Pick persona`:`Pick a contact type first`,isDisabled:!i||s||o.length===0,selectedKeys:t?[t]:[],onSelectionChange:e=>{let t=Array.from(e)[0]?.toString();r(t??null)},children:o.map(e=>(0,Q.jsx)(I,{textValue:e.displayName??e.personaId??``,children:(0,Q.jsxs)(`div`,{className:`flex flex-col`,children:[(0,Q.jsx)(`span`,{className:`text-sm`,children:e.displayName}),e.description&&(0,Q.jsx)(`span`,{className:`text-xs text-default-500`,children:e.description})]})},e.personaId??``))})]})}var ws=/^slack:([UW][A-Z0-9]{2,})$/i,Ts=/^telegram:([0-9]+)$/;function Es(e){if(!e)return[];let t=[];e.externalId&&t.push(e.externalId.trim());for(let n of e.externalIds??[])n.isActive!==!1&&n.externalEntityId&&t.push(n.externalEntityId.trim());return t}function Ds(e,t){for(let n of Es(e)){let e=t.exec(n);if(e)return e[1]}return null}function Os(e){let t=Ds(e,ws);return t?t.toUpperCase():null}function ks(e){return Ds(e,Ts)}var As={firstName:``,lastName:``,email:``,phone:``,address:``,payoutAccountNumber:``,notes:``,tags:``,externalId:``,preferredContactMethod:``};function js(e){return{firstName:e.firstName??``,lastName:e.lastName??``,email:e.email??``,phone:e.phone??``,address:e.address??``,payoutAccountNumber:e.payoutAccountNumber??``,notes:e.notes??``,tags:e.tags??``,externalId:e.externalId??``,preferredContactMethod:e.preferredContactMethod??``,partnerOrganizationId:e.partnerOrganizationId??void 0,clearPartnerOrganization:!1,userId:e.userId??void 0}}function Ms({contactId:e,organizationId:t,initialPhone:n,isOpen:r=!0,onCreated:i}){let a=!e,{data:o,isLoading:s}=Yn(e??void 0),c=Hn(),l=Un(),u=o?.organizationId??t??void 0,[d,f]=(0,Z.useState)(As),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{o?f(js(o)):e||f({...As,phone:n??``})},[o,e,n]),(0,Z.useEffect)(()=>{r||(f(o?js(o):{...As,phone:n??``}),m(null),g(!1),v(null))},[r,o,n]),{contactId:e,isCreate:a,contact:o??void 0,isLoading:s,isGroup:o?.isGroup===!0,orgId:u,form:d,setForm:f,orgRole:p,setOrgRole:m,aiSimulated:h,setAiSimulated:g,personaId:_,setPersonaId:v,save:async()=>
5{if(a){if(!u)return q.error(`No organization selected — cannot create a contact.`),!1;if(h&&!_)return q.error(`Pick a persona for the AI-simulated contact.`),!1;let e=await c.mutateAsync({organizationId:u,firstName:d.firstName,lastName:d.lastName,email:d.email,phone:d.phone,address:d.address,payoutAccountNumber:d.payoutAccountNumber,tags:d.tags,organizationRole:p??void 0,partnerOrganizationId:d.partnerOrganizationId??void 0,simulatedPersonaId:h&&_?_:void 0});return e?.id&&i?.(e.id),!0}return e?(await l.mutateAsync({id:e,...d,clearPartnerOrganization:!d.partnerOrganizationId&&!!o?.partnerOrganizationId}),!0):!1},isSaving:c.isPending||l.isPending}}function Ns({editor:e,avatarLayout:t=`row`,conversationPath:n=e=>`/inbox?conversationId=${encodeURIComponent(e)}`,onNavigateAway:r}){let{contact:a,contactId:o,isCreate:s,isGroup:c,orgId:l,form:u,setForm:d}=e,{data:f=[]}=nr({organizationId:l,enabled:!!l}),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),b=i(),x=e=>!c||!!e,S=Os(a),w=async e=>{if(a?.id){g(e);try{let t=await dt({body:{organizationId:a.organizationId??null,contactIds:[a.id],matchByContact:!0,forceNew:!1}});if(t.error)throw Error(JSON.stringify(t.error));let i=t.data?.id;if(!i)throw Error(`Could not open a conversation for this contact`);r?.();let o=n(i);b(`${o}${o.includes(`?`)?`&`:`?`}channel=${e}`)}catch(t){q.error(t instanceof Error?t.message:`Could not open ${e} conversation`)}finally{g(null)}}};if(e.isLoading)return(0,Q.jsx)(`div`,{className:`flex justify-center py-8`,children:(0,Q.jsx)(ye,{size:`sm`})});let T=c?(0,Q.jsx)(v,{description:`Shown wherever this chat appears. Not a person — the group is the participant.`,label:`Group name`,value:u.firstName??``,onChange:e=>d({...u,firstName:e.target.value})}):(0,Q.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Q.jsx)(v,{label:`First name`,value:u.firstName??``,onChange:e=>d({...u,firstName:e.target.value})}),(0,Q.jsx)(v,{label:`Last name`,value:u.lastName??``,onChange:e=>d({...u,lastName:e.target.value})})]});return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,Q.jsxs)(`section`,{className:`flex flex-col gap-4`,children:[s?null:(0,Q.jsx)(Is,{contact:a??null,layout:t}),T]}),(0,Q.jsxs)(`section`,{className:`flex flex-col gap-4`,children:[x(u.email)&&(0,Q.jsx)(v,{label:`Email`,type:`email`,value:u.email??``,onChange:e=>d({...u,email:e.target.value})}),x(u.phone)&&(0,Q.jsx)(v,{label:`Phone`,type:`tel`,value:u.phone??``,onChange:e=>d({...u,phone:e.target.value})}),a?.id&&(c||a?.phone||S)?(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[!c&&a.phone&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(C,{icon:Pe,size:`sm`,variant:`tertiary`,onPress:()=>m(`Phone`),children:`Call`}),(0,Q.jsx)(C,{icon:De,size:`sm`,variant:`tertiary`,onPress:()=>m(`SMS`),children:`SMS`})]}),(c||a.phone)&&(0,Q.jsx)(C,{icon:Ee,isDisabled:h!==null&&h!==`WhatsApp`,isLoading:h===`WhatsApp`,size:`sm`,variant:`tertiary`,onPress:()=>w(`WhatsApp`),children:c?`Open group chat`:`WhatsApp`}),!c&&S&&(0,Q.jsx)(C,{icon:Ce,isDisabled:h!==null&&h!==`Slack`,isLoading:h===`Slack`,size:`sm`,variant:`tertiary`,onPress:()=>w(`Slack`),children:`Slack`})]}):null,x(u.address)&&(0,Q.jsx)(v,{label:`Address`,value:u.address??``,onChange:e=>d({...u,address:e.target.value})}),x(u.payoutAccountNumber)&&(0,Q.jsx)(v,{description:`Bank account this owner is paid out to (fallback when a property sets none)`,label:`Payout account`,placeholder:`e.g. 1234.56.78901`,value:u.payoutAccountNumber??``,onChange:e=>d({...u,payoutAccountNumber:e.target.value})}),!s&&(0,Q.jsx)(_e,{description:c?`Read by the AI agent: describe what this chat is for and which work belongs in it.`:`Read by the AI agent: describe their role/responsibilities and who should get which kind of work. Shown on the contact's card in the org map.`,label:c?`Purpose & notes`:`Role & notes`,minRows:3,placeholder:c?`What belongs in this chat and who is in it, e.g. 'Cleaning crew for Bergen — dispatch cleaning jobs here'`:`What this person does and any standing assignment rules, e.g. 'Operations manager — always assign management tasks here' or 'Handyman — Justin Mobile jobs go to them'`,value:u.notes??``,onChange:e=>d({...u,notes:e.target.value})}),s&&(0,Q.jsx)(tr,{value:e.orgRole,onChange:t=>e.setOrgRole(t??null)}),(0,Q.jsx)(E,{label:`Partner company`,placeholder:`No partner company`,selectedKeys:u.partnerOrganizationId?[u.partnerOrganizationId]:[`__none`],onSelectionChange:e=>{let t=Array.from(e)[0]?.toString();t!==void 0&&d({...u,partnerOrganizationId:t===`__none`?void 0:t,clearPartnerOrganization:t===`__none`})},children:[(0,Q.jsx)(I,{children:`No partner company`},`__none`),...f.map(e=>{let t=e.partnerOrganizationId??e.partnerOrganization?.id??``,n=e.partnerOrganization?.name??`Unnamed partner`;return(0,Q.jsx)(I,{children:n},t)})]}),(0,Q.jsx)(v,{description:`Comma separated`,label:`Tags`,value:u.tags??``,onChange:e=>d({...u,tags:e.target.value})}),!s&&(0,Q.jsx)(_e,{label:`Preferred contact method`,minRows:2,placeholder:`Free text for AI agents, e.g. 'Email for urgent issues, WhatsApp for updates'`,value:u.preferredContactMethod??``,onChange:e=>d({...u,preferredContactMethod:e.target.value})}),s&&(0,Q.jsx)(Cs,{aiSimulated:e.aiSimulated,personaId:e.personaId,onAiSimulatedChange:e.setAiSimulated,onPersonaIdChange:e.setPersonaId}),!s&&a?.simulatedPersonaId&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(y,{as:`span`,tone:`muted`,variant:`caption`,children:`AI-simulated:`}
5),(0,Q.jsx)(_,{intent:`accent`,size:`sm`,children:a.simulatedPersonaId}),(0,Q.jsx)(y,{as:`span`,tone:`subtle`,variant:`caption`,children:`(immutable)`})]})]}),!s&&o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ps,{}),(0,Q.jsx)(Vs,{contactId:o,externalIds:a?.externalIds??[]}),(0,Q.jsx)(Ps,{}),(0,Q.jsx)(zs,{contact:a??null,organizationId:a?.organizationId,userId:u.userId,onUserIdChange:e=>d(t=>({...t,userId:e}))}),(0,Q.jsx)(Bs,{contact:a??null,onNavigateAway:r}),(0,Q.jsx)(Ps,{}),(0,Q.jsx)(Hs,{contactId:o,contact:a??null,organizationId:a?.organizationId})]}):null]}),(0,Q.jsx)(xs,{channel:p??`Phone`,contact:a??null,isOpen:p!==null,onClose:()=>m(null)})]})}function Ps(){return(0,Q.jsx)(`hr`,{className:`border-divider`})}var Fs={telegram:`From Telegram profile`,whatsapp:`From WhatsApp profile`,line:`From LINE profile`,slack:`From Slack profile`,manual:`Uploaded manually`};function Is({contact:e,layout:t}){let n=Wn(),r=qn(),i=(0,Z.useRef)(null);if(!e?.id)return null;let a=async t=>{let r=t.target.files?.[0];if(t.target.value=``,r&&e.id){if(!r.type.startsWith(`image/`)){q.error(`Please pick an image file.`);return}if(r.size>10485760){q.error(`Image must be at most 10 MB.`);return}try{await n.mutateAsync({id:e.id,file:r})}catch{}}},o=async()=>{if(e.id)try{await r.mutateAsync(e.id)}catch{}},s=e.avatarSource?Fs[e.avatarSource]:void 0,c=t===`centered`;return(0,Q.jsxs)(`section`,{className:He(`flex gap-3`,c?`flex-col items-center text-center`:`flex-row items-center gap-4`),children:[(0,Q.jsx)(x,{fallbackIcon:e.isGroup?Be:void 0,name:e.displayName||`?`,size:`lg`,src:e.avatarUrl}),(0,Q.jsxs)(`div`,{className:He(`flex min-w-0 flex-col gap-1.5`,c&&`items-center`),children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[(0,Q.jsx)(C,{icon:Re,isDisabled:r.isPending,isLoading:n.isPending,size:`sm`,variant:`tertiary`,onPress:()=>i.current?.click(),children:e.avatarUrl?`Change photo`:`Add photo`}),e.avatarUrl?(0,Q.jsx)(C,{icon:G,isDisabled:n.isPending,isLoading:r.isPending,size:`sm`,variant:`danger-ghost`,onPress:o,children:`Remove`}):null]}),(0,Q.jsx)(y,{tone:`subtle`,variant:`caption`,children:s??`Auto-filled from the contact's chat profile when they message you.`})]}),(0,Q.jsx)(`input`,{ref:i,accept:`image/*`,className:`hidden`,type:`file`,onChange:a})]})}var Ls=`__no-membership`;function Rs(e){return e.user?.email??e.displayName??e.userId??`Unknown user`}function zs({contact:e,organizationId:t,userId:n,onUserIdChange:r}){let i=Tn(),{data:a=[]}=yn(t),{data:o=[]}=Cn(t),{organizations:s}=Dn(),{data:c=[]}=En(),[l,u]=(0,Z.useState)(`PropertyOwner`),{isGlobalAdmin:d}=gn(),f=Sn(t),p=d()||f===`Admin`,m=xn(),h=bn(),g=J(),[v,x]=(0,Z.useState)(e?.organizationRole??void 0);(0,Z.useEffect)(()=>{x(e?.organizationRole??void 0),e?.organizationRole&&u(e.organizationRole)},[e?.organizationRole]);let S=async n=>{if(!t||!e?.id||(n??null)===(v??null))return;let r=v;x(n??void 0);try{n?await m.mutateAsync({organizationId:t,memberId:e.id,roleData:{role:n}}):await h.mutateAsync({organizationId:t,memberId:e.id}),g.invalidateQueries({queryKey:[`contacts`]}),g.invalidateQueries({queryKey:[`organizations`,t,`members`]}),q.success(n?`Organization role updated.`:`Organization membership removed.`)}catch{x(r),q.error(`Could not update organization role.`)}},w=(0,Z.useMemo)(()=>a.find(t=>t.contactId===e?.id&&t.state===`Pending`),[a,e?.id]),T=(0,Z.useMemo)(()=>s.find(e=>e.id===t)?.name,[s,t]),D=(0,Z.useMemo)(()=>{let t=new Map;for(let e of o)e.userId&&!t.has(e.userId)&&t.set(e.userId,Rs(e));return e?.userId&&!t.has(e.userId)&&t.set(e.userId,e.user?.email??e.displayName??e.userId),n&&!t.has(n)&&t.set(n,n),Array.from(t,([e,t])=>({id:e,label:t})).sort((e,t)=>e.label.localeCompare(t.label))},[o,e?.userId,e?.user?.email,e?.displayName,n]),O=(0,Z.useMemo)(()=>{let e=new Map;for(let t of c)t.role&&e.set(t.role,t.label??t.role);return v&&!e.has(v)&&e.set(v,v),Array.from(e,([e,t])=>({role:e,label:t}))},[c,v]),k=e?.isGroup===!0,A=n??``,j=A!==(e?.userId??``),M=!!A&&A===e?.userId,N=async()=>{if(!t||!e?.id)return;let n=e.email?.trim();if(!n){q.error(`Contact has no email address — add one before inviting.`);return}try{await i.mutateAsync({organizationId:t,input:{email:n,role:l,contactId:e.id}}),q.success(`Invitation sent and link copied to clipboard.`)}catch{}};return(0,Q.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,Q.jsx)(b,{as:`h3`,children:`Application user`}),A?(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 rounded-medium border border-divider px-3 py-2`,children:[(0,Q.jsx)(we,{className:`shrink-0 text-success`,size:14}),(0,Q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(y,{className:`font-medium`,tone:`success`,variant:`caption`,children:`Linked`}),(0,Q.jsx)(y,{className:`truncate`,tone:`muted`,variant:`caption`,children:D.find(e=>e.id===A)?.label??A}),T?(0,Q.jsx)(y,{className:`truncate`,tone:`subtle`,variant:`caption`,children:T}):null]}),M?p?(0,Q.jsx)(E,{className:`max-w-44 shrink-0`,hideLabel:!0,isDisabled:m.isPending,isLoading:m.isPending,label:`Organization role`,selectedKeys:v?[v]:[],onSelectionChange:e=>{let t=Array.from(e)[0];t&&S(t)},children:O.map(e=>(0,Q.jsx)(I,{children:e.label},e.role))}):v?(0,Q.jsx)(_,{intent:`success`,size:`sm`,children:v}):null:null]}):w?(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 rounded-medium border border-divider px-3 py-2`,children:[(0,Q.jsx)(ze,{className:`shrink-0 text-warning`,size:14}),(0,Q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(y,{className:`font-medium`,tone:`warning`,variant:`caption`,children:`Invite pending`}),(0,Q.jsx)(y,{className:`truncate`,tone:`muted`,variant:`caption`,children:w.email})]}),(0,Q.jsx)(_,{intent:`warning`,size:`sm`,children:w.role??`PropertyOwner`})]}):(0,Q.jsx)(y,{tone:`subtle`,variant:`caption`,children:`No application user linked to this contact.`}),!A&&e?.id?p?(0,Q.jsx)(E,{description:`Applied immediately. The contact appears as an organization member now; app access follows once they sign in and are linked to a user.`,isDisabled:m.isPending||h.isPending,label:`Membership role`,selectedKeys:[v??Ls],onSelectionChange:e=>{let t=Array.from(e)[0]?.toString();t&&S(t===Ls?null:t)},children:[(0,Q.jsx)(I,{className:`text-default-500`,children:`— No membership —`},Ls),...O.map(e=>(0,Q.jsx)(I,{children:e.label},e.role))]}):v?(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(y,{as:`span`,tone:`muted`,variant:`caption`,children:`Membership role`}),(0,Q.jsx)(_,{intent:`neutral`,size:`sm`,children:v})]}):null:null,(0,Q.jsx)(ce,{label:`Linked application user`,onChange:e=>r(e??``),options:D.map(e=>({value:e.id,label:e.label})),placeholder:`— Not linked —`,value:A||null}),j?(0,Q.jsx)(y,{tone:`warning`,variant:`caption`,children:A?`User link will change when you save.`:`User will be unlinked when you save.`}):null,!A&&!w&&!k?(0,Q.jsxs)(`div`,{className:`flex items-end gap-2`,children:[(0,Q.jsx)(E,{className:`max-w-50`,label:`Invite as`,selectedKeys:[l],onSelectionChange:e=>{let t=Array.from(e)[0];t&&u(t)},children:c.map(e=>(0,Q.jsx)(I,{children:e.label??e.role},e.role??``))}),(0,Q.jsx)(C,{icon:ze,isDisabled:i.isPending,isLoading:i.isPending,variant:`secondary`,onPress:N,children:`Invite`})]}):null]})}function Bs({contact:e,onNavigateAway:t}){let{data:n,isLoading:r}=Bt({OwnerContactId:e?.id,OrganizationIds:e?.organizationId?[e.organizationId]:void 0,PageSize:100},{enabled:!!e?.id}),i=n?.data??[];return!r&&i.length===0?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ps,{}),(0,Q.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Q.jsx)(b,{as:`h3`,children:`Connected properties`}),r?null:(0,Q.jsxs)(y,{as:`span`,tone:`muted`,variant:`caption`,children:[i.length,` owned`]})]}
5),r?(0,Q.jsx)(`div`,{className:`flex justify-center py-3`,children:(0,Q.jsx)(ye,{size:`sm`})}):(0,Q.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:i.map(e=>{let n=[e.street,e.city].filter(Boolean).join(`, `);return(0,Q.jsxs)(a,{className:He(`flex w-full items-center gap-2 rounded-medium border border-divider px-3 py-2 text-left transition-colors hover:bg-default-100`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus focus-visible:ring-offset-2`),to:`/properties/${e.id}`,onClick:()=>t?.(),children:[(0,Q.jsx)(p,{className:`shrink-0 text-default-500`,size:14}),(0,Q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(y,{className:`truncate font-medium`,variant:`caption`,children:e.nickname||n||`Unnamed property`}),n?(0,Q.jsx)(y,{className:`truncate`,tone:`subtle`,variant:`caption`,children:n}):null]}),e.isActive===!1?(0,Q.jsx)(_,{intent:`warning`,size:`sm`,children:`Onboarding`}):null]},e.id)})})]})]})}function Vs({contactId:e,externalIds:t}){let{integrations:n}=rr(),r=$n(),i=er(),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(``),l=async()=>{if(!a||!s.trim()){q.error(`Pick an integration and enter an entity ID`);return}try{await r.mutateAsync({id:e,externalIntegrationId:a,externalEntityId:s.trim()}),o(``),c(``)}catch{}},u=async t=>{try{await i.mutateAsync({id:e,linkId:t})}catch{}};return(0,Q.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Q.jsx)(b,{as:`h3`,children:`External IDs`}),(0,Q.jsxs)(y,{as:`span`,tone:`muted`,variant:`caption`,children:[t.length,` linked`]})]}),t.length>0?(0,Q.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:t.map(e=>(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 rounded-medium border border-divider px-2 py-1.5`,children:[(0,Q.jsx)(_,{intent:`neutral`,size:`sm`,children:e.externalIntegrationType}),(0,Q.jsx)(y,{as:`span`,className:`truncate`,tone:`muted`,variant:`caption`,children:e.externalIntegrationName}),(0,Q.jsx)(y,{as:`span`,className:`flex-1 truncate font-mono`,variant:`caption`,children:e.externalEntityId}),(0,Q.jsx)(A,{icon:ie,isDisabled:!e.id||i.isPending,label:`Remove external ID`,size:`sm`,variant:`danger-ghost`,onPress:()=>e.id&&u(e.id)})]},e.id))}):(0,Q.jsx)(y,{tone:`subtle`,variant:`caption`,children:`No external IDs linked yet.`}),(0,Q.jsxs)(`div`,{className:`flex items-end gap-2`,children:[(0,Q.jsx)(E,{className:`flex-1`,label:`Integration`,placeholder:`Pick integration`,selectedKeys:a?[a]:[],onSelectionChange:e=>o(Array.from(e)[0]?.toString()??``),children:n.filter(e=>!!e.id).map(e=>(0,Q.jsx)(I,{children:`${e.name} (${e.type})`},e.id))}),(0,Q.jsx)(v,{className:`flex-1`,label:`External entity ID`,placeholder:`e.g. telegram:123456`,value:s,onChange:e=>c(e.target.value)}),(0,Q.jsx)(C,{icon:Ie,isDisabled:!a||!s.trim()||r.isPending,isLoading:r.isPending,variant:`secondary`,onPress:l,children:`Add`})]})]})}function Hs({contactId:e,contact:t,organizationId:n}){let r=Qn(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)([]),[u,d]=(0,Z.useState)([]),[f,p]=(0,Z.useState)(!0),m=o.trim(),{data:h=[]}=Kn({search:m.length>=2?m:void 0,organizationIds:n?[n]:void 0,includeAllTypes:!0}),x=(0,Z.useMemo)(()=>h.filter(t=>t.id&&t.id!==e).slice(0,8),[h,e]),S=Gn(t?.organizationRole,u.map(e=>e.organizationRole)),w=e=>{let t=e.id;t&&(l(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t]),d(n=>n.some(e=>e.id===t)?n.filter(e=>e.id!==t):[...n,e]))};return(0,Q.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Q.jsx)(b,{as:`h3`,children:`Merge contacts`}),(0,Q.jsx)(C,{icon:dr,size:`sm`,variant:`tertiary`,onPress:()=>a(e=>!e),children:i?`Hide merge tools`:`Merge another contact in`})]}),i&&(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-medium border border-divider p-3`,children:[(0,Q.jsx)(v,{hideLabel:!0,label:`Search contacts to merge`,placeholder:`Search by name, email or phone`,value:o,onChange:e=>s(e.target.value)}),m.length<2?(0,Q.jsx)(y,{tone:`subtle`,variant:`caption`,children:`Type at least 2 characters to search.`}):x.length===0?(0,Q.jsx)(y,{tone:`subtle`,variant:`caption`,children:`No matches.`}):(0,Q.jsx)(`div`,{className:`flex max-h-44 flex-col gap-1 overflow-y-auto`,children:x.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:He(`w-full rounded-medium border px-2 py-2 text-left text-caption transition-colors`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus focus-visible:ring-offset-2`,e.id&&c.includes(e.id)?`border-primary bg-primary/10`:`border-divider hover:bg-default-100`),onClick:()=>w(e),children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Q.jsx)(`span`,{className:`font-medium`,children:e.displayName}),e.organizationRole?(0,Q.jsx)(_,{intent:e.organizationRole===`Admin`?`warning`:`neutral`,size:`sm`,children:e.organizationRole}):null]}),(0,Q.jsx)(y,{as:`div`,tone:`muted`,variant:`caption`,children:[e.email,e.phone].filter(
5Boolean).join(` · `)||`—`})]},e.id))}),(0,Q.jsx)(g,{isSelected:f,label:`Overwrite empty fields on this contact from sources`,size:`sm`,onValueChange:p}),S&&(0,Q.jsxs)(B,{icon:Le,intent:`warning`,children:[`A source contact is an Organization `,(0,Q.jsx)(`span`,{className:`font-semibold`,children:S}),`. The merged contact will keep the `,(0,Q.jsx)(`span`,{className:`font-semibold`,children:S}),` role.`]}),(0,Q.jsx)(`div`,{className:`flex justify-end`,children:(0,Q.jsxs)(C,{icon:dr,isDisabled:c.length===0||r.isPending,isLoading:r.isPending,size:`sm`,variant:`danger`,onPress:async()=>{if(c.length===0)return;let t=`Merge ${c.length} contact${c.length===1?``:`s`} into this one? Source contacts will be deleted.`,n=S?`${t}\n\nA source contact is an Organization ${S}. The merged contact will keep the ${S} role.`:t;if(window.confirm(n))try{await r.mutateAsync({id:e,sourceContactIds:c,overwrite:f}),a(!1),l([]),d([]),s(``)}catch{}},children:[`Merge `,c.length,` contact`,c.length===1?``:`s`]})})]})]})}function Us(e){if(!e)return null;let t=e.replace(/[^0-9]/g,``);return t.length>=8?t:null}function Ws(e,t){let n=Us(e.phone);return!n||!e.id?[]:t.filter(t=>t.id&&t.id!==e.id&&!t.isGroup&&Us(t.phone)===n)}function Gs(e,t,n){return t?{kind:`open`,to:n(t)}:e.isGroup||e.phone?.trim()||Os(e)?{kind:`start`}:{kind:`off`,reason:`No conversation with this contact yet, and no number to start one on`}}function Ks({contactId:e,keptName:t,duplicates:n}){let r=Qn(),{confirm:i,confirmDialog:a}=N(),[o,s]=(0,Z.useState)(!1);if(n.length===0)return null;let c=async()=>{if(await i({title:n.length===1?`Merge 1 duplicate into ${t}?`:`Merge ${n.length} duplicates into ${t}?`,description:`Their messages, conversations, leads and integration links move onto this contact, and the duplicate records are deleted. This cannot be undone.`,confirmLabel:`Merge`})){s(!0);try{await r.mutateAsync({id:e,sourceContactIds:n.flatMap(e=>e.id?[e.id]:[]),overwrite:!0})}catch(e){q.error(e instanceof Error?e.message:`Could not merge the contacts`)}finally{s(!1)}}};return(0,Q.jsxs)(`section`,{className:`flex flex-col gap-3`,children:[(0,Q.jsx)(B,{intent:`warning`,children:n.length===1?`Another contact has this same number.`:`${n.length} other contacts have this same number.`}),(0,Q.jsx)(`ul`,{className:`flex flex-col divide-y divide-divider border-y border-divider`,children:n.map(e=>(0,Q.jsxs)(`li`,{className:`flex items-center gap-3 py-2`,children:[(0,Q.jsx)(x,{name:e.displayName??``,size:`sm`,src:e.avatarUrl}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,Q.jsx)(y,{as:`span`,className:`truncate`,variant:`body`,children:e.displayName}),(0,Q.jsx)(y,{as:`span`,className:`truncate`,tone:`muted`,variant:`caption`,children:[e.contactType,e.phone?H(e.phone):null].filter(Boolean).join(` · `)})]})]},e.id))}),(0,Q.jsx)(C,{className:`self-start`,icon:dr,isDisabled:o,isLoading:o,onPress:()=>void c(),variant:`secondary`,children:n.length===1?`Merge into this contact`:`Merge ${n.length} into this contact`}),a]})}function qs(){let e=Xn(),{confirm:t,confirmDialog:n}=N();return{remove:async(n,r)=>{if(!await t({title:`Delete ${r?.trim()||`this contact`}?`,description:`This cannot be undone.`,confirmLabel:`Delete`}))return!1;try{await e.mutateAsync(n)}catch(e){return q.error(`Failed to delete contact: ${e instanceof Error?e.message:String(e)}`),!1}return!0},isDeleting:e.isPending,confirmDialog:n}}function Js({contactId:e,organizationId:t,onCall:n,canCall:r=!1,
5conversationPath:a,onDeleted:o,onEditingChange:s}){let{data:c,isLoading:l}=Yn(e),u=qs(),d=i(),f=J(),[m,h]=(0,Z.useState)(null),g=m===e;(0,Z.useEffect)(()=>(s?.(g),()=>s?.(!1)),[g,s]);let{data:v=[],isLoading:b}=Kn(c?.phone?{phone:c.phone,organizationIds:[t],includeAllTypes:!0}:void 0),S=c?.phone?.trim()||c?.email?.trim()||c?.displayName?.trim()||``,{data:w=[]}=Y({queryKey:[Jn,t,S],enabled:!!t&&S.length>0,staleTime:6e4,queryFn:async({signal:e})=>{let n=await et({signal:e,query:{OrganizationIds:[t],QueryString:S,skip:0,take:25}});if(n.error)throw Error(JSON.stringify(n.error));return n.data?.items??[]}}),T=(0,Z.useMemo)(()=>w.find(t=>t.id===e),[w,e]),E=(0,Z.useMemo)(()=>c?Ws(c,v):[],[c,v]),[D,O]=(0,Z.useState)(!1),k=async()=>{if(c?.id){O(!0);try{let e=await dt({body:{organizationId:c.organizationId??t,contactIds:[c.id],matchByContact:!0,forceNew:!1}});if(e.error)throw Error(JSON.stringify(e.error));let n=e.data?.id;if(!n)throw Error(`Could not open a conversation for this contact`);f.invalidateQueries({queryKey:[Jn]}),d(a(n))}catch(e){q.error(e instanceof Error?e.message:`Could not open a conversation`)}finally{O(!1)}}};if(l)return(0,Q.jsx)(fe,{rows:6,withHeader:!0});if(!c)return(0,Q.jsx)(ne,{description:`It may have been merged into another contact, or deleted.`,icon:K,size:`inline`,title:`Contact not found`});let A=c.displayName||c.fullName||H(c.phone??``)||`Unnamed contact`;if(g)return(0,Q.jsx)(Ys,{contactId:e,conversationPath:a,name:A,organizationId:t,onClose:()=>h(null),onDeleted:o});let j=Oe(c.phone)&&!c.isGroup,M=Gs(c,T?.latestConversationId??null,a),N=async()=>{await u.remove(e,A)&&o?.(e)};return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full max-w-2xl flex-col gap-6 px-4 py-6`,children:[(0,Q.jsxs)(`header`,{className:`flex flex-col items-center gap-3 text-center`,children:[(0,Q.jsx)(x,{fallbackIcon:c.isGroup?Be:void 0,name:A,size:`lg`,src:c.avatarUrl}),(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-1`,children:[(0,Q.jsx)(y,{as:`h1`,variant:`title-1`,children:A}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-1`,children:[c.isGroup?(0,Q.jsx)(_,{icon:Be,intent:`accent`,size:`sm`,children:`Group`}):null,c.contactType?(0,Q.jsx)(_,{size:`sm`,children:c.contactType}):null,c.partnerOrganizationName?(0,Q.jsx)(_,{icon:p,intent:`primary`,size:`sm`,children:c.partnerOrganizationName}):null]})]}),(0,Q.jsxs)(`div`,{className:`flex items-start justify-center gap-4 pt-1`,children:[(0,Q.jsx)(ts,{disabledReason:j?`Turn on calls in this browser to ring out`:`This contact has no number to ring`,icon:Pe,isDisabled:!r||!j||!n,label:`Call`,onPress:()=>n?.(c)}),(0,Q.jsx)(ts,{disabledReason:M.kind===`off`?M.reason:void 0,icon:De,isDisabled:M.kind===`off`,isLoading:D,label:`Message`,onPress:M.kind===`start`?()=>void k():void 0,to:M.kind===`open`?M.to:void 0}),(0,Q.jsx)(ts,{disabledReason:`This contact has no email address`,icon:Te,isDisabled:!c.email,label:`Mail`,to:c.email?`mailto:${c.email}`:void 0}),(0,Q.jsx)(ts,{icon:U,label:`Edit`,onPress:()=>h(e)})]})]}),(0,Q.jsxs)(`dl`,{className:`flex flex-col divide-y divide-divider border-y border-divider`,children:[(0,Q.jsx)(Xs,{label:`Phone`,value:!c.isGroup&&c.phone?H(c.phone)||c.phone:null,tabular:!0}),(0,Q.jsx)(Xs,{label:`Email`,value:c.isGroup?null:c.email}),(0,Q.jsx)(Xs,{label:`Address`,value:c.address}),(0,Q.jsx)(Zs,{value:c.tags}),(0,Q.jsx)(Xs,{label:`Preferred language`,value:c.preferredLanguage}),(0,Q.jsx)(Xs,{label:`Organization role`,value:c.organizationRole}),(0,Q.jsx)(Xs,{label:`Notes`,value:c.notes}),(0,Q.jsx)(Qs,{contact:c})]}),b?null:(0,Q.jsx)(Ks,{contactId:e,duplicates:E,keptName:A}),(0,Q.jsx)(`div`,{className:`flex justify-end border-t border-divider pt-4`,children:(0,Q.jsx)(C,{icon:G,isDisabled:u.isDeleting,isLoading:u.isDeleting,onPress:()=>void N(),variant:`danger-ghost`,children:`Delete contact`})}),u.confirmDialog]})}function Ys({contactId:e,organizationId:t,name:n,conversationPath:r,onClose:i,onDeleted:a}){let o=Ms({contactId:e,organizationId:t}),s=qs(),c=async()=>{try{await o.save()&&i()}catch{}},l=async()=>{await s.remove(e,n)&&a?.(e)};return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full max-w-2xl flex-col gap-6 px-4 pb-6`,children:[(0,Q.jsxs)(`div`,{className:`sticky top-0 z-10 flex items-center justify-between gap-3 border-b border-divider bg-background py-3`,children:[(0,Q.jsx)(C,{isDisabled:o.isSaving,variant:`ghost`,onPress:i,children:`Cancel`}),(0,Q.jsx)(y,{as:`span`,tone:`muted`,variant:`footnote`,children:o.isGroup?`Edit group chat`:`Edit contact`}),(0,Q.jsx)(C,{isDisabled:o.isLoading,isLoading:o.isSaving,variant:`primary`,onPress:()=>void c(),children:`Done`})]}),(0,Q.jsx)(Ns,{avatarLayout:`centered`,conversationPath:r,editor:o,onNavigateAway:i}),(0,Q.jsx)(`div`,{className:`flex justify-end border-t border-divider pt-4`,children:(0,Q.jsx)(C,{icon:G,isDisabled:s.isDeleting||o.isSaving,isLoading:s.isDeleting,onPress:()=>void l(),variant:`danger-ghost`,children:`Delete contact`})}),s.confirmDialog]})}function Xs({label:e,value:t,tabular:n}){let r=t?.trim();return r?(0,Q.jsx)(`div`,{className:`py-3`,children:(0,Q.jsx)(pe,{label:e,value:(0,Q.jsx)(y,{as:`span`,className:`whitespace-pre-wrap break-words`,tabular:n,variant:`body`,children:r})})}):null}function Zs({value:e}){let t=(e??``).split(`,`).map(e=>
5e.trim()).filter(Boolean);return t.length===0?null:(0,Q.jsx)(`div`,{className:`py-3`,children:(0,Q.jsx)(pe,{label:`Tags`,value:(0,Q.jsx)(`span`,{className:`flex flex-wrap gap-1`,children:t.map(e=>(0,Q.jsx)(_,{intent:`primary`,size:`sm`,children:e},e))})})})}function Qs({contact:e}){let t=e.user,n=[t?.firstName,t?.lastName].filter(Boolean).join(` `)||t?.email||e.userId;return(0,Q.jsx)(`div`,{className:`py-3`,children:(0,Q.jsx)(pe,{label:`Linked account`,value:e.userId?(0,Q.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Q.jsx)(x,{name:n||`?`,size:`sm`}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-col`,children:[(0,Q.jsx)(y,{as:`span`,className:`truncate`,variant:`body`,children:n}),t?.email?(0,Q.jsx)(y,{as:`span`,className:`truncate`,tone:`muted`,variant:`caption`,children:t.email}):null]})]}):(0,Q.jsx)(y,{as:`span`,tone:`subtle`,variant:`caption`,children:`None. Use Edit to connect this contact to a Proptonomy login so their activity is unified.`})})})}var $s=25,ec=[`OrgStaff`,`PropertyOwner`,`Partner`];function tc(e,t={}){let{showGuests:n=!1,search:r}=t,i=n||!!r?.trim(),a=r?.trim()||``,o=a.length>0,s=We({queryKey:[Zn,e??`no-organization`,a,i],enabled:!!e,staleTime:3e5,initialPageParam:0,queryFn:async({pageParam:t,signal:n})=>{let r=await et({signal:n,query:{OrganizationIds:[e],QueryString:a||void 0,IncludeContactTypes:i?void 0:ec,skip:t,take:$s}});if(r.error)throw Error(JSON.stringify(r.error));return r.data??{items:[],total:0,totalIsExact:!0,maxPageableRows:0}},getNextPageParam:(e,t)=>{let n=t.reduce((e,t)=>e+(t.items?.length??0),0);if((e.items?.length??0)<$s)return;let r=e.maxPageableRows??0;if(!(r>0&&n>=r))return n}});return{contacts:(0,Z.useMemo)(()=>s.data?.pages.flatMap(e=>e.items??[])??[],[s.data]),total:s.data?.pages[0]?.total??0,totalIsExact:s.data?.pages[0]?.totalIsExact??!0,pagesLoaded:s.data?.pages.length??0,isSearch:o,isLoading:s.isLoading,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:()=>{s.fetchNextPage()}}}function nc({contactId:e,isOpen:t,onClose:n,organizationId:r,onCreated:i,initialPhone:a}){let o=Ms({contactId:e,organizationId:r,initialPhone:a,isOpen:t,onCreated:i}),s=qs(),{contact:c,isCreate:l,isGroup:u}=o,d=async()=>{await o.save()&&n()},f=async()=>{e&&await s.remove(e,c?.displayName)&&n()};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(L,{isOpen:t,onClose:n,scrollBehavior:`inside`,size:`2xl`,children:(0,Q.jsxs)(D,{children:[(0,Q.jsxs)(h,{className:`flex flex-col gap-1`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{children:l?`New contact`:u?`Edit group chat`:`Edit contact`}),u&&(0,Q.jsx)(_,{icon:Be,intent:`accent`,size:`sm`,children:`Group chat`})]}),!l&&c?.displayName&&(0,Q.jsx)(y,{as:`span`,className:`font-normal`,tone:`muted`,variant:`caption`,children:c.displayName})]}),(0,Q.jsx)(O,{children:(0,Q.jsx)(Ns,{editor:o,onNavigateAway:n})}),(0,Q.jsxs)(se,{className:`justify-between`,children:[l?(0,Q.jsx)(`span`,{}):(0,Q.jsx)(C,{icon:G,isDisabled:!e||s.isDeleting,isLoading:s.isDeleting,variant:`danger-ghost`,onPress:()=>void f(),children:`Delete`}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(C,{variant:`ghost`,onPress:n,children:`Cancel`}),(0,Q.jsx)(C,{icon:W,isDisabled:o.isLoading||o.isSaving,isLoading:o.isSaving,variant:`primary`,onPress:()=>void d(),children:l?`Create`:`Save`})]})]})]})}),s.confirmDialog]})}export{Ar as $,di as A,ci as B,Ji as C,Br as D,Ur as E,ai as F,Si as G,xi as H,li as I,Ci as J,mi as K,ei as L,ni as M,ti as N,vi as O,$r as P,Fr as Q,ui as R,$i as S,$ as T,hi as U,yi as V,_i as W,Rr as X,gi as Y,zr as Z,Ia as _,Os as a,Dr as at,Ea as b,bs as c,dr as ct,as as d,Mr as et,es as f,Qo as g,rs as h,qs as i,Tr as it,fi as j,pi as k,ls as l,lr as lt,$o as m,tc as n,kr as nt,ks as o,yr as ot,ns as p,bi as q,Js as r,Or as rt,xs as s,_r as st,nc as t,jr as tt,os as u,sr as ut,Pa as v,Vi as w,ea as x,Aa as y,oi as z};

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.