1import{r as i,j as e}from"./react-vendor-CU6Sz31W.js";import{R as Ct}from"./RoutePageHeaderContent-FkxdZGox.js";import{R as Nt}from"./RoutePageTitle-D_8Od-sv.js";import{al as Be,u as Ue,aE as jt,b as Se,as as Ee,pU as St,aF as q,aI as qe,aJ as Xe,cv as ee,cw as kt,ae as Tt,af as Vt,ag as Mt,pV as It,el as ke,i as Y,at as ut,dg as Lt,c3 as Et,ek as ne,fJ as Ae,eb as Ft,C as mt,a0 as se,cZ as je,fT as Pt,pW as $e,pE as ze,S as Rt,gB as ft,ly as Ye,dP as At,ce as et,fE as We,pX as $t,gx as zt,d as tt,ef as Bt,es as Ut,fM as Ot,gk as Dt,pY as pt,pZ as _t,p_ as Kt,eo as Ht,be as Gt,c4 as st,ee as Wt,jv as Jt,aw as Yt,t as ce,R as De}from"./index-DEXJEDAi.js";import{c as Zt,P as Ze,m as Qt,b as qt,a as Xt,d as es}from"./calendarBounds-DQCPEB1J.js";import{V as ht}from"./VisitNoShowAction-BKPozsIT.js";import{u as Qe}from"./useOpenPatientProfile-CASNKG5E.js";import{F as ts,i as ss,a as rs}from"./index-D8wjYP7x.js";import{q as rt,w as Fe,e as _e,f as Pe,d as as,g as ns}from"./firebase-w6DYUbFN.js";/* empty css */import{u as is}from"./useNetworkTimezone-DAycysvJ.js";import{a as os,g as Ke,i as ls}from"./statusBadge-Dq6-fXVv.js";import{b as Z,g as me,a as cs,d as de,f as ue,e as He,i as ds,h as us}from"./visitDisplay-XXmI5Egl.js";import{P as xt}from"./patient-name-link-BAfQKbEs.js";import{C as ms}from"./chartPalette-CFmN-0p5.js";import{T as fs}from"./text-highlight-BFqqfcjs.js";import"./calendar-RV2oTCrW.js";import{a as ps}from"./DataTableCard-BluwWKn_.js";import"./ExportCsvAction-BJr9eiP6.js";import{A as hs,D as xs}from"./cells-Db2ZEFlu.js";import{u as gs,w as ys}from"./useClientsById-BI_N6qCU.js";import{u as bs}from"./useTableSort-KpNOL2n3.js";import{V as gt}from"./VisitHistoryStatusBadge-CwrENSqG.js";import{g as fe,f as Je}from"./visitLastUpdated-BKQcd-p2.js";import{s as vs}from"./rawTableExport-DjSsUxyR.js";import{f as ws}from"./tenantColorRamps-QDc1G_tU.js";import{i as Cs,a as Ns,g as at,b as js,c as Ss}from"./productApprovalOnly-GEXGR3EQ.js";import{c as ks,a as Ts}from"./rescheduleVisitAccess-DtrPF0pi.js";import{A as Vs}from"./arrow-right-BC3JVmLt.js";import{P as Ms}from"./ProviderScheduleVisitModal-DArCs9CI.js";import{u as Is}from"./useProviderVisitLauncher-C95KBL53.js";import"./ChartStage-kk8qB2rS.js";import{S as Ls}from"./StatTile-DQJZPnfG.js";import{callVisitAction as Es,listNetworkClaimableSyncVisits as Fs,claimNetworkSyncVisit as Ps,requestPatientRescheduleOutOfCall as Rs}from"./visitActionApi-M5kT0GW2.js";import{u as As}from"./useProviderGoogleCalendar-Duj0Ag4G.js";import{i as nt,d as $s}from"./providerGoogleCalendarDismissal-DleKChI2.js";import{i as zs,f as Bs}from"./patientMessagingScope-DaW-b0v9.js";import{l as Us,a as Os,i as Ds,o as _s}from"./belugaExternalScheduling-Dg_RufXJ.js";import{C as Ks}from"./calendar-plus-BpNlzHvA.js";import"./payment-icons-Daq1K3F1.js";import"./user-round-c4EWOTq5.js";import"./addWeeks-1hrFjz19.js";import"./index-BSuGcRaZ.js";import"./table-CxPdvV_9.js";import"./arrow-up-D6DFVL4j.js";import"./arrow-down-BjUlbB4f.js";import"./pill-filter-CtZSNPVl.js";import"./date-picker-filter-Qp1kqu9t.js";import"./clear-filters-button-DmPemFGr.js";import"./modal-option-cards-Dksohkou.js";import"./ellipsis-vertical-C-dQ6Kzj.js";import"./PatientProfileBrandingContext-B4yn3g4G.js";import"./providerOperations-ELdKx_YD.js";import"./networkLicensurePolicy-Ct3PZM4V.js";import"./preferredProtocolEligibility-Wx-sDe0P.js";import"./VisitSchedulePicker-4J6xpsxo.js";import"./visitIcons-CG7YiClb.js";import"./badge-check-DS4dztDB.js";import"./useNetworkLicensurePolicy-DGC2H23P.js";import"./useVisitChartingLauncher-B1f2Z2_Q.js";import"./chartTheme-By-OHNNJ.js";import"./formatters-C_0Kn-_3.js";const Hs={"#2563eb":"#eff6ff","#7c3aed":"#f5f3ff","#db2777":"#fdf2f8","#dc2626":"#fef2f2","#ea580c":"#fff7ed","#ca8a04":"#fefce8","#16a34a":"#f0fdf4","#0891b2":"#ecfeff","#64748b":"#f1f5f9","#f59e0b":"#fffbeb","#ef4444":"#fef2f2"},it=ms;function Gs(){return e.jsx("div",{className:"px-3 pt-2 pb-3",children:e.jsxs("div",{className:"rounded-lg border border-subtle bg-surface-raised dark:bg-slate-900/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle px-4 py-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(se,{className:"size-8 rounded-full"}),e.jsx(se,{className:"size-8 rounded-full"}
1),e.jsx(se,{className:"h-8 w-14 rounded-full"})]}),e.jsx(se,{className:"h-6 w-40"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(se,{className:"h-8 w-24 rounded-full"}),e.jsx(se,{className:"h-8 w-20 rounded-full"})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-3 px-4 py-4",children:Array.from({length:7}).map((c,o)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"h-5 w-16"}),Array.from({length:6}).map((g,f)=>e.jsx(se,{className:"h-12 w-full rounded-lg"},f))]},o))})]})})}function Ge(c){return Hs[c]||"#eff6ff"}function Ws({onSelectVisit:c,multiProvider:o=!1,fullWidth:g=!1,showProviderSidebar:f=!1,selectedProviderIds:E=null,providerColors:_,allProviders:k}){const{branding:N}=Be(),{userDoc:u,selectedClientId:w}=Ue(),{isPhone:F,width:L}=jt(),P=L<1024,M=(N==null?void 0:N.accentColor)||Se,{networkTimezone:z}=is(),{openPatientProfile:K,buildPatientProfileHref:d}=Qe(),[b,y]=i.useState(!1),[p,T]=i.useState(null),[B,A]=i.useState(null),J=i.useRef(null),j=i.useRef(null),[C,v]=i.useState([]),[R,U]=i.useState([]),[I,W]=i.useState(null),[Q,S]=i.useState(!0),[O,V]=i.useState(new Date);i.useEffect(()=>{if(o){const s=Array.isArray(E)?E:[];if(s.length===0){v([]),S(!1);return}S(!0),v([]);const r=[];for(let m=0;m<s.length;m+=10)r.push(s.slice(m,m+10));const n=r.map(m=>{const x=rt(_e(Ee,"Visits"),Fe("providerId","in",m),Fe("clientId","==",w));return Pe(x,G=>{const a=G.docs.map(l=>({id:l.id,...l.data()})).filter(l=>String(l.visitMode||"").toLowerCase()!=="async"&&String(l.visitSource||"").toLowerCase()!=="async_visit");v(l=>[...l.filter(D=>!m.includes(D.providerId)),...a]),S(!1)})});return()=>n.forEach(m=>m())}else{if(!(u!=null&&u.id)||!(u!=null&&u.providerNetworkId)){v([]),S(!1);return}S(!0);const s=rt(_e(Ee,"Visits"),Fe("providerNetworkId","==",u.providerNetworkId),Fe("providerId","==",u.id)),r=Pe(s,n=>{const m=n.docs.map(x=>({id:x.id,...x.data()})).filter(x=>String(x.visitMode||"").toLowerCase()!=="async"&&String(x.visitSource||"").toLowerCase()!=="async_visit");v(m),S(!1)},n=>{console.error("Error listening to visits:",n),S(!1)});return()=>r()}},[u==null?void 0:u.id,u==null?void 0:u.providerNetworkId,w,o,E]),i.useEffect(()=>{if(!(u!=null&&u.id)){U([]);return}const s=_e(Ee,"Users",u.id,"Hours"),r=Pe(s,n=>{const m=n.docs.filter(x=>x.id!=="default").map(x=>({id:x.id,...x.data()}));U(m)},n=>{console.error("Error listening to availability blocks:",n)});return()=>r()},[u==null?void 0:u.id]),i.useEffect(()=>{if(!(u!=null&&u.providerNetworkId)){W(null);return}const s=as(Ee,"ProviderNetworks",u.providerNetworkId,"Hours","default"),r=Pe(s,n=>{n.exists()?W(n.data().schedule||null):W(null)},n=>{console.error("Error listening to network hours:",n)});return()=>r()},[u==null?void 0:u.providerNetworkId]);const $=i.useMemo(()=>{if(_)return _;if(!o||!k)return{};const s={};return k.forEach((r,n)=>{s[r.id]=it[n%it.length]}),s},[o,k,_]),pe=i.useMemo(()=>St(I,O,z||q()),[I,O,z]),Te=i.useMemo(()=>{const s=z||q();return R.filter(r=>!r.unavailable).map((r,n)=>{try{const m=qe(r.startAt)||Xe(r.date,r.startTime,s),x=qe(r.endAt)||Xe(r.date,r.endTime,s);return!m||!x||m>=x?null:{id:`avail-${r.id||n}`,start:m,end:x,display:"background",backgroundColor:"#dcfce7",classNames:["provider-availability-block"]}}catch(m){return console.error("Error parsing availability block:",m,r),null}}).filter(Boolean)},[R,z]),re=i.useMemo(()=>C.map(s=>{var r;try{const n=ee(s),m=kt(s);if(!n||!m||n>=m)return null;const x=s.status==="Confirmed";let G=M,a=x?M:Ge(M),l=x?"#ffffff":"#0f172a";o&&$[s.providerId]?(G=$[s.providerId],a=x?$[s.providerId]:Ge($[s.providerId])):s.status==="Completed"?(G="#64748b",a=x?"#64748b":"#f1f5f9"):s.status==="Pending Review"?(G="#f59e0b",a=x?"#f59e0b":"#fffbeb"):s.status==="Cancelled"&&(G="#ef4444",a=x?"#ef4444":"#fef2f2");const h=Z(s,"Patient"),D=s.preferredMethod==="video"?"ð¹":"ð",ae=((r=k==null?void 0:k.find(oe=>oe.id===s.providerId))==null?void 0:r.displayName)||"",te=o&&ae?`${D} ${h} - ${ae}`:`${D} ${h} - ${me(s,"Visit")}`;return{id:s.id,title:te,start:n,end:m,backgroundColor:a,borderColor:x?a:G,textColor:l,extendedProps:{visit:s,providerName:ae}}}catch(n){return console.error("Error parsing visit:",n,s),null}}
1).filter(Boolean),[C,M,o,$,k]),he=[...pe,...Te,...re],{slotMinTime:xe,slotMaxTime:ge,contentHeight:ye,scrollTime:be}=i.useMemo(()=>Zt(I,C,P?{minContentHeight:340,maxContentHeight:460,pixelsPerHour:44}:void 0),[I,C,P]),ve=i.useMemo(()=>{var x,G;if(!I)return!1;const s=["monday","tuesday","wednesday","thursday","friday"],r=((x=I.saturday)==null?void 0:x.enabled)===!1,n=((G=I.sunday)==null?void 0:G.enabled)===!1,m=s.every(a=>{var l;return((l=I[a])==null?void 0:l.enabled)===!0});return r&&n&&m},[I]),X=i.useCallback(s=>{var n;const r=(n=s.event.extendedProps)==null?void 0:n.visit;r&&(A(s.el),T(r),y(!0))},[]);i.useEffect(()=>{if(B&&j.current){const s=B.getBoundingClientRect();j.current.style.position="fixed",j.current.style.left=`${s.left}px`,j.current.style.top=`${s.bottom}px`,j.current.style.width=`${s.width}px`,j.current.style.height="0px"}},[B,b]);const we=i.useCallback(s=>{s!=null&&s.start&&V(s.start)},[]),H=F?"timeGridDay":"timeGridWeek",ie=i.useRef(H);i.useEffect(()=>{var s,r,n;Q||ie.current!==H&&(ie.current=H,(n=(r=(s=J.current)==null?void 0:s.getApi)==null?void 0:r.call(s))==null||n.changeView(H))},[H,Q]);const t=e.jsxs(mt,{className:`rounded-xl border border-subtle dark:bg-slate-800 overflow-hidden provider-calendar shadow-sm ${g?"w-full":""}`,style:{"--calendar-accent-color":M},children:[Q?e.jsx(Gs,{}):e.jsx("div",{className:"px-3 pt-2 pb-3 max-lg:px-1.5 max-lg:pt-1.5 max-lg:pb-2",children:e.jsx(ts,{ref:J,plugins:[ss,rs],initialView:H,headerToolbar:P?{left:"title",center:"",right:"prev,next today timeGridDay,timeGridWeek"}:{left:"prev,next today",center:"title",right:"timeGridWeek,timeGridDay"},slotMinTime:xe,slotMaxTime:ge,slotDuration:"00:30:00",slotLabelInterval:"01:00",allDaySlot:!1,nowIndicator:!0,editable:!1,selectable:!1,selectMirror:!1,dayMaxEvents:!0,weekends:!ve,events:he,eventClick:X,datesSet:we,height:ye,scrollTime:be,scrollTimeReset:!1,expandRows:!1,slotLabelFormat:{hour:"numeric",minute:"2-digit",meridiem:"short",omitZeroMinute:!0},eventTimeFormat:{hour:"numeric",minute:"2-digit",meridiem:"short",omitZeroMinute:!1},dayHeaderFormat:P?{weekday:"short",day:"numeric",omitCommas:!0}:{weekday:"short",month:"numeric",day:"numeric",omitCommas:!0},titleFormat:P?{year:"numeric",month:"short"}:{year:"numeric",month:"long"}})}),e.jsxs("div",{className:"flex items-center gap-4 px-4 pb-3 text-xs text-content-tertiary border-t border-slate-100 dark:border-slate-700 pt-2 max-lg:flex-wrap max-lg:gap-x-2.5 max-lg:gap-y-1 max-lg:px-2 max-lg:pb-2 max-lg:pt-1.5 max-lg:text-3xs max-lg:[&_span.inline-block]:h-2 max-lg:[&_span.inline-block]:w-2",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block size-2.5 rounded-sm border border-green-500 bg-green-50 dark:bg-green-950/50"}),"Your Availability"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block size-2.5 rounded-sm bg-slate-200 dark:bg-slate-600"}),"Network Offline"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block size-2.5 rounded-sm border border-amber-500 bg-amber-50 dark:bg-amber-950/50"}),"Pending"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block size-2.5 rounded-sm border",style:{borderColor:M,backgroundColor:Ge(M)}}),"Confirmed"]})]})]});return e.jsxs(e.Fragment,{children:[o&&f?e.jsx("div",{className:"app-sidebar-layout-narrow min-w-0",children:e.jsx("div",{className:"min-w-0",children:t})}):e.jsx("div",{className:"min-w-0",children:t}),e.jsxs(Tt,{open:b,onOpenChange:y,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("div",{ref:j,style:{position:"fixed",pointerEvents:"none",width:"1px",height:"1px",visibility:"hidden"}})}),e.jsx(Mt,{className:"w-80 p-0 rounded-lg shadow-xl border border-subtle",align:"start",side:"bottom",sideOffset:5,children:p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 border-b border-slate-100 dark:border-slate-700",children:[e.jsx("div",{className:"w-1 h-16 rounded-full flex-shrink-0",style:{backgroundColor:p.status==="Confirmed"?M:"#f59e0b"}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-content-primary text-sm mb-1",children:me(p,"Visit")}),e.jsxs("div",{className:"text-xs text-content-secondary mb-1",children:[It(ke(p,q()))," ⢠",p.duration||30," min"]}),e.jsx("span",{className:os(p.status),children:p.status||"Confirmed"})]}),e.jsx(Y,{variant:"ghost",size:"sm",className:"size-6 p-0 rounded-full",onClick:()=>y(!1),children:e.jsx(ut,{className:"size-3"})})]}),e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Lt,{className:"size-4 text-slate-400"}),e.jsx(xt,{name:Z(p,"Patient"),patientId:p.userId,onOpen:s=>{K(s),y(!1)},href:d(p.userId),className:"text-sm"}),e.jsx(Ze,{visit:p})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Et,{className:"size-4 text-slate-400"}),e.jsx("span",{className:"text-slate-700 dark:text-slate-300",children:ne(p,q(),"EEEE, MMMM d, yyyy")})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[p.preferredMethod==="video"?e.jsx(Ae,{className:"size-4 text-blue-500"}):e.jsx(Ft,{className:"size-4 text-green-500"}),e.jsx("span",{className:"text-slate-700 dark:text-slate-300 capitalize",children:p.preferredMethod||"video"})]}),p.notes&&e.jsx("div",{className:"pt-2 border-t border-slate-100 dar
1k:border-slate-700",children:e.jsx("p",{className:"text-xs text-content-secondary italic",children:p.notes})})]}),e.jsxs("div",{className:"p-3 border-t border-slate-100 dark:border-slate-700 flex justify-between gap-2",children:[e.jsx(Y,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{const s=q(),r=ne(p,s),n=ke(p,s),m=p.duration||30,[x,G,a]=r.split("-"),[l,h]=n.split(":"),D=new Date(x,G-1,a,l,h),ae=new Date(D.getTime()+m*6e4),te=le=>{const Ne=wt=>String(wt).padStart(2,"0");return`${le.getUTCFullYear()}${Ne(le.getUTCMonth()+1)}${Ne(le.getUTCDate())}T${Ne(le.getUTCHours())}${Ne(le.getUTCMinutes())}${Ne(le.getUTCSeconds())}Z`},oe=te(D),Ve=te(ae),Me=encodeURIComponent(p.visitType||"Visit"),Ie=encodeURIComponent(Z(p,"Patient")),Ce=`${window.location.origin}/sync-visits?visitId=${p.id}`,Le=`${p.notes||"Telehealth visit"} 2 3Join video call: ${Ce}`,yt=encodeURIComponent(Le),bt=encodeURIComponent(Ce),vt=`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${Me} with ${Ie}&dates=${oe}/${Ve}&details=${yt}&location=${bt}`;window.open(vt,"_blank")},children:"Add to Google Calendar"}),e.jsx(ht,{visit:p,onSuccess:()=>y(!1)}),e.jsx(Y,{size:"sm",className:"rounded-full text-white",style:{backgroundColor:M},onClick:()=>{y(!1),c&&c(p)},children:"View Details"})]})]})})]})]})}function Re(c){const o=q();return{date:ne(c,o),time:ke(c,o)}}function ot(c){return String(c||"").trim().toLowerCase()}function Js({visits:c,loading:o,error:g,showAllVisits:f,scopeToggleEnabled:E,onVisitScopeChange:_,onRetry:k,onViewSummary:N,claimableVisitIds:u=null,claimingVisitId:w=null,onClaimVisit:F=null}){const{branding:L}=Be(),{providerNetwork:P}=Ue(),M=!P||P.hideLastProviderColumn===!0,{openPatientProfile:z,buildPatientProfileHref:K}=Qe(),d=gs(i.useMemo(()=>c.map(t=>t.clientId),[c])),b=i.useMemo(()=>c.map(t=>ys(d,t)),[d,c]),[y,p]=i.useState(""),[T,B]=i.useState(),[A,J]=i.useState([]),[j,C]=i.useState([]),[v,R]=i.useState([]),[U,I]=i.useState([]),[W,Q]=i.useState([]),[S,O]=i.useState([]),{sortKey:V,sortDirection:$,handleSort:pe}=bs([],"confirmedDate","desc"),re=[...b.filter(t=>{const s=Z(t,""),r=cs(t),n=t.visitType||"",m=de(t,""),x=ue(t,"");if(!(!y||s.toLowerCase().includes(y.toLowerCase())||r.toLowerCase().includes(y.toLowerCase())||n.toLowerCase().includes(y.toLowerCase())||m.toLowerCase().includes(y.toLowerCase())||x.toLowerCase().includes(y.toLowerCase())||[t.id,t.userId,t.patientId,t.providerId,t.clientId,t.businessId,t.providerNetworkId].some(a=>String(a||"").toLowerCase().includes(y.toLowerCase())))||A.length>0&&!A.includes(t.clientId)||j.length>0&&!j.includes(t.providerId)||v.length>0&&!v.includes(ot(n||"Visit"))||!Qt(t,{visitStatusFilters:U,clinicalOutcomeFilters:W,fulfillmentFilters:S}))return!1;if(T!=null&&T.from){const a=je(t);if(!a)return!1;const l=new Date(T.from);if(l.setHours(0,0,0,0),T.to){const h=new Date(T.to);return h.setHours(23,59,59,999),a>=l.getTime()&&a<=h.getTime()}return a>=l.getTime()}return!0})].sort((t,s)=>{let r,n;if(V==="userId")r=Z(t,"").toLowerCase(),n=Z(s,"").toLowerCase();else if(V==="visitType")r=(t.visitType||"").toLowerCase(),n=(s.visitType||"").toLowerCase();else if(V==="confirmedDate")r=je(t)||0,n=je(s)||0;else if(V==="confirmedTime")r=je(t)||0,n=je(s)||0;else if(V==="duration")r=t.duration||0,n=s.duration||0;else if(V==="status")r=Ke(t).map(m=>m.label).join(" ").toLowerCase(),n=Ke(s).map(m=>m.label).join(" ").toLowerCase();else if(V==="clientId")r=de(t,"").toLowerCase(),n=de(s,"").toLowerCase();else if(V==="patientLastProviderName")r=He(t).toLowerCase(),n=He(s).toLowerCase();else if(V==="providerId")r=ue(t,"").toLowerCase(),n=ue(s,"").toLowerCase();else if(V==="lastUpdated")r=fe(t),n=fe(s);else return 0;return r<n?$==="asc"?-1:1:r>n?$==="asc"?1:-1:0}),he=i.useMemo(()=>{const t={},s={};return b.forEach(r=>{r.clientId&&(t[r.clientId]=(t[r.clientId]||0)+1,s[r.clientId]=s[r.clientId]||de(r,"Unknown client"))}),Object.entries(t).map(([r,n])=>({id:r,label:s[r],count:n})).sort((r,n)=>r.label.localeCompare(n.label))},[b]),xe=i.useMemo(()=>{const t={},s={};return b.forEach(r=>{const n=me(r,"Visit"),m=ot(n);m&&(t[m]=(t[m]||0)+1,s[m]=s[m]||n)}),Object.entries(t).map(([r,n])=>({id:r,label:s[r],count:n})).sort((r,n)=>r.label.localeCompare(n.label))},[b]),ge=i.useMemo(()=>{const t={},s={};return b.forEach(r=>{r.providerId&&(t[r.providerId]=(t[r.providerId]||0)+1,s[r.providerId]=s[r.providerId]||ue(r,"Provider"))}),Object.entries(t).map(([r,n])=>({id:r,label:s[r],count:n})).sort((r,n)=>r.label.localeCompare(n.label))},[b]);i.useEffect(()=>{f||C([])},[f]);const ye=i.useMemo(()=>qt(b),[b]),be=i.useMemo(()=>Xt(b),[b]),ve=i.useMemo(()=>es(b),[b]),X=!!y||A.length>0||j.length>0||v.length>0||U.length>0||W.length>0||S.length>0||!!(T!=null&&T.from),we=i.useMemo(()=>[{id:"userId",header:"Patient",sortKey:"userId",csvValue:t=>Z(t,"Unknown"),width:"22%",cellClassName:"py-2",renderCell:t=>{var r;const s=Z(t,"Unknown");return e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx(hs,{label:s,initials:((r=s[0])==null?void 0:r.toUpperCase())||"P",highlight:y,patientId:t.userId,onOpenPatient:z,href:K(t.userId)}),e.jsx(Ze,{visit:t})]})}}
3,...f?[{id:"providerId",header:"Assigned To",sortKey:"providerId",csvValue:t=>ue(t,"Unassigned"),width:"14%",cellClassName:"py-2",renderCell:t=>e.jsx("span",{className:"block truncate text-xs text-content-secondary",children:ue(t,"Unassigned")})}]:[],{id:"clientId",header:"Client",sortKey:"clientId",csvValue:t=>de(t,""),width:"12%",cellClassName:"py-2",renderCell:t=>{const s=de(t),r=t.clientAccentColor||Se;return s!=="â"?e.jsx(Pt,{accentColor:r,className:"max-w-[100px]",children:s}):e.jsx("span",{className:"text-xs text-content-tertiary",children:"â"})}},{id:"visitType",header:"Product",sortKey:"visitType",csvValue:t=>me(t,"Visit"),width:"14%",cellClassName:"py-2",renderCell:t=>e.jsx("span",{className:"text-xs text-content-secondary truncate block",children:e.jsx(fs,{text:me(t,"Visit"),highlight:y})})},{id:"confirmedDate",header:"Scheduled date",sortKey:"confirmedDate",csvValue:t=>$e(Re(t).date),width:"11%",cellClassName:"py-2",renderCell:t=>e.jsx("span",{className:"text-xs text-content-secondary",children:$e(Re(t).date)})},{id:"confirmedTime",header:"Time",sortKey:"confirmedTime",csvValue:t=>ze(Re(t).time),width:"9%",cellClassName:"py-2",renderCell:t=>e.jsx("span",{className:"text-xs text-content-secondary",children:ze(Re(t).time)})},{id:"lastProvider",header:"Last Provider",sortKey:"patientLastProviderName",csvValue:t=>us(t),width:"12%",cellClassName:"py-2",renderCell:t=>{const s=He(t);if(s==="â")return e.jsx("span",{className:"text-xs text-content-tertiary",children:"â"});const r=ds(t.patientLastProviderAt);return e.jsxs("div",{className:"text-xs text-content-secondary",children:[e.jsx("div",{className:"font-medium text-content-secondary",children:s}),r?e.jsx("div",{className:"text-2xs text-content-tertiary",children:r}):null]})}},{id:"duration",header:"Duration",sortKey:"duration",csvValue:t=>t.duration?`${t.duration} min`:"-",width:"8%",cellClassName:"py-2",renderCell:t=>e.jsx("span",{className:"text-xs text-content-secondary",children:t.duration?`${t.duration} min`:"-"})},{id:"lastUpdated",header:"Last updated",sortKey:"lastUpdated",csvValue:t=>{const{date:s,time:r}=Je(t);return r?`${s} ${r}`:s},width:"11%",minWidth:112,cellClassName:"py-2",renderCell:t=>{const{date:s,time:r}=Je(t);return e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-content-secondary",children:s}),r?e.jsx("p",{className:"text-2xs text-content-tertiary",children:r}):null]})}},{id:"status",header:"Status",sortKey:"status",csvValue:t=>Ke(t).map(s=>s.label).join("; "),width:"9%",align:"center",cellClassName:"py-2 text-center",renderCell:t=>e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-1",children:e.jsx(gt,{visit:t})})},{id:"actions",header:"Actions",width:f&&F?"12%":"6%",align:"center",cellClassName:"py-2 text-center",renderCell:t=>{const s=!!(F&&(u!=null&&u.has(t.id))),r=w===t.id;return e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[s?e.jsxs(Y,{type:"button",variant:"outline",size:"sm",className:"h-7 rounded-full px-2.5 text-2xs",disabled:!!w,"aria-label":`Claim visit for ${Z(t,"patient")}`,onClick:n=>{n.stopPropagation(),F(t)},children:[r?e.jsx(Rt,{size:"xs",className:"mr-1",label:"Claiming visit"}):null,"Claim"]}):null,e.jsx(Y,{type:"button",variant:"ghost",size:"sm",className:"size-7 p-0","aria-label":`View visit for ${Z(t,"patient")}`,onClick:n=>{n.stopPropagation(),N(t)},children:e.jsx(ft,{className:"size-3.5"})})]})}}],[y,f,N,u,w,F,z,K]),H=(L==null?void 0:L.accentColor)||Se,ie=e.jsx(Y,{type:"button",variant:"outline",size:"sm","aria-pressed":f,"aria-label":`Visit scope: ${f?"All Visits":"My Visits"}. Click to switch.`,title:`Click to show ${f?"My Visits":"All Visits"}`,onClick:()=>_(f?"mine":"all"),className:"h-7 rounded-full px-3 text-xs transition-colors",style:f?{backgroundColor:H,borderColor:H,color:ws(H)}:{borderColor:H,color:H},children:f?"All Visits":"My Visits"});return e.jsx(ps,{id:"provider-sync-visits",title:"Sync Visits",icon:Ye,accentColor:H,actions:E||g?e.jsxs(e.Fragment,{children:[E?ie:null,g?e.jsxs(Y,{type:"button",variant:"outline",size:"sm",className:"h-7 gap-1.5 rounded-full px-3 text-xs",onClick:k,children:[e.jsx(At,{className:"size-3.5","aria-hidden":!0}),"Retry"]}):null]}):null,error:g,className:"min-w-0",filteredCount:re.length,totalCount:b.length,search:{value:y,onChange:t=>p(t),placeholder:"Search by patient or visit typeâ¦"},filters:[...f?[{id:"provider",filters:ge,activeFilters:j,onFilterChange:C,multiSelect:!0,defaultLabel:"All providers",searchable:!0}]:[],{id:"client",filters:he,activeFilters:A,onFilterChange:J,multiSelect:!0,defaultLabel:"All clients",searchable:!0},{id:"product",filters:xe,activeFilters:v,onFilterChange:R,multiSelect:!0,defaultLabel:"All products",searchable:!0},{id:"visit-status",filters:ye,activeFilters:U,onFilterChange:I,multiSelect:!0,defaultLabel:"Visit status"},{id:"clinical-outcome",filters:be,activeFilters:W,onFilterChange:Q,multiSelect:!0,defaultLabel:"Clinical outcome"},{id:"fulfillment",filters:ve,activeFilters:S,onFilterChange:O,multiSelect:!0,defaultLabel:"Fulfillment"},{type:"date",id:"date-range",date:T,setDate:B,label:"Scheduled date"}],hasActiveFilters:X,onClearFilters:()=>{p(""),J([]),C([]),R([]),I([]),Q([]),O([]),B(void 0)},columns:we.filter(t=>!M||t.id!=="lastProvider"),rows:re,csvExport:{feature:"sync-visits",tenantSlug:L==null?void 0:L.businessName,rawExport:{getRows:()=>vs(re,b)},allData:{mode:"client",getRows:()=>b}},rowKey:"id",rowClick:N,sortKey:V,sortDirection:$,onSort:pe,loading:o,maxHeight:"500px",emptyMessage:X?"No matching sync visits found. Try adjusting your search or filters.":f?"No sync visits are available for this provider network.":"No sync visits are assigned to you."})}function Ys(c){if(!c)return Ae;const o=c.toLowerCase();return o.includes("consultation")||o.includes("visit")||o.includes("check-in")?Ae:o.includes("lab")||o.includes("review")?Ot:Ae}function Zs(c){const o=["Sunday","Monday","Tuesday","Wednesday","Thursday","Frid
3ay","Saturday"],g=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],f=o[c.getDay()],E=g[c.getMonth()],_=c.getDate(),k=c.getFullYear();let N=c.getHours();const u=c.getMinutes(),w=c.getSeconds(),F=N>=12?"PM":"AM";N=N%12||12;const L=u<10?"0"+u:u,P=w<10?"0"+w:w;return{date:`${f}, ${E} ${_}, ${k}`,time:`${N}:${L}:${P} ${F}`}}function Qs(){const[c,o]=i.useState(()=>new Date);i.useEffect(()=>{const f=setInterval(()=>o(new Date),1e3);return()=>clearInterval(f)},[]);const g=Zs(c);return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-content-secondary",children:[e.jsx("span",{children:g.date}),e.jsx("span",{className:"text-slate-400 dark:text-slate-500",children:"â¢"}),e.jsx("span",{className:"font-mono tabular-nums",children:g.time})]})}function qs({visits:c,loading:o,currentTime:g,accentColor:f,onEnterVisit:E,onViewSummary:_,startingVisitId:k,isDelegate:N=!1,onOpenPatientProfile:u,buildPatientProfileHref:w,userType:F,userId:L,onRescheduleVisit:P,onAskPatientToReschedule:M,canMessagePatient:z=null}){function K(d){const b=Ys(d.visitType),y=Z(d,"Unknown Patient"),p=q(),T=ne(d,p),B=ke(d,p),A=Je(d),J=d.status==="Confirmed"||We(d),j=d.status==="In Progress",C=$t(d,g),v=ks(d,{userType:F,userId:L,surface:"card"}),R=Ts(d,{userType:F,userId:L}),U=[d.userId&&{id:"view-profile",label:"View profile",onSelect:()=>u==null?void 0:u(d.userId)},d.userId&&(z?z(d):!0)&&{id:"message-patient",label:"Message patient",onSelect:()=>u==null?void 0:u(d.userId,{tab:"messages"})},v&&{id:"reschedule-visit",label:"Reschedule visit",separatorBefore:!0,onSelect:()=>P==null?void 0:P(d)},R&&{id:"ask-patient-reschedule",label:"Ask patient to reschedule",onSelect:()=>M==null?void 0:M(d)}].filter(Boolean);return e.jsxs("div",{className:"group relative flex flex-col gap-3 rounded-lg border border-subtle bg-surface-raised p-4 transition-[color,background-color,border-color,fill,stroke,box-shadow] hover:border-blue-300 hover:shadow-sm dark:hover:border-blue-700",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-10 flex-shrink-0 items-center justify-center rounded-full bg-blue-50 dark:bg-blue-900/30",children:e.jsx(b,{className:"size-5 text-blue-600 dark:text-blue-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(xt,{name:y,patientId:d.userId,onOpen:u,href:w==null?void 0:w(d.userId),className:"min-w-0 text-sm font-medium"}),e.jsx(Ze,{visit:d})]}),e.jsxs("p",{className:"flex min-w-0 items-center gap-1.5 text-xs text-content-tertiary",children:[e.jsx("span",{className:"truncate",children:me(d,"Visit")}),Cs(d)?e.jsx(zt,{tone:"purple",className:"shrink-0 text-3xs",title:at(d)?`${js(d)}: ${at(d)}`:Ss(d),children:Ns(d)}):null]})]}),e.jsx("span",{className:"flex-shrink-0",children:e.jsx(gt,{visit:d})})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-3 text-xs text-content-secondary",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ye,{className:"size-3"}),$e(T)]}),B&&e.jsx("span",{children:ze(B)}),d.duration&&e.jsxs("span",{children:["(",d.duration," min)"]})]}),e.jsxs("div",{className:"mt-1 text-2xs text-content-tertiary",children:["Last updated ",A.date,A.time?`, ${A.time}`:""]})]})]}),e.jsx(ht,{visit:{...d,patientName:y}}),e.jsxs("div",{className:"flex gap-2 mt-1",children:[!N&&J&&e.jsx(Y,{size:"sm",className:"flex-1 rounded-full text-white font-medium",style:{backgroundColor:C?f:void 0},onClick:()=>E(d),disabled:k===d.id||!C,children:k===d.id?e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"size-4 mr-2 animate-spin"}),"Starting..."]}):C?e.jsxs(e.Fragment,{children:[e.jsx(Ut,{className:"size-4 mr-2"}),"Start Visit"]}):e.jsxs(e.Fragment,{children:[e.jsx(Bt,{className:"size-4 mr-2"}),"Too Early"]})}),!N&&j&&e.jsx(Y,{size:"sm",className:"flex-1 rounded-full text-white font-medium",style:{backgroundColor:f},onClick:()=>E(d),disabled:k===d.id,children:k===d.id?e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"size-4 mr-2 animate-spin"}),"Loading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"size-4 mr-2"}),"Continue Visit"]})}),e.jsxs(Y,{variant:"outline",size:"sm",className:"flex-1 rounded-full",onClick:I=>{I.stopPropagation(),_(d)},children:[e.jsx(ft,{className:"size-4 mr-2"}),"Visit Details"]}
3),U.length>0?e.jsx(xs,{actions:U,label:`Open actions for ${y}`,align:"end",borderless:!0,testId:`button-schedule-actions-${d.id}`}):null,N&&e.jsx(et,{variant:"outline",className:"rounded-full text-xs bg-slate-100 text-slate-700 border-subtle dark:bg-slate-700 dark:text-slate-300",children:"Delegates cannot join calls"})]})]},d.id)}return e.jsxs(mt,{className:"border-subtle p-6 dark:bg-slate-800",children:[e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h2",{className:"font-display text-xl font-medium text-content-primary",children:"Today's Schedule"}),e.jsxs(et,{className:"bg-blue-50 text-blue-600 border border-blue-100 dark:bg-blue-900/30 dark:text-blue-400 dark:border-blue-800",children:[c.length," ",c.length===1?"visit":"visits"]})]}),e.jsx(Qs,{})]}),o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("p",{className:"text-content-tertiary",children:"Loading visits..."})}):c.length===0?e.jsx("div",{className:"flex items-center justify-center rounded-lg border border-dashed border-subtle bg-surface-sunken py-12 text-center text-slate-400 dark:text-slate-500",children:e.jsx("p",{children:"No visits scheduled for today"})}):e.jsx("div",{className:"space-y-3 max-h-[700px] max-lg:max-h-[60dvh] overflow-y-auto pr-2 -mr-2 scrollbar-thin scrollbar-thumb-slate-300 scrollbar-track-slate-100 dark:scrollbar-thumb-slate-600 dark:scrollbar-track-slate-800",children:c.map(d=>K(d))})]})}function Xs(c,o){return!c||!o?!1:typeof c=="string"||typeof o=="string"?c===o:c.id===o.id&&Number(c.updatedAt)===Number(o.updatedAt)}function lt({enabled:c,scope:o,userId:g,networkId:f,retry:E=0}){const[_,k]=i.useState({visits:[],loading:!1,loadingMore:!1,hasMore:!1,scanMessage:"",error:""}),N=i.useRef(null),u=i.useCallback(()=>{var w;return(w=N.current)==null?void 0:w.call(N)},[]);return i.useEffect(()=>{if(!c||!g||!f){k({visits:[],loading:!1,loadingMore:!1,hasMore:!1,scanMessage:"",error:""});return}let w=!1,F=null,L=!1,P=!1,M=!1,z=!0,K="",d="";const b=new Map,y=new Map,p=j=>pt(j)&&(o==="network"?j.providerNetworkId===f:j.providerId===g);function T(){w||k({visits:[...b.values()],loading:!L||!P,loadingMore:M,hasMore:z,scanMessage:d,error:K})}async function B(){if(M||!z||w)return;M=!0,K="",T();const j=new Map(y);try{const C=await Es({action:"listSyncVisits",scope:o,cursor:F},"Unable to load more sync visits. Try again.");if(w)return;if(C.visits.forEach(v=>{p(v)&&y.get(v.id)===j.get(v.id)&&b.set(v.id,v)}),C.nextCursor&&Xs(C.nextCursor,F))throw new Error("Visit pagination stalled. Refresh the schedule.");F=C.nextCursor,z=!!F,d=z&&C.visits.length===0?"No additional visits in this batch. Load more to continue searching history.":""}catch(C){K=C.message}finally{M=!1,P=!0,T()}}const A=o==="network"?_t(f):Kt(g,f),J=Dt(A.key,A.buildQuery,{next:j=>{const C=L?j.docChanges():j.docs.map(v=>({type:"added",doc:v}));L=!0;for(const v of C){const R=v.doc.id,U=(y.get(R)||0)+1;if(y.set(R,U),v.type!=="removed"){const I={...v.doc.data(),id:R};p(I)?b.set(R,I):b.delete(R)}else b.delete(R),ns(v.doc.ref).then(I=>{if(w||y.get(R)!==U)return;const W={...I.data(),id:R};I.exists()&&p(W)&&b.set(R,W),T()}).catch(()=>{K="A visit changed but its latest status could not load. Refresh the schedule.",T()})}T()},error:()=>{L=!0,K="Unable to load active visits. Refresh the schedule.",T()}});return N.current=B,B(),()=>{w=!0,N.current=null,J()}},[c,o,g,f,E]),{..._,loadMore:u}}function er({enabled:c=!0}){const o=Ht(),{branding:g}=Be(),{userDoc:f}=Ue(),E=(f==null?void 0:f.id)||"",[_,k]=i.useState(()=>nt(E)),{status:N,loading:u}=As({enabled:c});i.useEffect(()=>{k(nt(E))},[E]);const w=()=>{$s(E),k(!0)},F=()=>{w(),o("/integrations")};return!c||u||N.connected||_?null:e.jsxs("div",{className:"flex items-center gap-3 rounded-lg px-3 py-2 text-xs text-white max-lg:gap-2 max-lg:px-2 max-lg:py-1.5",style:{backgroundColor:(g==null?void 0:g.accentColor)||Se},role:"status","data-testid":"notice-provider-google-calendar",children:[e.jsxs("p",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"font-display text-sm font-semibold max-lg:text-xs",children:"Google Calendar"}),e.jsx("span",{className:"ml-1.5 text-white/90 max-lg:ml-1 max-lg:text-2xs",children:"Add scheduled SYNC visits automatically."})]}),e.jsx(Y,{type:"button",variant:"ghost",size:"sm",className:"h-7 shrink-0 rounded-full px-2.5 text-xs text-white hover:bg-white/15 hover:text-white",onClick:F,children:"Set up"}),e.jsx("button",{type:"button",className:"flex size-7 shrink-0 items-center justify-center rounded-full text-white/80 hover:bg-white/15 hover:text-white",onClick:w,"aria-label":"Dismiss Google Calendar notice","data-testid":"button-provider-google-calendar-notice-dismiss",children:e.jsx(ut,{className:"size-3.5","aria-hidden":"true"})})]})}const tr=new Set(["completed","cancelled","canceled","no show","no_show","patient no-show","provider no-show","no-show"]);function ct(c){return c?typeof c=="number"?c:typeof c.toMillis=="function"?c.toMillis():typeof c._seconds=="number"?c._seconds*1e3+(c._nanoseconds||0)/1e6:typeof c.seconds=="number"?c.seconds*1e3:null:null}function dt(c){const o=c.filter(g=>pt(g)).map(g=>({...g,createdAt:ct(g.createdAt),updatedAt:ct(g.updatedAt)}));return o.sort((g,f)=>fe(f)-fe(g)),o}function sr(){try{return localStorage.getItem("syncVisitScope")==="all"?"all":"mine"}catch{return"mine"}}function ua({isDelegate:c=!1}){const{userDoc:o,availableClients:g}=Ue(),{branding:f}=Be(),{openPatientProfile:E,buildPatientProfileHref:_}=Qe(),[k,N]=i.useState(sr),[u,w]=i.useState(0),[F,L]=i.useState(()=>new Set),[P,M]=i.useState(null),[z,K]=i.useState(0),[d,b]=i.useState(new Date),[y,p]=i.useState(null),[T,B]=i.useState(null),[A,J]=i.useState(!1),j=(f==null?void 0:f.accentColor)||Se,C=q(),v=i.useMemo(()=>!zs(o==null?void 0:o.userType)||!Array.isArray(g)||!g.length?null:new Set(Bs(g,o==null?void 0:o.providerNetworkId).map(a=>a.id)),[g,o==null?void 0:o.providerNetworkId,o==null?void 0:o.userType]),R=i.useCallback(a=>
3{if(!v)return!0;const l=(a==null?void 0:a.clientId)||(a==null?void 0:a.client)||null;return!!l&&v.has(l)},[v]),U=o==null?void 0:o.id,I=o==null?void 0:o.userType,W=o==null?void 0:o.providerNetworkId,Q=Gt(o==null?void 0:o.userType,"Provider"),S=k==="all"&&Q&&!c;i.useEffect(()=>{const a=setInterval(()=>{b(new Date)},3e4);return()=>clearInterval(a)},[]);const O=lt({enabled:!0,scope:c?"network":"mine",userId:U,networkId:W,retry:u}),V=lt({enabled:S,scope:"network",userId:U,networkId:W,retry:u}),$=i.useMemo(()=>dt(O.visits),[O.visits]),pe=i.useMemo(()=>dt(V.visits),[V.visits]),Te=O.loading,re=V.loading,he=V.error;i.useEffect(()=>{if(!S){L(new Set);return}let a=!1;return(async()=>{try{const l=await Fs();if(a)return;L(new Set(((l==null?void 0:l.visits)||[]).filter(h=>h.claimable===!0).map(h=>h.visitId||h.id).filter(Boolean)))}catch{a||L(new Set)}})(),()=>{a=!0}},[S,z]);async function xe(a){if(!(!(a!=null&&a.id)||P)){M(a.id);try{await Ps({visitId:a.id,expectedProviderId:a.providerId||null}),ce.success("Visit claimed. It now appears under My Visits."),K(l=>l+1)}catch(l){De(l,{area:"visits",surface:"Sync visits",operation:"Sync visits failed"}),ce.error((l==null?void 0:l.message)||"Unable to claim this visit. Please try again."),K(h=>h+1)}finally{M(null)}}}function ge(a){const l=a==="all"?"all":"mine";N(l);try{localStorage.setItem("syncVisitScope",l)}catch{}}async function ye(a){try{const l=await Us(a);if(String(Os(l).adapterKey||"").trim().toLowerCase()==="beluga"||Ds(l)){if(await _s(l))return;ce.info("Beluga scheduling link is not available yet. Please check back shortly.");return}p(l||a)}catch(l){De(l,{area:"visits",surface:"Sync visits",operation:"Sync visits failed"}),ce.error((l==null?void 0:l.message)||"Unable to open the reschedule window. Please try again.")}}async function be(){var l;const a=T;if(a!=null&&a.id){J(!0);try{await Rs({visitId:a.id,expectedScheduledAtMillis:(l=ee(a))==null?void 0:l.getTime()}),ce.success("The patient was asked to pick a new time."),B(null)}catch(h){De(h,{area:"visits",surface:"Sync visits",operation:"Sync visits failed"}),ce.error((h==null?void 0:h.message)||"Unable to ask the patient to reschedule.")}finally{J(!1)}}}const ve=i.useMemo(()=>{const a=st(d,"yyyy-MM-dd");return[...$].filter(l=>{if(ne(l,C)!==a)return!1;const h=(l.status||"").toLowerCase();return(!tr.has(h)||We(l))&&!ls(l)}).sort((l,h)=>{var Ve,Me,Ie,Oe;const D=(l.status||"").toLowerCase(),ae=(h.status||"").toLowerCase(),te=D==="in progress"?0:1,oe=ae==="in progress"?0:1;if(te!==oe)return te-oe;if(te===0){const Ce=l.updatedAt||((Ve=ee(l))==null?void 0:Ve.getTime())||0,Le=h.updatedAt||((Me=ee(h))==null?void 0:Me.getTime())||0;if(Ce!==Le)return Le-Ce}return(((Ie=ee(l))==null?void 0:Ie.getTime())||0)-(((Oe=ee(h))==null?void 0:Oe.getTime())||0)})},[$,d,C]),X=i.useMemo(()=>{const a=d.getTime();return $.filter(l=>{const h=ee(l);if(!h)return!1;const D=l.status||"";return D!=="In Progress"&&D!=="Confirmed"&&!We(l)?!1:h.getTime()>=a})},[$,d]),we=i.useMemo(()=>{const a=st(d,"yyyy-MM");return $.filter(l=>{const h=ne(l,C);return!!(h&&h.startsWith(a))})},[$,d,C]),H=i.useMemo(()=>[...$].sort((a,l)=>fe(l)-fe(a)),[$]),ie=S?pe:H,{startingVisitId:t,enterVisit:s,viewSummary:r,licensureLoading:n}=Is({isDelegate:c}),m=Te||n,x=i.useMemo(()=>[...X].sort((a,l)=>{var h,D;return(((h=ee(a))==null?void 0:h.getTime())||1/0)-(((D=ee(l))==null?void 0:D.getTime())||1/0)})[0],[X]),G=[{label:"Upcoming",value:X.length.toString(),helper:`${X.length===1?"Scheduled visit":"Scheduled visits"}`,icon:Ye},{label:"This month",value:we.length.toString(),helper:"Total visits",icon:Wt},{label:"Next visit",value:x?$e(ne(x,q())):"None",helper:x?ze(ke(x,q())):"No upcoming visits",icon:Ks}];return e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"app-page-shell min-w-0 w-full max-w-full space-y-6",children:[e.jsx(Ct,{children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Jt,{mode:"sync"}),e.jsx(Nt,{className:"app-page-title",children:"Visits"})]}),e.jsx("p",{className:"mt-1 text-sm text-content-secondary",children:c?"View visits for your provider network":"Manage your visit schedule and chart workflows"})]})}),Q&&!c?e.jsx(er,{}):null,e.jsx("div",{className:"grid min-w-0 grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:G.map(a=>
3e.jsx(Ls,{label:a.label,display:a.value,helper:a.helper,icon:a.icon,accentColor:j,loading:m},a.label))}),e.jsxs("div",{className:"app-adaptive-grid min-w-0 gap-6",children:[e.jsx("div",{className:"min-w-0",children:e.jsx(qs,{visits:ve,loading:m,currentTime:d,accentColor:j,onEnterVisit:s,onViewSummary:r,startingVisitId:t,isDelegate:c,onOpenPatientProfile:E,buildPatientProfileHref:_,userType:I,userId:U,onRescheduleVisit:ye,onAskPatientToReschedule:B,canMessagePatient:R})}),e.jsx("div",{className:"min-w-0 overflow-x-auto",children:e.jsx("div",{className:"min-w-[400px] max-lg:min-w-0",children:e.jsx(Ws,{onSelectVisit:r})})})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground",children:[e.jsxs("div",{children:[e.jsx("p",{children:"Active visits are live. Search and sorting include loaded visits; load more visits to expand the results."}),(S?V:O).scanMessage&&e.jsx("p",{role:"status",children:(S?V:O).scanMessage})]}),(S?V:O).hasMore&&e.jsx(Y,{variant:"outline",onClick:(S?V:O).loadMore,disabled:(S?V:O).loadingMore,children:(S?V:O).loadingMore?"Loading visitsâ¦":"Load more visits"})]}),e.jsx(Js,{visits:ie,loading:S?re:m,error:S?he:O.error,showAllVisits:S,scopeToggleEnabled:Q&&!c,onVisitScopeChange:ge,onRetry:()=>w(a=>a+1),onViewSummary:r,claimableVisitIds:F,claimingVisitId:P,onClaimVisit:xe}),e.jsx(Ms,{open:!!y,onClose:()=>p(null),onSuccess:()=>p(null),patientId:y==null?void 0:y.userId,rescheduleVisit:y,userType:I,userDoc:o,visitFlow:"sync"}),e.jsx(Yt,{open:!!T,onOpenChange:a=>{!a&&!A&&B(null)},title:"Ask the patient to reschedule?",description:"This cancels the current time and emails the patient a new booking link.",confirmLabel:A?"Sendingâ¦":"Ask patient",confirmDisabled:A,busy:A,onConfirm:be})]})})}export{ua as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.