1import{r as o,j as e,f as Wc,e as $l,d as Gc}from"./react-vendor-CU6Sz31W.js";import{a$ as xa,u as Se,al as Ce,hj as Bl,be as Ts,b8 as rs,as as ce,i as B,dB as Sr,a0 as ue,L as oe,c7 as yt,c8 as vt,c9 as Nt,ca as jt,cb as st,g9 as Pt,az as Me,b as je,t as I,R as un,h2 as Kc,I as be,S as $e,df as Vl,ex as it,ee as Yc,l$ as Qc,i$ as Jc,x2 as vn,d as Ve,cd as ot,ce as De,cc as bt,ax as at,x3 as ql,nw as xi,cq as Nn,e as K,bN as Wt,dP as ts,aQ as Ze,aw as _s,ad as ms,ef as Er,x4 as Xc,B as Zc,gG as ed,n as Le,K as Tr,k5 as td,go as Hl,kV as Ke,x5 as sd,uZ as pi,x6 as ad,x7 as nd,J as rd,kX as id,l4 as It,de as ld,uL as xn,u_ as ia,ih as lt,c6 as $t,kI as Ga,kJ as Ka,x8 as jn,u$ as Zn,U as Is,v0 as er,v1 as Ya,v2 as ss,v3 as kn,v4 as od,ae as Wl,af as Gl,ag as Kl,cr as pn,x9 as Pr,mG as Us,v5 as wn,bb as pa,u9 as cd,v6 as Ps,v7 as dd,me as Cn,fn as gi,v8 as ea,v9 as md,bX as Mt,eM as Ar,va as As,ah as Yl,vb as ud,vc as as,vd as ns,ta as xd,ve as pd,vf as gd,dn as hd,vg as Ql,vh as fd,xa as bd,xb as yd,O as Ge,uY as ta,xc as Sn,xd as vd,xe as hi,lI as bs,f7 as Nd,vi as jd,xf as kd,id as Qa,bM as wd,vj as Cd,s as Sd,bV as Ed,xg as Td,xh as En,xi as Pd,xj as Ad,ep as Jl,i8 as Xl,i9 as Zl,at as Ft,xk as tr,bW as eo,xl as to,gK as so,xm as Id,s_ as Ja,bO as is,bP as ls,aY as Ds,bQ as os,gJ as Xa,gH as ao,wX as Za,wY as no,C as xt,h0 as Ir,wZ as ro,c_ as io,c$ as lo,d0 as oo,d2 as co,d3 as mo,aN as Ne,a2 as Rr,es as uo,ac as Rs,cf as ds,jH as Rd,gB as xo,eC as gn,pg as Ld,ph as Od,ii as Md,xn as sr,lN as ar,et as Fd,eu as zd,lW as po,h1 as Ua,ev as _d,gi as qs,di as Da,eE as Ud,eF as Dd,eG as $d,eI as Hs,eH as Bd,cJ as Vd,cK as qd,z as Hd,au as Ls,g as go,t0 as ho,hS as ga,gN as fo,jh as Wd,gQ as Lr,bg as bo,h8 as yo,aA as Or,xo as fi,xp as Gd,xq as bi,fM as Kd,A as Yd,sR as Qd,ed as Jd,j as ys,cx as Tn,pV as yi,d8 as Xd,d1 as Zd,d4 as em,ms as tm,d5 as sm,d7 as am,ha as vi,fx as nm,ib as Pn,i_ as rm,dg as Ni,f2 as im,ij as Et,hZ as vo,tv as ba,xr as lm,xs as om,uB as cm,xt as dm,g3 as No,f0 as mm,xu as um,tw as xm,fy as jo,ak as pm,e4 as ko,xv as ji,xw as gm,xx as hm,xy as ki,fH as fm,mE as wi,j$ as sa,qm as Ot,mI as bm,xz as ym,dW as vm,dX as Nm}from"./index-DEXJEDAi.js";import{f as qe,q as mt,w as Ue,e as Xe,d as he,t as Fe,s as Pe,c as wo,i as jm,m as nr,v as Qt,k as Co,j as km}from"./firebase-w6DYUbFN.js";import{C as wm}from"./calendar-RV2oTCrW.js";import{a as $s,b as tt}from"./DataTableCard-BluwWKn_.js";import{E as Cm}from"./ExportCsvAction-BJr9eiP6.js";import"./patient-name-link-BAfQKbEs.js";import"./text-highlight-BFqqfcjs.js";import{U as Sm,k as So,l as Eo,j as Ci,m as Si,d as ya,P as Em,g as Tm}from"./StaffMessageAlertPreferencesSection-tCF7Mp0T.js";import{S as To,g as Pm,a as An,i as Am}from"./SettingsCategoryHub-chYD0p2m.js";import{B as Os}from"./BrandAssetUploader-BMswDsUm.js";import{b as Im,D as en,B as Po,a as Ao,L as Io,g as Ro,s as Lo,u as Rm}from"./useBrandingFormDraft-D8sdU2_Y.js";import{u as Oo}from"./useDebouncedBrandColorSave-H9_jJOf1.js";import{e as la,T as oa,a as At,b as Be,c as ca,d as Ie}from"./table-CxPdvV_9.js";import{E as Lm}from"./ellipsis-tooltip-CfKm8VFV.js";import{f as Om}from"./formatDistanceToNow-110oImMD.js";import{C as Mm}from"./circle-dashed-BpzaptvF.js";import{c as Mo,a as Fo}from"./tenantDomainApi-CfLoxpJP.js";import{C as Fm}from"./CheckoutShell-DPiImp5d.js";import{a as zm}from"./checkoutShellChrome-B_HUtum-.js";import{E as Ei}from"./EditorialCheckoutAccordion-BKtWmc-J.js";import{P as _m,a as Um}from"./PublicCheckoutContactStep-CBDZu5yA.js";import{C as Dm}from"./CheckoutPreviewViewport-D2aw1liL.js";import{u as $m,g as Bm,P as Vm,n as aa,a as zo,b as Ti}from"./PatientCustomFieldsSection-DCuc54t7.js";import{c as qm,n as _o,d as Uo}from"./brandColorUtils-CmIuziqQ.js";import{F as Hm,b as Wm}from"./monacoSetup-BmLIy17x.js";import{B as va,f as Gm}from"./businessTagEmojiCatalog-DyuQVEw_.js";import{C as Km}from"./combobox-D0C_yDo2.js";import{k as Mr,l as Fr,P as zr,D as tn,m as sn,C as hn,G as ha}from"./core.esm-DPjjHB-Z.js";import{S as an,v as nn,a as rr,u as fn}from"./sortable.esm-Cj9Co3ow.js";import{u as Ym,H as Qm}from"./HealthCategoryIcon-ToygNn-5.js";import{M as us,o as xs}from"./modal-form-CqN5DZuv.js";
1import{A as Pi}from"./arrow-up-D6DFVL4j.js";import{A as Ai}from"./arrow-down-BjUlbB4f.js";import{P as zt}from"./pencil-CpqYHolO.js";import{C as Jm}from"./chevrons-up-down-DBsg_kZs.js";import{u as Xm}from"./UnsavedGuard-CHqsTdlf.js";import{S as Zm}from"./store-BJ_KlhiM.js";import{L as eu}from"./log-in-DrQuRn0i.js";import{M as Do}from"./monitor-CzX6E2vl.js";import{C as tu,a as Cs,b as da,c as ir,W as Ms,i as lr,m as Ii,f as Ri,d as su,e as au,g as nu,h as ru,u as iu,j as lu}from"./ClientApiDocsContent-By_m5ljy.js";import{D as $o,S as Bo,M as _r}from"./cells-Db2ZEFlu.js";import{u as Ur}from"./useTableSort-KpNOL2n3.js";import{P as Vo}from"./pause-COS6hXZe.js";import{E as ou}from"./ellipsis-C0FvDuxB.js";import{c as cu}from"./filterDescriptorUtils-NUS9ISaN.js";import{A as du}from"./arrow-up-right-DG_mPx_g.js";import{T as qo,A as mu}from"./ApiNetworkActivityPanel-DSCo5u5f.js";import{P as uu}from"./PaymentProcessorConfigSection-vEVKCxMV.js";import{h as xu,n as Ho,b as or,M as cr,S as Wo}from"./messageAlertPreferences-CKXCeAva.js";import{R as Go}from"./RoutePageHeader-9W0v4VlT.js";import{T as pu}from"./TwilioMessagingSettingsCard-DsoTjUdN.js";import{M as gu}from"./message-square-text-CBK4eOxL.js";import{u as hu}from"./useNetworkTimezone-DAycysvJ.js";import"./ChartStage-kk8qB2rS.js";import{S as Jt}from"./StatTile-DQJZPnfG.js";import{i as fu}from"./networkLicensurePolicy-Ct3PZM4V.js";import{n as bu}from"./resolveClientProductToPrescriptionLine-B2vrGarB.js";import{q as yu,t as Li,u as Oi,w as Ko,x as dr,D as vs,y as vu,z as Nu,A as ju,C as rn,n as mr,j as Zt,B as Mi,E as ku,F as ft,G as Yo,H as In,I as wu}from"./chartingWorkflow-C6kNA8aD.js";import{P as Cu,G as Su,V as Qo}from"./PatientFieldDefinitionDialog-BZBSN9SQ.js";import{l as Eu}from"./usePatientFieldDefinitions-DS6fhdRU.js";import{r as Tu}from"./patientFieldDefinitionCaches-PDqtgCkY.js";import{n as Pu}from"./syncVisitClaiming-DMQn7ZCY.js";import{B as Fi,c as Au,a as ln,A as Ws,i as Iu}from"./belugaSyncVisitPolicy-D9EEWL4u.js";import{Q as Ru}from"./quill-editor-D-DS6c39.js";import{S as Lu}from"./ScrollPagination-ChbtpYdB.js";import{M as Ou}from"./MessageTemplatesManager-BesVHpQc.js";import{a as Mu}from"./collectExportPages-B1mgoF_8.js";import{u as Fu}from"./use-unsaved-changes-B6nL5Xdd.js";import{B as zu}from"./bot-CKyIH0jX.js";import"./payment-icons-Daq1K3F1.js";import"./addWeeks-1hrFjz19.js";import"./index-BSuGcRaZ.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"./scopedCategoryFirestore-C15ZJbmw.js";import"./user-round-c4EWOTq5.js";import"./messages-square-DnsDR3ke.js";import"./checkoutDisplay-6C7UrTTD.js";import"./usePatientCustomFieldDefinitions-D8T6S06N.js";import"./archive-restore-1_z2aByp.js";import"./sliders-horizontal-Bt65nPrH.js";import"./moon-star-CZ9ZVii6.js";import"./formReviewWorkflowSettings-BffZ3dCL.js";import"./clientWorkflowSettingsCache-Bq3pRC3F.js";import"./code-xml-Ca2tsB5V.js";import"./ellipsis-vertical-C-dQ6Kzj.js";import"./ProfileAdministratorPlanCard-C6brNhoH.js";import"./billingFormat-BA-DkSSw.js";import"./arrow-right-BC3JVmLt.js";import"./ban-DZ1NMSKK.js";import"./localTableUtils-D6jRZlmf.js";import"./file-pen-line-Dk_v9Q45.js";import"./RoutePageHeaderContent-FkxdZGox.js";import"./chartTheme-By-OHNNJ.js";import"./formatters-C_0Kn-_3.js";import"./formularyVariants-BV7CaEYS.js";import"./editor-D8UbQKN1.js";import"./audio-lines-GJL3_Ka2.js";import"./square-D7DkS8S2.js";import"./link-2-a8lhpkQ6.js";import"./code-BEcI87AG.js";import"./strikethrough-CiKozLGy.js";import"./underline-B_XtWKJP.js";import"./list-ordered-GNrnoOhB.js";import"./useTemplateVariableInsertion-DRs-_PWy.js";import"./prescriptionMessageTemplateVariables-AMxKc8BX.js";/** 2 * @license lucide-react v0.475.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const _u=[["path",{d:"M17 7 7 17",key:"15tmo1"}],["path",{d:"M17 17H7V7",key:"1org7z"}]],Jo=xa("ArrowDownLeft",_u);/** 7 * @license lucide-react v0.475.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const Uu=[["path",{d:"m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08",key:"1styjt"}],["path",{d:"M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z",key:"z0l1mu"}]],Du=xa("Brush",Uu);/** 12 * @license lucide-react v0.475.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const $u=[["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 11.75V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7.25",key:"1jrsq6"}],["path",{d:"m22 22-1.875-1.875",key:"13zax7"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],Bu=xa("CalendarSearch",$u);/** 17 * @license lucide-react v0.475.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const Vu=[["path",{d:"M18 8c0 3.613-3.869 7.429-5.393 8.795a1 1 0 0 1-1.214 0C9.87 15.429 6 11.613 6 8a6 6 0 0 1 12 0",key:"11u0oz"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["path",{d:"M8.714 14h-3.71a1 1 0 0 0-.948.683l-2.004 6A1 1 0 0 0 3 22h18a1 1 0 0 0 .948-1.316l-2-6a1 1 0 0 0-.949-.684h-3.712",key:"q8zwxj"}]],on=xa("MapPinned",Vu);/** 22 * @license lucide-react v0.475.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const qu=[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M14 8H8",key:"1l3xfs"}],["path",{d:"M16 12H8",key:"1fr5h0"}
26],["path",{d:"M13 16H8",key:"wsln4y"}]],Hu=xa("ReceiptText",qu),zi=[{id:"issueRefunds",name:"Issue refunds and void payments",area:"Orders",description:"Whole-order payments only. Installment refunds remain restricted to Client Admin."},{id:"createPaymentRequests",name:"Create payment requests",area:"Orders",description:"Create manual invoices for this clientâs patients."},{id:"manageCoupons",name:"Manage coupons",area:"Catalog",description:"Create, edit, deactivate, and assign coupons when coupons are enabled for this client."},{id:"sendMarketing",name:"Send marketing",area:"Marketing",description:"Compose, schedule, and send campaigns and flows."},{id:"manageSubscriptions",name:"Manage subscriptions",area:"Subscriptions",description:"Pause, resume, and cancel patient subscription enrollments."},{id:"createVisits",name:"Create visits",area:"Visits",description:"Book visits for patients or ask patients to schedule one."}];function Wu(){const{userDoc:t,userType:s}=Se(),{branding:a}=Ce(),i=t==null?void 0:t.clientId,n=Bl(t),r=Ts(s,"Client Admin")&&n==="Client",[l,c]=o.useState(null),[u,m]=o.useState(null),[h,g]=o.useState(""),[y,p]=o.useState(!1),[d,x]=o.use
26State(0),[f,C]=o.useState([]),[N,v]=o.useState(!0),[k,P]=o.useState(""),[A,E]=o.useState("");o.useEffect(()=>{if(!r||!i)return;let j=!1;return c(null),g(""),rs("manageClient",{action:"getClientStaffPermissions",clientId:i}).then(({data:L})=>{j||(c(L),m(L))}).catch(L=>{j||g(L.message||"Unable to load permissions.")}),()=>{j=!0}},[r,i,d]),o.useEffect(()=>{if(!(!r||!i))return v(!0),P(""),E(""),qe(mt(Xe(ce,"Users"),Ue("clientId","==",i),Ue("userType","==","Client Staff")),j=>{C(j.docs.map(L=>({...L.data(),id:L.id}))),v(!1)},j=>{P(j.message||"Unable to load staff."),v(!1)})},[r,i,d]);async function z(){p(!0),g("");try{const{data:j}=await rs("manageClient",{action:"updateClientStaffPermissions",clientId:i,permissions:l});c(j),m(j),Pt.success("Staff permissions updated")}catch(j){g(j.message||"Unable to save permissions. Your changes have been kept.")}finally{p(!1)}}if(!r||!i)return null;const q=l&&zi.some(j=>l[j.id]!==(u==null?void 0:u[j.id])),R=f.find(j=>j.id===A),O=[{id:"permission",header:"Permission",width:"56%",renderCell:j=>e.jsxs("div",{className:"space-y-1 py-2",children:[e.jsx("p",{className:"text-xs text-content-tertiary",children:j.area}),e.jsx("p",{className:"font-medium text-content-primary",children:j.name}),e.jsx("p",{className:"max-w-md whitespace-normal text-xs text-content-secondary",children:j.description})]})},{id:"admin",header:"Client Admin",headerClassName:"whitespace-normal",width:"22%",renderCell:j=>e.jsx(Me,{checked:!0,disabled:!0,"aria-label":`Client Admin: ${j.name} (always allowed)`})},{id:"staff",header:"Client Staff",headerClassName:"whitespace-normal",width:"22%",renderCell:j=>e.jsx(Me,{checked:(l==null?void 0:l[j.id])===!0,disabled:!l||y,"aria-label":`Client Staff: ${j.name}`,onCheckedChange:L=>c(b=>({...b,[j.id]:L===!0}))})}];return e.jsxs("div",{className:"space-y-6 max-lg:space-y-3",children:[e.jsx("p",{className:"text-sm text-content-secondary",children:"Choose what Client Staff can do. Changes apply to every Client Staff member in this client. Client Admin permissions are fixed."}),h?e.jsxs("div",{role:"alert",className:"space-y-2 text-sm text-destructive",children:[e.jsx("p",{children:h}),l?null:e.jsx(B,{variant:"outline",onClick:()=>x(j=>j+1),children:"Retry"})]}):null,e.jsx($s,{id:"client-staff-permissions",title:"Permissions",accentColor:a==null?void 0:a.accentColor,columns:O,rows:zi,loading:!l&&!h,tableLabel:"Client role permissions",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",disabled:!q||y,onClick:()=>c(u),children:"Discard"}),e.jsx(B,{disabled:!q||y,onClick:z,children:y?"Savingâ¦":"Save permissions"})]})}),e.jsx(Sr,{title:"Catalog visibility",description:"Choose which catalog categories each staff member sees. These display filters do not restrict access to patient records or replace data authorization.",accentColor:a==null?void 0:a.accentColor,children:N?e.jsx(ue,{className:"h-10 w-full"}):k?e.jsxs("div",{role:"alert",children:[e.jsx("p",{className:"text-sm text-destructive",children:k}),e.jsx(B,{variant:"outline",onClick:()=>x(j=>j+1),children:"Retry"})]}):f.length===0?e.jsx("p",{className:"text-sm text-content-secondary",children:"No Client Staff members yet. Add a staff member to configure catalog visibility."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"catalog-staff",children:"Staff member"}),e.jsxs(yt,{value:A,onValueChange:E,children:[e.jsx(vt,{id:"catalog-staff",children:e.jsx(Nt,{placeholder:"Choose a staff member"})}),e.jsx(jt,{children:f.map(j=>e.jsx(st,{value:j.id,children:[j.firstName,j.lastName].filter(Boolean).join(" ")||j.email||"Staff member"},j.id))})]})]})}),R?e.jsx(Sm,{checkboxMode:!0,user:R,viewerUserType:s,viewerUserDoc:t,isReadOnly:!1},R.id):null]})}function Gu(t){return(t||"").replace(/[^0-9.]/g,"")}function Ku(t){if(t==null||t==="")return"";const s=Number.parseFloat(String(t));return!Number.isFinite(s)||s<0?"":s.toFixed(2)}function Yu(){const{userDoc:t}=Se(),{branding:s}=Ce(),a=t==null?void 0:t.clientId,i=(s==null?void 0:s.accentColor)||je,[n,r]=o.useState(!0),[l,c]=o.useState(!1),[u,m]=o.useState(""),h=o.useRef("");o.useEffect(()=>{if(!a){r(!1);return}const y=qe(he(ce,"Clients",a),p=>{const d=p.exists()?p.data():{},x=Ku((d==null?void 0:d.defaultShippingPrice)??"");m(x),h.current=x,r(!1)},p=>{console.error("Error loading shipping settings:",p),I.error("Unable to load shipping settings."),r(!1)});return()=>y()},[a]);const g=o.useCallback(async y=>{if(!a)return;const p=y.trim(),d=p===""?null:Number.parseFloat(p);if(p!==""&&(!Number.isFinite(d)||d<0)){I.error("Enter a valid shipping price (e.g. 5.00)"),m(h.current);return}const x=d!=null?d.toFixed(2):"";if(x!==h.current)try{c(!0),await Fe(he(ce,"Clients",a),{defaultShippingPrice:d!=null?x:null,updatedAt:Pe()}),h.current=x,I.success("Default shipping price updated")}
26catch(f){un(f,{area:"checkout",surface:"frontend/src/pages/settings/SettingsClientAdminView/SettingsPayments/ClientShippingSection.jsx",operation:"frontend/src/pages/settings/SettingsClientAdminView/SettingsPayments/ClientShippingSection.jsx:81"}),console.error("Error saving shipping price:",f),I.error("Unable to save shipping price. Please try again."),m(h.current)}finally{c(!1)}},[a]);return a?e.jsx(tt,{id:"client-default-shipping",title:"Default shipping price",description:"Applies to all products unless a per-product override is set. Leave blank or 0 for free shipping.",icon:Kc,accentColor:i,loading:n,bodyClassName:"bg-surface-raised p-4",actions:l?e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-content-tertiary",children:[e.jsx($e,{size:"xs"}),"Savingâ¦"]}):null,children:n?e.jsx(ue,{className:"h-9 w-40 max-lg:h-8"}):e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsx(oe,{htmlFor:"client-default-shipping-price",className:"text-xs text-content-secondary max-lg:text-2xs",children:"Amount (USD)"}),e.jsxs("div",{className:"relative w-40",children:[e.jsx("span",{className:"pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-content-tertiary max-lg:left-2.5 max-lg:text-xs",children:"$"}),e.jsx(be,{id:"client-default-shipping-price",type:"text",inputMode:"decimal",className:"h-9 pl-6 text-sm max-lg:h-8 max-lg:pl-5",placeholder:"0.00",value:u,disabled:l,onChange:y=>m(Gu(y.target.value)),onBlur:y=>g(y.target.value),onKeyDown:y=>{y.key==="Enter"&&y.currentTarget.blur()}})]})]})}):null}function Qu(){const{userDoc:t}=Se(),{branding:s}=Ce(),a=t==null?void 0:t.clientId,i=(s==null?void 0:s.accentColor)||je,[n,r]=o.useState(!0),[l,c]=o.useState(!1),[u,m]=o.useState(!1);o.useEffect(()=>{if(!a){r(!1);return}const y=qe(he(ce,"Clients",a),p=>{const d=p.exists()?p.data():{};m((d==null?void 0:d.vaultChargeOrdersEnabled)===!0),r(!1)},p=>{console.error("Error loading vault charge orders setting:",p),I.error("Unable to load vault charge orders setting."),r(!1)});return()=>y()},[a]);async function h(y){if(!a)return;const p=u;m(y);try{c(!0),await Fe(he(ce,"Clients",a),{vaultChargeOrdersEnabled:y,updatedAt:Pe()}),I.success(y?"Vault charge orders enabled":"Vault charge orders disabled")}catch(d){un(d,{area:"checkout",surface:"frontend/src/pages/settings/SettingsClientAdminView/SettingsPayments/ClientVaultChargeOrdersSection.jsx",operation:"frontend/src/pages/settings/SettingsClientAdminView/SettingsPayments/ClientVaultChargeOrdersSection.jsx:62"}),console.error("Error updating vault charge orders setting:",d),m(p),I.error("Unable to update vault charge orders. Please try again.")}finally{c(!1)}}if(!a)return null;const g=n||l;return e.jsx(tt,{id:"client-vault-charge-orders",title:"Charge saved payment methods after approval",description:"For orders created through an integration, automatically charge the patientâs saved payment method when a provider approves treatment or a reviewed lab order is released.",icon:Vl,accentColor:i,loading:n,bodyClassName:"bg-surface-raised p-4",actions:l?e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-content-tertiary",children:[e.jsx($e,{size:"xs"}),"Savingâ¦"]}):null,children:e.jsxs("div",{className:"flex items-start justify-between gap-4 max-lg:gap-2",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:"client-vault-charge-orders-enabled",className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Enable vault charge orders"}),e.jsx("p",{className:"text-xs leading-5 text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"When off, API requests with medication_amount and stored payment references are rejected."})]}),e.jsx(it,{id:"client-vault-charge-orders-enabled",checked:u,disabled:g,onCheckedChange:h,"aria-label":"Enable vault charge orders"})]})})}function Ju(){const{userDoc:t}=Se(),{branding:s}=Ce(),a=t==null?void 0:t.clientId,i=(s==null?void 0:s.accentColor)||je,[n,r]=o.useState(!0),[l,c]=o.useState(!1),[u,m]=o.useState(!1),[h,g]=o.useState(!1);o.useEffect(()=>{if(!a){r(!1);return}const d=qe(he(ce,"Clients",a),x=>{const f=x.exists()?x.data():{};m((f==null?void 0:f.finiteInstallmentBillingEnabled)===!0),g((f==null?void 0:f.vaultChargeOrdersEnabled)===!0),r(!1)},x=>{console.error("Error loading finite installment billing setting:",x),I.error("Unable to load finite installment billing setting."),r(!1)});return()=>d()},[a]);async function y(d){if(!a||!h)return;const x=u;m(d);try{c(!0),await Fe(he(ce,"Clients",a),{finiteInstallmentBillingEnabled:d,updatedAt:Pe()}),I.success(d?"Finite installment billing enabled":"Finite installment billing disabled")}
26catch(f){un(f,{area:"checkout",surface:"frontend/src/pages/settings/SettingsClientAdminView/SettingsPayments/ClientFiniteInstallmentBillingSection.jsx",operation:"frontend/src/pages/settings/SettingsClientAdminView/SettingsPayments/ClientFiniteInstallmentBillingSection.jsx:64"}),console.error("Error updating finite installment billing setting:",f),m(x),I.error("Unable to update finite installment billing. Please try again.")}finally{c(!1)}}if(!a)return null;const p=n||l||!h;return e.jsx(tt,{id:"client-finite-installment-billing",title:"Finite installment billing",description:"Allow pay-in-full or split-3 medication billing on vault-charge orders using NMI, SimPay, or SlidePay. Installment 1 is charged at prescribe; installments 2â3 are collected via a finite gateway subscription.",icon:Yc,accentColor:i,loading:n,bodyClassName:"bg-surface-raised p-4",actions:l?e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-content-tertiary",children:[e.jsx($e,{size:"xs"}),"Savingâ¦"]}):null,children:e.jsxs("div",{className:"flex items-start justify-between gap-4 max-lg:gap-2",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:"client-finite-installment-billing-enabled",className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Enable finite installment billing"}),e.jsx("p",{className:"text-xs leading-5 text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:h?"When off, API requests with payment_option or installment_billing are rejected. Split-3 is only offered for 3+ month products.":"Requires vault charge orders to be enabled first."})]}),e.jsx(it,{id:"client-finite-installment-billing-enabled",checked:u,disabled:p,onCheckedChange:y,"aria-label":"Enable finite installment billing"})]})})}function _i(t){return String(t||"").trim().replace(/\s+/g," ")}function Xu(){const{userDoc:t,clientData:s}=Se(),a=(t==null?void 0:t.clientId)||(s==null?void 0:s.id)||null,[i,n]=o.useState(""),[r,l]=o.useState(!1),c=o.useMemo(()=>Qc(s==null?void 0:s.customOrderStatuses),[s==null?void 0:s.customOrderStatuses]);async function u(g,y){var p;if(!(!a||r)){l(!0);try{const d=await rs("manageClient",{action:"updateCustomOrderStatuses",clientId:a,statuses:g.map(x=>({name:x.name}))});return I.success(y),((p=d==null?void 0:d.data)==null?void 0:p.customOrderStatuses)||g}catch(d){return I.error((d==null?void 0:d.message)||"Unable to update custom order statuses."),null}finally{l(!1)}}}async function m(g){g.preventDefault();const y=_i(i);if(!y)return;if(y.length>vn){I.error(`Status names must be ${vn} characters or fewer.`);return}if(c.some(d=>d.name.toLowerCase()===y.toLowerCase())){I.error("That custom status already exists.");return}if(c.length>=20){I.error("You can create up to 20 custom statuses.");return}await u([...c,{name:y}],"Custom order status added")&&n("")}async function h(g){c.find(p=>p.id===g)&&await u(c.filter(p=>p.id!==g),"Custom order status removed")}return a?e.jsxs(tt,{id:"client-custom-order-statuses",title:"Custom order statuses",description:"Add optional statuses for your team to use on client orders. Standard statuses remain available.",icon:Jc,accentColor:(s==null?void 0:s.accentColor)||je,countLabel:`${c.length} of 20 used`,bodyClassName:"space-y-4 p-4 max-lg:space-y-2.5 sm:p-5",children:[e.jsxs("form",{onSubmit:m,className:"flex flex-col gap-2 max-lg:gap-1.5 sm:flex-row",children:[e.jsx(be,{value:i,onChange:g=>n(g.target.value),maxLength:vn,placeholder:"e.g. Ready for pickup","aria-label":"New custom order status",disabled:r||c.length>=20,className:"h-9 flex-1 max-lg:h-8 dark:border-slate-600 dark:bg-slate-900"}),e.jsxs(B,{type:"submit",disabled:r||!_i(i)||c.length>=20,className:"h-9 rounded-full max-lg:h-8",children:[r?e.jsx(Ve,{className:"mr-1.5 size-4 animate-spin max-lg:mr-1 max-lg:size-3.5","aria-hidden":!0}):e.jsx(ot,{className:"mr-1.5 size-4 max-lg:mr-1 max-lg:size-3.5","aria-hidden":!0}),"Add status"]})]}),c.length===0?e.jsx("p",{className:"rounded-lg border border-dashed border-default px-4 py-6 text-center text-sm text-content-tertiary max-lg:px-3 max-lg:py-3 max-lg:text-xs",children:"No custom statuses yet. Add one when your team needs an extra order milestone."}):e.jsx("div",{className:"grid gap-3 max-lg:gap-1.5 sm:grid-cols-2",children:c.map(g=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-subtle bg-slate-50/60 p-3 max-lg:gap-2 max-lg:p-2 dark:bg-slate-900/30",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-content-primary max-lg:text-xs",children:g.name}),e.jsx(De,{variant:"outline",className:"mt-1 text-3xs font-normal text-content-tertiary max-lg:mt-0.5 max-lg:px-1.5 max-lg:py-0",children:"Custom"})]}
26),e.jsx(B,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove ${g.name}`,onClick:()=>h(g.id),disabled:r,className:"size-8 shrink-0 text-content-tertiary hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/30",children:e.jsx(bt,{className:"size-4 max-lg:size-3.5","aria-hidden":!0})})]},g.id))})]}):null}function Zu({className:t}){return e.jsxs("svg",{viewBox:"0 0 200 260",className:t,"aria-hidden":!0,focusable:"false",children:[e.jsx("ellipse",{cx:"100",cy:"72",rx:"46",ry:"50"}),e.jsx("path",{d:"M36 250 C36 168 164 168 164 250 Z"})]})}function ex({open:t,onOpenChange:s,logoUrl:a,backgroundColor:i,virtualBackgroundUrl:n=""}){const[r,l]=o.useState(""),[c,u]=o.useState(!1),[m,h]=o.useState("");return o.useEffect(()=>{if(!t){l(""),h(""),u(!1);return}if(n){l(n),h(""),u(!1);return}if(!a){l(""),h("Upload a client logo to preview the virtual background."),u(!1);return}let g="",y=!1;async function p(){u(!0),h("");try{const d=await ql(a,i);g=URL.createObjectURL(d),y||l(g)}catch(d){y||(l(""),h((d==null?void 0:d.message)||"Unable to generate preview."))}finally{y||u(!1)}}return p(),()=>{y=!0,g&&URL.revokeObjectURL(g)}},[t,a,i,n]),e.jsx(at,{open:t,onOpenChange:s,size:"md",title:"Virtual background example",titleClassName:"font-display text-lg font-semibold text-content-primary",description:"Patients see the provider on camera with your branded logo background during sync visits, similar to visit charting video.",children:e.jsxs("div",{children:[e.jsxs("div",{className:"relative mx-auto aspect-video w-full overflow-hidden rounded-xl border border-subtle bg-slate-950 shadow-sm",children:[c?e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-slate-100 dark:bg-slate-900",children:[e.jsx(Ve,{className:"size-6 animate-spin text-slate-400 max-lg:size-5","aria-hidden":!0}),e.jsx("span",{className:"sr-only",children:"Loading preview"})]}):null,!c&&m?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-surface-sunken px-6 text-center max-lg:px-3",children:e.jsx("p",{className:"text-sm text-content-secondary max-lg:text-xs",children:m})}):null,!c&&!m&&r?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:r,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-t from-slate-950/25 via-transparent to-transparent","aria-hidden":!0}),e.jsx("div",{className:"absolute inset-0 flex items-end justify-center pb-[10%]",children:e.jsx(Zu,{className:"h-[62%] w-auto fill-slate-900/70 drop-shadow-[0_8px_24px_rgba(15,23,42,0.35)]"})})]}):null]}),e.jsx("p",{className:"text-center text-xs text-content-tertiary max-lg:text-2xs",children:"Illustration only â the provider's live camera feed appears in front of this background."})]})})}const tx=new Set(["co.uk","org.uk","ac.uk","com.au","net.au","org.au","co.nz","co.in","com.br","com.mx","co.za","com.sg","com.hk","co.jp"]),Ns="notifications",sx=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,ax=/^[a-z0-9._-]{1,64}$/;function Ui(t){return String(t||"").trim().toLowerCase().replace(/^https?:\/\//,"").split("/")[0].replace(/\.+$/,"")}function nx(t){return String(t||"").trim().toLowerCase()}function Xs(t){const s=String(t||"").replace(/\.$/,"").split(".").filter(Boolean);if(s.length<=2)return s.join(".");const a=s.slice(-2).join(".");return s.slice(tx.has(a)?-3:-2).join(".")}function Gs(t,s){const a=String(t||"").replace(/\.$/,"");return!s||a===s?"@":a.endsWith(`.${s}`)?a.slice(0,-(s.length+1)):a}function Xo(t){const s=t.split(".");return s.length>=2&&t.length<=253&&s.every(a=>sx.test(a))}function Di(t){return t?Xo(t)?Xs(t)===t?"Use a subdomain, like portal.yourclinic.com. Root domains are not supported.":"":"Enter a valid address, like portal.yourclinic.com.":""}function $i(t){return t?Xo(t)?"":"Enter a valid domain, like yourclinic.com.":""}function rx(t){return t?ax.test(t)?"":"Use letters, numbers, dots, dashes, or underscores, like notifications.":""}function Bi(t){if(!t)return null;let s=null;return typeof t.toDate=="function"?s=t.toDate():typeof t=="string"||typeof t=="number"?s=new Date(t):typeof t.seconds=="number"?s=new Date(t.seconds*1e3):typeof t._seconds=="number"&&(s=new Date(t._seconds*1e3)),s&&!Number.isNaN(s.getTime())?s:null}const ix=["dns_verified","activating","active"],Vi={pending_dns:{label:"Waiting for DNS",tone:"warning"},dns_verified:{label:"DNS verified",tone:"info"},activating:{label:"Activating",tone:"info"},active:{label:"Active",tone:"success"},error:{label:"Needs attention",tone:"danger"}},ur={success:"border-status-success bg-status-success text-status-success",warning:"border-status-warning bg-status-warning text-status-warning",info:"border-status-info bg-status-info text-status-info",danger:"border-status-danger bg-status-danger text-status-danger",neutral:"border-subtle bg-surface-sunken text-content-secondary"},qi={found:{label:"Found",tone:"success",Icon:Ze},pending:{label:"Pending",tone:"warning",Icon:Er},not_checked:{label:"Not checked",tone:"neutral",Icon:Mm}},js={portal:"Portal",email:"Email"};function Zo({tone:t,Icon:s,children:a,testId:i}){return e.jsxs("span",{className:K(Xc,"w-fit whitespace-nowrap",ur[t]),"data-testid":i,children:[s?e.jsx(s,{className:"size-3","aria-hidden":"true"}):null,a]})}function Hi({status:t}){const s=Vi[t]||Vi.pending_dns;return e.jsx(Zo,{tone:s.tone,children:s.label})}function Wi({status:t}){const s=qi[t]||qi.not_checked;return e.jsx(Zo,{tone:s.tone,Icon:s.Icon,children:s.label})}const Gi="opacity-0 [filter:blur(var(--icon-swap-blur))] [transform:scale(var(--icon-swap-start-scale))]";function $a({swapped:t,from:s,to:a}){return e.jsxs("span",{className:"t-icon-swap size-4 shrink-0 place-items-center",children:[e.jsx("span",{className:K("t
26-icon inline-flex",t&&Gi),"aria-hidden":"true",children:s}),e.jsx("span",{className:K("t-icon inline-flex",!t&&Gi),children:a})]})}const lx=1600;function ec({text:t,label:s}){const[a,i]=o.useState(!1),n=o.useRef(null);o.useEffect(()=>()=>clearTimeout(n.current),[]);async function r(){try{await navigator.clipboard.writeText(t),i(!0),clearTimeout(n.current),n.current=setTimeout(()=>i(!1),lx)}catch{Pt.error({message:"Could not copy. Select the text and copy it by hand."})}}return e.jsxs(B,{type:"button",variant:"ghost",size:"icon",className:"size-8 shrink-0 rounded-full text-content-tertiary hover:text-content-primary",onClick:r,"aria-label":s,title:a?"Copied":s,children:[e.jsx($a,{swapped:a,from:e.jsx(ms,{className:"!size-3.5"}),to:e.jsx(Ze,{className:"!size-3.5 text-status-success","aria-hidden":"true"})}),e.jsx("span",{className:"sr-only",role:"status",children:a?"Copied":""})]})}const ox="Appears after you save";function Na({text:t,preview:s=!1,copyLabel:a}){return t?e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(Lm,{text:t,className:K("flex-1 py-1.5 font-mono text-xs",s?"text-content-tertiary":"text-content-primary")}),s?null:e.jsx(ec,{text:t,label:a})]}):e.jsx("span",{className:"block py-1.5 text-xs italic text-content-tertiary",children:ox})}function Ks({configured:t,found:s,checked:a}){return t?s?"found":a?"pending":"not_checked":"not_checked"}function tc({tenantId:t,customDomain:s,emailDomain:a,accentColor:i,customDomainApi:n,emailDomainApi:r,testIdPrefix:l="tenant-domain",signInLink:c=null}){const u=i||je,[m,h]=o.useState(s||null),[g,y]=o.useState(a||null),[p,d]=o.useState(null),[x,f]=o.useState(null),[C,N]=o.useState(""),[v,k]=o.useState(""),[P,A]=o.useState((a==null?void 0:a.fromLocalPart)||Ns),[E,z]=o.useState({}),[q,R]=o.useState(!1),[O,j]=o.useState(!1),[L,b]=o.useState(!1),[w,F]=o.useState(null),[M,W]=o.useState(!1),H=o.useRef(null),ae=o.useRef(null),xe=o.useRef(null),Ae=o.useRef(null);o.useEffect(()=>{h(s||null)},[s]),o.useEffect(()=>{y(a||null)},[a]);const se=(m==null?void 0:m.hostname)||"",Z=!!se,fe=(m==null?void 0:m.status)||"pending_dns",J=(g==null?void 0:g.hostname)||"",ge=!!J,ye=(g==null?void 0:g.status)||"pending_dns",Re=(g==null?void 0:g.fromLocalPart)||Ns;o.useEffect(()=>{A(Re)},[Re]),o.useEffect(()=>{d(null)},[se]);const G=Ui(C),U=Ui(v),V=nx(P),D=!Z&&!!G,T=!ge&&!!U,$=ge&&(V||Ns)!==Re,S=!!c&&String(c.value||"")!==String(c.savedValue||""),Q=D||T||$||S,Y=q||O||L||M,ve=`${V||Ns}@${J||U||"yourclinic.com"}`,Ee=Z&&["dns_verified","activating","error"].includes(fe),Oe=se||(Di(G)?"":G),nt=J,ze=J||($i(U)?"":U),pt=!!(Oe&&ze&&Xs(Oe)!==Xs(ze)),Bt=o.useMemo(()=>{const ee=Xs(Oe),Ye=!!(p||m!=null&&m.lastCheckedAt),ht=ix.includes(fe),He=new URL(xi()).hostname.startsWith("staging.")?"_gen-health-staging":"_gen-health",re=(m==null?void 0:m.verificationRecordName)||(Oe?`${He}.${Oe}`:""),pe=!Z,me=[{key:"portal-cname",type:"CNAME",purpose:"portal",hint:"Points your portal address to us.",host:Oe?Gs(Oe,ee):"",value:Z&&(m==null?void 0:m.dnsTarget)||"",preview:pe,status:Ks({configured:Z,found:ht||!!(p!=null&&p.cnameVerified),checked:Ye})},{key:"portal-txt",type:"TXT",purpose:"portal",hint:"Proves you own the domain.",host:re?Gs(re,ee):"",value:Z&&(m==null?void 0:m.verificationToken)||"",preview:pe,status:Ks({configured:Z,found:ht||!!(p!=null&&p.txtVerified),checked:Ye})}],ie=m==null?void 0:m.certificateRecord;Z&&ie&&me.push({key:"portal-certificate",type:ie.type||"CNAME",purpose:"portal",hint:"Keeps your portal secure (SSL). Leave it in place.",host:Gs(ie.name,ee),value:ie.value||"",preview:!1,status:Ks({configured:!0,found:!!ie.live,checked:Ye})});const _e=Xs(nt),kt=ye==="active",ke=(g==null?void 0:g.dkim)||{},Kt=(g==null?void 0:g.returnPath)||{},Ct=!!(g!=null&&g.lastCheckedAt||ke.verified||Kt.verified);return me.push({key:"email-dkim",type:"TXT",purpose:"email",hint:"Proves emails really come from you.",host:ge&&ke.host?Gs(ke.host,_e):"",value:ge&&ke.textValue||"",preview:!1,status:Ks({configured:ge,found:kt||!!ke.verified,checked:Ct})},{key:"email-return-path",type:"CNAME",purpose:"email",hint:"Handles bounced emails.",host:ge&&Kt.host?Gs(Kt.host,_e):"",value:ge&&Kt.cnameValue||"",preview:!1,status:Ks({configured:ge,foun
26d:kt||!!Kt.verified,checked:Ct})}),me},[Oe,p,m,fe,Z,nt,g,ye,ge]),Gt=o.useMemo(()=>{const ee=[Bi(m==null?void 0:m.lastCheckedAt),Bi(g==null?void 0:g.lastCheckedAt),x].filter(Boolean);return ee.length?new Date(Math.max(...ee.map(Ye=>Ye.getTime()))):null},[m==null?void 0:m.lastCheckedAt,g==null?void 0:g.lastCheckedAt,x]),cs=Bt.every(ee=>ee.status==="found"),X=Z||ge;function We(ee){z(Ye=>Ye[ee]?{...Ye,[ee]:""}:Ye)}function ct(){var ee;N(""),k(""),A(Re),z({}),S&&((ee=c.onDiscard)==null||ee.call(c))}async function gt(ee){var pe,me;if(ee.preventDefault(),Y||!Q)return;const Ye={portal:D?Di(G):"",emailDomain:T?$i(U):"",localPart:T||$?rx(V):""},ht=[["portal",H],["localPart",xe],["emailDomain",ae]].find(([ie])=>Ye[ie]);if(ht){z(Ye),(pe=ht[1].current)==null||pe.focus();return}R(!0);const Qe={},He=[],re=V||Ns;if(D)try{const ie=await n.configure(t,G);ie!=null&&ie.data&&h(ie.data),N("")}catch(ie){Qe.portal=(ie==null?void 0:ie.message)||"Could not save the portal address. Try again.",He.push("portal address")}if(T)try{const ie=await r.configure(t,U,re);ie!=null&&ie.data&&y(ie.data),k("")}catch(ie){Qe.emailDomain=(ie==null?void 0:ie.message)||"Could not save the email address. Try again.",He.push("email address")}else if($)try{const ie=await r.setLocalPart(t,J,re);ie!=null&&ie.data&&y(ie.data)}catch(ie){Qe.localPart=(ie==null?void 0:ie.message)||"Could not update the mailbox name. Try again.",He.push("email address")}if(S)try{await c.onSave()}catch(ie){Qe.slug=(ie==null?void 0:ie.message)||"Could not save the sign-in link. Try again.",He.push("sign-in link")}if(z(Qe),R(!1),He.length){Pt.error({message:`Could not save your ${He.join(" and ")}. Your edits are kept â fix the field and save again.`}),(me=(Qe.portal?H:Qe.localPart?xe:Qe.emailDomain?ae:Ae).current)==null||me.focus();return}Pt.success("Domain settings saved")}async function _t(){var Qe;if(Y||!X)return;j(!0);const ee=[];Z&&ee.push(n.verify(t,se).then(He=>{He!=null&&He.data&&(h(He.data),d(He.data.dnsCheck||null))})),ge&&ee.push(r.verify(t,J).then(He=>{He!=null&&He.data&&y(He.data)}));const Ye=await Promise.allSettled(ee);j(!1);const ht=Ye.find(He=>He.status==="rejected");if(ht){Pt.error({message:((Qe=ht.reason)==null?void 0:Qe.message)||"Could not check DNS. Try again in a moment."});return}f(new Date),Pt.success("DNS check complete")}async function dt(){if(!Y){b(!0);try{const ee=await n.activate(t,se);ee!=null&&ee.data&&h(ee.data),Pt.success("Activation requested")}catch(ee){Pt.error({message:(ee==null?void 0:ee.message)||"Could not activate the portal address. Try again."})}finally{b(!1)}}}async function et(){if(w){W(!0);try{w==="portal"?(await n.remove(t,se),h(null),Pt.success("Portal address removed")):(await r.remove(t,J),y(null),Pt.success("Email address removed")),F(null)}catch(ee){Pt.error({message:(ee==null?void 0:ee.message)||"Could not remove it. Try again."})}finally{W(!1)}}}const Rt=[Z&&(m!=null&&m.lastError)&&fe!=="pending_dns"?{key:"portal",tone:fe==="error"?"danger":"info",text:`Portal: ${m.lastError}`}:null,ge&&(g!=null&&g.lastError)&&ye!=="pending_dns"?{key:"email",tone:ye==="error"?"danger":"info",text:`Email: ${g.lastError}`}:null].filter(Boolean),rt=c?`${xi()}/login?brand=${String(c.value||"").trim()||"example-brand"}`:"",Lt=!!(c&&String(c.savedValue||"").trim()&&!S);return e.jsxs(e.Fragment,{children:[e.jsxs("form",{className:"space-y-6 max-lg:space-y-4",onSubmit:gt,noValidate:!0,"data-testid":`section-${l}`,children:[e.jsxs("div",{className:"grid grid-cols-1 gap-5 md:grid-cols-2 max-lg:gap-4",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex min-h-6 flex-wrap items-center justify-between gap-2",children:[e.jsxs(oe,{htmlFor:Z?void 0:`${l}-portal`,className:"text-sm font-medium text-content-primary",children:["Portal address",Z?null:e.jsx(Nn,{})]}),Z?e.jsx(Hi,{status:fe}):null]}),Z?e.jsxs("div",{className:"flex min-h-11 items-center gap-2 rounded-md border border-subtle bg-surface-sunken pl-3 pr-1 max-lg:min-h-9",children:[e.jsx("span",{id:`${l}-portal`,className:"min-w-0 flex-1 break-all font-mono text-sm text-content-primary","data-testid":`text-${l}-portal`,children:se}
26),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"size-8 shrink-0 rounded-full text-status-danger",onClick:()=>F("portal"),disabled:Y,"aria-label":"Remove portal address",title:"Remove portal address","data-testid":`button-${l}-portal-remove`,children:e.jsx(bt,{"aria-hidden":"true"})})]}):e.jsx(be,{ref:H,id:`${l}-portal`,value:C,onChange:ee=>{N(ee.target.value),We("portal")},placeholder:"portal.yourclinic.com",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,className:"h-11 font-mono text-sm max-lg:h-9",error:E.portal||void 0,"data-testid":`input-${l}-portal`}),e.jsx("p",{className:"text-xs text-content-tertiary",children:Z?fe==="active"?e.jsxs(e.Fragment,{children:["Patients sign in at ",e.jsxs("span",{className:"font-mono text-content-primary",children:["https://",se]}),"."]}):"Patients start using this address once your records are found.":"Use a subdomain, like portal.yourclinic.com. Root domains are not supported."})]}),e.jsxs("div",{role:"group","aria-labelledby":`${l}-email-label`,className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex min-h-6 flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{id:`${l}-email-label`,className:"text-sm font-medium text-content-primary",children:["Send emails from",ge?null:e.jsx(Nn,{})]}),ge?e.jsx(Hi,{status:ye}):null]}),e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsxs("div",{className:"w-36 shrink-0 max-sm:w-28",children:[e.jsx(oe,{htmlFor:`${l}-local-part`,className:"sr-only",children:"Mailbox name"}),e.jsx(be,{ref:xe,id:`${l}-local-part`,value:P,onChange:ee=>{A(ee.target.value),We("localPart")},placeholder:Ns,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,className:"h-11 font-mono text-sm max-lg:h-9",error:E.localPart||void 0,"data-testid":`input-${l}-local-part`})]}),e.jsx("span",{className:"flex h-11 shrink-0 items-center font-mono text-sm text-content-tertiary max-lg:h-9","aria-hidden":"true",children:"@"}),e.jsx("div",{className:"min-w-0 flex-1",children:ge?e.jsxs("div",{className:"flex min-h-11 items-center gap-1 rounded-md border border-subtle bg-surface-sunken pl-3 pr-1 max-lg:min-h-9",children:[e.jsx("span",{className:"min-w-0 flex-1 break-all font-mono text-sm text-content-primary","data-testid":`text-${l}-email-domain`,children:J}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"size-8 shrink-0 rounded-full text-status-danger",onClick:()=>F("email"),disabled:Y,"aria-label":"Remove email domain",title:"Remove email domain","data-testid":`button-${l}-email-remove`,children:e.jsx(bt,{"aria-hidden":"true"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(oe,{htmlFor:`${l}-email-domain`,className:"sr-only",children:"Email domain"}),e.jsx(be,{ref:ae,id:`${l}-email-domain`,value:v,onChange:ee=>{k(ee.target.value),We("emailDomain")},placeholder:"yourclinic.com",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,className:"h-11 font-mono text-sm max-lg:h-9",error:E.emailDomain||void 0,"data-testid":`input-${l}-email-domain`})]})})]}),e.jsxs("p",{className:"text-xs text-content-tertiary",children:[ge&&ye==="active"&&!$?"Patients get emails from ":"Patients will get emails from ",e.jsx("span",{className:"break-all font-mono text-content-primary",children:ve}),"."]})]})]}),pt?e.jsxs("p",{className:K("rounded-lg border px-3 py-2 text-xs motion-safe:animate-in motion-safe:fade-in-0 [animation-duration:var(--text-swap-dur)]",ur.info),"data-testid":`text-${l}-domain-mismatch`,children:["Your portal and emails use different domains. Using the same one helps emails reach the inbox."," ",e.jsx(Im,{accentColor:u,variant:"link",label:"Why it matters",className:"text-status-info"})]}):null,c?e.jsxs("div",{className:"space-y-1.5","data-testid":`section-${l}-sign-in-link`,children:[e.jsxs(oe,{htmlFor:"brandingSlug",className:"text-sm font-medium text-content-primary",children:["Branded sign-in link",e.jsx(Nn,{})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start",children:[e.jsx("div",{className:"sm:w-56 sm:shrink-0",children:e.jsx(be,{ref:Ae,id:"brandingSlug",name:"brandingSlug",placeholder:"example-brand",value:c.value,onChange:ee=>{c.onChange(ee),We("slug")},className:"h-11 font-mono text-sm max-lg:h-9",maxLength:80,autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,error:E.slug||void 0,"aria-describedby":`${l}-sign-in-link-help`})}),e.jsxs("div",{className:"flex min-h-11 min-w-0 flex-1 items-center gap-1 rounded-md border border-subtle bg-surface-sunken pl-3 pr-1 max-lg:min-h-9",children:[e.jsx("span",{className:K("min-w-0 flex-1 break-all py-1 font-mono text-xs",Lt?"text-content-primary":"text-content-tertiary"),"data-testid":`text-${l}-sign-in-link`,children:rt}),Lt?e.jsx(ec,{text:rt,label:"Copy sign-in link"}):null]})]}),e.jsx("p",{id:`${l}-sign-in-link-help`,className:"text-xs text-content-tertiary",children:"A short name for your sign-in link. Lowercase letters, numbers, and dashes."})]}):null,e.jsx(Wt,{delayDuration:300,children:e.jsxs("section",{className:"space-y-3","aria-labelledby":`${l}-records-title`,children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{id:`${l}-records-title`,className:"text-sm font-semibold text-content-primary",children:"Add these records at your DNS provider"}),e.jsx("p",{className:"text-xs text-content-tertiary",children:"Paste each Host exactly as shown. Your provider adds the rest of your domain on its own."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-content-tertiary","data-testid":`text-${l}-last-checked`,children:Gt?`Last checked ${Om(Gt,{addSuffix:!0})}`:X?"Not checked yet":"Save an address to start checking"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"rounded-full",onClick:_t,disabled:Y||!X,"data-testid":`button-${l}-check`,children:[e.jsx($a,{swapped:O,from:e.jsx(ts,{}),to:e.jsx($e,{active:O,delayMs:0,label:"Checking records"})}),"Check now"]})]})]}),e.jsx("div",{className:"hidden overflow-hidden rounded-lg border border-subtle xl:block",children:e.jsxs(la,{noScrollContainer:!0,className:"table-fixed",children:[e.jsx(oa,{children:e.jsxs(At,{className:"hover:bg-transparent",children:[e.jsx(Be,{className:"h-9 w-20 px-3 text-xs",children:"Type"}),e.jsx(Be,{className:"h-9 w-1/5 px-3 text-xs",children:"Host"}),e.jsx(Be,{className:"h-9 px-3 text-xs",children:"Value"}),e.jsx(Be,{className:"h-9 w-36 px-3 text-xs",children:"Purpose"}),e.jsx(Be,{className:"h-9 w-32 px-3 text-xs",children:"Status"})]})}),e.jsx(ca,{children:Bt.map(ee=>e.jsxs(At,{className:"hover:bg-transparent","data-testid":`row-${l}-${ee.key}`,children:[e.jsx(Ie,{className:"px-3 py-2 align-middle",children:e.jsx("span",{className:"block font-mono text-xs font-semibold text-content-primary",children:ee.type})}),e.jsx(Ie,{className:"px-3 py-2 align-middle",children:e.jsx(Na,{text:ee.host,preview:ee.preview,copyLabel:`Copy host for ${js[ee.purpose].toLowerCase()} ${ee.type} record`})}),e.jsx(Ie,{className:"px-3 py-2 align-middle",children:e.jsx(Na,{text:ee.value,preview:ee.preview,copyLabel:`Copy value for ${js[ee.purpose].toLowerCase()} ${ee.type} record`})}),e.jsxs(Ie,{className:"px-3 py-2 align-middle",children:[e.jsx("span",{className:"block text-xs font-medium text-content-primary",children:js[ee.purpose]}),e.jsx("span",{className:"block text-2xs text-content-tertiary",children:ee.hint})]}),e.jsx(Ie,{className:"px-3 py-2 align-middle",children:e.jsx(Wi,{status:ee.status})})]},ee.key))})]})}),e.jsx("ul",{className:"divide-y divide-subtle rounded-lg border border-subtle xl:hidden",children:Bt.map(ee=>e.jsxs("li",{className:"space-y-2 p-3","data-testid":`row-${l}-${ee.key}-mobile`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"font-mono text-xs font-semibold text-content-primary",children:ee.type}),e.jsxs("span",{className:"text-xs text-content-secondary",children:[js[ee.purpose]," · ",ee.hint]})]}),e.jsx(Wi,{status:ee.status})]}),e.jsxs("dl",{className:"grid grid-cols-[3rem_minmax(0,1fr)] items-center gap-x-2 gap-y-1",children:[e.jsx("dt",{className:"text-2xs font-semibold uppercase text-content-tertiary",children:"Host"}),e.jsx("dd",{className:"min-w-0",children:e.jsx(Na,{text:ee.host,preview:ee.preview,copyLabel:`Copy host for ${js[ee.purpose].toLowerCase()} ${ee.type} record`})}),e.jsx("dt",{className:"text-2xs font-semibold uppercase text-content-tertiary",children:"Value"}),e.jsx("dd",{className:"min-w-0",children:e.jsx(Na,{text:ee.value,preview:ee.preview,copyLabel:`Copy value for ${js[ee.purpose].toLowerCase()} ${ee.type} record`})})]})]},ee.key))}),e.jsx("p",{className:"text-xs text-content-tertiary",role:"status",children:cs?"All records foun
26d. Your portal and emails are using your domain.":"We check for new records on our own. It usually takes about 20 minutes, and can take a few hours."}),Rt.map(ee=>e.jsx("p",{className:K("rounded-lg border px-3 py-2 text-xs",ur[ee.tone]),children:ee.text},ee.key))]})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 border-t border-subtle pt-4 max-lg:pt-3",children:[Ee?e.jsxs(B,{type:"button",variant:"outline",className:"mr-auto rounded-full",onClick:dt,disabled:Y,"data-testid":`button-${l}-activate`,children:[e.jsx($a,{swapped:L,from:e.jsx(Ze,{}),to:e.jsx($e,{active:L,delayMs:0,label:"Activating portal"})}),"Activate portal"]}):null,Q?e.jsx(B,{type:"button",variant:"ghost",className:"rounded-full",onClick:ct,disabled:q,children:"Discard"}):null,e.jsxs(B,{type:"submit",className:"rounded-full text-white",style:{backgroundColor:u},disabled:!Q||Y,"data-testid":`button-${l}-save`,children:[e.jsx($a,{swapped:q,from:e.jsx(Ze,{}),to:e.jsx($e,{active:q,delayMs:0,label:"Saving domain settings"})}),"Save changes"]})]})]}),e.jsx(_s,{open:!!w,onOpenChange:ee=>{!ee&&!M&&F(null)},title:w==="portal"?"Remove portal address?":"Remove email domain?",description:w==="portal"?`Patients go back to the default sign-in address instead of ${se}. You can add it again later.`:`Patient emails go back to the default sender instead of @${J}. You can add it again later.`,confirmLabel:w==="portal"?"Remove portal address":"Remove email domain",tone:"destructive",busy:M,onConfirm:et})]})}const cx={firstName:"Alex",lastName:"Morgan",email:"[email protected]",phone:"",dateOfBirth:"1990-01-15",sexAtBirth:"Female"},dx=()=>{};function mx({theme:t,branding:s,cornerStyle:a,viewportWindow:i}){var m,h;const n=t.layoutPreset==="sidecar",r=s.appThemeMode==="dark",l=ed(s.backgroundColor),c=Le({...s.experienceConfig,portalChrome:{...(m=s.experienceConfig)==null?void 0:m.portalChrome,cornerStyle:a},checkoutTheme:t}),u=((h=Tr({},t))==null?void 0:h.backgroundColor)||(r?l.canvas:s.backgroundColor);return e.jsx("main",{inert:"","data-client-theme":r?"dark":"light",className:K(r?"checkout-dark":"checkout-light","min-h-dvh w-full",!n&&"p-0 lg:p-4"),style:{...r?{"--client-dark-canvas":l.canvas,"--client-dark-surface":l.surface,"--client-dark-surface-muted":l.surfaceMuted}:{},...Hl(c),backgroundColor:n?"var(--surface-page)":u,"--checkout-accent":s.accentColor,...s.headerFont?{"--font-display":`"${s.headerFont}", ui-serif, Georgia, serif`}:{}},children:e.jsx("div",{className:K("mx-auto w-full",n?"max-w-none":"max-w-7xl pt-0 pb-3 sm:pt-1 sm:pb-6"),children:e.jsx(Fm,{...zm(t.layoutPreset),viewportWindow:i,checkoutTheme:t,accentColor:s.accentColor,backgroundColor:u,rightPanelColor:s.rightPanelColor,brandName:s.name,brandLogoUrl:s.logoUrl,brandWebsiteUrl:s.website,logoWhiteBackground:s.logoWhiteBackground===!0,forceDarkTheme:r,panelRadius:a==="sharp"?"0rem":a==="medium"?"0.5rem":"1.5rem",className:n?"min-h-dvh":"bg-transparent",sidecarCenterContent:n,centerStepIndicator:!0,showStepIndicator:!1,headerContent:n||t.logoTreatment==="hidden"||!s.logoUrl?null:e.jsx("img",{src:s.logoUrl,alt:s.name||"Client",className:"h-12 w-auto object-contain sm:h-16"}),leftContent:e.jsxs(td,{type:"single",value:"contact",className:K("space-y-4",n&&"space-y-3"),children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(_m,{isSidecarCheckout:n,accentColor:s.accentColor,children:e.jsx(Um,{billingInfo:cx,setBillingInfo:dx,isSidecarCheckout:n})}),e.jsx(Ei,{value:"shipping",number:"2",title:"Shipping address",disabled:!0})]}),e.jsx(Ei,{value:"payment",number:"3",title:"Payment",disabled:!0})]}),summaryProps:{title:"Summary",itemCount:1,primaryItem:{name:"Sample product",description:"Patient checkout item",amount:129},includedItems:[],subtotalAmount:129,totalAmount:129,loading:!1,accentColor:s.accentColor}})})})}function ux({theme:t,branding:s,cornerStyle:a,device:i}){return e.jsx(Dm,{device:i,children:n=>e.jsx(Zc,{subscription:{branding:s,experience:s.experienceConfig},children:e.jsx(mx,{theme:t,branding:s,cornerStyle:a,viewportWindow:n})})})}
26function xx({accentColor:t,useBrandAccent:s,surfaceText:a,compact:i=!1}){return e.jsxs("div",{className:"space-y-2 sm:space-y-3","aria-hidden":"true",children:[e.jsxs("div",{children:[e.jsx(oe,{style:{color:a.label},children:"Email"}),e.jsx(be,{readOnly:!0,value:"[email protected]",className:"pointer-events-none"})]}),e.jsx(B,{type:"button",disabled:!0,className:K("h-9 w-full text-sm sm:h-10",!s&&"bg-slate-700"),style:s?{backgroundColor:t}:void 0,children:"Continue"}),i?null:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 py-1",children:[e.jsx("div",{className:"h-px flex-1",style:{backgroundColor:a.divider}}),e.jsx("span",{className:"text-xs font-medium",style:{color:a.muted},children:"or"}),e.jsx("div",{className:"h-px flex-1",style:{backgroundColor:a.divider}})]}),e.jsx(B,{type:"button",variant:"outline",disabled:!0,className:"pointer-events-none h-9 w-full text-sm sm:h-10",children:"Sign in with password"}),e.jsx(B,{type:"button",variant:"outline",disabled:!0,className:"pointer-events-none h-9 w-full text-sm sm:h-10",children:"Sign in with Google"})]})]})}function px({theme:t,branding:s,accentColor:a,layoutPreset:i,compact:n=!1,className:r}){const l={...t||{},layoutPreset:i||(t==null?void 0:t.layoutPreset)||Ke.SIDECAR},c=Tr(s,l),u=(c==null?void 0:c.accentColor)||a||"#475569",m=(c==null?void 0:c.name)||"Sign in",h=(c==null?void 0:c.logoUrl)||"",g=!!(c!=null&&c.accentColor||a),y=l.layoutPreset,p=rd(y),d=id(y),x=sd({theme:l,branding:c,accentColor:u}),f=(c==null?void 0:c.rightPanelColor)||"#ffffff",C=pi(p||d?f:"#ffffff"),N=pi(x),v=ad(l),k=l.headline||(p||d?"Welcome back":m),P=l.subhead||(p||d?"Enter your email to continue with a magic link.":"Access your personalized health portal"),A=d?e.jsx("div",{className:"shrink-0 px-6 pt-8 text-center sm:px-8 sm:pt-10",children:h?e.jsx("div",{className:"mx-auto inline-flex max-w-full items-center justify-center",style:{padding:v.logoPadding,borderRadius:v.logoBorderRadius,backgroundColor:(c==null?void 0:c.logoBackgroundColor)||"#ffffff"},children:e.jsx("img",{src:h,alt:`${m} logo`,className:"max-h-16 max-w-[min(100%,18rem)] object-contain sm:max-h-20"})}):e.jsx("h1",{className:"font-display text-xl font-semibold sm:text-2xl",style:{color:C.heading},children:m})}):!p&&!d?e.jsx("div",{className:"shrink-0 border-b border-gray-100 px-4 py-3 sm:p-6 sm:pb-4",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"font-display text-xl font-medium sm:text-2xl",style:{color:C.heading},children:k}),e.jsx("p",{className:"text-2xs sm:text-sm",style:{color:C.body},children:P})]})}):null,E=e.jsxs(e.Fragment,{children:[p||d?e.jsxs("div",{className:"mb-5 text-center sm:mb-7",children:[e.jsx("h2",{className:"font-display text-2xl font-semibold sm:text-3xl",style:{color:C.heading},children:k}),e.jsx("p",{className:"mt-2 text-sm leading-relaxed",style:{color:C.body},children:P}),d&&l.trustNote?e.jsx("p",{className:"mt-2 text-xs font-medium",style:{color:u},children:l.trustNote}):null]}):null,e.jsx(xx,{accentColor:u,useBrandAccent:g,surfaceText:C,compact:n})]}),z=e.jsx(nd,{preview:!0,theme:l,branding:c,accentColor:u,brandName:m,logoUrl:h,sidecarHeaderLogoUrl:h,loginBackgroundColor:x,formBackgroundColor:f,text:C,pageText:N,cardHeader:A,formContent:E,className:K(n?"min-h-[6rem]":"min-h-[20rem]",r)});return n?e.jsx("div",{className:"relative h-24 overflow-hidden rounded-lg bg-slate-100 dark:bg-slate-900",children:e.jsx("div",{className:"pointer-events-none absolute left-0 top-0 origin-top-left",style:{transform:"scale(0.22)",width:"454.545%"},children:z})}):z}const we={primary:"#2563eb",background:"#f1f5f9",cardBackground:"#ffffff",text:"#1f2937",textMuted:"#475569",textLight:"#64748b",border:"#e2e8f0",infoBackground:"#f8fafc",white:"#ffffff",darkBackground:"#0f172a",darkCardBackground:"#1e293b",darkText:"#f1f5f9",darkTextMuted:"#cbd5e1",darkBorder:"#334155",darkInfoBackground:"#1e293b"},gx=` 27 body { 28 font-family: 'Roboto', sans-serif; 29 line-height: 1.6; 30 color: ${we.text}; 31 margin: 0; 32 padding: 0; 33 background-color: ${we.background}; 34 -webkit-font-smoothing: antialiased; 35 -moz-osx-font-smoothing: grayscale; 36 } 37 table { 38 border-collapse: collapse; 39 mso-table-lspace: 0pt; 40 mso-table-rspace: 0pt; 41 } 42 img { 43 border: 0; 44 height: auto; 45 line-height: 100%; 46 outline: none; 47 text-decoration: none; 48 -ms-interpolation-mode: bicubic; 49 } 50 .email-wrapper { max-width: 600px; margin: 0 auto; padding: 20px; } 51 .email-theme-classic { max-width: 600px; } 52 .email-theme-banner { max-width: 640px; padding: 28px 20px 32px; } 53 .email-theme-letterhead { max-width: 620px; } 54 .container {
55 background: ${we.cardBackground}; 56 border-radius: 12px; 57 border: 1px solid ${we.border}; 58 overflow: hidden; 59 box-shadow: none; 60 } 61 .email-theme-classic .container { 62 border-radius: 12px; 63 border: 1px solid ${we.border}; 64 box-shadow: none; 65 } 66 .email-theme-banner .container { 67 border-radius: 20px; 68 border: 0; 69 box-shadow: 0 18px 45px rgba(15, 23, 42, 0.16); 70 } 71 .email-theme-letterhead .container { 72 border-radius: 8px; 73 border-top-width: 6px; 74 } 75 .header { 76 text-align: center; 77 padding: 40px 30px; 78 border-bottom: 3px solid rgba(0,0,0,0.1); 79 } 80 .email-theme-letterhead .header { 81 background: ${we.cardBackground} !important; 82 text-align: left; 83 padding: 28px 32px 22px; 84 border-bottom: 1px solid ${we.border}; 85 } 86 .email-theme-banner .header { 87 padding: 56px 40px 48px; 88 border-bottom: 0; 89 } 90 .logo { 91 max-width: 200px; 92 max-height: 80px; 93 width: auto; 94 height: auto; 95 margin: 0 auto 20px auto; 96 display: block; 97 border-radius: 12px; 98 box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); 99 object-fit: contain; 100 } 101 .email-theme-letterhead .logo { 102 margin-left: 0; 103 margin-right: 0; 104 max-width: 180px; 105 max-height: 64px; 106 box-shadow: none; 107 } 108 .logo--white-background { 109 background: ${we.white}; 110 padding: 12px 16px; 111 box-shadow: 0 8px 24px rgba(15, 23, 42, 0.18); 112 } 113 h1 { 114 font-family: 'Roboto', sans-serif; 115 color: ${we.white} !important; 116 margin: 0; 117 font-size: 28px; 118 font-weight: 700; 119 } 120 .email-theme-letterhead h1 { 121 color: ${we.text} !important; 122 font-size: 24px; 123 } 124 .email-theme-banner h1 { 125 font-size: 32px; 126 letter-spacing: -0.02em; 127 } 128 .email-banner-title { display: none; } 129 .subtitle { 130 color: rgba(255, 255, 255, 0.9) !important; 131 font-size: 15px; 132 margin-top: 8px; 133 font-weight: 500; 134 } 135 .email-theme-letterhead .subtitle { 136 color: ${we.textMuted} !important; 137 } 138 .content { 139 padding: 40px 30px; 140 background-color: ${we.cardBackground}; 141 } 142 .email-theme-banner .content { 143 padding: 36px 34px; 144 } 145 .email-theme-letterhead .content { 146 padding: 32px; 147 } 148 p { 149 color: ${we.textMuted}; 150 margin: 0 0 16px; 151 font-size: 15px; 152 line-height: 1.6; 153 } 154 .button-container { 155 text-align: center; 156 margin: 32px 0; 157 } 158 .cta-button { 159 display: inline-block; 160 color: ${we.white} !important; 161 padding: 14px 32px; 162 text-decoration: none; 163 border-radius: 9999px; 164 font-weight: 600; 165 font-size: 16px; 166 mso-hide: all; 167 } 168 .email-theme-letterhead .cta-button { border-radius: 10px; } 169 .email-theme-banner .cta-button { border-radius: 10px; padding: 16px 36px; font-size: 17px; } 170 .email-theme-banner .footer { border-top: 0; padding: 24px 34px; } 171 .info-box { 172 background: ${we.infoBackground}; 173 border: 1px solid ${we.border}; 174 border-radius: 8px; 175 padding: 20px; 176 margin: 24px 0; 177 } 178 .info-box strong { 179 color: #1e293b; 180 display: block; 181 margin-bottom: 8px; 182 } 183 .footer { 184 text-align: center; 185 padding: 24px; 186 background: ${we.infoBackground}; 187 color: ${we.textLight}; 188 font-size: 13px; 189 border-top: 1px solid ${we.border}; 190 } 191 .footer p { margin: 6px 0; color: ${we.textLight}; } 192 .confidentiality-notice { 193 text-align: center; 194 padding: 20px 30px; 195 background: ${we.background}; 196 color: #94a3b8; 197 font-size: 10px; 198 line-height: 1.5; 199 border-top: 1px solid ${we.border}; 200 } 201 .confidentiality-notice p { margin: 0; color: #94a3b8; font-size: 10px; } 202 @media (prefers-color-scheme: dark) { 203 body { background-color: ${we.darkBackground} !important; color: ${we.darkText} !important; } 204 .container { background: ${we.darkCardBackground} !important; border-color: ${we.darkBorder} !important; } 205 .content { background-color: ${we.darkCardBackground} !important; } 206 p { color: ${we.darkTextMuted} !important; } 207 .info-box { background: ${we.darkInfoBackground} !important; border-color: ${we.darkBorder} !important; } 208 .info-box strong { color: ${we.darkText} !important; }
209 .footer { background: ${we.darkInfoBackground} !important; color: ${we.darkTextMuted} !important; border-color: ${we.darkBorder} !important; } 210 .footer p { color: ${we.darkTextMuted} !important; } 211 .confidentiality-notice { background: ${we.darkBackground} !important; color: #64748b !important; border-color: ${we.darkBorder} !important; } 212 .confidentiality-notice p { color: #64748b !important; } 213 .header { border-bottom-color: rgba(255,255,255,0.1) !important; } 214 .email-theme-letterhead .header { background: ${we.darkCardBackground} !important; border-color: ${we.darkBorder} !important; } 215 .email-theme-letterhead h1 { color: ${we.darkText} !important; } 216 img[src*="logo"] { filter: brightness(0.9) contrast(1.1); } 217 } 218`,hx=new Set(["classic","banner","letterhead"]);function qt(t,s){if(typeof t!="string")return s;const a=t.trim();return/^#[0-9a-fA-F]{6}$/.test(a)?a:s}function Rn(t,s,a,i){const n=Number(t);return Number.isFinite(n)?Math.min(i,Math.max(a,Math.round(n))):s}function fx(t=we.primary){var i,n,r,l,c,u,m,h,g,y,p,d;if(!t||typeof t!="object")return{brandColor:qt(t,we.primary),secondaryColor:null,backgroundColor:null,logoBackgroundColor:we.white,containerBorderRadius:12,logoBorderRadius:12,logoPadding:12,emailThemeLayout:"classic"};const s=(n=(i=t.experienceConfig)==null?void 0:i.emailTheme)==null?void 0:n.layoutPreset,a=((l=(r=t.experienceConfig)==null?void 0:r.emailTheme)==null?void 0:l.brandingOverrides)||{};return{brandColor:qt(a.accentColor,qt(t.accentColor,we.primary)),secondaryColor:qt(a.secondaryColor,qt(t.secondaryColor,null)),backgroundColor:qt(a.backgroundColor,qt(t.backgroundColor,null)),logoBackgroundColor:qt(a.logoBackgroundColor,qt(t.logoBackgroundColor,qt((u=(c=t.experienceConfig)==null?void 0:c.emailTheme)==null?void 0:u.logoBackgroundColor,we.white))),containerBorderRadius:Rn((h=(m=t.experienceConfig)==null?void 0:m.emailTheme)==null?void 0:h.containerBorderRadius,12,0,32),logoBorderRadius:Rn((y=(g=t.experienceConfig)==null?void 0:g.emailTheme)==null?void 0:y.logoBorderRadius,12,0,32),logoPadding:Rn((d=(p=t.experienceConfig)==null?void 0:p.emailTheme)==null?void 0:d.logoPadding,12,0,32),emailThemeLayout:hx.has(s)?s:"classic"}}function bx(){return'<div class="confidentiality-notice"><p><strong>CONFIDENTIALITY NOTICE:</strong> This email, including all accompanying pages and attachments, contains confidential information that is intended solely for the use of the designated recipient. This information may be legally protected. The sender retains all privileges associated with this communication. If you are not the intended recipient, you are hereby notified that any review, dissemination, distribution, or reliance upon the contents of this email is strictly prohibited. If you have received this email in error, please contact the sender immediately by replying to this email or by phone, and delete the email from your system without making any copies.</p></div>'}function yx(t=!1){return`logo${t?" logo--white-background":""}`}function vx(t,s,a,i,n=!1){return` 219 <div class="header"> 220 ${t?`<img src="${t}" alt="${s}" class="${yx(n)}">`:""} 221 <h1>${a}</h1> 222 ${`<p class="subtitle">${i}</p>`} 223 </div> 224 <div class="email-banner-title"> 225 <h1>${a}</h1> 226 </div> 227 `}function Nx(t){return`<div class="footer"><p>© ${new Date().getFullYear()} ${t}. All rights reserved.</p></div>`}function jx(t,s,a=we.primary){return` 228 <div class="button-container"> 229 <!--[if mso]> 230 <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="${t}" style="height:48px;v-text-anchor:middle;width:200px;" arcsize="50%" strokecolor="${a}" fillcolor="${a}"> 231 <w:anchorlock/> 232 <center style="color:#ffffff;font-family:'Roboto', sans-serif;font-size:16px;font-weight:600;">${s}</center> 233 </v:roundrect> 234 <![endif]--> 235 <!--[if !mso]><!--> 236 <a href="${t}" class="cta-button" style="background-color:${a};">${s}</a> 237 <!--<![endif]--> 238 </div> 239 `}function kx({branding:t={},overrides:s={}}={}){var d;const a=((d=t==null?void 0:t.experienceConfig)==null?void 0:d.emailTheme)||{},i={...t,experienceConfig:{...t.experienceConfig||{},emailTheme:{...a,...s}}},n=fx(i),r=n.brandColor,l=`email-wrapper email-theme-${n.emailThemeLayout}`,c=n.emailThemeLayout==="banner"?n.backgroundColor||"#e2e8f0":we.background,u=n.emailThemeLayout==="letterhead"?r:we.border,m=(t==null?void 0:t.name)||"Client",h=(t==null?void 0:t.logoUrl)||"",g=!!(t!=null&&t.logoWhiteBackgroun
239d),y="Visit Scheduled",p=` 240 ${vx(h,m,y,m,g)} 241 <div class="content"> 242 <p>Hello Patient,</p> 243 <p>This is how patient-facing transactional email will render with this surface branding.</p> 244 ${jx("#","Review details",r)} 245 </div> 246 ${Nx(m)} 247 `;return`<!DOCTYPE html> 248<html lang="en" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> 249<head> 250 <meta charset="UTF-8"> 251 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 252 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 253 <meta name="x-apple-disable-message-reformatting"> 254 <meta name="color-scheme" content="light dark"> 255 <meta name="supported-color-schemes" content="light dark"> 256 <title>${y}</title> 257 <!--[if mso]> 258 <noscript> 259 <xml> 260 <o:OfficeDocumentSettings> 261 <o:PixelsPerInch>96</o:PixelsPerInch> 262 </o:OfficeDocumentSettings> 263 </xml> 264 </noscript> 265 <![endif]--> 266 <style> 267 @font-face { 268 font-family: 'Roboto'; 269 font-style: normal; 270 font-weight: 400; 271 font-display: swap; 272 src: url('https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2') format('woff2'); 273 unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 274 } 275 @font-face { 276 font-family: 'Roboto'; 277 font-style: normal; 278 font-weight: 500 600; 279 font-display: swap; 280 src: url('https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmEU9fBBc4AMP6lQ.woff2') format('woff2'); 281 unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 282 } 283 @font-face { 284 font-family: 'Roboto'; 285 font-style: normal; 286 font-weight: 700; 287 font-display: swap; 288 src: url('https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBBc4AMP6lQ.woff2') format('woff2'); 289 unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 290 } 291 ${gx} 292 .header, .cta-button { background-color: ${r}; } 293 .container, .email-theme-classic .container, .email-theme-banner .container, .email-theme-letterhead .container { border-radius: ${n.containerBorderRadius}px; } 294 .logo { border-radius: ${n.logoBorderRadius}px; } 295 .logo--white-background { background: ${n.logoBackgroundColor}; padding: ${n.logoPadding}px ${Math.max(n.logoPadding+4,n.logoPadding)}px; } 296 .email-theme-letterhead .container { border-top-color: ${u}; } 297 .email-theme-banner .header { background-color: ${r}; } 298 .email-theme-banner .footer { background-color: ${n.secondaryColor||"#f8fafc"}; } 299 .email-theme-banner .header { text-align: left; padding: 28px 34px; } 300 .email-theme-banner .header .logo { margin-left: 0; margin-right: 0; margin-bottom: 0; } 301 .email-theme-banner .header h1, .email-theme-banner .header .subtitle { display: none; } 302 .email-theme-banner .email-banner-title { display: block; padding: 34px 34px 0; background: ${we.cardBackground}; } 303 .email-theme-banner .email-banner-title h1 { color: ${we.text} !important; text-align: left; font-size: 30px; letter-spacing: -0.02em; } 304 @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { 305 .cta-button { padding: 0 !important; } 306 .button-link { display: block; padding: 14px 32px; } 307 } 308 </style> 309</head> 310<body style="margin:0;padding:0;background-color:${c};"> 311 <div class="${l}"> 312 <div class="container"> 313 ${p} 314 </div> 315 ${bx()} 316 </div> 317</body> 318</html>`}function wx({ExperienceSurfaceCard:t,LargeCheckboxOption:s,SegmentedChoiceGroup:a,accentColor:i,isSavingExperienceConfig:n,isSavingPostVisitRedirect:r,isValidHttpUrl:l,normalizedExperienceConfig:c,onPatientReceiptsEnabledChange:u,onPatientFormResubmissionChange:m,onPostPurchaseConsultationPromptEnabledChange:h,onPostVisitRedirectChange:g,onQueueLabOrderReviewEnabledChange:y,onQueuePrescriptionReviewEnabledChange:p,onClientCollectedProductPaymentEnabledChange:d,onRequireIdVerificationForNewPatientsOnlyChange:x,onMinimumSignupAgeChange:f,onShowPatientCustomFieldsChange:C,onShowVisitPurchasesInPatientOrdersChange:N,onPatientOrderRoadmapChange:v,patientOrderRoadmap:k,patientOrderRoadmapOptions:P=[],customFormularyTerminalStepOptions:A=[],postVisitRedirectEnabled:E,postVisitRedirectUrl:z,savingField:q,tenantCollection:R}){var j,L,b,w,F;const O=R===It.CLIENT;
318return e.jsx(t,{id:"patient-experience-settings",title:"Experience settings",description:"Controls checkout and visit behaviors patients experience.",icon:Hu,accentColor:i,saving:n||r||q==="patientOrderRoadmap",children:e.jsxs("div",{className:"grid gap-3 max-lg:gap-1.5 lg:grid-cols-2",children:[O?e.jsxs("div",{className:"space-y-2 rounded-xl border border-subtle bg-slate-50/60 p-3 dark:bg-slate-900/20 max-lg:space-y-1.5 max-lg:p-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Patient order roadmap"}),e.jsx("p",{className:"mt-1 text-xs text-content-tertiary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:"Choose whether visit-first orders start with Booked Visit and show visit and medication charges as separate steps. Other checkout flows keep the standard roadmap."})]}),e.jsx(a,{value:(k==null?void 0:k.variant)||((j=P[0])==null?void 0:j.key),options:P,onChange:M=>v({variant:M}),accentColor:i})]}):null,O?e.jsx(s,{id:"endCustomFormularyAtMedicationPayment",checked:(k==null?void 0:k.endCustomFormularyAtMedicationPayment)===!0,disabled:q==="patientOrderRoadmap",onCheckedChange:M=>v({endCustomFormularyAtMedicationPayment:M===!0}),title:"End custom-formulary orders early",description:"Products mapped to a custom (non-OnlyScripts) medication stop the patient roadmap early. Choose where it ends once this is on."}):null,O&&(k==null?void 0:k.endCustomFormularyAtMedicationPayment)===!0?e.jsxs("div",{className:"space-y-2 rounded-xl border border-subtle bg-surface-sunken p-3 max-lg:space-y-1.5 max-lg:p-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Custom-formulary roadmap ends at"}),e.jsx("p",{className:"mt-1 text-xs text-content-tertiary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:'Medication payment hides Pharmacy and Shipped. Pharmacy submission keeps a "Submitted to pharmacy" step as the last one and hides tracking â use it when your providers send these orders to a pharmacy themselves.'})]}),e.jsx(a,{value:(k==null?void 0:k.customFormularyTerminalStep)||((L=A[0])==null?void 0:L.key),options:A,onChange:M=>v({customFormularyTerminalStep:M}),accentColor:i})]}):null,O?e.jsx(s,{id:"showPatientCustomFields",checked:((b=c.patientProfile)==null?void 0:b.showPartnerCustomFields)===!0,disabled:n,onCheckedChange:M=>C==null?void 0:C(M===!0),title:"Show partner API data on staff patient profiles",description:"Staff see partner-written customFields keys (read-only) on the patient profile. Patient fields you define here are always shown. Patients never see partner data. Off by default."}):null,e.jsx(s,{id:"patientReceiptsEnabled",checked:c.patientReceipts.enabled===!0,disabled:n,onCheckedChange:M=>u(M===!0),title:"Send receipts to patients for every order",description:"Patients get a receipt email after each paid order."}),O?e.jsx(s,{id:"patientFormResubmissionEnabled",checked:((w=c.patientFormResubmission)==null?void 0:w.enabled)===!0,disabled:n,onCheckedChange:M=>m==null?void 0:m(M===!0),title:"Start every form resubmission blank",description:"A new submission of a form the patient already completed starts empty, except for profile details and the patient data fields you configured. Off by default."}):null,O?e.jsx(s,{id:"requireIdVerificationForNewPatientsOnly",checked:c.requireIdVerificationForNewPatientsOnly.enabled===!0,disabled:n,onCheckedChange:M=>x(M===!0),title:"Require ID verification for new patients only",description:"New patients verify ID; existing patients skip it. Off requires ID for everyone."}):null,O?e.jsx(s,{id:"minimumSignupAgeEnabled",checked:((F=c.minimumSignupAge)==null?void 0:F.enabled)===!0,disabled:n,onCheckedChange:M=>f==null?void 0:f(M===!0),title:"Require patients to be 18 or older",description:"Blocks signup when a date of birth is under 18. Applies to patient onboarding, public checkout, and public form links. Staff-created patients are unaffected. Off by default."}):null,e.jsx(s,{id:"queuePrescriptionReviewEnabled",checked:c.queuePrescriptionReview.enabled===!0,disabled:n,onCheckedChange:M=>p(M===!0),title:"Review prescription orders before checkout",description:"Hold prescription payment prompts until your team reviews the order."}),O?e.jsx(s,{id:"clientCollectedProductPaymentEnabled",checked:c.clientCollectedProductPayment.enabled===!0,disabled:n,onCheckedChange:M=>d==null?void 0:d(M===!0),title:"Partner collects product payment off-platform",description:"API orders stay unpaid until your system charges the patient and marks the order paid. Patients won't see a pay button; prescriptions are held until payment is confirmed."}):null,e.jsx(s,{id:"queueLabOrderReviewEnabled",checked:c.queueLabOrderReview.enabled===!0,disabled:n,onCheckedChange:M=>y(M===!0),title:"Review lab orders before sending",description:"Hold patient lab orders so your team can release or cancel them."}),e.jsx(s,{id:"showVisitPurchasesInPatientOrders",checked:c.showVisitPurchasesInPatientOrders.enabled===!0,disabled:n,onCheckedChange:M=>N(M===!0),title:"Show visit purchases in the patient Orders tab",description:"Visit purchases also appear as orders patients can open and pay. Visits always stay on the Visits tab. Off by default."}),e.jsx(s,{id:"postPurchaseConsultationPromptEnabled",checked:c.postPurchaseConsultationPrompt.enabled!==!1,disabled:n,onCheckedChange:M=>h(M===!0),title:"Ask patients if they want a video call",description:"For async purchases, show the âDo you need a live video call?â choice."}),e.jsx(s,{id:"postVisitRedirectEnabled",checked:E,disabled:q==="postVisitRedirectEnabled",onCheckedChange:M=>g("postVisitRedirectEnabled",M===!0),title:"Redirect patients when they leave a visit",descriptionClassName:E?"mt-2":"",description:E?e.jsxs("div",{className:"space-y-1",children:[e.jsx(be,{id:"postVisitRedirectUrl",type:"url","aria-label":"Post-visit redirect URL",placeholder:"https://example.com/thank-you",value:z,onChange:M=>g("postVisitRedirectUrl",M.target.value),className:K("h-8 rounded-lg border-subtle bg-surface-raised text-xs transition-colors",z&&!l(z)&&"border-red-400 dark:border-red-500")}),z&&!l(z)?e.jsx("span",{className:"sr-only",children:"Enter a valid URL starting with http:// or https://"}):null]}):"Send patients to this URL when they leave a sync video visit, including Back."})]})})}const Cx=400;function xr(t){return t.map((s,a)=>({categoryId:s.categoryId,enabled:s.enabled!==!1,displayOrder:a,customLabel:s.customLabel||""}))}function Ki(t,s){return JSON.stringify(xr(t))===JSON.stringify(xr(s))}function Sx({category:t,onToggle:s,onCustomLabelChange:a}){const{attributes:i,listeners:n,setNodeRef:r,transform:l,transition:c,isDragging:u}=fn({id:t.categoryId}),m=t.enabled!==!1,h={transform:hn.Transform.toString(l),transition:c};
318return e.jsxs(At,{ref:r,style:h,className:K("bg-surface-raised",u&&"relative z-raised bg-surface-sunken shadow-lg"),children:[e.jsx(Ie,{className:"w-10 py-2 pl-3 pr-1",children:e.jsx("button",{type:"button",className:"inline-flex size-7 items-center justify-center rounded-md text-content-tertiary transition-colors hover:text-slate-700 dark:hover:text-slate-200",...i,...n,"aria-label":`Reorder ${t.title}`,children:e.jsx(ha,{className:"size-4 max-lg:size-3.5"})})}),e.jsx(Ie,{className:"w-14 py-2 px-2",children:e.jsx(Me,{id:`health-category-enabled-${t.categoryId}`,checked:m,onCheckedChange:g=>s(t.categoryId,g===!0),className:"size-5","aria-label":`${t.title} ${m?"enabled":"disabled"}`})}),e.jsx(Ie,{className:"py-2 px-3",children:e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-content-primary max-lg:gap-1 max-lg:text-2xs",children:[e.jsx(Qm,{categoryId:t.categoryId,className:"opacity-70"}),t.title]})}),e.jsx(Ie,{className:"py-2 px-3",children:e.jsx(be,{id:`health-category-label-${t.categoryId}`,value:t.customLabel||"",placeholder:t.title,onChange:g=>a(t.categoryId,g.target.value),className:"h-8 max-w-[14rem] text-sm max-lg:h-7 max-lg:max-w-[9rem]"})})]})}function Ex({tenantId:t,accentColor:s,loading:a,draftCategories:i,sensors:n,handleDragEnd:r,handleToggle:l,handleCustomLabelChange:c}){return t?a&&i.length===0?e.jsx("div",{className:"flex h-28 items-center justify-center max-lg:h-20",children:e.jsx(Ve,{className:"size-6 animate-spin max-lg:size-5",style:{color:s}})}):e.jsx(tn,{sensors:n,collisionDetection:sn,onDragEnd:r,children:e.jsx(an,{items:i.map(u=>u.categoryId),strategy:nn,children:e.jsx("div",{className:"overflow-x-auto max-lg:min-w-0",children:e.jsxs(la,{children:[e.jsx(oa,{children:e.jsxs(At,{className:"border-b border-subtle bg-slate-50/80 hover:bg-slate-50/80 dark:bg-slate-800/40 dark:hover:bg-slate-800/40",children:[e.jsx(Be,{className:"h-9 w-10 px-3 py-2 text-xs font-medium text-content-secondary"}),e.jsx(Be,{className:"h-9 w-14 px-2 py-2 text-xs font-medium text-content-secondary",children:"Status"}),e.jsx(Be,{className:"h-9 px-3 py-2 text-xs font-medium text-content-secondary",children:"Category"}),e.jsx(Be,{className:"h-9 px-3 py-2 text-xs font-medium text-content-secondary",children:"Display name"})]})}),e.jsx(ca,{children:i.map(u=>e.jsx(Sx,{category:u,accentColor:s,onToggle:l,onCustomLabelChange:c},u.categoryId))})]})})})}):e.jsx("div",{className:"text-sm text-content-tertiary max-lg:text-xs",children:"This account is not linked to a tenant yet."})}function Tx({clientId:t,tenantCollection:s=It.CLIENT,tenantId:a,accentColor:i,embedded:n=!1,grouped:r=!1,inline:l=!1}){const{userDoc:c}=Se(),{branding:u}=Ce(),m=s,h=a||t||(m===It.BUSINESS?c==null?void 0:c.businessId:c==null?void 0:c.clientId)||null,g=i||(u==null?void 0:u.accentColor)||je,{categories:y,loading:p}=Ym(h,{tenantCollection:m}
318),[d,x]=o.useState([]),[f,C]=o.useState(!1),N=o.useRef(d),v=o.useRef(y),k=o.useRef(null),P=o.useRef(!1),A=Mr(Fr(zr,{activationConstraint:{distance:6}})),E=o.useMemo(()=>!Ki(d,y),[d,y]);o.useEffect(()=>{N.current=d},[d]),o.useEffect(()=>{v.current=y},[y]),o.useEffect(()=>{(d.length===0||!E&&!p)&&x(y)},[y,d.length,E,p]);const z=o.useCallback(async()=>{if(!h)return;const w=N.current,F=v.current;if(!Ki(w,F))try{C(!0);const M=await $m(m,h,xr(w));x(M.map((W,H)=>({...F.find(ae=>ae.categoryId===W.categoryId),...W,displayOrder:W.displayOrder??H})))}catch(M){I.error((M==null?void 0:M.message)||"Unable to update health categories."),x(F)}finally{C(!1)}},[m,h]),q=o.useCallback(()=>{if(!h||p||!E)return;k.current&&clearTimeout(k.current);const w=P.current?0:Cx;P.current=!1,k.current=setTimeout(()=>{k.current=null,z()},w)},[h,E,p,z]);o.useEffect(()=>(q(),()=>{k.current&&clearTimeout(k.current)}),[d,q]);function R(w,F){P.current=!0,x(M=>M.map(W=>W.categoryId===w?{...W,enabled:F}:W))}function O(w,F){x(M=>M.map(W=>W.categoryId===w?{...W,customLabel:F}:W))}function j(w){const{active:F,over:M}=w;!M||F.id===M.id||(P.current=!0,x(W=>{const H=W.findIndex(xe=>xe.categoryId===F.id),ae=W.findIndex(xe=>xe.categoryId===M.id);return rr(W,H,ae).map((xe,Ae)=>({...xe,displayOrder:Ae}))}))}const L=f?e.jsx(Ve,{className:"size-4 animate-spin",style:{color:g},"aria-label":"Saving"}):null,b=e.jsx(Ex,{tenantId:h,accentColor:g,loading:p,draftCategories:d,saving:f,sensors:A,handleDragEnd:j,handleToggle:R,handleCustomLabelChange:O});return l?e.jsxs("div",{children:[f?e.jsx("div",{className:"mb-2 flex items-center justify-end gap-2",children:L}):null,b]}):r?e.jsxs("div",{className:"px-4 py-4 max-lg:px-2.5 max-lg:py-2.5 sm:px-5 sm:py-5",children:[e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3 max-lg:mb-2 max-lg:gap-2",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Health categories"}),e.jsx("p",{className:"text-xs leading-relaxed text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:"Enable categories, rename labels, and drag to set dashboard order."})]}),L]}),b]}):e.jsx(Sr,{title:n?"Health categories":"Patient health categories",description:"Enable categories, rename labels, and drag to set dashboard order.",icon:n?void 0:ld,accentColor:g,actions:L,bodyClassName:"p-3 max-lg:p-2",children:b})}Wm();const Px=120,Ln="__none__",Dt="h-11 rounded-lg border-subtle bg-surface-raised shadow-sm transition-[border-color,box-shadow] duration-150 placeholder:text-slate-400 hover:border-slate-300 focus-visible:border-slate-400 focus-visible:ring-2 focus-visible:ring-slate-200/90 focus-visible:ring-offset-0 dark:text-slate-100 dark:placeholder:text-slate-500 dark:hover:border-slate-500 dark:focus-visible:border-slate-500 dark:focus-visible:ring-slate-600/35",ut="text-xs font-medium text-content-secondary max-lg:text-2xs",Dr="justify-end gap-3 border-t border-subtle bg-slate-50/50 px-6 py-4 max-[1024px]:gap-1.5 max-[1024px]:px-3 max-[1024px]:py-2.5 dark:bg-slate-900/80 sm:px-10 sm:py-5";function $r({id:t,value:s,onChange:a,getSidebarItemIcon:i,accentColor:n,fallbackIcon:r}){var A;const l=ss(s,r),[c,u]=o.useState(!1),[m,h]=o.useState(kn(l)?"emoji":"lucide"),[g,y]=o.useState(""),[p,d]=o.useState(((A=va[0])==null?void 0:A.id)||"smileys"),x=o.useMemo(()=>od(),[]),{filteredLucideOptions:f,lucideMatchCount:C}=o.useMemo(()=>{const E=g.trim().toLowerCase(),z=E?x.filter(q=>q.value.toLowerCase().includes(E)||q.label.toLowerCase().includes(E)):x;return{filteredLucideOptions:z.slice(0,Px),lucideMatchCount:z.length}},[x,g]),N=va.find(E=>E.id===p)||va[0],v=o.useMemo(()=>Gm(N,g).slice(0,160),[N,g]),k=kn(l)?l:l.replace(/([a-z0-9])([A-Z])/g,"$1 $2");function P(E){a==null||a(ss(E)),u(!1)}return e.jsxs(Wl,{modal:!0,open:c,onOpenChange:u,children:[e.jsx(Gl,{asChild:!0,children:e.jsxs(B,{id:t,type:"button",variant:"outline",className:K(Dt,"w-full justify-between px-3 text-sm text-content-primary"),"aria-label":"Select patient sidebar icon","aria-expanded":c,children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-full",style:{backgroundColor:`${n}1A`,color:n},children:i(l,"size-3.5")}),e.jsx("span",{className:"truncate",children:k})]}),e.jsx(Jm,{className:"size-3.5 shrink-0 text-slate-400"})]})}),e.jsx(Kl,{align:"start",sideOffset:8,className:"z-[10080] w-[min(30rem,calc(100vw-2rem))] p-3 max-lg:w-[min(30rem,calc(100vw-1rem))] max-lg:p-2",accessibleLabel:"Patient sidebar icon selector",children:e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsx("div",{className:"grid grid-cols-2 gap-1 rounded-lg border border-subtle bg-surface-sunken p-1 max-lg:p-0.5",children:[{id:"lucide",label:"Icons"},{id:"emoji",label:"Emoji"}].map(E=>e.jsx("button",{type:"button",onClick:()=>{h(E.id),y("")}
318,className:K("rounded-md px-3 py-1.5 text-xs font-medium transition-colors","max-lg:px-2 max-lg:py-1 max-lg:text-2xs",m===E.id?"bg-surface-raised text-content-primary shadow-sm":"text-content-tertiary hover:text-slate-900 dark:hover:text-slate-100"),children:E.label},E.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(pn,{className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-slate-400"}),e.jsx(be,{value:g,onChange:E=>y(E.target.value),placeholder:m==="emoji"?"Search emojis or paste one":"Search icons","aria-label":"Search patient sidebar icons",className:K(Dt,"pl-8 text-sm")})]}),m==="emoji"&&g&&kn(g)?e.jsxs(B,{type:"button",variant:"outline",className:"h-8 rounded-full",onClick:()=>P(g),children:["Use ",ss(g)]}):null,m==="emoji"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-1 max-lg:pb-0.5",children:va.map(E=>e.jsx("button",{type:"button",onClick:()=>d(E.id),className:K("shrink-0 rounded-full border px-2.5 py-1 text-2xs font-medium",p===E.id?"border-slate-900 bg-slate-900 text-white dark:border-slate-100 dark:bg-slate-100 dark:text-slate-900":"border-subtle bg-surface-raised text-content-secondary"),children:E.label},E.id))}),e.jsx("div",{className:"grid max-h-64 grid-cols-10 gap-1 overflow-y-auto rounded-lg border border-subtle p-2 max-lg:max-h-52 max-lg:p-1.5",children:v.length?v.map(({ch:E},z)=>e.jsx("button",{type:"button",onClick:()=>P(E),className:K("flex size-8 items-center justify-center rounded-md text-lg hover:bg-slate-100 dark:hover:bg-slate-800",l===E&&"bg-slate-100 ring-1 ring-slate-300 dark:bg-slate-800 dark:ring-slate-600"),"aria-label":`Use ${E}`,children:E},`${E}-${z}`)):e.jsx("p",{className:"col-span-10 py-6 text-center text-xs text-content-tertiary max-lg:py-3 max-lg:text-2xs",children:"No emojis found."})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid max-h-72 grid-cols-8 gap-1 overflow-y-auto rounded-lg border border-subtle p-2 max-lg:max-h-56 max-lg:p-1.5 sm:grid-cols-10",children:f.length?f.map(E=>e.jsxs("button",{type:"button",onClick:()=>P(E.value),className:K("relative flex size-9 items-center justify-center rounded-md text-content-secondary hover:bg-slate-100 dark:hover:bg-slate-800",l===E.value&&"bg-slate-100 ring-1 ring-slate-300 dark:bg-slate-800 dark:ring-slate-600"),title:E.label,"aria-label":`Use ${E.label}`,children:[i(E.value,"size-4"),l===E.value?e.jsx(Ze,{className:"absolute right-0.5 top-0.5 size-3",style:{color:n}}):null]},E.value)):e.jsx("p",{className:"col-span-8 py-6 text-center text-xs text-content-tertiary max-lg:py-3 max-lg:text-2xs sm:col-span-10",children:"No Lucide icons found."})}),C>f.length?e.jsxs("p",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:["Showing the first ",f.length," matches. Search to narrow the list."]}):null]})]})})]})}function ja(t,s){const a=(t==null?void 0:t.target)===lt.FORM?lt.FORM:lt.URL;return{id:(t==null?void 0:t.id)||"",label:String((t==null?void 0:t.label)||"").slice(0,40),target:a,url:String((t==null?void 0:t.url)||""),formId:String((t==null?void 0:t.formId)||"").trim(),notifyEmails:Array.isArray(t==null?void 0:t.notifyEmails)?t.notifyEmails.join(", "):String((t==null?void 0:t.notifyEmails)||""),icon:ss(t==null?void 0:t.icon),openMode:(t==null?void 0:t.openMode)===s.NEW_TAB?s.NEW_TAB:s.EMBED,sectionId:String((t==null?void 0:t.sectionId)||"").trim(),enabled:(t==null?void 0:t.enabled)!==!1}}function Ax(t){return Pr(String(t||"").split(/[,;\s]+/))}function Ix(t){const s=String(t||"").split(/[,;\s]+/).map(a=>a.trim().toLowerCase()).filter(Boolean);return new Set(s).size}function ka(t){return{id:(t==null?void 0:t.id)||"",label:String((t==null?void 0:t.label)||"").slice(0,40),icon:ss((t==null?void 0:t.icon)||"FolderOpen"),enabled:(t==null?void 0:t.enabled)!==!1}}function Rx({accentColor:t,clientFormOptions:s=[],clientFormsStatus:a="idle",getSidebarItemIcon:i,initialItem:n,isValidPatientSidebarUrl:r,mode:l,onOpenChange:c,onSave:u,open:m,patientCustomLinkOpenModes:h,sections:g=[],supportsFormTarget:y=!1}){const p=l==="edit"?"Edit sidebar link":"Add sidebar link",[d,x]=o.use
318State(()=>ja(n,h)),[f,C]=o.useState("");o.useEffect(()=>{if(!m)return;x(ja(n,h)),C("");const E=window.requestAnimationFrame(()=>{var z;(z=document.getElementById("patient-sidebar-link-label"))==null||z.focus()});return()=>window.cancelAnimationFrame(E)},[n,m,h]);function N(E){x(z=>ja({...z,...E},h)),C("")}const v=y&&d.target===lt.FORM,k=!!d.label.trim()&&(v?!!d.formId:!!d.url.trim()),P=v&&!!d.formId&&!s.some(E=>E.value===d.formId);function A(){const E=ja(d,h);if(!E.label.trim()){C("Enter a label.");return}if(v){if(!E.formId){C("Choose a form.");return}const z=Ix(E.notifyEmails),q=Ax(E.notifyEmails);if(z>0&&q.length===0){C("Enter a valid email address, or leave the field empty.");return}if(z>jn){C(`Enter at most ${jn} email addresses.`);return}if(z>q.length){C("One of those email addresses is not valid. Remove it or correct it.");return}u({...E,target:lt.FORM,openMode:h.EMBED,url:"",notifyEmails:q});return}if(!r(E.url)){C("Enter a valid http:// or https:// URL.");return}u({...E,target:lt.URL,formId:"",notifyEmails:[]})}return e.jsx(at,{open:m,onOpenChange:c,title:p,description:"Configure the patient-facing link. The live portal changes only after you save.",mobileCompactHeaderRow:!0,mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",contentClassName:"max-w-xl",titleClassName:"font-display text-2xl font-bold tracking-tight text-content-primary max-[1024px]:text-base max-[1024px]:leading-tight",bodyClassName:"px-6 pb-6 pt-2 max-[1024px]:px-3 max-[1024px]:pb-3 max-[1024px]:pt-1.5 sm:px-10 sm:pb-8",footerClassName:Dr,containChildOverlays:!0,footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",className:"min-h-10 rounded-lg max-lg:min-h-9",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{type:"submit",form:"settings-patient-dashboard-section-form-1",className:"min-h-10 rounded-lg text-white max-lg:min-h-9",style:{backgroundColor:t},disabled:!k,children:"Save link"})]}),children:e.jsx("form",{id:"settings-patient-dashboard-section-form-1",className:us,onSubmit:xs(A,{disabled:!k}),children:e.jsxs($t,{className:"overflow-visible p-0",bodyClassName:"divide-y divide-slate-200/90 dark:divide-slate-700/90",children:[e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"patient-sidebar-link-label",className:ut,children:"Label"}),e.jsx(be,{id:"patient-sidebar-link-label",value:d.label,maxLength:40,autoComplete:"off","data-testid":"input-patient-sidebar-link-label",onChange:E=>N({label:E.target.value}),className:K(Dt,"text-sm")})]}),y?e.jsxs("div",{className:"space-y-2 px-5 py-4 max-lg:space-y-1.5 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{className:ut,children:"Link to"}),e.jsx(Ga,{value:d.target,onValueChange:E=>N({target:E}),className:"grid gap-2 max-lg:gap-1.5",children:[{value:lt.URL,label:"Website URL"},{value:lt.FORM,label:"Client form"}].map(E=>e.jsxs("label",{htmlFor:`patient-sidebar-link-target-${E.value}`,className:"flex h-10 cursor-pointer items-center gap-3 rounded-lg border border-subtle bg-surface-raised px-3 text-sm text-content-primary transition-colors max-lg:h-9 max-lg:gap-2 max-lg:px-2.5 max-lg:text-xs hover:bg-slate-50 dark:hover:bg-slate-900",children:[e.jsx(Ka,{id:`patient-sidebar-link-target-${E.value}`,value:E.value}),e.jsx("span",{children:E.label})]},E.value))}),e.jsx("p",{className:"text-2xs text-content-tertiary max-lg:text-3xs",children:"A client form opens in a new tab with the patient already signed in and the questions already showing, so they never re-enter their details. It does not appear in the mobile app."})]}):null,v?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"patient-sidebar-link-form",className:ut,children:"Form"}),e.jsx(Km,{testId:"combobox-patient-sidebar-link-form",options:s,value:d.formId,onChange:E=>N({formId:E}),placeholder:"Choose a form",searchPlaceholder:"Search formsâ¦",loading:a==="loading",emptyMessage:a==="error"?"Your forms could not be loaded. Close this dialog and try again.":"No active intake or consent forms.",ariaLabel:"Cho
318ose a client form",className:"w-full",modal:!0}),P?e.jsx("p",{role:"alert",className:"text-2xs text-[var(--status-warning-text)] max-lg:text-3xs",children:"The selected form is no longer active. Patients opening this link see âThis form is no longer availableâ until you choose another."}):a==="error"?e.jsx("p",{role:"alert",className:"text-2xs text-[var(--status-danger-text)] max-lg:text-3xs",children:"Your forms could not be loaded, so the list is empty. Reopen this dialog to retry."}):e.jsx("p",{className:"text-2xs text-content-tertiary max-lg:text-3xs",children:"Active intake and consent forms only. Patients can submit it more than once."})]}),e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsxs(oe,{htmlFor:"patient-sidebar-link-notify",className:ut,children:["Notify on submission ",e.jsx("span",{className:"font-normal text-content-tertiary",children:"(optional)"})]}),e.jsx(be,{id:"patient-sidebar-link-notify",type:"text",value:d.notifyEmails,placeholder:"[email protected], [email protected]","data-testid":"input-patient-sidebar-link-notify","aria-describedby":"patient-sidebar-link-notify-help",onChange:E=>N({notifyEmails:E.target.value}),className:K(Dt,"text-sm")}),e.jsxs("p",{id:"patient-sidebar-link-notify-help",className:"text-2xs text-content-tertiary max-lg:text-3xs",children:["Up to ",jn," addresses, comma separated. Each one receives the patient name, the form name and a link â never the answers, which stay in the form review queue."]})]})]}):e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"patient-sidebar-link-url",className:ut,children:"URL"}),e.jsx(be,{id:"patient-sidebar-link-url",type:"url",value:d.url,placeholder:"e.g. https://example.com","data-testid":"input-patient-sidebar-link-url","aria-describedby":f?"patient-sidebar-link-error":void 0,onChange:E=>N({url:E.target.value}),className:K(Dt,"text-sm")})]}),e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"patient-sidebar-link-icon",className:ut,children:"Icon"}),e.jsx($r,{id:"patient-sidebar-link-icon",value:d.icon,onChange:E=>N({icon:E}),getSidebarItemIcon:i,accentColor:t})]}),e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"patient-sidebar-link-section",className:ut,children:"Section"}),e.jsxs(yt,{value:d.sectionId||Ln,onValueChange:E=>N({sectionId:E===Ln?"":E}),children:[e.jsx(vt,{id:"patient-sidebar-link-section",className:K(Dt,"w-full text-sm"),children:e.jsx(Nt,{placeholder:"No section"})}),e.jsxs(jt,{className:"max-h-[min(320px,50vh)]",children:[e.jsx(st,{value:Ln,children:"No section"}),g.map(E=>e.jsx(st,{value:E.id,children:E.label||"Section"},E.id))]})]})]}),e.jsxs("div",{className:K("space-y-2 px-5 py-4 max-lg:space-y-1.5 max-lg:px-3 max-lg:py-2.5 sm:px-6",v&&"hidden"),children:[e.jsx(oe,{className:ut,children:"Open"}),e.jsx(Ga,{value:d.openMode,onValueChange:E=>N({openMode:E}),className:"grid gap-2 max-lg:gap-1.5",children:[{value:h.EMBED,label:"Embed in portal"},{value:h.NEW_TAB,label:"Open in new tab"}].map(E=>e.jsxs("label",{htmlFor:`patient-sidebar-link-open-mode-${E.value}`,className:"flex h-10 cursor-pointer items-center gap-3 rounded-lg border border-subtle bg-surface-raised px-3 text-sm text-content-primary transition-colors max-lg:h-9 max-lg:gap-2 max-lg:px-2.5 max-lg:text-xs hover:bg-slate-50 dark:hover:bg-slate-900",children:[e.jsx(Ka,{id:`patient-sidebar-link-open-mode-${E.value}`,value:E.value}),e.jsx("span",{children:E.label})]},E.value))})]}),f?e.jsx("p",{id:"patient-sidebar-link-error",role:"alert",className:"px-5 py-3 text-sm text-red-600 max-lg:px-3 max-lg:py-2 max-lg:text-xs dark:text-red-400 sm:px-6",children:f}):null]})})})}function Lx({accentColor:t,getSidebarItemIcon:s,initialSection:a,mode:i,onOpenChange:n,onSave:r,open:l}){const c=i==="edit"?"Edit sidebar section":"Add sidebar section",[u,m]=o.useState(()=>ka(a)),[h,g]=o.useState("");o.useEffect(()=>{if(!l)return;m(ka(a)),g("");const d=window.requestAnimationFrame(()=>{var x;(x=document.getElementById("patient-sidebar-section-label"))==null||x.focus()});return()=>window.cancelAnimationFrame(d)},[a,l]);function y(d){m(x=>ka({...x,...d})),g("")}function p(){const d=ka(u);if(!d.label.trim()){g("Enter a title.");return}r(d)}return e.jsx(at,{open:l,onOpenChange:n,title:c,description:"Group related patient links. The live portal changes only after you save.",mobileCompactHeaderRow:!0,mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",contentClassName:"max-w-xl",titleClassName:"font-display text-2xl font-bold tracking-tight text-content-primary max-[1024px]:text-base max-[1024px]:leading-tight",bodyClassName:"px-6 pb-6 pt-2 max-[1024px]:px-3 max-[1024px]:pb-3 max-[1024px]:pt-1.5 sm:px-10 sm:pb-8",footerClassName:Dr,containChildOverlays:!0,footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{t
318ype:"button",variant:"outline",className:"min-h-10 rounded-lg max-lg:min-h-9",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{type:"submit",form:"settings-patient-dashboard-section-form-2",className:"min-h-10 rounded-lg text-white max-lg:min-h-9",style:{backgroundColor:t},disabled:!u.label.trim(),children:"Save section"})]}),children:e.jsx("form",{id:"settings-patient-dashboard-section-form-2",className:us,onSubmit:xs(p,{disabled:!u.label.trim()}),children:e.jsxs($t,{className:"overflow-visible p-0",bodyClassName:"divide-y divide-slate-200/90 dark:divide-slate-700/90",children:[e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"patient-sidebar-section-label",className:ut,children:"Title"}),e.jsx(be,{id:"patient-sidebar-section-label",value:u.label,maxLength:40,autoComplete:"off","data-testid":"input-patient-sidebar-section-label",onChange:d=>y({label:d.target.value}),className:K(Dt,"text-sm")})]}),e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"patient-sidebar-section-icon",className:ut,children:"Icon"}),e.jsx($r,{id:"patient-sidebar-section-icon",value:u.icon,onChange:d=>y({icon:d}),getSidebarItemIcon:s,accentColor:t})]}),h?e.jsx("p",{role:"alert",className:"px-5 py-3 text-sm text-red-600 max-lg:px-3 max-lg:py-2 max-lg:text-xs dark:text-red-400 sm:px-6",children:h}):null]})})})}function Yi(t={}){var s,a,i;return{label:String(((s=t==null?void 0:t.override)==null?void 0:s.label)||"").slice(0,Zn),description:String(((a=t==null?void 0:t.override)==null?void 0:a.description)||"").slice(0,er),icon:String(((i=t==null?void 0:t.override)==null?void 0:i.icon)||"")}}function Ox({accentColor:t,getSidebarItemIcon:s,initialItem:a,onOpenChange:i,onSave:n,open:r}){const[l,c]=o.useState(()=>Yi(a)),u=(a==null?void 0:a.defaultLabel)||"",m=(a==null?void 0:a.defaultIcon)||"",h=(a==null?void 0:a.id)!=="wallet";o.useEffect(()=>{if(!r)return;c(Yi(a));const p=window.requestAnimationFrame(()=>{var d;(d=document.getElementById("patient-sidebar-default-item-label"))==null||d.focus()});return()=>window.cancelAnimationFrame(p)},[a,r]);function g(p){c(d=>({label:String(p.label??d.label).slice(0,Zn),description:String(p.description??d.description).slice(0,er),icon:String(p.icon??d.icon)}))}function y(){n({label:l.label.trim(),description:h?l.description.trim():"",icon:l.icon.trim()})}return e.jsx(at,{open:r,onOpenChange:i,title:`Edit ${u||"menu item"}`,description:"Rename this menu item, choose its icon, and set the copy patients see on its page. Leave a field blank to use the default.",mobileCompactHeaderRow:!0,mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",contentClassName:"max-w-xl",titleClassName:"font-display text-2xl font-bold tracking-tight text-content-primary max-[1024px]:text-base max-[1024px]:leading-tight",bodyClassName:"px-6 pb-6 pt-2 max-[1024px]:px-3 max-[1024px]:pb-3 max-[1024px]:pt-1.5 sm:px-10 sm:pb-8",footerClassName:Dr,containChildOverlays:!0,footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",className:"min-h-10 rounded-lg max-lg:min-h-9",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{type:"submit",form:"settings-patient-dashboard-section-form-3",className:"min-h-10 rounded-lg text-white max-lg:min-h-9",style:{backgroundColor:t},"data-testid":"button-save-patient-sidebar-default-item",children:"Save"})]}),children:e.jsx("form",{id:"settings-patient-dashboard-section-form-3",className:us,onSubmit:xs(y),children:e.jsxs($t,{className:"overflow-visible p-0",bodyClassName:"divide-y divide-slate-200/90 dark:divide-slate-700/90",children:[e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(oe,{htmlFor:"patient-sidebar-default-item-icon",className:ut,children:"Icon"}),l.icon?e.jsx(B,{type:"button",variant:"ghost",className:"h-7 rounded-full px-2.5 text-2xs font-medium text-content-secondary max-lg:h-6 max-lg:text-3xs",onClick:()=>g({icon:""}),"data-testid":"button-reset-patient-sidebar-default-item-icon",children:"Use default"}):null]}),e.jsx($r,{id:"patient-sidebar-default-item-icon",fallbackIcon:m,value:l.icon,onChange:p=>g({icon:p}),getSidebarItemIcon:s,accentColor:t}),e.jsx("p",{className:"text-2xs text-content-tertiary max-lg:text-3xs",children:"Leave default to keep the current icon."})]}),e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"patient-sidebar-default-item-label",className:ut,children:"Menu label"}),e.jsx(be,{id:"patient-sidebar-default-item-label",value:l.label,maxLength:Zn,autoComplete:"off",placeholder:u,"data-testid":"input-patient-sidebar-default-item-label",onCh
318ange:p=>g({label:p.target.value}),className:K(Dt,"text-sm")}),e.jsx("p",{className:"text-2xs text-content-tertiary max-lg:text-3xs",children:"Shown in the patient sidebar and as the page title."})]}),h?e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"patient-sidebar-default-item-description",className:ut,children:"Page description"}),e.jsx(Is,{id:"patient-sidebar-default-item-description",value:l.description,maxLength:er,rows:2,"data-testid":"input-patient-sidebar-default-item-description",onChange:p=>g({description:p.target.value}),className:K(Dt,"min-h-[4.5rem] resize-y py-2.5 text-sm"),placeholder:"Optional supporting text under the page title"})]}):e.jsx("p",{className:"px-5 py-4 text-xs text-content-tertiary max-lg:px-3 max-lg:py-2.5 max-lg:text-2xs sm:px-6",children:"Wallet opens as a pop-up, so only the menu label applies."})]})})})}function On(t={}){return{title:String((t==null?void 0:t.title)||""),description:String((t==null?void 0:t.description)||""),html:String((t==null?void 0:t.html)||"")}}function Mx({accentColor:t,initialSection:s,mode:a,onOpenChange:i,onSave:n,open:r}){const l=a==="edit"?"Edit custom section":"Add custom section",[c,u]=o.useState(()=>On(s)),[m,h]=o.useState("");o.useEffect(()=>{if(!r)return;u(On(s)),h("");const p=window.requestAnimationFrame(()=>{var d;(d=document.getElementById("patient-dashboard-custom-section-title"))==null||d.focus()});return()=>window.cancelAnimationFrame(p)},[s,r]);function g(p){u(d=>On({...d,...p})),h("")}function y(){const p=Ya(c);if(!p.title.trim()){h("Enter a title.");return}n({title:p.title,description:p.description,html:p.html})}return e.jsx(at,{open:r,onOpenChange:i,title:l,description:"Adds a titled block with optional description and custom HTML on the patient dashboard.",mobileCompactHeaderRow:!0,mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",contentClassName:"max-w-2xl",titleClassName:"font-display text-2xl font-bold tracking-tight text-content-primary max-[1024px]:text-base max-[1024px]:leading-tight",bodyClassName:"px-4 pb-4 pt-2 max-[1024px]:px-2.5 max-[1024px]:pb-2.5 max-[1024px]:pt-1.5 sm:pb-6",footerClassName:"justify-end gap-3 bg-transparent px-4 py-4 max-[1024px]:gap-1.5 max-[1024px]:px-2.5 max-[1024px]:py-2.5 sm:py-5",footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",className:"min-h-10 rounded-lg max-lg:min-h-9",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{type:"submit",form:"settings-patient-dashboard-section-form-4",className:"min-h-10 rounded-lg text-white max-lg:min-h-9",style:{backgroundColor:t},disabled:!c.title.trim(),"data-testid":"button-save-custom-dashboard-section",children:"Save section"})]}),children:e.jsx("form",{id:"settings-patient-dashboard-section-form-4",className:us,onSubmit:xs(y,{disabled:!c.title.trim()}),children:e.jsxs($t,{className:"overflow-visible p-0",bodyClassName:"divide-y divide-slate-200/90 dark:divide-slate-700/90",children:[e.jsxs("div",{className:"space-y-1.5 px-4 py-4 max-lg:space-y-1 max-lg:px-2.5 max-lg:py-2.5",children:[e.jsx(oe,{htmlFor:"patient-dashboard-custom-section-title",className:ut,children:"Title"}),e.jsx(be,{id:"patient-dashboard-custom-section-title",value:c.title,maxLength:80,autoComplete:"off","data-testid":"input-custom-dashboard-section-title",onChange:p=>g({title:p.target.value}),className:K(Dt,"text-sm")})]}),e.jsxs("div",{className:"space-y-1.5 px-4 py-4 max-lg:space-y-1 max-lg:px-2.5 max-lg:py-2.5",children:[e.jsx(oe,{htmlFor:"patient-dashboard-custom-section-description",className:ut,children:"Description"}),e.jsx(Is,{id:"patient-dashboard-custom-section-description",value:c.description,maxLength:240,rows:2,"data-testid":"input-custom-dashboard-section-description",onChange:p=>g({description:p.target.value}),className:K(Dt,"min-h-[4.5rem] resize-y py-2.5 text-sm"),placeholder:"Optional supporting text under the title"})]}),e.jsxs("div",{className:"space-y-1.5 px-4 py-4 max-lg:space-y-1 max-lg:px-2.5 max-lg:py-2.5",children:[e.jsx(oe,{htmlFor:"patient-dashboard-custom-section-html",className:ut,children:"Custom HTML"}),e.jsx("div",{id:"patient-dashboard-custom-section-html","data-testid":"input-custom-dashboard-section-html",className:"overflow-hidden rounded-lg border border-subtle shadow-sm",children:e.jsx(Hm,{height:"160px",language:"html",value:c.html,theme:typeof document<"u"&&document.documentElement.classList.contains("dark")?"vs-dark":"light",onCh
318ange:p=>g({html:p??""}),options:{automaticLayout:!0,contextmenu:!1,fontFamily:"SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', monospace",fontSize:12,glyphMargin:!1,lineDecorationsWidth:8,lineNumbers:"on",lineNumbersMinChars:3,minimap:{enabled:!1},overviewRulerBorder:!1,overviewRulerLanes:0,padding:{top:12,bottom:12},renderLineHighlight:"line",scrollBeyondLastLine:!1,wordWrap:"on",scrollbar:{alwaysConsumeMouseWheel:!1,horizontal:"auto",horizontalScrollbarSize:8,vertical:"auto",verticalScrollbarSize:8}}})}),e.jsx("p",{className:"text-2xs text-content-tertiary max-lg:text-3xs",children:"Scripts and unsafe tags are stripped. Links, lists, headings, images, and basic layout tags are allowed."}),e.jsxs("p",{className:"text-2xs text-content-tertiary max-lg:text-3xs",children:["To open an active client form, add its ID to an element, for example:"," ",e.jsx("code",{className:"rounded bg-slate-100 px-1 py-0.5 dark:bg-slate-800",children:'<a href="#" data-gh-client-form="FORM_ID">Start form</a>'})]})]}),m?e.jsx("p",{role:"alert",className:"px-4 py-3 text-sm text-red-600 max-lg:px-2.5 max-lg:py-2 max-lg:text-xs dark:text-red-400",children:m}):null]})})})}function Fx({ExperienceSurfaceCard:t,PatientDashboardPreview:s,accentColor:a,clientFormOptions:i=[],clientFormsStatus:n="idle",clientId:r,reviewOnlyTenant:l=!1,tenantCollection:c=It.CLIENT,createCustomSidebarItem:u,createCustomSidebarSection:m,dashboardEditorTab:h,dashboardSectionOptions:g,getSidebarItemIcon:y,hexToRgba:p,isSavingExperienceConfig:d,isSavingPatientSidebar:x,isSavingWearables:f,isValidPatientSidebarUrl:C,monitoringSectionEnabled:N,normalizedExperienceConfig:v,onAddCustomPatientSidebarItem:k,onAddCustomPatientSidebarSection:P,onMovePatientSidebarItem:A,onRemoveCustomPatientSidebarItem:E,onRemoveCustomPatientSidebarSection:z,onTogglePatientSidebarItem:q,onUpdateCustomPatientSidebarItem:R,onUpdateCustomPatientSidebarSection:O,onUpdatePatientSidebarItemOverride:j,onWearablesChange:L,patientCustomLinkOpenModes:b,patientSidebarRows:w,setDashboardEditorTab:F,updateDashboardSectionEnabled:M,visibleDashboardSections:W,visiblePatientSidebarRows:H,wearables:ae,moveDashboardSection:xe,onAddCustomDashboardSection:Ae,onUpdateCustomDashboardSection:se,onRemoveCustomDashboardSection:Z}){const[fe,J]=o.useState(()=>({open:!1,mode:"add",itemId:null,initialItem:null})),[ge,ye]=o.useState(()=>({open:!1,mode:"add",sectionId:null,initialSection:null})),[Re,G]=o.useState(()=>({open:!1,mode:"add",sectionKey:null,initialSection:null})),[U,V]=o.useState(()=>({open:!1,itemId:null,initialItem:null})),D=w.filter(X=>X.type==="section").map(X=>X.section);function T(){J(X=>({...X,open:!1}))}function $(){ye(X=>({...X,open:!1}))}function S(){G(X=>({...X,open:!1}))}function Q(){V(X=>({...X,open:!1}))}function Y(X){V({open:!0,itemId:X.id,initialItem:X})}function de(X){j==null||j(U.itemId,X),Q()}function ve(){J({open:!0,mode:"add",itemId:null,initialItem:u==null?void 0:u()})}function Ee(X){J({open:!0,mode:"edit",itemId:X.id,initialItem:X.customItem})}function Oe(){ye({open:!0,mode:"add",sectionId:null,initialSection:m==null?void 0:m()})}function nt(X){ye({open:!0,mode:"edit",sectionId:X.id,initialSection:X.section})}function ze(){G({open:!0,mode:"add",sectionKey:null,initialSection:Ya()})}function pt(X){G({open:!0,mode:"edit",sectionKey:X.key,initialSection:X})}function Bt(X){fe.mode==="edit"?R==null||R(fe.itemId,{label:X.label,target:X.target,url:X.url,formId:X.formId,notifyEmails:X.notifyEmails,icon:X.icon,openMode:X.openMode,sectionId:X.sectionId}):k==null||k(X),T()}function Gt(X){ge.mode==="edit"?["label","icon"].forEach(We=>{O==null||O(ge.sectionId,We,X[We])}):P==null||P(X),$()}function cs(X){Re.mode==="edit"?se==null||se(Re.sectionKey,X):Ae==null||Ae(X),S()}return e.jsx(t,{id:"patient-dashboard",title:"Patient dashboard",description:"Edit portal navigation and dashboard sections against the same patient preview.",icon:xn,accentColor:a,saving:x||d||f,children:e.jsxs("div",{className:"grid gap-6 max-lg:gap-2.5 xl:grid-cols-2 xl:items-start",children:[e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-1 rounded-xl border border-subtle bg-surface-sunken p-1 max-lg:p-0.5",children:[e.jsx("button",{type:"button",onClick:()=>
318F("sidebar"),className:K("rounded-lg px-3 py-2 text-xs font-medium transition-colors","max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs",h==="sidebar"?"bg-surface-raised text-content-primary shadow-sm":"text-content-tertiary hover:text-slate-900 dark:hover:text-slate-100"),children:"Sidebar menu"}),e.jsx("button",{type:"button",onClick:()=>F("dashboard"),className:K("rounded-lg px-3 py-2 text-xs font-medium transition-colors","max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs",h==="dashboard"?"bg-surface-raised text-content-primary shadow-sm":"text-content-tertiary hover:text-slate-900 dark:hover:text-slate-100"),children:"Dashboard sections"})]}),h==="sidebar"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overflow-hidden rounded-xl border border-subtle",children:[H.map((X,We)=>{var Lt;const ct=X.enabled!==!1,gt=X.required===!0,_t=X.type==="custom",dt=X.type==="section",et=ct,Rt=w.filter(ee=>ee.enabled!==!1),rt=Rt.findIndex(ee=>ee.key===X.key);return e.jsxs("div",{className:K("p-3 max-lg:p-2",We>0&&"border-t border-subtle",!ct&&"bg-slate-50/60 dark:bg-slate-900/20"),children:[e.jsxs("div",{className:"flex items-start gap-3 max-lg:gap-2",children:[e.jsx(ha,{className:"mt-1 size-4 shrink-0 text-slate-300 max-lg:size-3.5 dark:text-slate-600"}),e.jsx(Me,{id:`experience-patient-nav-${X.key}`,checked:ct,disabled:gt,onCheckedChange:ee=>{_t?R==null||R(X.id,"enabled",!!ee):dt?O==null||O(X.id,"enabled",!!ee):q(X.id,!!ee)},className:"mt-0.5 size-4 shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("label",{htmlFor:`experience-patient-nav-${X.key}`,className:"flex min-w-0 cursor-pointer items-center gap-2",children:[e.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-full max-lg:size-6",style:{backgroundColor:p(a,.1),color:a},children:y(X.icon,"size-3.5")}),e.jsx("span",{className:K("truncate text-sm font-medium max-lg:text-xs",ct?"text-content-primary":"text-content-tertiary"),children:X.label})]})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 max-lg:[&_svg]:h-3 max-lg:[&_svg]:w-3 max-lg:[&_button]:h-7 max-lg:[&_button]:w-7",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-8 text-content-tertiary hover:text-slate-800 dark:hover:text-slate-100",disabled:!et||rt<=0,onClick:()=>A==null?void 0:A(X.key,"up"),"aria-label":`Move ${X.label} up`,children:e.jsx(Pi,{className:"size-3.5"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-8 text-content-tertiary hover:text-slate-800 dark:hover:text-slate-100",disabled:!et||rt>=Rt.length-1,onClick:()=>A==null?void 0:A(X.key,"down"),"aria-label":`Move ${X.label} down`,children:e.jsx(Ai,{className:"size-3.5"})}),_t||dt?e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-8 text-content-tertiary hover:text-slate-800 dark:hover:text-slate-100",onClick:()=>dt?nt(X):Ee(X),"aria-label":`Edit ${X.label}`,children:e.jsx(zt,{className:"size-3.5"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-8 text-content-tertiary hover:text-red-600 dark:hover:text-red-400",onClick:()=>dt?z==null?void 0:z(X.id):E==null?void 0:E(X.id),"aria-label":`Remove ${X.label}`,children:e.jsx(bt,{className:"size-3.5"})})]}):e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-8 text-content-tertiary hover:text-slate-800 dark:hover:text-slate-100",onClick:()=>Y(X),"aria-label":`Edit ${X.label}`,"data-testid":`button-edit-patient-nav-${X.key}`,children:e.jsx(zt,{className:"size-3.5"})})]})]}),dt?e.jsx("div",{className:"mt-3 space-y-2 border-l border-subtle pl-6 max-lg:mt-2 max-lg:space-y-1.5 max-lg:pl-4",children:(Lt=X.children)!=null&&Lt.length?X.children.map(ee=>e.jsxs("div",{className:K("flex items-center gap-3 rounded-lg bg-slate-50/70 px-3 py-2 dark:bg-slate-900/30","max-lg:gap-2 max-lg:px-2 max-lg:py-1.5",ee.enabled===!1&&"opacity-70"),children:[e.jsx(Me,{id:`experience-patient-nav-${ee.key}`,checked:ee.enabled!==!1,onCheckedChange:Ye=>R==null?void 0:R(ee.id,"enabled",!!Ye),className:"size-4 shrink-0"}),e.jsxs("label",{htmlFor:`experience-patient-nav-${ee.key}`,className:"flex min-w-0 flex-1 cursor-pointer items-center gap-2",children:[e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-full",style:{backgroundColor:p(a,.1),c
318olor:a},children:y(ee.icon,"size-3")}),e.jsx("span",{className:"truncate text-sm font-medium text-slate-700 max-lg:text-xs dark:text-slate-200",children:ee.label})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 max-lg:[&_svg]:h-3 max-lg:[&_svg]:w-3 max-lg:[&_button]:h-7 max-lg:[&_button]:w-7",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-7 text-content-tertiary max-lg:size-6 hover:text-slate-800 dark:hover:text-slate-100",onClick:()=>Ee(ee),"aria-label":`Edit ${ee.label}`,children:e.jsx(zt,{className:"size-3.5"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-7 text-content-tertiary max-lg:size-6 hover:text-red-600 dark:hover:text-red-400",onClick:()=>E==null?void 0:E(ee.id),"aria-label":`Remove ${ee.label}`,children:e.jsx(bt,{className:"size-3.5"})})]})]},ee.key)):e.jsx("p",{className:"rounded-lg bg-slate-50/70 px-3 py-2 text-xs text-content-tertiary max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs dark:bg-slate-900/30",children:"Add links to this section from the link editor."})}):null]},X.key)}),l?e.jsx("p",{role:"status",className:"border-t border-subtle px-4 py-3 text-2xs text-[var(--status-warning-text)] max-lg:px-2.5 max-lg:py-2 max-lg:text-3xs",children:"This account is Review Only. Patients see Dashboard, Visits, Forms and Support only, so custom links and sections below are saved but not shown to them."}):null,e.jsxs("div",{className:"grid grid-cols-2 gap-0 border-t border-subtle",children:[e.jsxs(B,{type:"button",variant:"ghost",className:"h-11 w-full rounded-none border-r border-subtle text-slate-700 max-lg:h-9 max-lg:text-xs hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800/60",onClick:ve,children:[e.jsx(ot,{className:"mr-2 size-4 max-lg:mr-1 max-lg:size-3.5"}),"Add link"]}),e.jsxs(B,{type:"button",variant:"ghost",className:"h-11 w-full rounded-none text-slate-700 max-lg:h-9 max-lg:text-xs hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800/60",onClick:Oe,children:[e.jsx(ot,{className:"mr-2 size-4 max-lg:mr-1 max-lg:size-3.5"}),"Add section"]})]})]}),e.jsx(Rx,{accentColor:a,clientFormOptions:i,clientFormsStatus:n,supportsFormTarget:c===It.CLIENT,getSidebarItemIcon:y,initialItem:fe.initialItem,isValidPatientSidebarUrl:C,mode:fe.mode,onOpenChange:X=>{X?J(We=>({...We,open:!0})):T()},onSave:Bt,open:fe.open,patientCustomLinkOpenModes:b,sections:D}),e.jsx(Lx,{accentColor:a,getSidebarItemIcon:y,initialSection:ge.initialSection,mode:ge.mode,onOpenChange:X=>{X?ye(We=>({...We,open:!0})):$()},onSave:Gt,open:ge.open}),e.jsx(Ox,{accentColor:a,getSidebarItemIcon:y,initialItem:U.initialItem,onOpenChange:X=>{X?V(We=>({...We,open:!0})):Q()},onSave:de,open:U.open})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overflow-hidden rounded-xl border border-subtle",children:[W.map((X,We)=>{const ct=ia(X),gt=ct?{label:X.title||"Custom section",description:X.description||"Custom HTML section."}:g[X.key]||{label:X.key,description:"Additional patient dashboard section."},_t=X.key==="lifestyle",dt=X.key==="monitoring",et=X.enabled!==!1,Rt=v.patientDashboard.sections.findIndex(rt=>rt.key===X.key);return e.jsxs("div",{className:K("p-4 max-lg:p-2.5",We>0&&"border-t border-subtle",!et&&"opacity-80"),children:[e.jsxs("div",{className:"flex items-start gap-3 max-lg:gap-2",children:[e.jsx(Me,{id:`dashboard-section-${X.key}`,checked:et,onCheckedChange:rt=>M(X.key,rt===!0),className:"mt-0.5 size-5 shrink-0 max-lg:size-4"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("label",{htmlFor:`dashboard-section-${X.key}`,className:"block cursor-pointer",children:[e.jsx("span",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:gt.label}),e.jsx("p",{className:"mt-0.5 text-xs leading-relaxed text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:gt.description})]})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 max-lg:[&_svg]:h-3 max-lg:[&_svg]:w-3 max-lg:[&_button]:h-7 max-lg:[&_button]:w-7",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-8 text-content-tertiary hover:text-slate-800 dark:hover:text-slate-100",disabled:Rt===0,onClick:()=>xe(X.key,"up"),"aria-label":`Move ${gt.label} up`,children:e.jsx(Pi,{className:"size-3.5"})}
318),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-8 text-content-tertiary hover:text-slate-800 dark:hover:text-slate-100",disabled:Rt===v.patientDashboard.sections.length-1,onClick:()=>xe(X.key,"down"),"aria-label":`Move ${gt.label} down`,children:e.jsx(Ai,{className:"size-3.5"})}),ct?e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-8 text-content-tertiary hover:text-slate-800 dark:hover:text-slate-100",onClick:()=>pt(X),"aria-label":`Edit ${gt.label}`,children:e.jsx(zt,{className:"size-3.5"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-8 text-content-tertiary hover:text-red-600 dark:hover:text-red-400",onClick:()=>Z==null?void 0:Z(X.key),"aria-label":`Remove ${gt.label}`,children:e.jsx(bt,{className:"size-3.5"})})]}):null]})]}),et&&_t?e.jsx("div",{className:"mt-4 border-t border-subtle pt-4 max-lg:mt-2.5 max-lg:pt-2.5",children:e.jsx(Tx,{clientId:r,tenantCollection:c,tenantId:r,accentColor:a,inline:!0})}):null,et&&dt?e.jsxs("div",{className:"mt-4 flex items-start gap-3 pl-11 max-lg:mt-2.5 max-lg:gap-2 max-lg:pl-8",children:[e.jsx(Me,{id:"patient-wearables-enabled",checked:(ae==null?void 0:ae.enabled)===!0,disabled:f,onCheckedChange:rt=>L==null?void 0:L("enabled",rt===!0),className:"mt-0.5 size-5 shrink-0 max-lg:size-4"}),e.jsxs("label",{htmlFor:"patient-wearables-enabled",className:"min-w-0 cursor-pointer",children:[e.jsx("span",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Enable wearable connections"}),e.jsx("p",{className:"mt-0.5 text-xs leading-relaxed text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:"Patients can connect supported health devices from the monitoring section."})]})]}):null,et&&ct&&X.html?e.jsx("div",{className:"prose prose-sm mt-4 max-w-none rounded-lg border border-subtle bg-slate-50/70 p-3 text-slate-700 max-lg:mt-2.5 max-lg:p-2 dark:bg-slate-900/40 dark:prose-invert dark:text-slate-200",dangerouslySetInnerHTML:{__html:X.html}}):null]},X.key)}),e.jsx("div",{className:"border-t border-subtle",children:e.jsxs(B,{type:"button",variant:"ghost",className:"h-11 w-full rounded-none text-slate-700 max-lg:h-9 max-lg:text-xs hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800/60",onClick:ze,"data-testid":"button-add-custom-dashboard-section",children:[e.jsx(ot,{className:"mr-2 size-4 max-lg:mr-1 max-lg:size-3.5"}),"Add custom section"]})})]}),e.jsx(Mx,{accentColor:a,initialSection:Re.initialSection,mode:Re.mode,onOpenChange:X=>{X?G(We=>({...We,open:!0})):S()},onSave:cs,open:Re.open})]})]}),e.jsx(s,{rows:w,sections:v.patientDashboard.sections,accentColor:a,cornerStyle:v.portalChrome.cornerStyle,layoutWidth:v.portalChrome.layoutWidth,wearablesEnabled:(ae==null?void 0:ae.enabled)===!0&&N,activeArea:h==="sidebar"?"sidebar":"dashboard"})]})})}function zx({ExperienceSurfaceCard:t,accentColor:s,isSavingNotifications:a,onPatientNotificationChange:i,patientNotifications:n,visibleNotificationRows:r}){return e.jsxs(t,{id:"patient-notifications",title:"Notifications",description:"Email and SMS delivery for patient-facing messages.",icon:Us,accentColor:s,saving:a,children:[e.jsxs("div",{className:"mb-3 hidden grid-cols-[minmax(0,1fr)_4.5rem_4.5rem] gap-2 border-b border-subtle pb-2 text-xs font-medium text-content-tertiary max-lg:mb-2 max-lg:pb-1.5 max-lg:text-2xs sm:grid",children:[e.jsx("span",{children:"Notification"}),e.jsx("span",{className:"text-center",children:"Email"}),e.jsx("span",{className:"text-center",children:"SMS"})]}),e.jsx("div",{className:"grid gap-3 max-lg:gap-2",children:r.map(l=>{const c=l.supportsSms===!0,u=(n==null?void 0:n[l.key])||{},m=u.email!==!1,h=u.sms===!0;return e.jsx("div",{className:"border-b border-subtle pb-3 max-lg:pb-2 last:border-0 last:pb-0",children:e.jsxs("div",{className:"grid grid-cols-1 gap-3 max-lg:gap-1.5 sm:grid-cols-[minmax(0,1fr)_4.5rem_4.5rem] sm:items-start",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 max-lg:gap-1.5",children:[e.jsx("span",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:l.label}),c?null:e.jsx(De,{variant:"outline",className:"rounded-full border-subtle bg-surface-raised text-2xs font-medium text-content-secondary max-lg:px-1.5 max-lg:py-0 max-lg:text-3xs",children:"Email only"})]}),e.jsx("p",{className:"mt-0.5 text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:Bm(l.key)})]}),e.jsx("div",{className:"flex justify-start sm:justify-center",children:e.jsxs("label",{className:"inline-flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs sm:hidden",children:"Email"}),e.jsx(Me,{checked:m,onCheckedChange:g=>i(l.key,y=>({...y,email:g===!0})),className:"size-4","aria-label":`Email for ${l.label}`})]})}),e.jsx("div",{className:"flex justify-start sm:justify-center",children:c?e.jsxs("label",{className:"inline-flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs sm:hidden",children:"SMS"}),e.jsx(Me,{checked:h,onCheckedChange:g=>i(l.key,y=>({...y,sms:g===!0})),className:"size-4","aria-label":`SMS for ${l.label}`})]}):e.jsx("span",{className:"text-xs text-slate-400 max-lg:text-2xs dark:text-slate-500",children:"N/A"})})]})},l.key)})})]})}const Mn="h-11 rounded-lg border-subtle bg-surface-raised text-content-primary shadow-sm";function Fn({id:t,checked:s,disabled:a,title:i,description:n,onCheckedChange:r}){return e.jsxs("div",{className:"flex items-start justify-between gap-4 py-3 max-lg:gap-2 max-lg:py-2 first:pt-0 last:pb-0",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(oe,{htmlFor:t,className:"text-sm font-medium text-content-primary max-lg:text-xs",children:i}),e.jsx("p",{id:`${t}-description`,className:"mt-1 text-xs leading-5 text-content-secondary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:n})]}),e.jsx(it,{id:t,checked:s,disabled:a,onCheckedChange:r,"aria-describedby":`${t}-description`})]})}function _x({ExperienceSurfaceCard:t,accentColor:s,isSaving:a,normalizedExperienceConfig:i,onPatientMessagingChange:n,tenantCollection:r}){const l=i.patientMessaging,c=r===It.CLIENT,u=a||!l.enabled,m=wn.find(h=>h.key===l.patientView)||wn[0];return e.jsx(t,{id:"patient-messaging-settings",title:"Patient messaging",description:"Choose whether patients can message and which care destinations they can select.",icon:pa,accentColor:s,saving:a,children:e.jsxs("div",{className:"divide-y divide-slate-200 dark:divide-slate-700",children:[e.jsx(Fn,{id:"patientMessagingEnabled",checked:l.enabled,disabled:a,onCheckedChange:h=>n("enabled",h===!0),title:"Allow patients to send messages",description:"Turning this off keeps conversation history available in read-only mode."}),e.jsx(Fn,{id:"patientMessagingAiDraftsEnabled",checked:l.aiDraftsEnabled,disabled:a,onCheckedChange:h=>n("aiDraftsEnabled",h===!0),title:"AI-assisted staff drafts",description:c?"Allow authorized staff to generate editable drafts from recent message text. Drafts are never sent automatically and linked provider networks must also approve.":"Allow authorized staff to generate editable drafts from recent message text. Drafts are never sent automatically."}),c?e.jsx(Fn,{id:"patientMessagingAllowWithoutOrders",checked:l.allowWithoutOrders,disabled:u,onCheckedChange:h=>n("allowWithoutOrders",h===!0),title:"Allow messaging without an order",description:"Patients can open Messages before they have placed an order."}):null,e.jsxs("div",{className:"py-3 max-lg:py-2 first:pt-0 last:pb-0",children:[e.jsx(oe,{htmlFor:"patientMessagingPatientView",className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Patient inbox layout"}),e.jsx("p",{id:"patientMessagingPatientView-description",className:"mt-1 text-xs leading-5 text-content-secondary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:"How patients see who on your team has messaged them."}),e.jsxs(yt,{value:l.patientView,onValueChange:h=>n("patientView",h),disabled:a||!l.enabled,children:[e.jsx(vt,{id:"patientMessagingPatientView",className:K(Mn,"mt-2 w-full text-sm"),"aria-describedby":"patientMessagingPatientView-description patientMessagingPatientView-option",children:e.jsx(Nt,{})}),e.jsx(jt,{className:"max-h-[min(320px,50vh)]",children:wn.map(h=>e.jsx(st,{value:h.key,children:h.label},h.key))})]}),e.jsx("p",{id:"patientMessagingPatientView-option",className:"mt-2 text-xs leading-5 text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:m.description}),l.patientView===cd.BY_MEMBER?e.jsx("p",{className:"mt-2 text-xs leading-5 text-content-secondary max-lg:text-2xs",role:"status",children:"Replies still go to your care team unless individual provider messaging is enabled for this client."}):null]}),e.jsxs("div",{className:"py-3 max-lg:py-2 first:pt-0 last:pb-0",children:[e.jsx(oe,{htmlFor:"patientMessagingDeliveryMode",className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Patient text notifications"}),e.jsx("p",{id:"patientMessagingDeliveryMode-description",className:"mt-1 text-xs leading-5 text-content-secondary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:"Full text is the default. Prescription messages, attachments, and messages sent from visit charting always require the patient to sign in."}),e.jsxs(yt,{value:l.deliveryMode,onValueChange:h=>n("deliveryMode",h),disabled:a,children:[e.jsx(vt,{id:"patientMessagingDeliveryMode",className:K(Mn,"mt-2 w-full text-sm"),"aria-describedby":"patientMessagingDeliveryMode-description patientMessagingDeliveryMode-option",children:e.jsx(Nt,{})}),e.jsx(jt,{className:"max-h-[min(320px,50vh)]",children:Ps.map(h=>e.jsx(st,{value:h.key,children:h.label},h.key))})]}),e.jsx("p",{id:"patientMessagingDeliveryMode-option",className:"mt-2 text-xs leading-5 text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:(Ps.find(h=>h.key===l.deliveryMode)||Ps[0]).description})]}),e.jsxs("div",{className:"py-3 max-lg:py-2 first:pt-0 last:pb-0",children:[e.jsx(oe,{htmlFor:"patientMessagingSmsDisplayName",className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"SMS display name"}),e.jsx("p",{id:"patientMessagingSmsDisplayName-description",className:"mt-1 text-xs leading-5 text-content-secondary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:"Shown on lock screens. Use a name that does not state a specialty, medication, or clinical service. 32 characters max."}),e.jsx(be,{id:"patientMessagingSmsDisplayName",value:l.smsDisplayName||"",onChange:h=>n("smsDisplayName",h.target.value),maxLength:32,placeholder:"e.g. Northside Care",disabled:a,className:K(Mn,"mt-2"),"aria-describedby":"patientMessagingSmsDisplayName-description"})]})]})})}const Ux=[{id:"dashboard",label:"Dashboard",icon:"Heart",required:!0},{id:"visits",label:"Visits",icon:"Calendar"},{id:"forms",label:"Forms",icon:"ClipboardList",required:!0},{id:"messages",label:"Messages",icon:"MessageSquare"},{id:"knowledge-base",label:"Knowledge base",icon:"BookOpen"},{id:"prescriptions",label:"Prescriptions",icon:"Pill"},{id:"services",label:"Services",icon:"Scissors",businessOnly:!0},{id:"products",label:"Products",icon:"ShoppingBag"},{id:"labs",label:"Labs",icon:"TestTube"},{id:"orders",label:"Orders",icon:"Receipt"},{id:"wallet",label:"Wallet",icon:"Wallet",required:!0},{id:"support",label:"Support",icon:"LifeBuoy",clientOnly:!0}];function fa(t=It.CLIENT){return Ux.filter(s=>(!s.businessOnly||t===It.BUSINESS)&&(!s.clientOnly||t===It.CLIENT))}function Br(t=It.CLIENT){return fa(t).map(s=>s.id).filter(s=>!dd.has(s))}const Dx={allowShort:!0,expandShort:!0},sc=new Set(["accentColor","secondaryColor","backgroundColor","rightPanelColor","logoBackgroun
318dColor","formBackgroundColor","cardBackgroundColor"]);function $x({ExperienceSurfaceCard:t,SegmentedChoiceGroup:s,accentColor:a,isSavingExperienceConfig:i,normalizedExperienceConfig:n,portalBorderStyleOptions:r,portalLayoutWidthOptions:l,portalNavModeOptions:c,onPortalChromeChange:u}){return e.jsx(t,{id:"patient-portal-layout",title:"Portal layout",description:"Navigation style, border style, and layout width for the authenticated client portal shell.",icon:Do,accentColor:a,saving:i,children:e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsx(s,{label:"Navigation style",value:n.portalChrome.navMode,options:c,onChange:m=>u("navMode",m),accentColor:a}),e.jsx(s,{label:"Border style",value:n.portalChrome.cornerStyle,options:r,onChange:m=>u("cornerStyle",m),accentColor:a}),e.jsx(s,{label:"Layout width",value:n.portalChrome.layoutWidth,options:l,onChange:m=>u("layoutWidth",m),accentColor:a})]})})}function Bx({ExperienceSurfaceCard:t,SegmentedChoiceGroup:s,LargeCheckboxOption:a,accentColor:i,checkoutRows:n,checkoutSequenceOptions:r,isSavingExperienceConfig:l,normalizedExperienceConfig:c,publicCheckoutDisclaimerOptions:u,onPatientCheckoutSequenceChange:m,onPublicCheckoutDisclaimerModeChange:h,onPerProductSummaryCustomizationChange:g}){return e.jsx(t,{id:"patient-checkout-sequence",title:"Checkout",description:"Whether authenticated patients complete intake before payment, and how the public checkout disclaimer is presented.",icon:xd,accentColor:i,saving:l,children:e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsx(a,{id:"per-product-checkout-summary",checked:c.patientCheckout.perProductSummaryCustomization.enabled===!0,onCheckedChange:y=>g(y===!0),title:"Per-product order summary",description:"When enabled, each catalog product gets an Order summary tab to customize the checkout summary panel (copy, bullets, shipping labels) with a live preview before save."}),n.map(y=>e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:y.label}),e.jsx("p",{className:"mt-0.5 text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:y.description})]}),e.jsx(s,{value:c.patientCheckout.sequence[y.key],options:r,onChange:p=>m(y.key,p),accentColor:i})]},y.key)),e.jsxs("div",{className:"space-y-2 border-t border-subtle pt-3 max-lg:space-y-1.5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Public checkout disclaimer"}),e.jsx("p",{className:"mt-0.5 text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:"How âchanges cannot be made once an order is submittedâ appears on public product checkout. Checkbox requires the patient to acknowledge it before payment can be completed."})]}),e.jsx(s,{value:c.publicCheckoutDisclaimer.mode,options:u,onChange:h,accentColor:i})]})]})})}const pr={updates:{label:"Orders",description:"Care updates, recommendations, add-on requests, and visit timing."},lifestyle:{label:"Daily health",description:"Health tracking cards, charts, and quick log."},monitoring:{label:"Wearables & apps",description:"The wearable and device gallery."}},ac=[{key:Ke.FOCUSED,label:"Focused"},{key:Ke.SIDECAR,label:"Sidecar"},{key:Ke.EDITORIAL,label:"Editorial"}],Vx=[{key:Ke.SIDECAR,label:"Sidecar"},{key:Ke.FOCUSED,label:"Focused"}],qx=[{key:"headline",label:"Headline",placeholder:"Optional headline"},{key:"subhead",label:"Subhead",placeholder:"Short supporting line",multiline:!0},{key:"trustNote",label:"Trust note",placeholder:"Short reassurance note",multiline:!0}],Qi=[{key:Ge.STANDARD,label:"Standard"},{key:Ge.CONTAINED,label:"Contained"},{key:Ge.MINIMAL,label:"Minimal"}],gr=[{key:Ge.SMALL,label:"Small"},{key:Ge.MEDIUM,label:"Medium"},{key:Ge.LARGE,label:"Large"},{key:Ge.HIDDEN,label:"Hidden"}],Ji=[{key:Ge.STANDARD,label:"Shown"},{key:Ge.HIDDEN,label:"Hidden"}],Hx=[{key:Ge.STANDARD,label:"Standard"},{key:Ge.CONTAINED,label:"Contained"},{key:Ge.HIDDEN,label:"Hidden"}],Wx=[{key:ta.SOFT,label:"Soft"},{key:ta.SOLID,label:"Solid"},{key:ta.NONE,label:"None"}],es=gr.map(t=>t.key),Gx=[{key:As.CLASSIC,label:"Classic",hint:"Bordered card on neutral canvas"},{key:As.BANNER,label:"Banner",hint:"Hero banner on tinted canvas"},{key:As.LETTERHEAD,label:"Letterhead",hint:"Left-aligned header with accent stripe"}],Kx=[{key:ud.CARD,label:"Form",hint:"Public form and assessment intake layout"}],St={checkoutTheme:{title:"Checkout theme",surface:"checkout",saveLabel:"Save checkout theme",options:ac},loginTheme:{title:"Login theme",surface:"login",saveLabel:"Save login theme",options:Vx},emailTheme:{title:"Email theme",surface:"email",saveLabel:"Save email theme",options:Gx},formTheme:{title:"Form theme",surface:"form",saveLabel:"Save form theme",options:Kx}},Yx=[{key:gi.INTAKE_BEFORE_PAYMENT,label:"Intake first"},{key:gi.PAYMENT_BEFORE_INTAKE,label:"Payment first"}],Qx=[{key:Cn.HIDDEN,label:"Hidden"},{key:Cn.TEXT,label:"Text"},{key:Cn.CHECKBOX,label:"Checkbox"}
318],Jx=[{key:"rounded",label:"Rounded"},{key:"medium",label:"Medium"},{key:"sharp",label:"Sharp"}],Xx=[{key:"contained",label:"Contained"},{key:"wide",label:"Wide"}],Zx=[{key:"side",label:"Side menu"},{key:"icon",label:"Icon bar"},{key:"top",label:"Top menu"}],ep=[{key:"products",label:"Products",description:"Checkout sequence for authenticated patient product purchases."},{key:"labs",label:"Labs",description:"Checkout sequence for authenticated patient lab purchases."}];function tp(t){try{const s=new URL(t);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}}function sp(t,s="size-4"){return pd(t,s)}function ap(t){if(!Array.isArray(t))return[];const s=new Set;return t.map(a=>{const i=String((a==null?void 0:a.id)||"").trim();if(!i||s.has(i))return null;s.add(i);const n=ss(a==null?void 0:a.icon),r=(a==null?void 0:a.openMode)===ea.NEW_TAB?ea.NEW_TAB:ea.EMBED,l=(a==null?void 0:a.target)===lt.FORM?lt.FORM:lt.URL,c=l===lt.FORM;return{id:i,label:String((a==null?void 0:a.label)||"").slice(0,40),target:l,url:c?"":String((a==null?void 0:a.url)||""),icon:n,openM
318ode:r,sectionId:String((a==null?void 0:a.sectionId)||"").trim()||null,enabled:(a==null?void 0:a.enabled)!==!1,...c?{formId:String((a==null?void 0:a.formId)||"").trim(),notifyEmails:Pr(a==null?void 0:a.notifyEmails)}:{}}}).filter(Boolean)}function np(t){if(!Array.isArray(t))return[];const s=new Set;return t.map(a=>{const i=String((a==null?void 0:a.id)||"").trim();return!i||s.has(i)?null:(s.add(i),{id:i,label:String((a==null?void 0:a.label)||"").slice(0,40),icon:ss(a==null?void 0:a.icon),enabled:(a==null?void 0:a.enabled)!==!1})}).filter(Boolean)}function rp(t,{tenantCollection:s=It.CLIENT}={}){const a=fa(s),i=Br(s),n=a.map(d=>d.id),r=new Set(a.filter(d=>d.required).map(d=>d.id)),l=np(t==null?void 0:t.sections),c=new Set(l.map(d=>d.id)),u=ap(t==null?void 0:t.customItems).map(d=>({...d,sectionId:c.has(d.sectionId)?d.sectionId:null})),m=new Map(u.map(d=>[as(d.id),d])),h=new Map(l.map(d=>[ns(d.id),d])),g=new Set(n),y=Array.isArray(t==null?void 0:t.enabledItems)?[...t.enabledItems]:[...i];(t==null?void 0:t.supportEnabled)===!0&&n.includes("support")&&!y.includes("support")&&y.push("support");const p=[];return y.forEach(d=>{const x=m.get(d),f=h.get(d);(g.has(d)||(x==null?void 0:x.enabled)===!0&&!x.sectionId||(f==null?void 0:f.enabled)===!0)&&!p.includes(d)&&p.push(d)}),n.forEach(d=>{r.has(d)&&!p.includes(d)&&p.push(d)}),u.forEach(d=>{const x=as(d.id);d.enabled&&!d.sectionId&&!p.includes(x)&&p.push(x)}),l.forEach(d=>{const x=ns(d.id);d.enabled&&!p.includes(x)&&p.push(x)}),{enabledItems:p,customItems:u,sections:l,itemOverrides:Ql(t==null?void 0:t.itemOverrides,n)}}function ip(t,s=It.CLIENT){const a=fa(s),i=rp(t,{tenantCollection:s}),n=i.itemOverrides,r=new Map(i.customItems.map(d=>[as(d.id),d])),l=new Map(i.sections.map(d=>[ns(d.id),d])),c=new Map;i.customItems.forEach(d=>{if(!d.sectionId)return;const x=c.get(d.sectionId)||[];x.push(d),c.set(d.sectionId,x)});const u=(d,x=d.enabled)=>({key:as(d.id),id:d.id,label:d.label||"Custom link",icon:d.icon,enabled:x,type:"custom",customItem:d,sectionId:d.sectionId||null}),m=new Set,h=i.enabledItems.map(d=>{var N,v;const x=a.find(k=>k.id===d);if(x)return m.add(d),{key:d,id:x.id,label:((N=n[d])==null?void 0:N.label)||x.label,defaultLabel:x.label,override:n[d]||null,icon:((v=n[d])==null?void 0:v.icon)||x.icon,defaultIcon:x.icon,enabled:!0,required:x.required===!0,type:"default"};const f=l.get(d);if(f)return m.add(d),{key:d,id:f.id,label:f.label||"Section",icon:f.icon,enabled:f.enabled,type:"section",section:f,children:(c.get(f.id)||[]).map(k=>u(k))};const C=r.get(d);return!C||C.sectionId?null:(m.add(d),u(C))}).filter(Boolean),g=a.filter(d=>!m.has(d.id)).map(d=>{var x,f;return{key:d.id,id:d.id,label:((x=n[d.id])==null?void 0:x.label)||d.label,defaultLabel:d.label,override:n[d.id]||null,icon:((f=n[d.id])==null?void 0:f.icon)||d.icon,defaultIcon:d.icon,enabled:!1,required:d.required===!0,type:"default"}}),y=i.sections.filter(d=>!m.has(ns(d.id))).map(d=>({key:ns(d.id),id:d.id,label:d.label||"Section",icon:d.icon,enabled:!1,type:"section",section:d,children:(c.get(d.id)||[]).map(x=>u(x))})),p=i.customItems.filter(d=>!d.sectionId&&!m.has(as(d.id))).map(d=>u(d,!1));return[...h,...g,...y,...p]}function lp(){return{id:`custom-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`,label:"New link",target:lt.URL,url:"",icon:"ExternalLink",openMode:ea.EMBED,enabled:!0}}function op(){return{id:`section-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`,label:"New section",icon:"FolderOpen",enabled:!0}}function Fs(t,s="card"){return fd(t,s)}function cp({saving:t,accentColor:s}){return t?e.jsx(Ve,{className:"size-4 shrink-0 animate-spin",style:{color:s},"aria-label":"Saving"}):null}function Ss({active:t,onClick:s,children:a,accentColor:i,className:n}){return e.jsx("button",{type:"button",onClick:s,className:K("rounded-full border px-3 py-1.5 text-xs font-medium transition-colors","max-lg:px-2 max-lg:py-1 max-lg:text-3xs",t?"text-white shadow-sm":"border-subtle bg-surface-raised text-content-secondary hover:border-slate-300",n),style:t?{backgroundColor:i,borderColor:i}:void 0,children:a})}function zn({label:t,value:s,options:a,onChange:i,accentColor:n}){const r=Math.max(0,a.findIndex(c=>c.key===s)),l=Math.max(a.length,1);return e.jsxs("div",{className:"space-y-2",children:[t?e.jsx("p",{className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:t}):null,e.jsxs("div",{className:"relative rounded-full border border-subtle bg-slate-100 p-1 dark:bg-slate-800",children:[e.jsx("span",{"aria-hidden":"true",className:"absolute bottom-1 top-1 rounded-full shadow-sm transition-transform duration-300 ease-out",style:{backgroundColor:n,left:"0.25rem",width:`calc((100% - 0.5rem) / ${l})`,transform:`translateX(${r*100}%)`}}),e.jsx("div",{className:"relative grid",style:{gridTemplateColumns:`repeat(${l}, minmax(0, 1fr))`},children:a.map(c=>{const u=c.key===s;return e.jsx("button",{type:"button","aria-pressed":u,onClick:()=>{u||i(c.key)},className:K("relative z-raised flex min-h-8 min-w-0 items-center justify-center rounded-full px-3 text-xs font-medium transition-colors duration-200","max-lg:min-h-7 max-lg:px-2 max-lg:text-3xs",u?"text-white":"text-content-secondary hover:text-slate-900 dark:hover:text-slate-100"),children:e.jsx("span",{className:"truncate",children:c.label})},c.key)})})]})]})}function Es({title:t,description:s,children:a}){return e.jsxs("div",{className:"rounded-xl border border-subtle bg-surface-sunken p-4 max-lg:p-2.5",children:[e.jsxs("div",{className:"mb-3 space-y-1 max-lg:mb-2 max-lg:space-y-0.5",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-content-tertiary max-lg:text-3xs",children:t}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:s})]}),a]})}function Ht({id:t,title:s,description:a,icon:i,accentColor:n,saving:r=!1,filters:l=[],hasActiveFilters:c=!1,onClearFilters:u=null,children:m,className:h="",bodyClassName:g="p-4 sm:p-5"}){return e.jsx(tt,{id:t,title:s,description:a,icon:i,accentColor:n,actions:e.jsx(cp,{saving:r,accentColor:n}),filters:l,hasActiveFilters:c,onClearFilters:u,className:h,bodyClassName:g,children:m})}function Xi({id:t,checked:s,disabled:a=!1,onCheckedChange:i,title:n,description:r,descriptionClassName:l="",actions:c=null}){return e.jsx("div",{className:"overflow-hidden rounded-xl border border-subtle bg-slate-50/60 transition-colors dark:bg-slate-900/20",children:e.jsxs("div",{className:"flex min-h-[5rem] items-center gap-3 p-3 max-lg:min-h-0 max-lg:gap-2 max-lg:p-2",children:[e.jsx(Me,{id:t,checked:s,disabled:a,onCheckedChange:i,className:"size-5 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("label",{htmlFor:t,className:"cursor-pointer text-sm font-medium text-content-primary max-lg:text-xs",children:n}),r?e.jsx("div",{className:K("mt-1 text-xs text-content-tertiary transition max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",l),children:r}):null]}),c?e.jsx("div",{className:"flex shrink-0 items-center gap-1",children:c}):null]})})}function dp({rows:t,sections:s,accentColor:a,cornerStyle:i,layoutWidth:n,wearablesEnabled:r=!1,activeArea:l="sidebar"}){const c=Fs(i,"card"),u=Fs(i,"pill"),m=s.filter(d=>d.enabled!==!1),h=s.filter(d=>
318d.enabled===!1),g=l==="sidebar",y=l==="dashboard",p={boxShadow:`0 0 0 2px ${a}`};return e.jsx(Es,{title:"Preview",description:"Sidebar menu and dashboard sections update the same patient portal preview.",children:e.jsx("div",{className:"border border-subtle bg-surface-raised p-3",style:{borderRadius:c},children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[8.5rem_minmax(0,1fr)]",children:[e.jsxs("div",{className:"border border-subtle bg-surface-raised p-3 transition-shadow",style:{borderRadius:c,...g?p:{}},children:[e.jsx("div",{className:"mb-3 h-8 w-24 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsx("div",{className:"space-y-1.5",children:t.map(d=>{var N;const x=d.enabled!==!1,f=d.id==="dashboard"&&x,C=d.type==="section";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:K("flex items-center justify-between px-3 py-2 text-xs font-medium transition-colors",x?"border border-subtle text-slate-700 dark:text-slate-200":"border border-dashed border-subtle text-slate-400 dark:text-slate-500"),style:{borderRadius:u,backgroundColor:f?a:x?Mt(a,.06):"transparent",borderColor:f?a:void 0,color:f?"#ffffff"
318:void 0},children:[e.jsx("span",{className:"min-w-0 truncate",children:d.label}),x?null:e.jsx("span",{className:"text-3xs uppercase tracking-wide",children:"Hidden"})]}),C&&((N=d.children)!=null&&N.length)?e.jsx("div",{className:"ml-3 space-y-1 border-l border-subtle pl-2",children:d.children.map(v=>e.jsx("div",{className:"truncate border border-subtle px-3 py-1.5 text-2xs font-medium text-content-tertiary",style:{borderRadius:u},children:v.label},v.key))}):null]},d.key)})})]}),e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:K("space-y-3 border border-transparent p-3 transition-shadow",n==="contained"&&"mx-auto w-full max-w-md"),style:{borderRadius:c,...y?p:{}},children:[e.jsxs("div",{className:"mb-1",children:[e.jsx("p",{className:"text-3xs font-semibold uppercase tracking-[0.22em] text-content-tertiary",children:"Today"}),e.jsx("div",{className:"mt-1 h-5 w-40 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsx("div",{className:"mt-1.5 h-2.5 w-2/3 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}})]}),e.jsx("div",{className:"space-y-2.5",children:m.map(d=>{const x=ia(d),f=x?{label:d.title||"Custom section",description:d.description||"Custom HTML section."}:pr[d.key]||{label:d.key,description:"Additional patient dashboard section."};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-3xs font-semibold uppercase tracking-[0.18em] text-content-tertiary",children:f.label}),x&&f.description?e.jsx("p",{className:"mt-0.5 text-2xs leading-snug text-content-tertiary",children:f.description}):e.jsx("div",{className:"mt-1 h-4 w-24 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}})]}),x?e.jsx("div",{className:"border border-subtle bg-surface-raised p-2.5 text-2xs leading-relaxed text-content-secondary",style:{borderRadius:c},dangerouslySetInnerHTML:{__html:gd(d.html)||'<span class="text-slate-400">Custom HTML</span>'}}):null,d.key==="updates"?e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:Array.from({length:2}).map((C,N)=>e.jsxs("div",{className:"border border-subtle bg-surface-raised p-2.5",style:{borderRadius:c},children:[e.jsx("div",{className:"h-2.5 w-14 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsx("div",{className:"mt-2 h-4 w-24 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[e.jsx("div",{className:"h-2.5 w-full bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsx("div",{className:"h-2.5 w-4/5 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}})]}),e.jsx("div",{className:"mt-2.5 h-6 w-20",style:{borderRadius:u,backgroundColor:Mt(a,.16)}})]},N))}):null,d.key==="lifestyle"?e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 xl:grid-cols-4",children:Array.from({length:3}).map((C,N)=>e.jsxs("div",{className:K("border border-subtle bg-surface-raised p-2.5",N===0?"sm:col-span-2 xl:col-span-2":""),style:{borderRadius:c},children:[e.jsx("div",{className:"h-14",style:{borderRadius:c,backgroundColor:Mt(a,N===0?.14:.08)}}),e.jsx("div",{className:"mt-2 h-4 w-16 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsx("div",{className:"mt-1.5 h-2.5 w-3/4 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}})]},N))}):null,d.key==="monitoring"?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"max-w-xl text-2xs leading-snug text-content-tertiary",children:f.description}),r?e.jsx(De,{variant:"outline",className:"rounded-full text-3xs font-normal",children:"Wearable connections enabled"}):null,e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:Array.from({length:3}).map((C,N)=>e.jsxs("div",{className:"border border-subtle bg-surface-raised p-2.5",style:{borderRadius:c},children:[e.jsx("div",{className:"h-12 bg-slate-100 dark:bg-slate-800",style:{borderRadius:c}}),e.jsx("div",{className:"mt-2 h-3 w-16 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}})]},N))})]}):null]},d.key)})}),h.length?e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:h.map(d=>{const x=ia(d)?{label:d.title||"Custom section"}:pr[d.key]||{label:d.key};return e.jsxs(De,{variant:"outline",className:"rounded-full text-2xs",children:[x.label," hidden"]},d.key)})}):null]})})]})})})}function mp({value:t,onChange:s,accentColor:a}){return e.jsx("div",{className:"flex items-center justify-end gap-2 max-lg:gap-1",children:[{key:"desktop",label:"Desktop",icon:Do},{key:"mobile",label:"Mobile",icon:Nd}].map(i=>{const n=i.icon;return e.jsxs("button",{type:"button",onClick:()=>s(i.key),className:K("inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors","max-lg:gap-1 max-lg:px-2 max-lg:py-1 max-lg:text-3xs",t===i.key?"text-white shadow-sm":"border-subtle bg-surface-raised text-content-secondary hover:border-slate-300"),style:t===i.key?{backgroundColor:a,borderColor:a}:void 0,"aria-pressed":t===i.key,children:[e.jsx(n,{className:"size-3.5 max-lg:size-3"}),i.label]},i.key)})})}function nc(t){const s=typeof(t==null?void 0:t.headerFont)=="str
318ing"?t.headerFont.trim():"";if(s)return{"--font-display":`"${s}", ui-serif, Georgia, Cambria, "Times New Roman", Times, serif`}}function hr({device:t,children:s,className:a,style:i}){return e.jsx("div",{className:K("mx-auto overflow-hidden border border-subtle bg-surface-raised shadow-sm",t==="mobile"?"w-full max-w-[390px] rounded-[2rem]":"w-full rounded-xl",a),style:i,children:s})}function up({theme:t,surfaceBranding:s,surfaceAccent:a,previewDevice:i,formPreviewStage:n}){const r=i==="mobile",l=t.formBackgroundColor||(s==null?void 0:s.backgroundColor)||"#f8fafc",c=t.cardBackgroundColor||"#ffffff",u=Number.isFinite(Number(t.cardBorderRadius))?Number(t.cardBorderRadius):24,m=Number.isFinite(Number(t.logoPadding))?Number(t.logoPadding):0,h=Number.isFinite(Number(t.logoBorderRadius))?Number(t.logoBorderRadius):12,g=t.introEnabled!==!1,y=n==="intro"&&g?"intro":"intake",p=t.footerText||"",d=(s==null?void 0:s.logoUrl)||"",x=!!d,f=[{id:"preview-product-1",name:"5-Amino-1MQ",description:"Peptide injection for metabolic support and care-team review.",valueLabel:"$0.00"},{id:"preview-product-2",name:"Quarter Zip",description:"Included package item shown as a separate treatment card.",valueLabel:"Included"}];return e.jsx(Es,{title:"Exact preview",description:"Replica of the assessment-first public shell with sample content.",children:e.jsx(hr,{device:i,className:"max-h-[44rem] overflow-auto bg-transparent shadow-none",style:nc(s),children:e.jsx("div",{className:K("checkout-light w-full p-4",r?"min-h-[40rem]":"min-h-[42rem]"),style:{backgroundColor:l},children:e.jsx("div",{className:K("mx-auto w-full",r?"max-w-[340px] py-2":"max-w-3xl py-3"),children:e.jsx(Sd,{logoUrl:d,logoAlt:(s==null?void 0:s.name)||"Client",showLogo:x,logoDescriptorText:t.logoDescriptorText,logoBackgroundColor:(s==null?void 0:s.logoBackgroundColor)||"transparent",logoBorderRadius:h,logoPadding:m,panelRadius:`${u}px`,panelBackgroundColor:c,cardTreatment:t.cardTreatment,footerNote:p,embedMode:!0,className:K(r?"min-h-[35rem]":"min-h-[38rem]"),formSecondaryAction:y==="intake"?e.jsx(B,{type:"button",variant:"outline",className:K("h-11 rounded-full",r?"w-full":"min-w-28"),children:"Back"}):null,formPrimaryAction:y==="intake"?e.jsx(B,{type:"button",className:K("h-11 rounded-full text-white",r?"w-full":"min-w-40"),style:{backgroundColor:a},children:"Continue"}):null,children:y==="intro"?e.jsx("div",{className:K("flex flex-1 flex-col justify-center px-5 py-8",r?"min-h-[360px]":"min-h-[420px] px-8"),children:e.jsxs("div",{className:"mx-auto w-full max-w-2xl space-y-6",children:[e.jsxs("div",{className:"space-y-3 text-center",children:[e.jsx("h1",{className:K("font-display font-semibold text-slate-950",r?"text-2xl":"text-4xl"),children:t.introTitle||"Start your assessment"}),e.jsx("p",{className:"mx-auto max-w-xl text-base leading-7 text-content-secondary",children:t.introText||"This is the start of your assessment for the selected treatments. Answer a few health questions so your provider can review your request and recommend the right next step."})]}),e.jsx("div",{className:K("grid gap-3",f.length===1?"mx-auto w-full max-w-md":!r&&"sm:grid-cols-2"),children:f.map(C=>e.jsxs("article",{className:"rounded-2xl border border-subtle bg-surface-raised p-4 text-left shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("h2",{className:"min-w-0 text-base font-semibold leading-snug text-content-primary",children:C.name}),e.jsx("span",{className:"shrink-0 text-sm font-semibold text-content-primary",children:C.valueLabel})]}),e.jsx("p",{className:"mt-2 line-clamp-3 text-sm leading-6 text-content-secondary",children:C.description})]},C.id))}),e.jsx(B,{type:"button",className:"h-11 w-full rounded-full text-white",style:{backgroundColor:a},children:t.introButtonLabel||"Start"})]})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:K("shrink-0 px-4 py-4",!r&&"sm:px-6"),style:{backgroundColor:t.cardTreatment!==bs.NONE?c:"transparent"},children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:K("font-display text-lg font-semibold leading-tight text-content-primary",!r&&"sm:text-xl"),children:"Health history"}),t.sectionDescriptorText?e.jsx("p",{className:"text-sm leading-6 text-content-tertiary",children:t.sectionDescriptorText}):null]}),e.jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-slate-200",children:e.jsx("div",{className:"h-full w-[38%] rounded-full transition-[width,background-color] duration-300",style:{backgroundColor:a}})})]})}),e.jsx("div",{className:K("min-h-0 flex-1 overflow-y-auto overflow-x-hidden px-4 py-4",!r&&"sm:px-6 sm:py-5"),style:{backgroundColor:t.cardTreatment!==bs.NONE?c:"transparent"},children:e.jsxs("div",{className:K("mx-auto grid w-full max-w-3xl grid-cols-1 gap-5",!r&&"md:grid-cols-2 md:gap-x-4 md:gap-y-6"),children:[e.jsxs("div",{className:K("min-w-0 max-w-full space-y-2",!r&&"md:col-span-2"),children:[e.jsx("p",{className:K("break-words text-base font-medium leading-relaxed text-slate-700",!r&&"sm:text-[17px]"),children:"What is your primary goal?"}
318),e.jsx("div",{className:"min-w-0 w-full max-w-full space-y-2.5",children:["Improve daily energy","Understand treatment options"].map((C,N)=>e.jsxs("div",{className:K("flex min-h-12 w-full min-w-0 max-w-full items-start gap-3 rounded-lg border p-3 text-sm font-normal leading-relaxed text-slate-700 transition-colors",!r&&"sm:p-3.5",N===0?"border-blue-500 bg-blue-50":"border-default bg-surface-raised"),children:[e.jsx("span",{className:K("mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full border-2 bg-surface-raised",N===0?"border-blue-500":"border-default"),children:N===0?e.jsx("span",{className:"size-2.5 rounded-full",style:{backgroundColor:a}}):null}),e.jsx("span",{className:"min-w-0 flex-1 break-words",children:C})]},C))})]}),e.jsxs("div",{className:"min-w-0 max-w-full space-y-2",children:[e.jsx("p",{className:K("break-words text-base font-medium leading-relaxed text-slate-700",!r&&"sm:text-[17px]"),children:"Date of birth"}),e.jsx("div",{className:"h-12 rounded-md border border-default bg-surface-raised px-3 py-3 text-sm text-slate-400",children:"MM/DD/YYYY"})]}),e.jsxs("div",{className:"min-w-0 max-w-full space-y-2",children:[e.jsx("p",{className:K("break-words text-base font-medium leading-relaxed text-slate-700",!r&&"sm:text-[17px]"),children:"State"}),e.jsx("div",{className:"h-12 rounded-md border border-default bg-surface-raised px-3 py-3 text-sm text-slate-400",children:"Select state"})]})]})})]})})})})})})}function xp({theme:t,accentColor:s,cornerStyle:a,surface:i,branding:n,previewDevice:r="desktop",formPreviewStage:l="intake"}){const c=Fs(a,"card"),u=Fs(a,"pill"),m=Tr(n,t),h=(m==null?void 0:m.accentColor)||s,g=nc(m),y=r==="mobile";if(i==="checkout")return e.jsx(Es,{title:"Exact preview",description:"Public checkout components with sample contact and order details.",children:e.jsx(ux,{theme:t,branding:m,cornerStyle:a,device:r})});if(i==="login")return e.jsx(Es,{title:"Exact preview",description:"Replica of the client-branded login shell with sample form content.",children:e.jsx(hr,{device:r,className:"max-h-[34rem] overflow-auto p-4",style:g,children:e.jsx(px,{theme:t,branding:n,accentColor:h})})});if(i==="email"){const v=kx({branding:{...n||{},experienceConfig:{emailTheme:t}}});return e.jsx(Es,{title:"Exact preview",description:"Replica of the shared patient email layout using the production email pipeline.",children:e.jsx(hr,{device:r,className:"overflow-hidden bg-transparent shadow-none p-0",style:g,children:e.jsx("iframe",{title:"Email theme preview",srcDoc:v,className:"w-full border-0",style:{minHeight:y?"40rem":"44rem"}})})})}if(i==="form")return e.jsx(up,{theme:t,surfaceBranding:m,surfaceAccent:h,previewDevice:r,formPreviewStage:l});const p=t.layoutPreset===Ke.SIDECAR,d=t.layoutPreset===Ke.EDITORIAL,x=t.layoutPreset===Ke.FOCUSED,f=t.headline||(i==="login"?"Access your portal":"Review payment details"),C=t.subhead||(i==="login"?"Sign in to continue.":"Complete checkout securely."),N=t.trustNote||(i==="login"?"Protected account access.":"Secure processing.");return e.jsx(Es,{title:"Preview",description:i==="login"?"Login layout, brand placement, and compact trust note.":"Shared checkout layout for public and in-app checkout.",children:e.jsxs("div",{className:K("overflow-hidden border border-subtle bg-surface-raised p-3",d&&"space-y-3",x&&"mx-auto max-w-sm",p&&"grid gap-3 sm:grid-cols-[0.8fr_1fr]"),style:{borderRadius:c},children:[e.jsxs("div",{className:K("space-y-3 p-3",x&&"text-center",p&&"flex min-h-48 flex-col justify-between",d&&"rounded-lg"),style:{borderRadius:c,backgroundColor:d?Mt(s,.12):p?Mt(s,.08):"transparent"},children:[e.jsx("div",{className:K("bg-slate-200 dark:bg-slate-800",t.logoTreatment===Ge.MINIMAL?"size-7":"h-8 w-28",x&&"mx-auto",t.logoTreatment===Ge.CONTAINED&&"border border-white bg-surface-raised shadow-sm"),style:{borderRadius:t.logoTreatment===Ge.MINIMAL?u:c}}),e.jsxs("div",{children:[e.jsx("p",{className:K("font-display font-semibold text-content-primary",d?"text-xl":"text-base"),children:f}),e.jsx("p",{className:"mt-1 text-xs leading-snug text-content-tertiary",children:C})]}),e.jsx("div",{className:"inline-flex max-w-full items-center justify-center border border-subtle bg-surface-raised px-3 py-1.5 text-3xs font-medium text-content-secondary",style:{borderRadius:u},children:e.jsx("span",{className:"truncate",children:N})})]}),e.jsxs("div",{className:K("grid gap-3",i==="checkout"&&!x?"grid-cols-[minmax(0,1fr)_7.5rem]":"grid-cols-1"),children:[e.jsxs("div",{className:"overflow-hidden border border-subtle bg-surface-raised",style:{borderRadius:c},children:[e.jsxs("div",{className:"border-b border-subtle px-4 pb-3 pt-3",children:[e.jsx("div",{className:"h-2 w-12 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsx("div",{className:"mt-2 h-4 w-40 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}})]}),e.jsxs("div",{className:"space-y-3 p-4",children:[e.jsx("div",{className:"h-2.5 w-20 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsx("div",{className:"h-8 border border-subtle bg-surface-sunken",style:{borderRadius:u}}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Array.from({length:3}).map((v,k)=>e.jsx("div",{className:"h-8 border border-subtle bg-surface-sunken",style:{borderRadius:u}},k))})]})]}),i==="checkout"&&!x?e.jsxs("div",{className:"border border-subtle bg-surface-raised p-3",style:{borderRadius:c},children:[e.jsx("div",{className:"h-2 w-10 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsxs("div",{className:"mt-2 flex items-start gap-2",children:[e.jsx("div",{className:"size-9 shrink-0",style:{borderRadius:c,backgroundColor:Mt(s,.14)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"h-3 w-full bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}}),e.jsx("div",{className:"mt-1.5 h-2.5 w-4/5 bg-slate-200 dark:bg-slate-800",style:{borderRadius:u}})]})]}),e.jsx("div",{className:"mt-3 h-8 w-full",style:{borderRadius:u,backgroundColor:s}})]}):null]})]})})}function Zi(t){const s=typeof t=="string"?t.trim():"";if(!s)return"";const a=s.replace(/^#/,"").replace(/[^0-9a-f]/gi,"").slice(0,6);return a?`#${a}`:""}function Vr(t){return Ed(t,"",Dx)}function rc(t){if(typeof t!="string")return!1;const s=t.trim();return s?!Vr(s):!1}function ic(t){return!t||typeof t!="object"?!1:Object.entries(t).some(([s,a])=>sc.has(s)&&rc(a)?!0:a&&typeof a=="object"?ic(a):!1)}function lc(t){return!t||typeof t!="object"?t:Object.entries(t).reduce((s,[a,i])=>sc.has(a)&&typeof i=="string"?(s[a]=Vr(i)||"",s):(s[a]=i&&typeof i=="object"?lc(i):i,s),Array.isArray(t)?[]:{})}function _n({id:t,label:s,value:a,fallback:i,onChange:n}){const l=Vr(a)||qm(i),c=rc(a);return e.jsxs("div",{className:"space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:t,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:s}),e.jsxs("div",{className:"flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx(be,{id:`${t}
318-picker`,type:"color",value:l,onChange:u=>n(u.target.value),className:"h-10 w-14 shrink-0 cursor-pointer rounded-lg border-subtle bg-surface-raised p-1 max-lg:h-8 max-lg:w-11","aria-label":`${s} picker`}),e.jsx(be,{id:t,type:"text",value:a||"",placeholder:i,inputMode:"text",maxLength:7,pattern:"^#?[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$",autoCapitalize:"off",spellCheck:!1,"aria-invalid":c?"true":void 0,onChange:u=>n(Zi(u.target.value)),onPaste:u=>{u.preventDefault(),n(Zi(u.clipboardData.getData("text")))},className:"rounded-lg border-subtle bg-surface-raised font-mono text-xs"})]}),c?e.jsx("p",{className:"text-xs text-red-600 max-lg:text-2xs dark:text-red-400",children:"Enter a 3- or 6-digit hex color."}):null]})}function Xt({id:t,label:s,value:a,min:i=0,max:n=32,onChange:r}){const l=Number.isFinite(Number(a))?Number(a):i;return e.jsxs("div",{className:"space-y-2 rounded-lg border border-subtle bg-surface-sunken p-3 max-lg:space-y-1.5 max-lg:p-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:gap-2",children:[e.jsx(oe,{htmlFor:t,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:s}),e.jsxs("span",{className:"font-mono text-xs text-content-tertiary max-lg:text-2xs",children:[l,"px"]})]}),e.jsx(Cd,{id:t,min:i,max:n,step:1,value:[l],onValueChange:([c])=>r(c)})]})}function pp(t,s){return(t==null?void 0:t.surface)==="login"?s===Ke.SIDECAR?[{key:"backgroundColor",label:"Left panel color",fallback:"#2563eb"},{key:"rightPanelColor",label:"Form color",fallback:"#ffffff"},{key:"accentColor",label:"CTA accent",fallback:"#2563eb"}]:[{key:"backgroundColor",label:"Background color",fallback:"#f8fafc"},{key:"rightPanelColor",label:"Form color",fallback:"#ffffff"},{key:"accentColor",label:"CTA accent",fallback:"#2563eb"}]:(t==null?void 0:t.surface)==="checkout"?s===Ke.SIDECAR?[{key:"backgroundColor",label:"Left half color",fallback:"#f8fafc"},{key:"rightPanelColor",label:"Right half color",fallback:"#ffffff"},{key:"accentColor",label:"CTA color",fallback:"#2563eb"}]:s===Ke.FOCUSED?[{key:"accentColor",label:"CTA color",fallback:"#2563eb"}]:[{key:"backgroundColor",label:"Page background color",fallback:"#f8fafc"},{key:"accentColor",label:"CTA color",fallback:"#2563eb"}]:(t==null?void 0:t.surface)==="form"?[{key:"accentColor",label:"Action color",fallback:"#2563eb"}]:[{key:"accentColor",label:"Accent color",fallback:"#2563eb"},{key:"secondaryColor",label:"Secondary color",fallback:"#93c5fd"},{key:"backgroundColor",label:"Background color",fallback:"#f8fafc"}]}function gp(t,s){return(t==null?void 0:t.surface)==="login"?s===Ke.SIDECAR?gr:s===Ke.FOCUSED?Ji:Qi:(t==null?void 0:t.surface)!=="checkout"?Qi:s===Ke.SIDECAR?gr:s===Ke.FOCUSED?Ji:Hx}function fr(t,s){if((t==null?void 0:t.surface)==="login"){const a={...s,panelFields:yd(s.panelFields),backgroundImageUrl:bd(s.backgroundImageUrl)};return a.layoutPreset===Ke.SIDECAR?{...a,logoTreatment:es.includes(a.logoTreatment)?a.logoTreatment:Ge.MEDIUM}:es.includes(a.logoTreatment)?{...a,logoTreatment:Ge.STANDARD}:a}return(t==null?void 0:t.surface)!=="checkout"?s:s.layoutPreset===Ke.SIDECAR?{...s,logoTreatment:es.includes(s.logoTreatment)?s.logoTreatment:Ge.MEDIUM,backgroundStyle:ta.SOFT}:es.includes(s.logoTreatment)?{...s,logoTreatment:Ge.STANDARD}:s}function hp({theme:t,themeKey:s,meta:a,accentColor:i,branding:n,clientId:r,onThemeChange:l}){const c=(a==null?void 0:a.surface)==="email",u=(a==null?void 0:a.surface)==="checkout",m=(a==null?void 0:a.surface)==="login",h=(a==null?void 0:a.surface)==="form",g=(a==null?void 0:a.options)||ac,y=g.length===1?"grid-cols-1":g.length<=2?"sm:grid-cols-2":"sm:grid-cols-3",p=t.brandingOverrides||{},d=pp(a,t.layoutPreset),x=gp(a,t.layoutPreset),f=(u||m)&&t.layoutPreset===Ke.SIDECAR&&!es.includes(t.logoTreatment)?Ge.MEDIUM:t.logoTreatment,C=!u&&!c&&!m&&!h,[N,v]=o.useState(!1),[k,P]=o.useState(!1),A=Array.isArray(t.panelFields)?t.panelFields:[],E={displayName:(n==null?void 0:n.displayName)||(n==null?void 0:n.name)||"",logoUrl:(n==null?void 0:n.logoUrl)||"",accentColor:(n==null?void 0:n.accentColor)||(n==null?void 0:n.primaryColor)||i||je,secondaryColor:(n==null?void 0:n.secondaryColor)||"#93c5fd",backgroundColor:(n==null?void 0:n.backgroundColor)||"#f8fafc",logoBackgroun
318dColor:"#ffffff"};function z(b){if(l(s,"layoutPreset",b),m){if(b===Ke.SIDECAR){es.includes(t.logoTreatment)||l(s,"logoTreatment",Ge.MEDIUM);return}es.includes(t.logoTreatment)&&l(s,"logoTreatment",Ge.STANDARD);return}if(u){if(b===Ke.SIDECAR){es.includes(t.logoTreatment)||l(s,"logoTreatment",Ge.MEDIUM),l(s,"backgroundStyle",ta.SOFT);return}es.includes(t.logoTreatment)&&l(s,"logoTreatment",Ge.STANDARD)}}async function q(b){if(!r){I.error("Client is not loaded yet.");return}v(!0);try{const w=await Qa({file:b,brandType:"client",brandId:r,assetRole:"logo"});l(s,"brandingOverrides",{...p,logoUrl:w.logoUrl}),I.success("Logo uploaded",{description:"Review the preview, then save your theme."})}catch(w){throw I.error((w==null?void 0:w.message)||"Unable to upload logo."),w}finally{v(!1)}}async function R(b){if(!r){I.error("Client is not loaded yet.");return}if(wd(b)){const w=new Error("Use a PNG, JPG, or WEBP image for the login background.");throw I.error(w.message),w}P(!0);try{const w=await Qa({file:b,brandType:"client",brandId:r,assetRole:"logo"});
318l(s,"backgroundImageUrl",w.logoUrl),I.success("Background uploaded",{description:"Review the preview, then save your theme."})}catch(w){throw I.error((w==null?void 0:w.message)||"Unable to upload background."),w}finally{P(!1)}}function O(b,w){const F=A.map((M,W)=>W===b?{...M,...w}:M);l(s,"panelFields",F)}function j(){A.length>=Sn||l(s,"panelFields",[...A,{...kd}])}function L(b){l(s,"panelFields",A.filter((w,F)=>F!==b))}return e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsxs("div",{className:"rounded-lg border border-subtle bg-surface-sunken p-3 max-lg:p-2",children:[e.jsx("p",{className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Layout"}),e.jsx("div",{className:K("mt-3 grid gap-2 max-lg:mt-2 max-lg:gap-1.5",y),children:g.map(b=>e.jsx("button",{type:"button",onClick:()=>z(b.key),className:K("rounded-lg border p-3 text-left text-xs font-medium transition-colors","max-lg:p-2 max-lg:text-2xs",t.layoutPreset===b.key?"text-white shadow-sm":"border-subtle bg-surface-raised text-content-secondary hover:border-slate-300"),style:t.layoutPreset===b.key?{backgroundColor:i,borderColor:i}:void 0,children:b.label},b.key))})]}),!c&&!h?e.jsx("div",{className:"grid gap-3 max-lg:gap-2",children:qx.map(b=>{const w=t[b.key]||"",F=b.multiline?e.jsx(Is,{id:`${s}-${b.key}`,value:w,onChange:M=>l(s,b.key,M.target.value),placeholder:b.placeholder,className:"min-h-[78px] rounded-lg border-subtle bg-surface-raised max-lg:min-h-[56px]"}):e.jsx(be,{id:`${s}-${b.key}`,value:w,onChange:M=>l(s,b.key,M.target.value),placeholder:b.placeholder,className:"rounded-lg border-subtle bg-surface-raised"});return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{htmlFor:`${s}-${b.key}`,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:b.label}),F]},b.key)})}):null,h?e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("label",{htmlFor:`${s}-intro-enabled`,className:"flex cursor-pointer items-start gap-3 rounded-lg border border-subtle bg-surface-sunken p-3 max-lg:gap-2 max-lg:p-2",children:[e.jsx(Me,{id:`${s}-intro-enabled`,checked:t.introEnabled!==!1,onCheckedChange:b=>l(s,"introEnabled",b===!0),className:"mt-0.5"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Show assessment intro page"}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-content-tertiary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:"Enabled by default for assessment-first product links. Turn this off to send patients directly into intake."})]})]}),e.jsx("div",{className:"grid gap-3 max-lg:gap-2",children:[{key:"logoDescriptorText",label:"Logo descriptor",placeholder:"Optional text shown under the logo",multiline:!0},{key:"logoLinkUrl",label:"Logo link",placeholder:"https://yourclinic.com",type:"url",hint:"Optional. Opens in a new tab when a patient clicks the logo."},{key:"introTitle",label:"Intro title",placeholder:"Start your assessment"},{key:"introText",label:"Intro page text",placeholder:"Explain what the assessment is for.",multiline:!0},{key:"introButtonLabel",label:"Intro button",placeholder:"Start"},{key:"sectionDescriptorText",label:"Section helper text",placeholder:"Optional text shown under each section title",multiline:!0},{key:"footerText",label:"Bottom text",placeholder:"Optional footer note",multiline:!0}].map(b=>{const w=t[b.key]||"",F=b.multiline?e.jsx(Is,{id:`${s}-${b.key}`,value:w,onChange:M=>l(s,b.key,M.target.value),placeholder:b.placeholder,className:"min-h-[78px] rounded-lg border-subtle bg-surface-raised max-lg:min-h-[56px]"}):e.jsx(be,{id:`${s}-${b.key}`,type:b.type||"text",inputMode:b.type==="url"?"url":void 0,value:w,onChange:M=>l(s,b.key,M.target.value),placeholder:b.placeholder,"aria-describedby":b.hint?`${s}-${b.key}-hint`:void 0,className:"rounded-lg border-subtle bg-surface-raised"});return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{htmlFor:`${s}-${b.key}`,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:b.label}),F,b.hint?e.jsx("p",{id:`${s}-${b.key}-hint`,className:"text-xs text-content-tertiary max-lg:text-2xs",children:b.hint}):null]},b.key)})})]}):null,e.jsx("div",{className:"grid gap-3 max-lg:gap-2 md:grid-cols-2",children:[{key:"displayName",label:"Display name",type:"text",placeholder:E.displayName,className:"md:col-span-2"}].map(b=>e.jsxs("div",{className:K("space-y-1.5",b.className),children:[e.jsx(oe,{htmlFor:`${s}-branding-${b.key}`,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:b.label}),e.jsx(be,{id:`${s}-branding-${b.key}`,type:b.type,value:p[b.key]||(c?E[b.key]:""),placeholder:b.placeholder,onChange:w=>l(s,"brandingOverrides",{...p,[b.key]:w.target.value}),className:"rounded-lg border-subtle bg-surface-raised"})]},b.key))}),m?e.jsxs("div",{className:"space-y-3 rounded-lg border border-subtle bg-surface-sunken p-3 max-lg:space-y-2 max-lg:p-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Login panel fields"}),e.jsxs("p",{className:"mt-1 text-xs leading-5 text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:["Optional names and links. Up to ",Sn,"."]}
318)]}),A.map((b,w)=>e.jsxs("div",{className:"grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] sm:items-end",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{htmlFor:`${s}-panel-${w}-title`,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Name"}),e.jsx(be,{id:`${s}-panel-${w}-title`,value:b.title||"",maxLength:vd,onChange:F=>O(w,{title:F.target.value}),placeholder:"Field name",className:"rounded-lg border-subtle bg-surface-raised"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{htmlFor:`${s}-panel-${w}-url`,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Link"}),e.jsx(be,{id:`${s}-panel-${w}-url`,type:"text",inputMode:"url",autoComplete:"url",value:b.url||"",maxLength:hi,onChange:F=>O(w,{url:F.target.value}),placeholder:"https://",className:"rounded-lg border-subtle bg-surface-raised"})]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove ${b.title||`field ${w+1}`}`,onClick:()=>L(w),className:"size-9 shrink-0 rounded-full text-content-tertiary hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/30 dark:hover:text-red-400",children:e.jsx(bt,{className:"size-4 max-lg:size-3.5","aria-hidden":!0})})]},`panel-field-${w}`)),A.length<Sn?e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:j,className:"h-9 rounded-full max-lg:h-8",children:[e.jsx(ot,{className:"mr-1.5 size-4 max-lg:mr-1 max-lg:size-3.5","aria-hidden":!0}),"Add field"]}):null]}):null,e.jsx("div",{className:"grid gap-3 max-lg:gap-2 md:grid-cols-2",children:[...d.map(b=>({...b,type:"color",placeholder:E[b.key]||b.fallback})),...c||m||h?[{key:"logoBackgroundColor",label:"Logo background color",type:"color",placeholder:E.logoBackgroundColor}]:[]].map(b=>{const w=p[b.key]||(c?E[b.key]:"");return b.type==="color"?e.jsx(_n,{id:`${s}-branding-${b.key}`,label:b.label,value:w,fallback:b.placeholder,onChange:F=>l(s,"brandingOverrides",{...p,[b.key]:F})},b.key):e.jsxs("div",{className:K("space-y-1.5",b.className),children:[e.jsx(oe,{htmlFor:`${s}-branding-${b.key}`,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:b.label}),e.jsx(be,{id:`${s}-branding-${b.key}`,type:b.type,value:w,placeholder:b.placeholder,onChange:F=>l(s,"brandingOverrides",{...p,[b.key]:F.target.value}),className:"rounded-lg border-subtle bg-surface-raised"})]},b.key)})}),e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{className:"space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:`${s}-branding-logoUrl`,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Logo URL"}),e.jsx(be,{id:`${s}-branding-logoUrl`,type:"url",value:p.logoUrl||"",placeholder:E.logoUrl||"Use client logo",onChange:b=>l(s,"brandingOverrides",{...p,logoUrl:b.target.value}),className:"rounded-lg border-subtle bg-surface-raised"})]}),e.jsx(Os,{label:"Logo upload",description:"Upload a theme-specific logo, or leave this empty to use the client logo.",cropTitle:`Crop ${a.title.toLowerCase()} logo`,cropDescription:"Adjust the crop, confirm the upload, review it in the preview, then save the theme.",previewUrl:p.logoUrl||null,aspect:3/1,uploading:N,accentColor:i,onUpload:q,onRemove:()=>l(s,"brandingOverrides",{...p,logoUrl:""}),previewFrameClassName:"aspect-[3/1]",previewImageClassName:"max-h-24",dropzoneClassName:"aspect-[3/1] min-h-28",changeLabel:"Change logo",emptyLabel:"Upload logo"})]}),m?e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{className:"space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:`${s}-backgroundImageUrl`,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Backgroun
318d URL"}),e.jsx(be,{id:`${s}-backgroundImageUrl`,type:"url",value:t.backgroundImageUrl||"",maxLength:hi,placeholder:"https://",onChange:b=>l(s,"backgroundImageUrl",b.target.value),className:"rounded-lg border-subtle bg-surface-raised"})]}),e.jsx(Os,{label:"Background upload",description:"Optional. Sidecar uses this on the left panel. Focused uses it behind the form. Leave empty to keep the color background.",cropTitle:"Crop login background",cropDescription:"Adjust the crop, confirm the upload, review it in the preview, then save the theme.",previewUrl:t.backgroundImageUrl||null,aspect:16/9,uploading:k,accentColor:i,onUpload:R,onRemove:()=>l(s,"backgroundImageUrl",""),previewFrameClassName:"aspect-video",previewImageClassName:"max-h-28",dropzoneClassName:"aspect-video min-h-28",changeLabel:"Change background",emptyLabel:"Upload background"})]}):null,h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 max-lg:gap-2 md:grid-cols-2",children:[e.jsx(_n,{id:`${s}-form-background`,label:"Form background",value:t.formBackgroundColor||"",fallback:E.backgroundColor,onChange:b=>l(s,"formBackgroundColor",b)}),e.jsx(_n,{id:`${s}-card-background`,label:"Card background",value:t.cardBackgroundColor||"",fallback:"#ffffff",onChange:b=>l(s,"cardBackgroundColor",b)})]}),e.jsxs("div",{className:"rounded-lg border border-subtle bg-surface-sunken p-3 max-lg:p-2",children:[e.jsx("p",{className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Card"}),e.jsxs("div",{className:"mt-3 flex gap-2 max-lg:mt-2 max-lg:gap-1.5",children:[e.jsx(Ss,{active:t.cardTreatment!==bs.NONE,onClick:()=>l(s,"cardTreatment",bs.CARD),accentColor:i,className:"min-w-0 flex-1 justify-center",children:"Card"}),e.jsx(Ss,{active:t.cardTreatment===bs.NONE,onClick:()=>l(s,"cardTreatment",bs.NONE),accentColor:i,className:"min-w-0 flex-1 justify-center",children:"No card"})]})]}),e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsx(Xt,{id:`${s}-card-radius`,label:"Card border rounding",value:t.cardBorderRadius,max:48,onChange:b=>l(s,"cardBorderRadius",b)}),e.jsx(Xt,{id:`${s}-logo-radius`,label:"Logo border rounding",value:t.logoBorderRadius,onChange:b=>l(s,"logoBorderRadius",b)}),e.jsx(Xt,{id:`${s}-logo-padding`,label:"Logo padding",value:t.logoPadding,onChange:b=>l(s,"logoPadding",b)})]})]}):null,m?e.jsx(e.Fragment,{children:e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsx(Xt,{id:`${s}-form-radius`,label:"Form border rounding",value:t.formBorderRadius,max:48,onChange:b=>l(s,"formBorderRadius",b)}),e.jsx(Xt,{id:`${s}-logo-radius`,label:"Logo border rounding",value:t.logoBorderRadius,onChange:b=>l(s,"logoBorderRadius",b)}),e.jsx(Xt,{id:`${s}-logo-padding`,label:"Logo padding",value:t.logoPadding,onChange:b=>l(s,"logoPadding",b)})]})}):null,c?e.jsx(e.Fragment,{children:e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsx(Xt,{id:`${s}-container-radius`,label:"Email border rounding",value:t.containerBorderRadius,onChange:b=>l(s,"containerBorderRadius",b)}),e.jsx(Xt,{id:`${s}-logo-radius`,label:"Logo border rounding",value:t.logoBorderRadius,onChange:b=>l(s,"logoBorderRadius",b)}),e.jsx(Xt,{id:`${s}-logo-padding`,label:"Logo padding",value:t.logoPadding,onChange:b=>l(s,"logoPadding",b)})]})}):null,!c&&!h?e.jsxs("div",{className:K("grid gap-3 max-lg:gap-2",C&&"md:grid-cols-2"),children:[e.jsxs("div",{className:"rounded-lg border border-subtle bg-surface-sunken p-3 max-lg:p-2",children:[e.jsx("p",{className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Logo"}),e.jsx("div",{className:"mt-3 flex gap-2 max-lg:mt-2 max-lg:gap-1.5",children:x.map(b=>e.jsx(Ss,{active:f===b.key,onClick:()=>l(s,"logoTreatment",b.key),accentColor:i,className:"min-w-0 flex-1 justify-center",children:b.label},b.key))})]}),C?e.jsxs("div",{className:"rounded-lg border border-subtle bg-surface-sunken p-3 max-lg:p-2",children:[e.jsx("p",{className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Backgroun
318d"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:Wx.map(b=>e.jsx(Ss,{active:t.backgroundStyle===b.key,onClick:()=>l(s,"backgroundStyle",b.key),accentColor:i,children:b.label},b.key))})]}):null]}):null]})}function fp({surface:t,preset:s,accentColor:a,cornerStyle:i,theme:n}){const r=Fs(i,"card"),l=Fs(i,"pill"),c=s===As.CLASSIC,u=s===As.BANNER,m=s===As.LETTERHEAD;if(t==="form"){const y=Number.isFinite(Number(n==null?void 0:n.cardBorderRadius))?Number(n.cardBorderRadius):24,p=(n==null?void 0:n.cardTreatment)!==bs.NONE;return e.jsx("div",{className:"h-24 rounded-lg p-1.5",style:{backgroundColor:(n==null?void 0:n.formBackgroundColor)||Mt(a,.12)},children:e.jsxs("div",{className:K("mx-auto flex h-full max-w-[9rem] flex-col overflow-hidden",p?"border border-subtle bg-surface-raised shadow-sm":"bg-transparent shadow-none"),style:{borderRadius:p?`${Math.max(4,y/2)}px`:0,backgroundColor:p?(n==null?void 0:n.cardBackgroundColor)||"#ffffff":"transparent"},children:[e.jsxs("div",{className:K("px-3 py-2",p&&"border-b border-slate-100 dark:border-slate-800"),children:[e.jsx("div",{className:"mx-auto h-2.5 w-14 bg-slate-300 dark:bg-slate-700",style:{borderRadius:l}}),e.jsx("div",{className:"mx-auto mt-2 h-1.5 w-20 bg-slate-200 dark:bg-slate-800",style:{borderRadius:l}})]}),e.jsxs("div",{className:"flex-1 space-y-1.5 p-3",children:[e.jsx("div",{className:"mx-auto h-3 w-20 bg-slate-300 dark:bg-slate-700",style:{borderRadius:l}}),e.jsx("div",{className:"h-1.5 w-full bg-slate-200 dark:bg-slate-800",style:{borderRadius:l}}),e.jsx("div",{className:"h-1.5 w-4/5 bg-slate-200 dark:bg-slate-800",style:{borderRadius:l}}),e.jsx("div",{className:"mt-2 h-4 w-16 rounded-full",style:{backgroundColor:a}})]})]})})}if(t==="email"){const y=Number.isFinite(Number(n==null?void 0:n.containerBorderRadius))?Number(n.containerBorderRadius):12;return e.jsx("div",{className:K("h-24 rounded-lg p-1.5",u?"":"bg-slate-200 dark:bg-slate-900"),style:u?{backgroundColor:Mt(a,.18)}:void 0,children:e.jsxs("div",{className:K("mx-auto h-full max-w-[9rem] overflow-hidden bg-surface-raised",u?"shadow-md":"border border-subtle"),style:{borderRadius:`${Math.max(4,y/2)}px`,borderTopColor:m?a:void 0,borderTopWidth:m?4:void 0},children:[e.jsxs("div",{className:K("px-3",u||m?"py-2 text-left":"py-2 text-center"),style:{backgroundColor:m?"#ffffff":a},children:[e.jsx("div",{className:K("h-2.5 w-12",c?"mx-auto bg-white/80":"bg-slate-100 dark:bg-slate-800"),style:{borderRadius:l}}),u?null:e.jsx("div",{className:K("mt-2 h-2 w-16",m?"bg-slate-200 dark:bg-slate-800":"mx-auto bg-white/60"),style:{borderRadius:l}})]}),u?e.jsx("div",{className:"px-3 pt-2",children:e.jsx("div",{className:"h-2 w-20 bg-slate-300 dark:bg-slate-700",style:{borderRadius:l}})}):null,e.jsxs("div",{className:"space-y-1.5 p-3",children:[e.jsx("div",{className:"h-1.5 w-full bg-slate-200 dark:bg-slate-800",style:{borderRadius:l}}),e.jsx("div",{className:"h-1.5 w-4/5 bg-slate-200 dark:bg-slate-800",style:{borderRadius:l}}),e.jsx("div",{className:K("mt-2 h-4",c?"mx-auto w-16 rounded-full":"w-14 rounded-md"),style:{backgroundColor:a}})]})]})})}if(t==="login"){const y=s===Ke.SIDECAR;return e.jsx("div",{className:"h-24 overflow-hidden rounded-lg bg-slate-100 p-1.5 dark:bg-slate-900",children:e.jsx("div",{className:K("h-full overflow-hidden border border-subtle bg-surface-raised",y?"grid grid-cols-[0.9fr_1.1fr]":"p-2"),style:{borderRadius:r},children:y?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col justify-between p-2",style:{backgroundColor:Mt(a,.16)},children:[e.jsx("div",{className:"h-4 w-12 bg-white/80 dark:bg-slate-800",style:{borderRadius:l}}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"h-2 w-16 bg-white/70 dark:bg-slate-800",style:{borderRadius:l}}),e.jsx("div",{className:"h-1.5 w-12 bg-white/50 dark:bg-slate-700",style:{borderRadius:l}})]})]}),e.jsxs("div",{className:"space-y-2 p-2",children:[e.jsx("div",{className:"h-2.5 w-14 bg-slate-300 dark:bg-slate-700",style:{borderRadius:l}}),e.jsx("div",{className:"h-6 w-full border border-subtle bg-surface-sunken",style:{borderRadius:l}}),e.jsx("div",{className:"h-6 w-full border border-subtle bg-surface-sunken",style:{borderRadius:l}}),e.jsx("div",{className:"h-5 w-full",style:{backgroundColor:a,borderRadius:l}})]})]}):e.jsxs("div",{className:"mx-auto flex h-full max-w-[8.5rem] flex-col items-center justify-center space-y-2",children:[e.jsx("div",{className:"h-4 w-16 bg-slate-200 dark:bg-slate-800",style:{borderRadius:l}}),e.jsx("div",{className:"h-2 w-20 bg-slate-300 dark:bg-slate-700",style:{borderRadius:l}}),e.jsx("div",{className:"h-5 w-full border border-subtle bg-surface-sunken",style:{borderRadius:l}}),e.jsx("div",{className:"h-5 w-full border border-subtle bg-surface-sunken",style:{borderRadius:l}}),e.jsx("div",{className:"h-5 w-20",style:{backgroundColor:a,borderRadius:l}})]})})})}const h=s===Ke.SIDECAR,g=s===Ke.EDITORIAL;return e.jsx("div",{className:K("h-24 overflow-hidden rounded-lg p-1.5",g?"":"bg-slate-100 dar
318k:bg-slate-900"),style:g?{backgroundColor:Mt(a,.16)}:void 0,children:e.jsx("div",{className:K("h-full overflow-hidden border border-subtle bg-surface-raised",h?"grid grid-cols-[1fr_0.78fr]":"p-2",g&&"shadow-sm"),style:{borderRadius:r},children:h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2 p-2",children:[e.jsx("div",{className:"h-2.5 w-16 bg-slate-300 dark:bg-slate-700",style:{borderRadius:l}}),e.jsx("div",{className:"h-6 w-full border border-subtle bg-surface-sunken",style:{borderRadius:l}}),e.jsx("div",{className:"h-6 w-full border border-subtle bg-surface-sunken",style:{borderRadius:l}}),e.jsx("div",{className:"h-5 w-20",style:{backgroundColor:a,borderRadius:l}})]}),e.jsxs("div",{className:"space-y-2 border-l border-subtle bg-surface-sunken p-2",children:[e.jsx("div",{className:"h-3 w-14 bg-slate-300 dark:bg-slate-700",style:{borderRadius:l}}),e.jsx("div",{className:"h-2 w-full bg-slate-200 dark:bg-slate-800",style:{borderRadius:l}}),e.jsx("div",{className:"h-2 w-4/5 bg-slate-200 dark:bg-slate-800",style:{borderRadius:l}}),e.jsx("div",{className:"mt-2 h-3 w-full",style:{backgroundColor:a,borderRadius:l}})]})]}):e.jsxs("div",{className:K("h-full",g?"grid grid-cols-[0.75fr_1fr] gap-2":"space-y-2"),children:[g?e.jsxs("div",{className:"flex flex-col justify-between rounded-md p-2",style:{backgroundColor:Mt(a,.12)},children:[e.jsx("div",{className:"h-3 w-12 bg-white/80 dark:bg-slate-800",style:{borderRadius:l}}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"h-2 w-14 bg-white/70 dark:bg-slate-800",style:{borderRadius:l}}),e.jsx("div",{className:"h-1.5 w-10 bg-white/60 dark:bg-slate-700",style:{borderRadius:l}})]})]}):null,e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"h-2.5 w-16 bg-slate-300 dark:bg-slate-700",style:{borderRadius:l}}),e.jsx("div",{className:"h-6 w-full border border-subtle bg-surface-sunken",style:{borderRadius:l}}),e.jsx("div",{className:"h-6 w-full border border-subtle bg-surface-sunken",style:{borderRadius:l}}),e.jsx("div",{className:"h-5 w-24",style:{backgroundColor:a,borderRadius:l}})]})]})})})}function bp({option:t,active:s,accentColor:a,cornerStyle:i,surface:n,onClick:r,editable:l,theme:c,branding:u}){return e.jsxs("button",{type:"button",onClick:r,className:K("group rounded-xl border bg-surface-raised p-2 text-left transition-colors",s?"border-transparent ring-2":"border-subtle hover:border-slate-300 dark:hover:border-slate-600"),style:s?{"--tw-ring-color":a}:void 0,"aria-pressed":s,children:[e.jsx(fp,{surface:n,preset:t.key,accentColor:a,cornerStyle:i,theme:c,branding:u}),e.jsxs("div",{className:"mt-2 flex items-start justify-between gap-2 px-0.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-700 max-lg:text-2xs dark:text-slate-200",children:t.label}),t.hint?e.jsx("span",{className:"mt-0.5 block text-3xs font-normal leading-tight text-content-tertiary",children:t.hint}):null]}),s?e.jsx("span",{className:"inline-flex size-4 items-center justify-center rounded-full text-white",style:{backgroundColor:a},children:e.jsx(Ze,{className:"size-2.5"})}):null]}),s&&l?e.jsx("p",{className:"mt-1 px-0.5 text-2xs text-content-tertiary",children:"Click to edit"}):null]})}function wa({options:t,value:s,surface:a,accentColor:i,cornerStyle:n,onSelect:r,onEdit:l,editable:c=!1,theme:u,branding:m}){const h=t.length===1?"grid-cols-1":t.length<=2?"sm:grid-cols-2":"sm:grid-cols-3";return e.jsx("div",{className:K("grid gap-2 max-lg:gap-1.5",h),children:t.map(g=>{const y=s===g.key;return e.jsx(bp,{option:g,active:y,accentColor:i,cornerStyle:n,surface:a,theme:u,branding:m,editable:c,onClick:()=>{if(y&&c){l();return}r(g.key)}},g.key)})})}function Ca({open:t,onOpenChange:s,meta:a,theme:i,themeKey:n,accentColor:r,branding:l,clientId:c,cornerStyle:u,onThemeSave:m,onSendTestEmail:h,currentUserEmail:g,saving:y}){const[p,d]=o.useState(i),[x,f]=o.useState(g||""),[C,N]=o.useState(!1),[v,k]=o.useState("desktop"),P=(a==null?void 0:a.surface)==="email",A=(a==null?void 0:a.surface)==="form",[E,z]=o.useState("intake"),q=(p==null?void 0:p.introEnabled)!==!1,R=ic(p);o.useEffect(()=>{t&&(d(i),f(g||""),k("desktop"),z((i==null?void 0:i.introEnabled)===!1?"intake":"intro"))},[g,t,i]),o.useEffect(()=>{t&&A&&!q&&E==="intro"&&z("intake")},[q,E,A,t]);function O(w,F,M){w===n&&d(W=>({...W,[F]:M}))}function j(){if(R){I.error("Complete each hex color before saving.");return}let w=p;
318if(A){const F=typeof(p==null?void 0:p.logoLinkUrl)=="string"?p.logoLinkUrl.trim():"",M=jd(F);if(F&&!M){I.error("Enter a valid logo link, like https://yourclinic.com.");return}w={...p,logoLinkUrl:M}}m==null||m(n,fr(a,lc(w)))}async function L(){if(!P||!h)return;const w=x.trim();if(!w){I.error("Enter an email address for the test.");return}N(!0);try{await h({recipientEmail:w,emailTheme:fr(a,p)})}catch(F){I.error((F==null?void 0:F.message)||"Unable to send test email.")}finally{N(!1)}}const b=Xm({formId:"client-experience-settings-section-form",open:t,onClose:()=>s(!1)});return e.jsxs(at,{open:t,onOpenChange:s,...b.dialogProps,title:a.title,description:"Edit copy and brand treatments for the selected layout.",mobileCompactHeaderRow:!0,mobileStickyFooter:!0,contentClassName:"h-[min(56rem,calc(100dvh-1rem))] max-h-[calc(100dvh-1rem)] max-w-[min(96rem,calc(100vw-2rem))]",headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",bodyClassName:"p-0",footerClassName:"justify-end border-t-0 bg-transparent !py-2 max-[1024px]:!py-2 max-[1024px]:!pb-2 max-[1024px]:!px-3 max-[1024px]:gap-1.5",footer
318:e.jsx(B,{type:"submit",form:"client-experience-settings-section-form",size:"sm",disabled:y||R,className:"text-white",style:{backgroundColor:r},children:y?e.jsxs(e.Fragment,{children:[e.jsx($e,{size:"md"}),"Saving..."]}):"Save changes"}),children:[e.jsx("form",{id:"client-experience-settings-section-form",className:us,onSubmit:xs(j,{disabled:y||R}),children:e.jsxs("div",{className:"grid min-h-full gap-4 p-4 max-lg:gap-2 max-lg:p-2 lg:grid-cols-[minmax(0,24rem)_minmax(0,1fr)]",children:[e.jsx("div",{className:"min-h-0 overflow-y-auto rounded-xl border border-subtle bg-surface-raised p-4 max-lg:p-2.5",children:e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsx(hp,{theme:p,themeKey:n,meta:a,accentColor:r,branding:l,clientId:c,onThemeChange:O}),P?e.jsxs("div",{className:"space-y-2 rounded-lg border border-subtle bg-surface-sunken p-3 max-lg:space-y-1.5 max-lg:p-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Test email"}),e.jsx("p",{className:"mt-1 text-xs text-content-tertiary max-lg:mt-0.5 max-lg:text-2xs",children:"Send this draft theme to any recipient."})]}),e.jsxs("div",{className:"space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:`${n}-test-email`,className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Recipient"}),e.jsx(be,{id:`${n}-test-email`,type:"email",value:x,placeholder:"[email protected]",onChange:w=>f(w.target.value),className:"rounded-lg border-subtle bg-surface-raised"})]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:L,disabled:C||y,className:"w-full",style:{borderColor:`${r}66`,color:r},children:[C?e.jsx(Ve,{className:"size-4 animate-spin max-lg:size-3.5"}):e.jsx(Ar,{className:"size-4 max-lg:size-3.5"}),"Send test email"]})]}):null]})}),e.jsxs("div",{className:"min-h-0 overflow-y-auto",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-end gap-2 max-lg:mb-2 max-lg:flex-nowrap max-lg:gap-1 max-lg:overflow-x-auto max-lg:[&>*]:shrink-0",children:[A&&q?e.jsxs("div",{className:"flex items-center gap-2 max-lg:gap-1",children:[e.jsx(Ss,{active:E==="intro",onClick:()=>z("intro"),accentColor:r,children:"Intro"}),e.jsx(Ss,{active:E==="intake",onClick:()=>z("intake"),accentColor:r,children:"Intake"})]}):null,e.jsx(mp,{value:v,onChange:k,accentColor:r})]}),e.jsx(xp,{theme:p,accentColor:r,branding:l,cornerStyle:u,surface:a.surface,previewDevice:v,formPreviewStage:E})]})]})}),b.confirmElement]})}function yp({clientFormOptions:t=[],clientFormsStatus:s="idle",reviewOnlyTenant:a=!1,accentColor:i="#2563eb",branding:n=null,clientId:r=null,tenantCollection:l=It.CLIENT,experienceConfig:c,patientOrderRoadmap:u,patientOrderRoadmapOptions:m=[],customFormularyTerminalStepOptions:h=[],patientSidebar:g,patientNotifications:y,wearables:p={enabled:!1},postVisitRedirectEnabled:d=!1,postVisitRedirectUrl:x="",savingField:f=null,onTogglePatientSidebarItem:C,onUpdatePatientSidebarItemOverride:N,onMovePatientSidebarItem:v,onAddCustomPatientSidebarItem:k,onUpdateCustomPatientSidebarItem:P,onRemoveCustomPatientSidebarItem:A,onAddCustomPatientSidebarSection:E,onUpdateCustomPatientSidebarSection:z,onRemoveCustomPatientSidebarSection:q,onExperienceConfigChange:R,onExperienceConfigSave:O,onPatientOrderRoadmapChange:j,onPatientNotificationChange:L,onWearablesChange:b,onPostVisitRedirectChange:w,onFlushPendingSaves:F,mode:M="experience"}){const{userDoc:W,currentUser:H}=Se(),[ae,xe]=o.useState(null),[Ae,se]=o.useState("sidebar"),Z=Le(c),fe=f==="experienceConfig",J=f==="checkoutTheme",ge=f==="loginTheme",ye=f==="emailTheme",Re=f==="formTheme",G=f==="patientSidebar",U=f==="patientNotifications",V=f==="wearables",D=f==="postVisitRedirectEnabled"||f==="postVisitRedirectUrl",T=ip(g,l),$=o.useMemo(()=>Hl({portalChrome:{cornerStyle:Z.portalChrome.cornerStyle,layoutWidth:Z.portalChrome.layoutWidth,navMode:Z.portalChrome.navMode}}),[Z.portalChrome.cornerStyle,Z.portalChrome.layoutWidth,Z.portalChrome.navMode]);function S(re,pe){if(!pe){F==null||F(),xe(null);return}xe(re)}function Q(re,pe){R(me=>({...Le(me),portalChrome:{...Le(me).portalChrome,[re]:pe}}),{savingScope:"experienceConfig"})}function Y(re,pe){R(me=>{const ie=Le(me),_e=St[re];return{...ie,[re]:fr(_e,{...ie[re],layoutPreset:pe})}},{savingScope:re})}async function de(re,pe){if(O){await O(ie=>({...Le(ie),[re]:pe}),{savingScope:re})&&xe(null);return}R(me=>({...Le(me),[re]:pe}),{savingScope:re}),xe(null)}async function ve({recipientEmail:re,emailTheme:pe}){if(!r){I.error("Client is not loaded yet.");return}await hd("manageClient",{action:"sendEmailThemeTest",clientId:r,recipientEmail:re,emailTheme:pe}),I.success("Test email queued",{description:`Sent to ${re}`})}function Ee(re,pe){R(me=>{const ie=Le(me);return{...ie,patientDashboard:{...ie.patientDashboard,sections:ie.patientDashboard.sections.map(_e=>_e.key===re?{..._e,enabled:pe}:_e)}}},{savingScope:"experienceConfig"})}function Oe(re,pe){R(me=>{const ie=Le(me);return{...ie,patientCheckout:{...ie.patientCheckout,sequence:{...ie.patientCheckout.sequence,[re]:pe}}}},{savingScope:"experienceConfig"})}function nt(re){R(pe=>{const me=Le(pe);return{...me,publicCheckoutDisclaimer:{...me.publicCheckoutDisclaimer,mode:re}}},{savingScope:"experienceConfig"})}function ze(re){R(pe=>{const me=Le(pe);return{...me,patientCheckout:{...me.patientCheckout,perProductSummaryCustomization:{enabled:re===!0}}}},{savingScope:"experienceConfig"})}function pt(re){R(pe=>{const me=Le(pe);return{...me,patientReceipts:{...me.patientReceipts,enabled:re}}},{savingScope:"experienceConfig"})}function Bt(re){R(pe=>{const me=Le(pe);return{...me,patientFormResubmission:{...me.patientFormResubmission,enabled:re}}},{savingScope:"experienceConfig"})}function Gt(re){R(pe=>{const me=Le(pe);return{...me,requireIdVerificationForNewPatientsOnly:{...me.requireIdVerificationForNewPatientsOnly,enabled:re}}},{savingScope:"experienceConfig"})}function cs(re){R(pe=>{const me=Le(pe);return{...me,minimumSignupAge:{...me.minimumSignupAge,enabled:re}}},{savingScope:"experienceConfig"})}function X(re){R(pe=>{const me=Le(pe);return{...me,queuePrescriptionReview:{...me.queuePrescriptionReview,enabled:re}}},{savingScope:"experienceConfig"})}function We(re){R(pe=>{const me=Le(pe);return{...me,clientCollectedProductPayment:{...me.clientCollectedProductPayment,enabled:re}}},{savingScope:"experienceConfig"})}function ct(re){R(pe=>{const me=Le(pe);return{...me,queueLabOrderReview:{...me.queueLabOrderReview,enabled:re}}},{savingScope:"experienceConfig"})}function gt(re){R(pe=>{const me=Le(pe);
318return{...me,showVisitPurchasesInPatientOrders:{...me.showVisitPurchasesInPatientOrders,enabled:re}}},{savingScope:"experienceConfig"})}function _t(re){R(pe=>{const me=Le(pe);return{...me,postPurchaseConsultationPrompt:{...me.postPurchaseConsultationPrompt,enabled:re}}},{savingScope:"experienceConfig"})}function dt(re){R(pe=>{const me=Le(pe);return{...me,patientProfile:{...me.patientProfile,showPartnerCustomFields:re===!0}}},{savingScope:"experienceConfig"})}function et(re,pe){R(me=>{const ie=Le(me);if(re.startsWith("destinations.")){const _e=re.slice(13);return{...ie,patientMessaging:{...ie.patientMessaging,destinations:{...ie.patientMessaging.destinations,[_e]:pe}}}}if(re.startsWith("intake.")){const _e=re.slice(7);return{...ie,patientMessaging:{...ie.patientMessaging,intake:{...ie.patientMessaging.intake,[_e]:pe}}}}return{...ie,patientMessaging:{...ie.patientMessaging,[re]:pe}}},{savingScope:"experienceConfig"})}function Rt(re,pe){R(me=>{const ie=Le(me);return{...ie,emailTheme:{...ie.emailTheme,[re]:pe}}},{savingScope:"emailTheme"})}function rt(re,pe){R(me=>{const ie=Le(me),_e=[...ie.patientDashboard.sections],kt=_e.findIndex(Ct=>Ct.key===re);if(kt===-1)return ie;const ke=pe==="up"?kt-1:kt+1;if(ke<0||ke>=_e.length)return ie;const[Kt]=_e.splice(kt,1);return _e.splice(ke,0,Kt),{...ie,patientDashboard:{...ie.patientDashboard,sections:_e}}},{savingScope:"experienceConfig"})}function Lt(re){const pe=Ya(re);pe.title&&R(me=>{const ie=Le(me);return{...ie,patientDashboard:{...ie.patientDashboard,sections:[...ie.patientDashboard.sections,pe]}}},{savingScope:"experienceConfig"})}function ee(re,pe){R(me=>{const ie=Le(me);return{...ie,patientDashboard:{...ie.patientDashboard,sections:ie.patientDashboard.sections.map(_e=>_e.key!==re||!ia(_e)?_e:{...Ya(pe),key:_e.key,enabled:_e.enabled!==!1})}}},{savingScope:"experienceConfig"})}function Ye(re){R(pe=>{const me=Le(pe);return{...me,patientDashboard:{...me.patientDashboard,sections:me.patientDashboard.sections.filter(ie=>!(ie.key===re&&ia(ie)))}}},{savingScope:"experienceConfig"})}const ht=Z.patientDashboard.sections.some(re=>re.key==="monitoring"&&re.enabled!==!1),Qe=M!=="themes",He=M!=="experience";return e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",style:$,children:[Qe?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 max-lg:gap-2 lg:grid-cols-2",children:[e.jsx($x,{ExperienceSurfaceCard:Ht,SegmentedChoiceGroup:zn,accentColor:i,isSavingExperienceConfig:fe,normalizedExperienceConfig:Z,portalBorderStyleOptions:Jx,portalLayoutWidthOptions:Xx,portalNavModeOptions:Zx,onPortalChromeChange:Q}),e.jsx(Bx,{ExperienceSurfaceCard:Ht,SegmentedChoiceGroup:zn,LargeCheckboxOption:Xi,accentColor:i,checkoutRows:ep,checkoutSequenceOptions:Yx,isSavingExperienceConfig:fe,normalizedExperienceConfig:Z,publicCheckoutDisclaimerOptions:Qx,onPatientCheckoutSequenceChange:Oe,onPublicCheckoutDisclaimerModeChange:nt,onPerProductSummaryCustomizationChange:ze})]}),e.jsx(wx,{ExperienceSurfaceCard:Ht,LargeCheckboxOption:Xi,SegmentedChoiceGroup:zn,accentColor:i,isSavingExperienceConfig:fe,isSavingPostVisitRedirect:D,isValidHttpUrl:tp,normalizedExperienceConfig:Z,patientOrderRoadmap:u,patientOrderRoadmapOptions:m,customFormularyTerminalStepOptions:h,onPatientReceiptsEnabledChange:pt,onPatientFormResubmissionChange:Bt,onPostPurchaseConsultationPromptEnabledChange:_t,onPostVisitRedirectChange:w,onQueueLabOrderReviewEnabledChange:ct,onQueuePrescriptionReviewEnabledChange:X,onClientCollectedProductPaymentEnabledChange:We,onRequireIdVerificationForNewPatientsOnlyChange:Gt,onMinimumSignupAgeChange:cs,clientId:r,onShowPatientCustomFieldsChange:dt,onShowVisitPurchasesInPatientOrdersChange:gt,onPatientOrderRoadmapChange:j,postVisitRedirectEnabled:d,postVisitRedirectUrl:x,savingField:f,tenantCollection:l}),e.jsx(_x,{ExperienceSurfaceCard:Ht,accentColor:i,isSaving:fe,normalizedExperienceConfig:Z,onPatientMessagingChange:et,tenantCollection:l}),e.jsx(Fx,{ExperienceSurfaceCard:Ht,PatientDashboardPreview:dp,accentColor:i,clientFormOptions:t,clientFormsStatus:s,reviewOnlyTenant:a,clientId:r,tenantCollection:l,createCustomSidebarItem:lp,createCustomSidebarSection:op,dashboardEditorTab:Ae,dashboardSectionOptions:pr,getSidebarItemIcon:sp,hexToRgba:Mt,isSavingExperienceConfig:fe,isSavingPatientSidebar:G,isSavingWearables:V,isValidPatientSidebarUrl:md,monitoringSectionEnabled:ht,normalizedExperienceConfig:Z,onAddCustomPatientSidebarItem:k,onAddCustomPatientSidebarSection:E,onMovePatientSidebarItem:v,onRemoveCustomPatientSidebarItem:A,onRemoveCustomPatientSidebarSection:q,onTogglePatientSidebarItem:C,onUpdateCustomPatientSidebarItem:P,onUpdateCustomPatientSidebarSection:z,onUpdatePatientSidebarItemOverride:N,onWearablesChange:b,patientCustomLinkOpenModes:ea,patientSidebarRows:T,setDashboardEditorTab:se,updateDashboardSectionEnabled:Ee,visibleDashboardSections:Z.patientDashboard.sections,visiblePatientSidebarRows:T,wearables:p,moveDashboardSection:rt,onAddCustomDashboardSection:Lt,onUpdateCustomDashboardSection:ee,onRemoveCustomDashboardSection:Ye})]}):null,He?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 max-lg:gap-2 lg:grid-cols-2",children:[e.jsx(Ht,{id:"patient-storefront-theme",title:"Storefront theme",description:"Checkout and success screens.",icon:Zm,accentColor:i,saving:J,bodyClassName:"p-4",children:e.jsx(wa,{options:St.checkoutTheme.options,value:Z.checkoutTheme.layoutPreset,surface:St.checkoutTheme.surface,accentColor:i,cornerStyle:Z.portalChrome.cornerStyle,editable:!0,onSelect:re=>Y("checkoutTheme",re),onEdit:()=>xe("checkoutTheme")})}),e.jsx(Ht,{id:"patient-login-theme",title:"Login theme",description:"Client-branded patient sign-in.",icon:eu,accentColor:i,saving:ge,bodyClassName:"p-4",children:e.jsx(wa,{options:St.loginTheme.options,value:Z.loginTheme.layoutPreset,surface:St.loginTheme.surface,accentColor:i,cornerStyle:Z.portalChrome.cornerStyle,theme:Z.loginTheme,branding:n,editable:!0,onSelect:re=>Y("loginTheme",re),onEdit:()=>xe("loginTheme")})}),e.jsx(Ht,{id:"patient-email-theme",title:"Email theme",description:"Patient-facing email layout.",icon:Ar,accentColor:i,saving:ye,bodyClassName:"p-4",children:e.jsx(wa,{options:St.emailTheme.options,value:Z.emailTheme.layoutPreset,surface:St.emailTheme.surface,accentColor:i,cornerStyle:Z.portalChrome.cornerStyle,editable:!0,onSelect:re=>Rt("layoutPreset",re),onEdit:()=>xe("emailTheme")})}),e.jsx(Ht,{id:"patient-form-theme",title:"Form theme",description:"Public form and assessment intake layout.",icon:Yl,accentColor:i,saving:Re,bodyClassName:"p-4",children:e.jsx(wa,{options:St.formTheme.options,value:Z.formTheme.layoutPreset,surface:St.formTheme.surface,accentColor:i,cornerStyle:Z.portalChrome.cornerStyle,theme:Z.formTheme,branding:n,editable:!0,onSelect:re=>Y("formTheme",re),onEdit:()=>xe("formTheme")})})]}),e.jsx(Ca,{open:ae==="checkoutTheme",onOpenChange:re=>S("checkoutTheme",re),meta:St.checkoutTheme,theme:Z.checkoutTheme,themeKey:"checkoutTheme",accentColor:i,branding:n,clientId:r,cornerStyle:Z.portalChrome.cornerStyle,onThemeSave:de,currentUserEmail:(W==null?void 0:W.email)||(H==null?void 0:H.email)||"",saving:J}),e.jsx(Ca,{open:ae==="loginTheme",onOpenChange:re=>S("loginTheme",re),meta:St.loginTheme,theme:Z.loginTheme,themeKey:"loginTheme",accentColor:i,branding:n,clientId:r,cornerStyle:Z.portalChrome.cornerStyle,onThemeSave:de,currentUserEmail:(W==null?void 0:W.email)||(H==null?void 0:H.email)||"",saving:ge}),e.jsx(Ca,{open:ae==="emailTheme",onOpenChange:re=>S("emailTheme",re),meta:St.emailTheme,theme:Z.emailTheme,themeKey:"emailTheme",accentColor:i,branding:n,clientId:r,cornerStyle:Z.portalChrome.cornerStyle,onThemeSave:de,onSendTestEmail:ve,currentUserEmail:(W==null?void 0:W.email)||(H==null?void 0:H.email)||"",saving:ye}),e.jsx(Ca,{open:ae==="formTheme",onOpenChange:re=>S("formTheme",re),meta:St.formTheme,theme:Z.formTheme,themeKey:"formTheme",accentColor:i,branding:n,clientId:r,cornerStyle:Z.portalChrome.cornerStyle,onThemeSave:de,currentUserEmail:(W==null?void 0:W.email)||(H==null?void 0:H.email)||"",saving:Re})]}):null,Qe?e.jsx(zx,{ExperienceSurfaceCard:Ht,accentColor:i,isSavingNotifications:U,onPatientNotificationChange:L,patientNotifications:y,visibleNotificationRows:Vm}):null]})}const el=400;function tl(t){try{const s=new URL(t);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}}function gs(t,s){return JSON.stringify(t)===JSON.stringify(s)}function vp(t){if(!Array.isArray(t))return[];const s=new Set;return t.map(a=>{const i=String((a==null?void 0:a.id)||"").trim();if(!i||s.has(i))return null;s.add(i);const n=(a==null?void 0:a.target)===lt.FORM?lt.FORM:lt.URL,r=n===lt.FORM;return{id:i,label:String((a==null?void 0:a.label)||"").slice(0,40),target:n,url:r?"":String((a==null?void 0:a.url)||""),icon:ss(a==null?void 0:a.icon),openMode:(a==null?void 0:a.openMode)==="new_tab"?"new_tab":"embed",sectionId:String((a==null?void 0:a.sectionId)||"").trim()||null,enabled:(a==null?void 0:a.enabled)!==!1,...r?{formId:String((a==null?void 0:a.formId)||"").trim(),notifyEmails:Pr(a==null?void 0:a.notifyEmails)}:{}}}
318).filter(Boolean)}function Np(t){if(!Array.isArray(t))return[];const s=new Set;return t.map(a=>{const i=String((a==null?void 0:a.id)||"").trim();return!i||s.has(i)?null:(s.add(i),{id:i,label:String((a==null?void 0:a.label)||"").slice(0,40),icon:ss(a==null?void 0:a.icon),enabled:(a==null?void 0:a.enabled)!==!1})}).filter(Boolean)}function jp(t,s="Clients"){const a=fa(s),i=Br(s),n=a.map(d=>d.id),r=new Set(a.filter(d=>d.required).map(d=>d.id)),l=Np(t==null?void 0:t.sections),c=new Set(l.map(d=>d.id)),u=vp(t==null?void 0:t.customItems).map(d=>({...d,sectionId:c.has(d.sectionId)?d.sectionId:null})),m=new Map(u.map(d=>[as(d.id),d])),h=new Map(l.map(d=>[ns(d.id),d])),g=new Set(n),y=Array.isArray(t==null?void 0:t.enabledItems)?[...t.enabledItems]:[...i];(t==null?void 0:t.supportEnabled)===!0&&n.includes("support")&&!y.includes("support")&&y.push("support");const p=[];return y.forEach(d=>{const x=m.get(d),f=h.get(d);(g.has(d)||(x==null?void 0:x.enabled)===!0&&!x.sectionId||(f==null?void 0:f.enabled)===!0)&&!p.includes(d)&&p.push(d)}),n.forEach(d=>{r.has(d)&&!p.includes(d)&&p.push(d)}),u.forEach(d=>{const x=as(d.id);d.enabled&&!d.sectionId&&!p.includes(x)&&p.push(x)}),l.forEach(d=>{const x=ns(d.id);d.enabled&&!p.includes(x)&&p.push(x)}),{enabledItems:p,customItems:u,sections:l,itemOverrides:Ql(t==null?void 0:t.itemOverrides,n)}}function kp(t,s){if(!s||typeof s!="object")return t;const a=Object.fromEntries(Object.entries(s).filter(([,i])=>i!==void 0));return{...t||{},...a}}function oc({mode:t="experience",brandingOverride:s=null,tenantCollection:a="Clients",tenantId:i=null}){const{clientData:n,userDoc:r}=Se(),{branding:l}=Ce(),c=i||(a==="Businesses"?r==null?void 0:r.businessId:r==null?void 0:r.clientId),u=o.useMemo(()=>
318fa(a),[a]),m=o.useMemo(()=>u.map(T=>T.id),[u]),h=o.useMemo(()=>new Set(u.filter(T=>T.required).map(T=>T.id)),[u]),g=o.useCallback(T=>jp(T,a),[a]),[y,p]=o.useState(!0),[d,x]=o.useState(null),[f,C]=o.useState({patientSidebar:{enabledItems:Br("Clients"),customItems:[],sections:[],itemOverrides:{}},experienceConfig:Le(),patientOrderRoadmap:Td,patientNotifications:aa(),wearables:{enabled:!1},postVisitRedirectEnabled:!1,postVisitRedirectUrl:""}),[N,v]=o.useState(null),k=kp(l,s),P=(k==null?void 0:k.accentColor)||je,A=o.useRef(f),E=o.useRef(N),z=o.useRef({}),q=o.useRef(null);o.useEffect(()=>{A.current=f},[f]),o.useEffect(()=>{E.current=N},[N]);const[R,O]=o.useState([]),[j,L]=o.useState("idle");o.useEffect(()=>{if(!c||a!=="Clients"||t==="themes"){O([]),L("idle");return}let T=!1;return L("loading"),(async()=>{try{const $=await wo(Xe(ce,"Clients",c,"Forms"));if(T)return;const S=$.docs.map(Q=>({id:Q.id,...Q.data()||{}})).filter(Q=>Q.status==="active"&&["intake","consent"].includes(Q.formType)).map(Q=>({value:Q.id,label:String(Q.name||"Untitled form"),formType:Q.formType})).sort((Q,Y)=>Q.label.localeCompare(Y.label));O(S),L("ready")}catch($){if(T)return;console.error("Error loading client forms for sidebar links:",$),O([]),L("error")}})(),()=>{T=!0}},[t,a,c]),o.useEffect(()=>{if(!c){p(!1);return}const T=qe(he(ce,a,c),$=>{var Y;const S=$.exists()?$.data():{},Q={patientSidebar:g(S==null?void 0:S.patientSidebar),experienceConfig:Le(S==null?void 0:S.experienceConfig),patientOrderRoadmap:En(S==null?void 0:S.patientOrderRoadmap),patientNotifications:aa(S==null?void 0:S.patientNotifications),wearables:{enabled:((Y=S==null?void 0:S.wearables)==null?void 0:Y.enabled)===!0},postVisitRedirectEnabled:(S==null?void 0:S.postVisitRedirectEnabled)===!0,postVisitRedirectUrl:typeof(S==null?void 0:S.postVisitRedirectUrl)=="string"?S.postVisitRedirectUrl:""};C(Q),v(Q),p(!1)},$=>{console.error("Error loading client experience settings:",$),I.error("Unable to load patient experience settings."),p(!1)});return()=>T()},[a,c]);const b=o.useCallback(async(T,$,{silent:S=!1}={})=>{if(!c)return;const Q=T==="experienceConfig"?Le($):T==="patientOrderRoadmap"?En($):$;try{const Y=T==="experienceConfig"?q.current||"experienceConfig":T;x(Y);const de={[T]:Q,updatedAt:Pe()};return await Fe(he(ce,a,c),de),v(ve=>({...ve,[T]:Q})),S||I.success("Patient experience updated"),!0}catch(Y){return console.error(`Error updating ${T}:`,Y),I.error("Unable to update patient experience. Please try again."),C(de=>{var ve;return{...de,[T]:(ve=E.current)==null?void 0:ve[T]}}),!1}finally{q.current=null,x(null)}},[a,c]),w=o.useCallback(T=>{var Y,de,ve;const $=z.current[T];$&&(clearTimeout($),delete z.current[T]);const S=(Y=A.current)==null?void 0:Y[T],Q=(de=E.current)==null?void 0:de[T];if(S===void 0||gs(S,Q))return Promise.resolve();if(T==="postVisitRedirectUrl"){const Ee=((ve=A.current)==null?void 0:ve.postVisitRedirectEnabled)===!0,Oe=String(S||"");if(Ee&&Oe&&!tl(Oe))return Promise.resolve()}return b(T,S,{silent:!0})},[b]),F=o.useCallback((T,$=0)=>{if(y||!E.current)return;const S=z.current[T];S&&clearTimeout(S);const Q=()=>{var ve,Ee,Oe;delete z.current[T];const Y=(ve=A.current)==null?void 0:ve[T],de=(Ee=E.current)==null?void 0:Ee[T];if(!(Y===void 0||gs(Y,de))){if(T==="postVisitRedirectUrl"){const nt=((Oe=A.current)==null?void 0:Oe.postVisitRedirectEnabled)===!0,ze=String(Y||"");if(nt&&ze&&!tl(ze))return}b(T,Y,{silent:!0})}};if($>0){z.current[T]=setTimeout(Q,$);return}Q()},[y,b]),M=o.useCallback(()=>{const T=new Set([...Object.keys(z.current),"experienceConfig","postVisitRedirectUrl"]);return Promise.all([...T].map($=>w($)))},[w]);o.useEffect(()=>()=>{Object.values(z.current).forEach(T=>clearTimeout(T))},[]);const W=!y&&N!==null;o.useEffect(()=>{!W||gs(f.patientSidebar,N.patientSidebar)||F("patientSidebar",0)},[f.patientSidebar,N==null?void 0:N.patientSidebar,W,F]),o.useEffect(()=>{!W||gs(f.experienceConfig,N.experienceConfig)||F("experienceConfig",el)},[f.experienceConfig,N==null?void 0:N.experienceConfig,W,F]),o.useEffect(()=>{!W||gs(f.patientOrderRoadmap,N.patientOrderRoadmap)||F("patientOrderRoadmap",0)},[f.patientOrderRoadmap,N==null?void 0:N.patientOrderRoadmap,W,F]),o.useEffect(()=>{!W||gs(f.patientNotifications,N.patientNotifications)||F("patientNotifications",0)},[f.patientNotifications,N==null?void 0:N.patientNotifications,W,F]),o.useEffect(()=>{!W||gs(f.wearables,N.wearables)||F("wearables",0)},[f.wearables,N==null?void 0:N.wearables,W,F]),o.useEffect(()=>{!W||f.postVisitRedirectEnabled===N.postVisitRedirectEnabled||F("postVisitRedirectEnabled",0)},[f.postVisitRedirectEnabled,N==null?void 0:N.postVisitRedirectEnabled,W,F]),o.useEffect(()=>{!W||f.postVisitRedirectUrl===N.postVisitRedirectUrl||F("postVisitRedirectUrl",el)},[f.postVisitRedirectEnabled,f.postVisitRedirectUrl,N==null?void 0:N.postVisitRedirectUrl,W,F]);function H(T,$){h.has(T)&&$===!1||C(S=>{const Q=g(S.patientSidebar);let Y=[...Q.enabledItems];if($&&!Y.includes(T)){const de=m.indexOf(T),ve=m.slice(de+1).find(Ee=>Y.includes(Ee));ve?Y.splice(Y.indexOf(ve),0,T):Y.push(T)}else $||(Y=Y.filter(de=>de!==T));return h.forEach(de=>{Y.includes(de)||Y.push(de)}),{...S,patientSidebar:g({...Q,enabledItems:Y})}})}function ae(T,$){m.includes(T)&&C(S=>{var ze;const Q=g(S.patientSidebar),Y={...Q.itemOverrides},de=String(($==null?void 0:$.label)||"").trim(),ve=String(($==null?void 0:$.description)||"").trim(),Ee=String(($==null?void 0:$.icon)||"").trim(),Oe=((ze=u.find(pt=>
318pt.id===T))==null?void 0:ze.icon)||"",nt=Ee===Oe?"":Ee;return!de&&!ve&&!nt?delete Y[T]:Y[T]={label:de,description:ve,icon:nt},{...S,patientSidebar:g({...Q,itemOverrides:Y})}})}function xe(T,$){C(S=>{const Q=g(S.patientSidebar),Y=[...Q.enabledItems],de=Y.indexOf(T);if(de===-1)return S;const ve=$==="up"?de-1:de+1;if(ve<0||ve>=Y.length)return S;const[Ee]=Y.splice(de,1);return Y.splice(ve,0,Ee),{...S,patientSidebar:{...Q,enabledItems:Y}}})}function Ae(T){C($=>{const S=g($.patientSidebar),Q=[...S.customItems,T],Y=String((T==null?void 0:T.sectionId)||"").trim();return{...$,patientSidebar:g({...S,enabledItems:Y?S.enabledItems:[...S.enabledItems,as(T.id)],customItems:Q})}})}function se(T,$,S){const Q=$&&typeof $=="object"?$:{[$]:S};C(Y=>{const de=g(Y.patientSidebar),ve=de.customItems.map(Ee=>Ee.id===T?{...Ee,...Q}:Ee);return{...Y,patientSidebar:g({...de,customItems:ve})}})}function Z(T){C($=>{const S=g($.patientSidebar),Q=as(T);return{...$,patientSidebar:g({...S,enabledItems:S.enabledItems.filter(Y=>Y!==Q),customItems:S.customItems.filter(Y=>Y.id!==T)})}})}function fe(T){C($=>{const S=g($.patientSidebar),Q=[...S.sections,T];return{...$,patientSidebar:g({...S,enabledItems:[...S.enabledItems,ns(T.id)],sections:Q})}})}function J(T,$,S){C(Q=>{const Y=g(Q.patientSidebar),de=Y.sections.map(ve=>ve.id===T?{...ve,[$]:S}:ve);return{...Q,patientSidebar:g({...Y,sections:de})}})}function ge(T){C($=>{const S=g($.patientSidebar),Q=ns(T);return{...$,patientSidebar:g({...S,enabledItems:S.enabledItems.filter(Y=>Y!==Q),customItems:S.customItems.map(Y=>Y.sectionId===T?{...Y,sectionId:null}:Y),sections:S.sections.filter(Y=>Y.id!==T)})}})}function ye(T,$={}){$!=null&&$.savingScope&&(q.current=$.savingScope),C(S=>({...S,experienceConfig:Le(typeof T=="function"?T(S.experienceConfig):T)}))}function Re(T){C($=>({...$,patientOrderRoadmap:En({...$.patientOrderRoadmap,...typeof T=="string"?{variant:T}:T})}))}async function G(T,$={}){var ve;const S=z.current.experienceConfig;S&&(clearTimeout(S),delete z.current.experienceConfig),$!=null&&$.savingScope&&(q.current=$.savingScope);const Q=(ve=A.current)==null?void 0:ve.experienceConfig,Y=Le(typeof T=="function"?T(Q):T),de=await b("experienceConfig",Y);return de&&C(Ee=>({...Ee,experienceConfig:Y})),de}function U(T,$){C(S=>{var Q;return{...S,patientNotifications:{...S.patientNotifications,[T]:$(((Q=S.patientNotifications)==null?void 0:Q[T])||{})}}})}function V(T,$){C(S=>({...S,wearables:{...S.wearables||{},[T]:$}}))}function D(T,$){C(S=>({...S,[T]:$}))}return!y&&!c?null:y?e.jsx("div",{className:"space-y-10 max-lg:space-y-5",children:Array.from({length:t==="themes"?1:4}).map((T,$)=>e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsx(ue,{className:"h-6 w-40 max-lg:h-4 max-lg:w-28"}),e.jsx(ue,{className:"h-4 w-full max-w-2xl max-lg:h-3"}),e.jsx(ue,{className:"h-36 w-full rounded-xl max-lg:h-24"})]},$))}):e.jsxs("div",{className:"space-y-6 max-lg:space-y-3",children:[e.jsx(yp,{accentColor:P,branding:k,clientId:c,tenantCollection:a,experienceConfig:f.experienceConfig,patientOrderRoadmap:f.patientOrderRoadmap,patientOrderRoadmapOptions:Ad,customFormularyTerminalStepOptions:Pd,patientSidebar:f.patientSidebar,patientNotifications:f.patientNotifications,wearables:f.wearables,postVisitRedirectEnabled:f.postVisitRedirectEnabled,postVisitRedirectUrl:f.postVisitRedirectUrl,savingField:d,onTogglePatientSidebarItem:H,onUpdatePatientSidebarItemOverride:ae,onMovePatientSidebarItem:xe,onAddCustomPatientSidebarItem:Ae,onUpdateCustomPatientSidebarItem:se,clientFormOptions:R,clientFormsStatus:j,reviewOnlyTenant:Jl(n),onRemoveCustomPatientSidebarItem:Z,onAddCustomPatientSidebarSection:fe,onUpdateCustomPatientSidebarSection:J,onRemoveCustomPatientSidebarSection:ge,onExperienceConfigChange:ye,onExperienceConfigSave:G,onPatientOrderRoadmapChange:Re,onPatientNotificationChange:U,onWearablesChange:V,onPostVisitRedirectChange:D,onFlushPendingSaves:M,mode:t}),t!=="themes"?e.jsx(zo,{accentColor:P}):null]})}function wp(t){let s={...t},a=null;const i={},n={};return{read:()=>({draft:s,baseline:a}),edit(r){const l=typeof r=="function"?r(s):r;
318for(const c of Object.keys(l))Object.is(l[c],s[c])||(i[c]=(i[c]||0)+1);s=l},snapshot(r){const l={...r};for(const c of Object.keys(s))a&&!Object.is(s[c],a[c])&&(l[c]=s[c]);a={...r},s=l},beginSave(r){return n[r]=(n[r]||0)+1,{field:r,revision:i[r]||0,sequence:n[r]}},isCurrent(r){return n[r.field]===r.sequence&&(i[r.field]||0)===r.revision},acknowledge(r,l){const{field:c,revision:u,sequence:m}=r;n[c]===m&&(a={...a,[c]:l},(i[c]||0)===u&&(s={...s,[c]:l}))}}}function Cp(t){const s=o.useRef(null);s.current||(s.current=wp(t));const[,a]=o.useReducer(r=>r+1,0),i=s.current,n=o.useMemo(()=>({setDraft:r=>{i.edit(r),a()},snapshot:r=>{i.snapshot(r),a()},isCurrent:r=>i.isCurrent(r),beginSave:r=>i.beginSave(r),acknowledge:(r,l)=>{i.acknowledge(r,l),a()}}),[i]);return{...i.read(),...n}}const Sp=Fo({manageFunctionName:"manageClient",idField:"clientId",tenantKey:"Client"}),Ep=Mo({manageFunctionName:"manageClient",idField:"clientId",tenantKey:"Client"}),Tp="mx-auto aspect-square w-full max-w-[11rem] shrink-0",Pp="min-h-0 w-full flex-1",Ap=/^[a-z0-9-]+$/;function sl({accentColor:t,loading:s=!1,children:a}){return e.jsx(tt,{id:"client-business-brand",title:"Business brand",description:"Logo, colors, typography, and the public-facing brand identity patients see.",icon:Ja,accentColor:t,loading:s,bodyClassName:"space-y-6 p-5 max-lg:space-y-3",children:a})}function ks({htmlFor:t,children:s,description:a,id:i}){return e.jsxs("div",{className:"flex min-h-5 items-center gap-1.5 max-lg:gap-1",children:[e.jsx(oe,{htmlFor:t,id:i,className:"text-sm font-medium text-content-primary max-lg:text-xs",children:s}),a?e.jsx(Wt,{delayDuration:150,children:e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex size-4 items-center justify-center rounded-full text-slate-400 transition-colors hover:text-slate-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-300 dark:hover:text-slate-200","aria-label":`${s} info`,children:e.jsx(Ds,{className:"size-3.5 max-lg:size-3","aria-hidden":!0})})}),e.jsx(os,{className:"max-w-xs text-xs leading-relaxed",children:a})]})}):null]})}function Ip(t){const s=to(t);return s?tr(s):""}function Rp(){const{userDoc:t}=Se();return e.jsx(Lp,{clientId:t==null?void 0:t.clientId},(t==null?void 0:t.clientId)||"none")}function Lp({clientId:t}){const s=o.useRef(!0);o.useEffect(()=>(s.current=!0,()=>{s.current=!1}),[]);const[a,i]=o.useState(!0),{draft:n,baseline:r,setDraft:l,snapshot:c,beginSave:u,acknowledge:m,isCurrent:h}=Cp({displayName:"",website:"",supportEmail:"",phoneNumber:"",iconUrl:"",logoUrl:"",logoDisplaySize:"medium",accentColor:je,secondaryColor:"",backgroundColor:"",sidebarHeaderBackgroundColor:"",enableVirtualBackground:!1,logoWhiteBackground:!1,headerFont:null,appThemeMode:"light",customDomain:null,emailDomain:null,brandingSlug:""}),[g,y]=o.useState(!1),p=n.iconUrl||null,d=n.logoUrl||null,[x,f]=o.useState(null),[C,N]=o.useState(!1),[v,k]=o.useState(null),[P,A]=o.useState(""),[E,z]=o.useState(!1),q=n.accentColor||je;o.useEffect(()=>{if(!t){i(!1);return}const G=he(ce,"Clients",t),U=qe(G,V=>{if(V.exists()){const D=V.data(),T=!!D.virtualBackgroundUrl,$={displayName:D.displayName||"",website:D.website||"",supportEmail:D.supportEmail||"",phoneNumber:Ip(D.phoneNumber),iconUrl:D.iconUrl||"",logoUrl:D.logoUrl||"",logoDisplaySize:D.logoDisplaySize||"medium",accentColor:D.accentColor||D.primaryColor||je,secondaryColor:D.secondaryColor||"",backgroundColor:D.backgroundColor||"",sidebarHeaderBackgroundColor:D.sidebarHeaderBackgroundColor||"",enableVirtualBackground:typeof D.enableVirtualBackground=="boolean"?D.enableVirtualBackground:T,logoWhiteBackground:D.logoWhiteBackground||!1,headerFont:D.headerFont||null,appThemeMode:D.appThemeMode==="dark"?"dark":"light",customDomain:D.customDomain||null,emailDomain:D.emailDomain||null,brandingSlug:D.brandingSlug||""};c($),A(D.virtualBackgroundUrl||"")}i(!1)},V=>{console.error("Error fetching client:",V),I.error("Unable to load branding data. Please try again."),i(!1)});return()=>U()},[t,c]);function R(G){return G||n.backgroundColor||n.accentColor||je}async function O(G={}){const{silent:U=!1,logoUrlOverride:V=null,backgroundColorOverride:D=null}
318=G,T=V||n.logoUrl,$=R(D);if(!t)return!1;if(!T)return U||I.error("Upload a client logo before generating a virtual background"),!1;try{N(!0);const S=await ql(T,$),Q=await Id(t,S);return s.current?(await Fe(he(ce,"Clients",t),{virtualBackgroundUrl:Q,updatedAt:Pe()}),A(Q),U||I.success("Virtual background generated"),!0):!1}catch(S){return console.error("Error generating virtual background:",{message:S==null?void 0:S.message,clientId:t,hasLogoUrl:!!T,logoOrigin:(()=>{try{return new URL(T).origin}catch{return"invalid-url"}})()}),U||I.error((S==null?void 0:S.message)||"Unable to generate virtual background. Please try again."),!1}finally{N(!1)}}async function j(G,U,V={}){const{showSuccessToast:D=!0}=V;if(!t)return;const T=u(G);try{k(G);const $=he(ce,"Clients",t),S={[G]:U,updatedAt:Pe()};return G==="accentColor"&&(S.primaryColor=U),await Fe($,S),m(T,U),G==="headerFont"&&s.current&&so(U||null),D&&I.success("Branding updated"),!0}catch($){return console.error(`Error updating ${G}:`,$),I.error(`Unable to update ${G}. Please try again.`),!1}finally{k(null)}}function L(G){l(U=>({...U,[G]:r[G]}))}async function b(){if(!t)return!1;const G=String(n.phoneNumber||"").trim(),U=G?to(G):null;if(G&&!U)return I.error("Please enter a valid US phone number."),!1;const V=U?tr(U):"",D=u("phoneNumber");try{return k("phoneNumber"),await Fe(he(ce,"Clients",t),{phoneNumber:U,updatedAt:Pe()}),m(D,V),I.success("Branding updated"),!0}catch(T){return console.error("Error updating phoneNumber:",T),I.error("Unable to update phone number. Please try again."),!1}finally{k(null)}}function w(G){l(U=>({...U,...Uo(U,G)}))}const F=o.useRef(n);F.current=n;const M=o.useRef(j);M.current=j;const W=o.useRef(O);W.current=O;const H=o.useCallback(async(G,U)=>{const V=_o(G,U);if(V===null||(V!==U&&l($=>$[G]===V?$:{...$,[G]:V}),!await M.current(G,V,{showSuccessToast:!1})))return;const T=F.current;T.enableVirtualBackground&&(G==="accentColor"||G==="backgroundColor")&&await W.current({silent:!0,backgroundColorOverride:G==="backgroundColor"?V:T.backgroundColor||V})},[l]);Oo({formData:n,originalData:r,enabled:!a&&!!r,onSave:H});function ae(G){const{name:U,value:V}=G.target;l(D=>({...D,[U]:V}))}function xe(G){const U=G.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"");l(V=>({...V,brandingSlug:U}))}async function Ae({quiet:G=!1}={}){var D;if(!t){if(G)throw new Error("No client associated with your account");return!1}const U=String(n.brandingSlug||"").trim();if(U&&!Ap.test(U)){const T="Brand slug can only use lowercase letters, numbers, and dashes.";if(G)throw new Error(T);return I.error(T),!1}const V=u("brandingSlug");try{k("brandingSlug");const T=await rs("manageClient",{action:"setClientBrandingSlug",clientId:t,slug:U}),$=((D=T==null?void 0:T.data)==null?void 0:D.slug)||"";return m(V,$),G||I.success($?"Brand slug updated":"Brand slug removed"),!0}catch(T){console.error("Error updating brandingSlug:",T);const $=(T==null?void 0:T.message)||"Unable to update brand slug. Please try again.";if(G)throw new Error($);return I.error($),!1}finally{k(null)}}async function se(){g||(await Promise.all(ao.map(G=>Xa(G.value))),y(!0))}async function Z(G){const U=G==="__default__"?null:G;(U??null)!==((r==null?void 0:r.headerFont)??null)&&(l(V=>({...V,headerFont:U})),U&&Xa(U),await j("headerFont",U,{showSuccessToast:!1}))}async function fe(G){const U=G?"dark":"light";if(U===(r==null?void 0:r.appThemeMode)){l(V=>({...V,appThemeMode:U}));return}l(V=>({...V,appThemeMode:U})),await j("appThemeMode",U,{showSuccessToast:!1})}async function J(G,U){const V=u(G);try{f(G);const D=await Qa({file:U,brandType:"client",brandId:t,assetRole:G==="iconUrl"?"icon":"logo"});if(!h(V))return!1;const T=D.logoUrl;l(S=>({...S,[G]:T}));const $=await j(G,T);if(!$)throw new Error("Unable to save image. Please retry.");G==="logoUrl"&&$&&n.enableVirtualBackground&&await O({silent:!0,logoUrlOverride:T})}catch(D){throw console.error(`Error uploading ${G}:`,D),I.error(D.message||"Unable to upload image. Please try again."),D}finally{s.current&&f(null)}}async function ge(G){if(t)if(G==="iconUrl")l(U=>({...U,iconUrl:""})),await j("iconUrl","");else{A(""),l(D=>
318({...D,logoUrl:"",enableVirtualBackground:!1}));const U=u("logoUrl"),V=u("enableVirtualBackground");await Fe(he(ce,"Clients",t),{logoUrl:"",enableVirtualBackground:!1,virtualBackgroundUrl:"",updatedAt:Pe()}),m(U,""),m(V,!1),I.success("Branding updated")}}async function ye(G){const U=G===!0;if(U&&!n.logoUrl){I.error("Upload a client logo before enabling virtual background");return}if(l(T=>({...T,enableVirtualBackground:U})),!await j("enableVirtualBackground",U,{showSuccessToast:!1}))return;if(!U){I.success("Virtual background disabled");return}if(!await O({silent:!0})){l(T=>({...T,enableVirtualBackground:!1})),await j("enableVirtualBackground",!1,{showSuccessToast:!1}),I.error("Could not enable virtual background. Verify logo availability and try again.");return}I.success("Virtual background enabled")}function Re(G){G.target.closest("button, a, input, label")||v==="enableVirtualBackground"||C||ye(!n.enableVirtualBackground)}return t?e.jsxs("div",{className:"space-y-6 scroll-mt-24 max-lg:space-y-3",children:[a?e.jsxs(e.Fragment,{children:[e.jsxs(sl,{accentColor:q,loading:!0,children:[e.jsxs("div",{className:"grid grid-cols-1 gap-6 max-lg:gap-2.5 md:grid-cols-3 md:items-start",children:[e.jsx(ue,{className:"h-52 w-full rounded-xl max-lg:h-32"}),e.jsx(ue,{className:"h-52 w-full rounded-xl max-lg:h-32 md:col-span-2"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 max-lg:gap-2 md:grid-cols-2",children:[e.jsx(ue,{className:"h-10 w-full max-lg:h-8"}),e.jsx(ue,{className:"h-10 w-full max-lg:h-8"})]}),e.jsx(ue,{className:"h-10 w-full max-lg:h-8"}),e.jsx(ue,{className:"h-32 w-full rounded-lg max-lg:h-20"})]}),e.jsx(en,{id:"client-domain-management",accentColor:q,loading:!0,children:e.jsx(ue,{className:"h-40 w-full rounded-xl max-lg:h-24"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(sl,{accentColor:q,children:[e.jsxs("div",{className:"grid grid-cols-1 gap-6 max-lg:gap-2.5 md:grid-cols-3 md:items-start",children:[e.jsx("div",{className:"md:col-span-1",children:e.jsx(Os,{label:"Icon",description:"Used for the browser favicon and square brand placements. Upload a square crop.",cropTitle:"Crop Client Icon",cropDescription:"Position the image inside a square frame for favicon and other compact brand slots.",previewUrl:p,aspect:1,uploading:x==="iconUrl",accentColor:n.accentColor,onUpload:G=>J("iconUrl",G),onRemove:()=>ge("iconUrl"),previewFrameClassName:Tp,previewImageClassName:"h-full w-full",dropzoneClassName:"h-44",changeLabel:"Change Icon",emptyLabel:"Click or drag to upload icon"})}),e.jsx("div",{className:"md:col-span-2",children:e.jsx(Os,{label:"Logo",description:"Used in patient-facing pages and communications. Upload a wide 3:1 crop.",cropTitle:"Crop Client Logo",cropDescription:"Position the image inside a wide 3:1 frame for client branding and patient-facing pages.",previewUrl:d,aspect:3,uploading:x==="logoUrl",accentColor:n.accentColor,onUpload:G=>J("logoUrl",G),onRemove:()=>ge("logoUrl"),previewFrameClassName:Pp,previewImageClassName:"h-full w-full",dropzoneClassName:"aspect-[3/1] min-h-0",changeLabel:"Change Logo",emptyLabel:"Click or drag to upload logo",containerClassName:"p-3",showLightBackgroun
318d:n.logoWhiteBackground,secondaryActionLabel:`Size: ${Zl(n.logoDisplaySize)}`,onSecondaryAction:()=>{const G=Xl(n.logoDisplaySize);l(U=>({...U,logoDisplaySize:G})),j("logoDisplaySize",G)},onToggleLightBackground:d||n.logoUrl?()=>{const G=!n.logoWhiteBackground;l(U=>({...U,logoWhiteBackground:G})),j("logoWhiteBackground",G)}:void 0})})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 max-lg:gap-2 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsxs("div",{className:"flex min-h-5 items-center justify-between",children:[e.jsx(ks,{htmlFor:"displayName",children:"Brand name"}),n.displayName!==(r==null?void 0:r.displayName)&&e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5",onClick:()=>j("displayName",n.displayName),disabled:v==="displayName",style:{color:n.accentColor},children:v==="displayName"?e.jsx($e,{size:"xs"}):e.jsx(Ze,{className:"size-3"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5 text-red-600 hover:bg-red-50 hover:text-red-700",onClick:()=>L("displayName"),disabled:v==="displayName",children:e.jsx(Ft,{className:"size-3"})})]})]}),e.jsx(be,{id:"displayName",name:"displayName",placeholder:"Optional public-facing name",value:n.displayName,onChange:ae,className:"text-sm"})]}),e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ks,{htmlFor:"website",children:"Website"}),n.website!==(r==null?void 0:r.website)&&e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5",onClick:()=>j("website",n.website),disabled:v==="website",style:{color:n.accentColor},children:v==="website"?e.jsx($e,{size:"xs"}):e.jsx(Ze,{className:"size-3"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5 text-red-600 hover:bg-red-50 hover:text-red-700",onClick:()=>L("website"),disabled:v==="website",children:e.jsx(Ft,{className:"size-3"})})]})]}),e.jsx(be,{id:"website",name:"website",type:"url",placeholder:"https://example.com",value:n.website,onChange:ae,className:"text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 max-lg:gap-2 md:grid-cols-2 md:items-start",children:[e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ks,{htmlFor:"supportEmail",description:"Used as the reply-to contact for branded emails.",children:"Support email"}),n.supportEmail!==(r==null?void 0:r.supportEmail)&&e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5",onClick:()=>{const G=String(n.supportEmail||"").trim();if(G&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G)){I.error("Please enter a valid email address.");return}j("supportEmail",G)},disabled:v==="supportEmail",style:{color:n.accentColor},children:v==="supportEmail"?e.jsx($e,{size:"xs"}):e.jsx(Ze,{className:"size-3"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5 text-red-600 hover:bg-red-50 hover:text-red-700",onClick:()=>L("supportEmail"),disabled:v==="supportEmail",children:e.jsx(Ft,{className:"size-3"})})]})]}
318),e.jsx(be,{id:"supportEmail",name:"supportEmail",type:"email",placeholder:"[email protected]",value:n.supportEmail,onChange:ae,className:"text-sm"})]}),e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ks,{htmlFor:"phoneNumber",description:"Public contact phone shown with branding. Messaging is configured separately.",children:"Phone number"}),n.phoneNumber!==(r==null?void 0:r.phoneNumber)&&e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5",onClick:b,disabled:v==="phoneNumber",style:{color:n.accentColor},children:v==="phoneNumber"?e.jsx($e,{size:"xs"}):e.jsx(Ze,{className:"size-3"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5 text-red-600 hover:bg-red-50 hover:text-red-700",onClick:()=>L("phoneNumber"),disabled:v==="phoneNumber",children:e.jsx(Ft,{className:"size-3"})})]})]}),e.jsx(be,{id:"phoneNumber",name:"phoneNumber",type:"tel",placeholder:"(555) 123-4567",value:n.phoneNumber,onChange:G=>l(U=>({...U,phoneNumber:tr(G.target.value)})),className:"text-sm",autoComplete:"tel"})]})]}),e.jsxs("div",{className:"grid gap-4 max-lg:gap-2 lg:grid-cols-2 lg:items-start",children:[e.jsx(Po,{className:"space-y-3",title:"Header font",value:n.headerFont,savingField:v,onValueChange:Z,onOpenChange:G=>{G&&se()}}),e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5 lg:min-w-[17rem]",children:[e.jsx(ks,{id:"appThemeMode-label",description:"Controls the default theme for patient and client portal surfaces.",children:"Portal theme"}),e.jsx("div",{className:"grid grid-cols-2 rounded-full border border-subtle bg-slate-100 p-1 max-lg:p-0.5 dark:bg-slate-900/40",role:"group","aria-labelledby":"appThemeMode-label",children:[{key:"light",label:"Light"},{key:"dark",label:"Dark"}].map(G=>{const U=n.appThemeMode===G.key;return e.jsx("button",{type:"button","aria-pressed":U,disabled:v==="appThemeMode",onClick:()=>fe(G.key==="dark"),className:`min-h-9 rounded-full px-4 text-xs font-semibold transition-colors max-lg:min-h-8 max-lg:px-2.5 max-lg:text-2xs ${U?"text-white shadow-sm":"text-slate-600 hover:text-slate-950 dark:text-slate-300 dark:hover:text-white"} disabled:cursor-not-allowed disabled:opacity-70`,style:U?{backgroundColor:q}:void 0,children:G.label},G.key)})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 max-lg:gap-2.5 lg:grid-cols-2 lg:items-start",children:[e.jsx(Ao,{className:"space-y-4",title:"Brand colors",formData:n,savingField:v,lightenColor:eo,onPrimaryColorChange:w,onSecondaryColorChange:G=>l(U=>({...U,secondaryColor:G})),onBackgroundColorChange:G=>l(U=>({...U,backgroundColor:G})),onSidebarHeaderColorChange:G=>l(U=>({...U,sidebarHeaderBackgroundColor:G}))}),e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 max-lg:gap-2",children:[e.jsx("div",{className:"min-w-0 space-y-1 max-lg:space-y-0.5",children:e.jsx(ks,{description:"Creates a branded provider-video background from the client logo.",children:"Virtual background"})}),e.jsx(B,{type:"button",variant:"link",className:"h-auto shrink-0 px-0 text-xs font-medium text-blue-600 max-lg:text-2xs hover:text-blue-700 dark:text-blue-400",onClick:()=>z(!0),disabled:!n.logoUrl&&!P,children:"See example"})]}),e.jsx("div",{className:"cursor-pointer rounded-lg border border-subtle bg-surface-sunken p-3 transition-colors max-lg:p-2 hover:bg-slate-100/80 dark:hover:bg-slate-900/50",role:"button",tabIndex:0,onClick:Re,onKeyDown:G=>{G.key!=="Enter"&&G.key!==" "||(G.preventDefault(),!(v==="enableVirtualBackground"||C)&&ye(!n.enableVirtualBackground))},children:e.jsxs("div",{className:"flex items-center gap-3 max-lg:gap-2",children:[e.jsx("div",{className:"flex h-5 items-center",children:e.jsx(Me,{id:"enableVirtualBackground",checked:n.enableVirtualBackground,disabled:v==="enableVirtualBackground"||C,onCheckedChange:ye,onClick:G=>G.stopPropagation()})}),e.jsxs("div",{className:"min-w-0 space-y-1 max-lg:space-y-0.5",children:[e.jsx(oe,{htmlFor:"enableVirtualBackgroun
318d",className:"cursor-pointer text-sm text-slate-700 max-lg:text-xs dark:text-slate-200",children:"Enable provider video logo background"}),e.jsxs("p",{className:"text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:[n.logoUrl?"Shows a branded background during sync visits.":"Upload a client logo to enable this setting.",n.enableVirtualBackground&&e.jsxs(e.Fragment,{children:[" ",C?"Preparing branded video backgroundâ¦":P?"Branded video background is ready.":"Branded video background will be prepared automatically."]})]})]})]})})]})]})]}),e.jsx(oc,{mode:"themes",brandingOverride:{name:n.displayName||(r==null?void 0:r.displayName)||void 0,displayName:n.displayName||(r==null?void 0:r.displayName)||void 0,iconUrl:n.iconUrl||"",logoUrl:n.logoUrl||"",logoWhiteBackground:n.logoWhiteBackground,accentColor:n.accentColor,primaryColor:n.accentColor,secondaryColor:n.secondaryColor||"",backgroundColor:n.backgroundColor||"",sidebarHeaderBackgroundColor:n.sidebarHeaderBackgroundColor||"",headerFont:n.headerFont||null,appThemeMode:n.appThemeMode==="dark"?"dark":"light"}}),e.jsx(en,{id:"client-domain-management",accentColor:q,howItWorks:!0,children:e.jsx(tc,{tenantId:t,customDomain:n.customDomain,emailDomain:n.emailDomain,accentColor:q,customDomainApi:Sp,emailDomainApi:Ep,testIdPrefix:"client-domain",signInLink:{value:n.brandingSlug,savedValue:(r==null?void 0:r.brandingSlug)||"",onChange:xe,onSave:()=>Ae({quiet:!0}),onDiscard:()=>L("brandingSlug")}})})]}),e.jsx(ex,{open:E,onOpenChange:z,logoUrl:n.logoUrl||d||"",backgroundColor:n.backgroundColor||n.accentColor,virtualBackgroundUrl:P})]}):e.jsx("div",{className:"rounded-xl border border-subtle bg-surface-raised p-6 text-center max-lg:p-3",children:e.jsx("p",{className:"text-sm text-content-tertiary max-lg:text-xs",children:"No client associated with your account"})})}const Op=[{value:"0",label:"Disabled"},{value:"15",label:"15 minutes"},{value:"30",label:"30 minutes"},{value:"60",label:"1 hour"},{value:"120",label:"2 hours"},{value:"240",label:"4 hours"}],al={client:{collection:"Clients",idField:"clientId",label:"client",testPrefix:"client"},business:{collection:"Businesses",idField:"businessId",label:"business",testPrefix:"business"},providerNetwork:{collection:"ProviderNetworks",idField:"providerNetworkId",label:"provider network",testPrefix:"provider-network"}};function Mp(t,{clientData:s,businessData:a,providerNetwork:i}){return t==="client"?s:t==="business"?a:i}function Fp({tenantType:t="providerNetwork",tenantId:s=null,tenantData:a=null,showInactivityLogout:i=!1}){var L,b;const{userDoc:n,providerNetwork:r,clientData:l,businessData:c}=Se(),u=al[t]||al.providerNetwork,m=s||(n==null?void 0:n[u.idField])||null,h=a||Mp(t,{clientData:l,businessData:c,providerNetwork:r})||{},g=Ro(t),y=Za(h,"staff"),p=Za(h,"patient"),d=no(h),x=((b=(L=h==null?void 0:h.security)==null?void 0:L.inactivityLogout)==null?void 0:b.timeoutMinutes)||0,f=o.useMemo(()=>({staff:y,patient:p,timeoutMinutes:String(x)}),[y,p,x]),[C,N]=o.useState({staff:f.staff,patient:f.patient}),[v,k]=o.useState(f.timeoutMinutes),[P,A]=o.useState(()=>new Set),E=w=>P.has(w),z=P.has("mfa-staff")||P.has("mfa-patient");o.useEffect(()=>{z||N({staff:f.staff,patient:f.patient})},[f.staff,f.patient,z]),o.useEffect(()=>{k(f.timeoutMinutes)},[f.timeoutMinutes]);async function q(w,F){if(!m)return I.error("Unable to update security settings",{description:`Missing ${u.label} record.`}),!1;A(M=>new Set(M).add(F));try{return await Fe(he(ce,u.collection,m),{...w,updatedAt:Pe()}),I.success("Security settings updated"),!0}catch(M){return I.error("Unable to update security settings",{description:M.message||"Please try again."}),!1}finally{A(M=>{const W=new Set(M);return W.delete(F),W})}}async function R(w,F){const M=C[w]===!0,W={...C,[w]:F};N(W),await q(ro({audience:w,nextValue:F,currentSecurity:Lo(W)}),`mfa-${w}`)||N(ae=>({...ae,[w]:M}))}async function O(w){const F=v;k(w);const M=Number(w);await q({"security.inactivityLogout.timeoutMinutes":Number.isFinite(M)&&M>0?M:0},"timeout")||k(F)}const j=`${u.testPrefix}-inactivity`;return e.jsxs(xt,{className:"overflow-hidden border border-subtle dark:bg-slate-800",children:[e.jsx("div",{className:"border-b border-subtle bg-surface-sunken p-4 max-lg:p-2.5",children:e.jsxs("div",{className:"flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx(Ir,{className:"size-4 text-content-tertiary max-lg:size-3.5","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Security"}),e.jsxs("p",{className:"text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:["Controls apply to users logging in under this ",u.label,"."]})]})]})}),e.jsxs("div",{className:"space-y-4 p-4 max-lg:space-y-2.5 max-lg:p-2.5",children:[d&&g.length>1?e.jsx("p",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-bg)] p-3 text-xs leading-relaxed text-[var(--status-info-text)] max-lg:p-2.5 max-lg:text-2xs","data-testid":"text-settings-security-mfa-legacy-note",children:Io}):null,g.map(w=>{const F=`${u.testPrefix}-mfa-${w.audience}`;return e.jsxs("div",{className:"flex items-start justify-between gap-4 roun
318ded-lg border border-subtle bg-surface-raised p-4 max-lg:gap-2 max-lg:p-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{htmlFor:F,className:"text-sm font-medium text-content-primary max-lg:text-xs",children:w.label}),e.jsxs("p",{className:"text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:[w.description," Users set up and verify with an email code or an authenticator app."]})]}),e.jsx(it,{id:F,checked:C[w.audience]===!0,disabled:E(`mfa-${w.audience}`),onCheckedChange:M=>R(w.audience,M),"aria-label":`Toggle ${w.label.toLowerCase()}`,"data-testid":w.testId})]},w.audience)}),i?e.jsxs("div",{className:"grid gap-3 rounded-lg border border-subtle bg-surface-raised p-4 max-lg:gap-1.5 max-lg:p-2.5 sm:grid-cols-[1fr_220px] sm:items-center",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{htmlFor:j,className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Timed logout after inactivity"}),e.jsx("p",{className:"text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"Activity in any open tab keeps the session active."})]}),e.jsxs(yt,{value:v,onValueChange:O,disabled:E("timeout"),children:[e.jsx(vt,{id:j,"aria-label":"Timed logout after inactivity","data-testid":"select-settings-security-inactivity",children:e.jsx(Nt,{})}),e.jsx(jt,{children:Op.map(w=>e.jsx(st,{value:w.value,children:w.label},w.value))})]})]}):null]})]})}function zp({open:t,onOpenChange:s,apiKey:a="",clientId:i="",shareableDocsUrl:n=""}){return e.jsx(io,{open:t,onOpenChange:s,children:e.jsxs(lo,{className:"flex h-[calc(100dvh-1rem)] min-h-0 max-h-none w-[calc(100vw-1rem)] max-w-7xl flex-col overflow-hidden rounded-xl border border-subtle bg-slate-100 p-0 text-content-primary dark:bg-slate-900 sm:h-[92vh] sm:max-h-[92vh] sm:w-[calc(100vw-2rem)]",style:{display:"flex",flexDirection:"column"},children:[e.jsxs(oo,{className:"shrink-0 border-b border-subtle px-4 pb-3 pt-4 max-[1024px]:space-y-1 max-[1024px]:px-3 max-[1024px]:pb-2 max-[1024px]:pt-3 sm:px-6",children:[e.jsx(co,{className:"max-[1024px]:text-base max-[1024px]:leading-tight",children:"GEN Health Developer Docs"}),e.jsx(mo,{className:"max-[1024px]:text-xs max-[1024px]:leading-snug",children:"General server-side API, hosted checkout, and SDK guidance."}),n?e.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"w-fit break-all text-sm font-medium text-blue-600 underline-offset-4 max-lg:text-xs hover:underline dark:text-blue-400",children:"Open public API docs"}):null]}),e.jsx("div",{className:"min-h-0 h-full flex-1 overflow-hidden px-4 pb-4 pt-3 max-lg:px-2 max-lg:pb-2 max-lg:pt-2 sm:px-6 sm:pb-6 sm:pt-4",children:e.jsx(tu,{manageWebhooks:!0,apiKey:a,clientId:i},i)})]})})}function cc({value:t=null,onChange:s,disabled:a=!1}){const{branding:i}=Ce(),n=(i==null?void 0:i.accentColor)||je,r=!Array.isArray(t),[l,c]=o.useState(""),u=o.useMemo(()=>new Set(r?Cs:da(t)),[r,t]),m=o.useMemo(()=>{const d=l.trim().toLowerCase();return d?ir.map(x=>({...x,events:x.events.filter(f=>[f.label,f.event,f.description,x.label].some(C=>String(C||"").toLowerCase().includes(d)))})).filter(x=>x.events.length>0):ir},[l]);function h(d){s(da(Array.from(d)))}function g(d,x){const f=new Set(u);x?f.add(d):f.delete(d),h(f)}function y(d,x){const f=new Set(u);d.forEach(C=>{x?f.add(C.event):f.delete(C.event)}),h(f)}const p=d=>K("rounded-full px-3 py-1 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 dark:focus-visible:ring-slate-500","max-lg:px-2 max-lg:text-2xs",d?"text-white":"text-content-secondary hover:text-slate-900 dark:hover:text-slate-100");return e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 max-lg:flex-nowrap max-lg:gap-1.5",children:[e.jsxs("div",{className:"inline-flex shrink-0 rounded-full border border-subtle bg-surface-raised p-0.5",role:"group","aria-label":"Event subscription mode",children:[e.jsx("button",{type:"button","aria-pressed":r,disabled:a,className:p(r),style:r?{backgroundColor:n}:void 0,onClick:()=>s(null),"data-testid":"button-client-webhooks-events-all",children:"All events"}),e.jsx("button",{type:"button","aria-pressed":!r,disabled:a,className:p(!r),style:r?void 0:{backgroundColor:n},onClick:()=>{r&&s([...Cs])},"data-testid":"button-client-webhooks-events-selected",children:"Selected events"})]}),r?null:e.jsxs("span",{className:"text-xs tabular-nums text-content-tertiary max-lg:shrink-0 max-lg:text-2xs",children:[u.size," of ",Cs.length," selected"]})]}),r?e.jsx("p",{className:"text-xs leading-relaxed text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:"Every current and future event is delivered to this endpoint."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 max-lg:flex-nowrap max-lg:gap-1 max-lg:[&>*]:shrink-0",children:[e.jsxs("div",{className:"relative min-w-0 flex-1 max-lg:!shrink",children:[e.jsx(pn,{className:"pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-slate-400"}
318),e.jsx(be,{value:l,onChange:d=>c(d.target.value),placeholder:"Search events","aria-label":"Search webhook events",disabled:a,className:"h-8 pl-8 text-xs max-lg:h-7","data-testid":"input-client-webhooks-event-search"})]}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",className:"h-8 px-2 text-xs max-lg:h-7 max-lg:px-1.5 max-lg:text-2xs",disabled:a||u.size===Cs.length,onClick:()=>s([...Cs]),children:"Select all"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",className:"h-8 px-2 text-xs max-lg:h-7 max-lg:px-1.5 max-lg:text-2xs",disabled:a||u.size===0,onClick:()=>s([]),children:"Clear"})]}),e.jsxs("div",{className:"max-h-80 space-y-3 overflow-y-auto pr-1 max-lg:max-h-64 max-lg:space-y-2",children:[m.length===0?e.jsx("p",{className:"px-1 py-4 text-center text-xs text-content-tertiary max-lg:py-2.5 max-lg:text-2xs",children:"No webhook events match your search."}):null,m.map(d=>{const x=d.events.every(f=>u.has(f.event));return e.jsxs("div",{className:"overflow-hidden rounded-lg border border-subtle",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle bg-surface-sunken px-3 py-2 max-lg:gap-2 max-lg:px-2 max-lg:py-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-800 max-lg:text-2xs dark:text-slate-100",children:d.label}),e.jsx("button",{type:"button",disabled:a,onClick:()=>y(d.events,!x),className:"text-xs font-medium text-content-tertiary transition-colors max-lg:shrink-0 max-lg:text-2xs hover:text-slate-700 dark:hover:text-slate-200","data-testid":`button-client-webhooks-group-${d.id}-select-all`,children:x?"Clear all":"Select all"})]}),e.jsx("div",{className:"divide-y divide-slate-200 bg-surface-raised dark:divide-slate-700",children:d.events.map(f=>e.jsxs("label",{className:K("flex items-start gap-3 px-3 py-2.5 transition-colors","max-lg:gap-2 max-lg:px-2 max-lg:py-1.5",a?"cursor-not-allowed opacity-70":"cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-800/60"),children:[e.jsx(Me,{checked:u.has(f.event),disabled:a,onCheckedChange:C=>g(f.event,C===!0),"aria-label":`Subscribe to ${f.event}`,className:"mt-0.5","data-testid":`input-client-webhooks-event-${f.event}`}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"flex min-w-0 flex-wrap items-baseline gap-x-2",children:[e.jsx("span",{className:"text-xs font-medium text-content-primary max-lg:text-2xs",children:f.label}),e.jsx("span",{className:"font-mono text-2xs text-slate-400 max-lg:text-3xs dark:text-slate-500",children:f.event})]}),e.jsx("span",{className:"block text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:f.description})]})]},f.event))})]},d.id)})]})]})]})}cc.propTypes={value:Ne.arrayOf(Ne.string),onChange:Ne.func.isRequired,disabled:Ne.bool};const nl="border-subtle bg-surface-raised shadow-sm transition-[border-color,box-shadow] duration-150 placeholder:text-slate-400 hover:border-slate-300 focus-visible:border-slate-400 focus-visible:ring-2 focus-visible:ring-slate-200/90 focus-visible:ring-offset-0 dark:text-slate-100 dark:placeholder:text-slate-500 dark:hover:border-slate-500 dark:focus-visible:border-slate-500 dark:focus-visible:ring-slate-600/35",Sa="text-xs font-medium text-content-secondary max-lg:text-2xs",Un="text-xs leading-relaxed text-content-tertiary max-lg:text-2xs max-lg:leading-snug";function _p(t){let s;try{s=new URL(t.trim())}catch{return"Enter a valid URL."}return s.protocol!=="https:"?"Endpoint URL must use HTTPS.":""}function Up(t,s){const a=!Array.isArray(t),i=!Array.isArray(s);if(a||i)return a===i;const n=da(t),r=da(s);return n.length===r.length&&n.every((l,c)=>l===r[c])}function dc({open:t,onClose:s,endpoint:a=null,onSubmit:i}){const{branding:n}=Ce(),r=(n==null?void 0:n.accentColor)||je,l=!!a,c=!!(a!=null&&a.isLegacy),[u,m]=o.useState(""),[h,g]=o.useState(""),[y,p]=o.useState(!0),[d,x]=o.use
318State(null),[f,C]=o.useState(""),[N,v]=o.useState(!1);o.useEffect(()=>{t&&(m((a==null?void 0:a.name)||""),g((a==null?void 0:a.url)||""),p(a?a.enabled!==!1:!0),x(Array.isArray(a==null?void 0:a.subscriptions)?da(a.subscriptions):null),C(""),v(!1),requestAnimationFrame(()=>{var z;(z=document.getElementById(c?"client-webhooks-endpoint-url":"client-webhooks-endpoint-name"))==null||z.focus()}))},[t,a,c]);function k(){if(!l)return{name:u.trim(),url:h.trim(),enabled:y,subscriptions:d};const z={};return!c&&u.trim()!==((a==null?void 0:a.name)||"")&&(z.name=u.trim()),h.trim()!==((a==null?void 0:a.url)||"")&&(z.url=h.trim()),y!==((a==null?void 0:a.enabled)!==!1)&&(z.enabled=y),Up(d,(a==null?void 0:a.subscriptions)??null)||(z.subscriptions=d),z}function P(z){if((!l||z.name!==void 0)&&!c&&!u.trim())return"Endpoint name is required.";if(!l||z.url!==void 0){if(!h.trim())return"Endpoint URL is required.";const q=_p(h);if(q)return q}return""}async function A(z){var O;(O=z==null?void 0:z.preventDefault)==null||O.call(z);const q=k(),R=P(q);if(R){C(R);return}if(l&&Object.keys(q).length===0){s();return}C(""),v(!0);try{await i(q),s()}catch(j){C(j.message||"Unable to save endpoint. Please try again.")}finally{v(!1)}}const E=N||!c&&!u.trim()||!h.trim();return e.jsx(at,{open:t,onOpenChange:z=>{!z&&!N&&s()},title:l?"Edit endpoint":"Add endpoint",description:l?"Update the destination, delivery state, and subscribed events for this endpoint.":"Receive signed events at an HTTPS URL you control.",mobileCompactHeaderRow:!0,mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",bodyClassName:"max-[1024px]:px-3 max-[1024px]:py-2.5",footerClassName:"max-[1024px]:gap-1.5 max-[1024px]:px-3 max-[1024px]:py-2.5",contentClassName:"max-w-2xl",contentTestId:"dialog-client-webhooks-endpoint",footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",className:"min-h-10 rounded-lg max-lg:min-h-9",onClick:s,disabled:N,"data-testid":"button-client-webhooks-endpoint-cancel",children:"Cancel"}),e.jsxs(B,{type:"submit",form:"client-webhooks-endpoint-form",className:"min-h-10 rounded-lg text-white max-lg:min-h-9 hover:opacity-95",style:{backgroundColor:r},disabled:E,"data-testid":"button-client-webhooks-endpoint-save",children:[N?e.jsx(Ve,{className:"mr-1.5 size-4 animate-spin max-lg:mr-1 max-lg:size-3.5"}):null,l?"Save changes":"Create endpoint"]})]}),children:e.jsxs("form",{id:"client-webhooks-endpoint-form",onSubmit:A,noValidate:!0,children:[e.jsxs("div",{className:"rounded-xl border border-slate-200/90 bg-surface-raised shadow-sm dark:border-slate-700",children:[e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"client-webhooks-endpoint-name",className:Sa,children:"Name"}),e.jsx(be,{id:"client-webhooks-endpoint-name",value:u,onChange:z=>m(z.target.value),placeholder:"e.g. Production CRM",autoComplete:"off",maxLength:120,disabled:c,className:K("h-11",nl),"data-testid":"input-client-webhooks-endpoint-name"}),c?e.jsx("p",{className:Un,children:"The legacy default endpoint cannot be renamed."}):null]}),e.jsxs("div",{className:"space-y-1.5 border-t border-slate-200/90 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 dark:border-slate-700/90 sm:px-6",children:[e.jsx(oe,{htmlFor:"client-webhooks-endpoint-url",className:Sa,children:"URL"}),e.jsx(be,{id:"client-webhooks-endpoint-url",type:"url",value:h,onChange:z=>g(z.target.value),placeholder:"e.g. https://example.com/webhooks/gen-health",autoComplete:"off",inputMode:"url",className:K("h-11 font-mono text-sm",nl),"data-testid":"input-client-webhooks-endpoint-url"}),e.jsx("p",{className:Un,children:"Must be HTTPS and publicly reachable."})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-slate-200/90 px-5 py-4 max-lg:gap-2 max-lg:px-3 max-lg:py-2.5 dark:border-slate-700/90 sm:px-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(oe,{htmlFor:"client-webhooks-endpoint-enabled",className:Sa,children:"Enabled"}),e.jsx("p",{className:Un,children:"Disabled endpoints do not receive deliveries."})]}),e.jsx(it,{id:"client-webhooks-endpoint-enabled",checked:y,onCheckedChange:z=>p(z===!0),disabled:N,style:y?{backgroundColor:r}:void 0,"data-testid":"input-client-webhooks-endpoint-enabled"})]}),e.jsxs("div",{className:"space-y-2 border-t border-slate-200/90 px-5 py-4 max-lg:space-y-1.5 max-lg:px-3 max-lg:py-2.5 dark:border-slate-700/90 sm:px-6",children:[e.jsx("p",{className:Sa,children:"Events"}),e.jsx(cc,{value:d,onChange:x,disabled:N})]})]}),f?e.jsx("p",{className:"mt-3 text-xs text-red-600 max-lg:mt-2 max-lg:text-2xs dark:text-red-400",role:"alert",children:f}):null]})})}dc.propTypes={open:Ne.bool.isRequired,onClose:Ne.func.isRequired,endpoint:Ne.object,onSubmit:Ne.func.isRequired};function Dn(t){return t.pausedReason==="auto_failure"?{label:"Auto-paused",badgeClass:ds("amber")}:t.enabled?{label:"Enabled",badgeClass:gn("active")}:{label:"Disabled",badgeClass:ds("slate")}}function rl(t){return Array.isArray(t)?`${t.length} event${t.length===1?"":"s"}`:"All events"}function mc({open:t,onClose:s,secret:a,endpointName:i,rotated:n}){const{branding:r}=Ce(),l=(r==null?void 0:r.accentColor)||je,[c,u]=o.useState(!1);async function m(){try{await navigator.clipboard.writeText(a),u(!0),I.success("Signing secret
318copied")}catch{I.error("Unable to copy. Select the secret and copy it manually.")}}return e.jsx(at,{open:t,onOpenChange:h=>{h||s()},title:n?"New signing secret":"Signing secret",description:`Use this secret to verify webhook signatures${i?` from ${i}`:""}. You can view it again anytime from the endpoints table.${n?" The previous secret is already invalid.":""}`,mobileCompactHeaderRow:!0,mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",bodyClassName:"max-[1024px]:px-3 max-[1024px]:py-2.5",footerClassName:"max-[1024px]:gap-1.5 max-[1024px]:px-3 max-[1024px]:py-2.5",contentClassName:"max-w-lg",contentTestId:"dialog-client-webhooks-secret",footer:e.jsx(B,{type:"button",className:"min-h-10 rounded-lg text-white max-lg:min-h-9 hover:opacity-95",style:{backgroundColor:l},onClick:s,"data-testid":"button-client-webhooks-secret-done",children:"Done"}),children:e.jsx("div",{className:"rounded-xl border border-slate-200/90 bg-surface-raised shadow-sm dark:border-slate-700",children:e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 max-lg:gap-1.5 max-lg:px-2.5 max-lg:py-2",children:[e.jsx("code",{className:"min-w-0 flex-1 select-all break-all font-mono text-sm text-content-primary max-lg:text-xs","data-testid":"input-client-webhooks-secret-value",children:a}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1.5 rounded-full px-3 text-xs max-lg:h-7 max-lg:gap-1 max-lg:px-2 max-lg:text-2xs",onClick:m,"aria-label":"Copy signing secret","data-testid":"button-client-webhooks-copy-secret",children:[c?e.jsx(Ze,{className:"size-3.5 max-lg:size-3"}):e.jsx(ms,{className:"size-3.5 max-lg:size-3"}),c?"Copied":"Copy"]})]})})})}mc.propTypes={open:Ne.bool.isRequired,onClose:Ne.func.isRequired,secret:Ne.string,endpointName:Ne.string,rotated:Ne.bool};function uc({store:t}){var ye,Re,G;const{branding:s}=Ce(),a=(s==null?void 0:s.accentColor)||je,{endpoints:i,maxEndpoints:n,loading:r,error:l,createEndpoint:c,updateEndpoint:u,deleteEndpoint:m,rotateSecret:h,sendTest:g}=t,[y,p]=o.useState({open:!1,endpoint:null}
318),[d,x]=o.useState({open:!1,secret:"",endpointName:"",rotated:!1}),[f,C]=o.useState(null),[N,v]=o.useState(!1),[k,P]=o.useState(null),[A,E]=o.useState(""),[z,q]=o.useState(""),R=i.length>=n,O=o.useMemo(()=>i.map(U=>({...U,statusLabel:Dn(U).label})),[i]),{sortedData:j,sortKey:L,sortDirection:b,handleSort:w}=Ur(O,"name","asc");async function F(U){if(y.endpoint){await u(y.endpoint.endpointId,U),I.success("Endpoint updated");return}const V=await c(U);I.success("Endpoint created");const D=(V==null?void 0:V.endpoint)||null;D!=null&&D.secret&&x({open:!0,secret:D.secret,endpointName:D.name||U.name||"",rotated:!1})}async function M(U){var D;P(U.endpointId);const V=I.loading(`Sending ping to ${U.name}...`);try{const T=await g(U.endpointId);I.dismiss(V);const $=((D=T==null?void 0:T.data)==null?void 0:D.statusCode)??(T==null?void 0:T.statusCode);I.success($?`Ping delivered (HTTP ${$})`:"Ping delivered")}catch(T){I.dismiss(V);const $=Number.isFinite(T==null?void 0:T.statusCode)?` (HTTP ${T.statusCode})`:"";I.error(`Ping failed${$}`,{description:T.message||"The receiver did not accept the request."})}finally{P(null)}}async function W(U){const V=!lr(U);P(U.endpointId);try{await u(U.endpointId,{enabled:V}),I.success(V?"Endpoint enabled":"Endpoint disabled")}catch(D){I.error(D.message||"Unable to update endpoint.")}finally{P(null)}}async function H(){if(!f)return;const{type:U,endpoint:V}=f;v(!0);try{if(U==="rotate"){const D=await h(V.endpointId);C(null),x({open:!0,secret:(D==null?void 0:D.secret)||"",endpointName:V.name||"",rotated:!0})}else U==="delete"&&(await m(V.endpointId),C(null),I.success("Endpoint deleted"))}catch(D){I.error(D.message||"Request failed. Please try again.")}finally{v(!1)}}async function ae(U){if(U.secret)try{await navigator.clipboard.writeText(U.secret),q(U.endpointId),setTimeout(()=>q(""),1500)}catch{I.error("Copy failed")}}function xe(U){const V=k===U.endpointId,D=lr(U);return[{id:"edit",label:"Edit",icon:zt,onSelect:()=>p({open:!0,endpoint:U})},{id:"send-test",label:"Send ping",icon:V?e.jsx($e,{size:"sm"}):Rr,disabled:V,onSelect:()=>M(U)},{id:"toggle-enabled",label:D?"Disable":"Enable",icon:D?Vo:uo,disabled:V,onSelect:()=>W(U)},{id:"rotate-secret",label:"Rotate secret",icon:Rs,disabled:V,onSelect:()=>C({type:"rotate",endpoint:U})},{id:"delete",label:"Delete",icon:bt,danger:!0,disabled:V,onSelect:()=>C({type:"delete",endpoint:U})}]}const Ae=e.jsxs(B,{size:"sm",className:"h-8 gap-1 rounded-full px-3 text-xs text-white hover:opacity-95",style:{backgroundColor:a},disabled:R||r,onClick:()=>p({open:!0,endpoint:null}),"data-testid":"button-client-webhooks-add-endpoint",children:[e.jsx(ot,{className:"size-3"}),"Add endpoint"]}),se=e.jsx("div",{className:"flex items-center gap-1.5 max-lg:gap-1",children:R?e.jsx(Wt,{delayDuration:150,children:e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:Ae})}),e.jsxs(os,{className:"max-w-xs text-xs",children:["Limit of ",n," endpoints reached. Delete one to add another."]})]})}):Ae}),Z={id:"client-webhooks-endpoints",title:"Webhook endpoints",icon:Ms,accentColor:a,countLabel:r?"":`${i.length} of ${n} · HTTPS URLs only`,actions:se,error:l},fe=[{id:"name",csvValue:U=>`${U.name}${U.isLegacy?" (Legacy)":""} · ${Ii(U.url)}`,header:"Name",sortKey:"name",minWidth:200,renderCell:U=>e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("p",{className:"truncate text-sm font-medium text-content-primary max-lg:text-xs",children:U.name}),U.isLegacy?e.jsx(De,{className:K(ds("slate"),"shrink-0","max-lg:px-1.5 max-lg:text-3xs"),children:"Legacy"}):null]}),e.jsx("p",{className:"truncate text-xs text-content-tertiary max-lg:text-2xs",children:Ii(U.url)})]}),skeletonClassName:"w-36"},{id:"status",csvValue:U=>Dn(U).label,header:"Status",sortKey:"statusLabel",minWidth:110,renderCell:U=>{const V=Dn(U);return e.jsx(De,{className:K(V.badgeClass,"max-lg:px-1.5 max-lg:text-3xs"),children:V.label})},skeletonClassName:"w-20 rounded-full"},{id:"subscriptions",csvValue:U=>rl(U.subscriptions),header:"Subscriptions",hideOnMobile:!0,minWidth:110,renderCell:U=>e.jsx("span",{className:"text-xs text-content-secondary max-lg:text-2xs",children:rl(U.subscriptions)}),skeletonClassName:"w-20"},{id:"secret",header:"Secret",hideOnMobile:!0,minWidth:170,renderCell:U=>{const V=A===U.endpointId;return e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx("span",{className:K("min-w-0 max-w-36 truncate font-mono text-xs text-content-secondary","max-lg:max-w-24 max-lg:text-2xs",V&&"select-all"),children:V?U.secret||"â":"â¢â¢â¢â¢â¢â¢â¢â¢"}
318),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"size-6 shrink-0","aria-label":V?`Hide secret for ${U.name}`:`Reveal secret for ${U.name}`,onClick:()=>E(V?"":U.endpointId),"data-testid":`button-client-webhooks-reveal-secret-${U.endpointId}`,children:V?e.jsx(Rd,{className:"size-3"}):e.jsx(xo,{className:"size-3"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"size-6 shrink-0","aria-label":`Copy secret for ${U.name}`,disabled:!U.secret,onClick:()=>ae(U),"data-testid":`button-client-webhooks-copy-secret-${U.endpointId}`,children:z===U.endpointId?e.jsx(Ze,{className:"size-3"}):e.jsx(ms,{className:"size-3"})})]})},skeletonClassName:"w-24"},{id:"health",csvValue:U=>U.stats?`${U.stats.deliveredCount||0} delivered · ${U.stats.failedCount||0} failed · Last delivery ${Ri(U.stats.lastSuccessAt||U.stats.lastAttemptAt)}`:"",header:"Health",hideOnMobile:!0,minWidth:190,renderCell:U=>{const V=U.stats;if(!V)return e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:"â"});const D=V.consecutiveFailures||0;return e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("p",{className:"truncate text-xs text-slate-700 max-lg:text-2xs dark:text-slate-300",children:[V.deliveredCount||0," delivered ·"," ",e.jsxs("span",{className:K(D>0&&"font-semibold text-red-600 dark:text-red-400"),children:[V.failedCount||0," failed"]})]}),e.jsxs("p",{className:"truncate text-xs text-content-tertiary max-lg:text-2xs",children:["Last delivery ",Ri(V.lastSuccessAt||V.lastAttemptAt)]})]})},skeletonClassName:"w-28"},{id:"actions",header:"Actions",align:"center",minWidth:64,renderCell:U=>e.jsx($o,{actions:xe(U),label:`Open actions for ${U.name||"endpoint"}`,testId:`menu-client-webhooks-endpoint-${U.endpointId}-actions`}),skeletonClassName:"w-7 rounded-md"}],J=!r&&i.length===0,ge=(f==null?void 0:f.type)==="delete"&&((ye=f==null?void 0:f.endpoint)==null?void 0:ye.isLegacy);return e.jsxs(e.Fragment,{children:[J?e.jsx(tt,{...Z,children:e.jsxs("div",{className:"px-6 py-12 text-center max-lg:px-3 max-lg:py-6","data-testid":"section-client-webhooks-endpoints-empty",children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"No endpoints yet"}),e.jsx("p",{className:"mt-1 text-xs text-content-tertiary max-lg:text-2xs",children:"Add an HTTPS endpoint to start receiving signed lifecycle events."}),e.jsxs(B,{size:"sm",className:"mt-4 h-8 gap-1 rounded-full px-3 text-xs text-white max-lg:mt-2.5 max-lg:h-7 max-lg:px-2.5 max-lg:text-2xs hover:opacity-95",style:{backgroundColor:a},onClick:()=>p({open:!0,endpoint:null}),"data-testid":"button-client-webhooks-add-endpoint-empty",children:[e.jsx(ot,{className:"size-3"}),"Add endpoint"]})]})}):e.jsx($s,{...Z,columns:fe,rows:j,csvExport:{feature:"webhook-endpoints",disabled:r},rowKey:"endpointId",rowTestId:U=>`row-client-webhooks-endpoint-${U==null?void 0:U.endpointId}`,contextMenuActions:xe,loading:r,skeletonRowCount:3,tableLabel:"Webhook endpoints table",tableTestId:"table-client-webhooks-endpoints",sortKey:L,sortDirection:b,onSort:w}),e.jsx(dc,{open:y.open,endpoint:y.endpoint,onClose:()=>p({open:!1,endpoint:null}),onSubmit:F}),e.jsx(mc,{open:d.open,secret:d.secret,endpointName:d.endpointName,rotated:d.rotated,onClose:()=>x({open:!1,secret:"",endpointName:"",rotated:!1})}),e.jsx(_s,{open:!!f,onOpenChange:U=>{!U&&!N&&C(null)},contentTestId:"dialog-client-webhooks-confirm",title:(f==null?void 0:f.type)==="rotate"?"Rotate signing secret?":"Delete endpoint?",description:(f==null?void 0:f.type)==="rotate"?`The current secret for ${((Re=f==null?void 0:f.endpoint)==null?void 0:Re.name)||"this endpoint"} becomes invalid immediately. Deliveries signed with the old secret will fail verification until you install the new one.`:ge?"This is the default endpoint from your original webhook configuration. Deleting it clears the legacy webhook URL, signing secret, and event subscriptions from this client, and any integration still using them stops receiving events immediately. This cannot be undone.":`${((G=f==null?void 0:f.endpoint)==null?void 0:G.name)||"This endpoint"} stops receiving events immediately. This cannot be undone.`,confirmLabel:(f==null?void 0:f.type)==="rotate"?"Rotate secret":"Delete",tone:(f==null?void 0:f.type)==="delete"?"destructive":"default",accentColor:(f==null?void 0:f.type)==="delete"?void 0:a,busy:N,onConfirm:H,confirmTestId:"button-client-webhooks-confirm",confirmationText:(f==null?void 0:f.type)==="rotate"?"ROTATE":"DELETE"})]})}uc.propTypes={store:Ne.shape({endpoints:Ne.arrayOf(Ne.object).isRequired,maxEndpoints:Ne.number.isRequired,loading:Ne.bool.isRequired,error:Ne.string,createEndpoint:Ne.func.isRequired,updateEndpoint:Ne.func.isRequired,deleteEndpoint:Ne.func.isRequired,rotateSecret:Ne.func.isRequired,sendTest:Ne.func.isRequired}).isRequired};const $n="__custom__",Ea="border-subtle bg-surface-raised shadow-sm transition-[border-color,box-shadow] duration-150 placeholder:text-slate-400 hover:border-slate-300 focus-visible:border-slate-400 focus-visible:ring-2 focus-visible:ring-slate-200/90 focus-visible:ring-offset-0 dark:text-slate-100 dar
318k:placeholder:text-slate-500 dark:hover:border-slate-500 dark:focus-visible:border-slate-500 dark:focus-visible:ring-slate-600/35",Ta="text-xs font-medium text-content-secondary max-lg:text-2xs",Pa="text-xs leading-relaxed text-content-tertiary max-lg:text-2xs max-lg:leading-snug",il="max-h-96 overflow-auto rounded-lg border border-subtle bg-surface-sunken p-3 font-mono text-xs leading-5 text-slate-800 max-lg:max-h-64 max-lg:p-2 max-lg:text-2xs max-lg:leading-snug dark:text-slate-200";function xc({clientId:t=null,endpoints:s=[],onSendEvent:a=null}){const[i,n]=o.useState(Cs[0]||"patient.created"),[r,l]=o.useState(""),[c,u]=o.useState(""),[m,h]=o.useState(()=>new Date().toISOString()),[g,y]=o.useState(""),[p,d]=o.useState(""),[x,f]=o.useState(""),[C,N]=o.useState(!1),v=o.useMemo(()=>su(i,t||"YOUR_CLIENT_ID",m),[t,i,m]),k=o.useMemo(()=>JSON.stringify(v,null,2),[v]),P=o.useMemo(()=>au(r.trim(),v.event,g,k),[r,v.event,g,k]);o.useEffect(()=>{x&&(s.some(M=>M.endpointId===x)||f(""))},[s,x]),o.useEffect(()=>{let M=!1;if(!c.trim()){y(""),d("");return}return nu(k,c.trim()).then(W=>{M||(y(W),d(""))}).catch(W=>{M||(y(""),d(W.message||"Unable to compute signature in this browser."))}),()=>{M=!0}},[k,c]);const A=o.useMemo(()=>s.find(M=>M.endpointId===x)||null,[s,x]),E=ru.get(i),z=!!x,q=!!(A&&Array.isArray(A.subscriptions)&&!A.subscriptions.includes(i)),R=!!(A&&!lr(A)),O=!!(A&&!A.secret),j=!t||!x||C||typeof a!="function",L=x?"":"Select a saved endpoint to send from GEN Health. Copy cURL to POST to a custom URL.";function b(M){const W=M===$n?"":M;if(f(W),!W)return;const H=s.find(ae=>ae.endpointId===W);H&&(l(H.url||""),u(H.secret||""))}async function w(M){try{await navigator.clipboard.writeText(String(M||"")),I.success("Copied")}catch{I.error("Copy failed")}}async function F(){var W;if(!t||!x||C||typeof a!="function")return;N(!0);const M=I.loading(`Sending ${i}â¦`);try{const H=await a(x,i);I.dismiss(M);const ae=((W=H==null?void 0:H.data)==null?void 0:W.statusCode)??(H==null?void 0:H.statusCode);I.success(ae?`Sample delivered (HTTP ${ae})`:"Sample delivered")}catch(H){I.dismiss(M);const ae=Number.isFinite(H==null?void 0:H.statusCode)?` (HTTP ${H.statusCode})`:"";I.error(`Send failed${ae}`,{description:H.message||"The receiver did not accept the request."})}finally{N(!1)}}return e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsxs("p",{className:"text-sm leading-6 text-content-secondary max-lg:text-xs max-lg:leading-snug",children:["Generate a realistic signed sample for any lifecycle event. Copy payload or cURL to replay locally, or send the sample to a saved endpoint. Demo ids such as ",e.jsx("span",{className:"font-mono",children:"pat_demo_123"})," are not live patient or order data."]}),s.length===0?e.jsx("p",{className:Pa,children:"No saved endpoints yet. Enter a destination URL and signing secret manually, or add an endpoint above."}):null,e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{className:K("grid gap-3 max-lg:gap-2",s.length>0?"lg:grid-cols-3":"lg:grid-cols-2"),children:[s.length>0?e.jsxs("div",{className:"min-w-0 space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:"webhook-sim-endpoint",className:Ta,children:"Use endpoint"}),e.jsxs(yt,{value:x||$n,onValueChange:b,children:[e.jsx(vt,{id:"webhook-sim-endpoint",className:K("h-11",Ea),"data-testid":"select-webhooks-endpoint",children:e.jsx(Nt,{placeholder:"Custom (enter URL and secret manually)"})}),e.jsxs(jt,{className:"max-h-[min(320px,50vh)]",children:[e.jsx(st,{value:$n,children:"Custom (enter URL and secret manually)"}),s.map(M=>e.jsx(st,{value:M.endpointId,children:M.name||M.url||M.endpointId},M.endpointId))]})]})]}):null,e.jsxs("div",{className:"min-w-0 space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:"webhook-sim-url",className:Ta,children:"Destination URL"}),e.jsx(be,{id:"webhook-sim-url",value:r,onChange:M=>l(M.target.value),placeholder:"https://partner.example.com/webhooks/gen-health",disabled:z,className:K("h-11 font-mono text-xs",Ea)})]}),e.jsxs("div",{className:"min-w-0 space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:"webhook-sim-secret",className:Ta,children:"Signing secret"}),e.jsx(be,{id:"webhook-sim-secret",type:"password",value:c,onChange:M=>u(M.target.value),placeholder:z?"":"Paste your signing secret to generate X-Webhook-Signature",disabled:z,className:K("h-11 font-mono text-xs",Ea)}),O?e.jsx("p",{className:Pa,children:"Reveal or rotate the secret in the endpoints table above to auto-fill it."}):null]})]}),e.jsxs("div",{className:"grid gap-3 max-lg:gap-2 lg:grid-cols-2 lg:items-end",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:"webhook-sim-event",className:Ta,children:"Event"}),e.jsxs(yt,{value:i,onValueChange:n,children:[e.jsx(vt,{id:"webhook-sim-event",className:K("h-11 font-mono",Ea),"data-testid":"select-webhooks-event",children:e.jsx(Nt,{})}),e.jsx(jt,{className:"max-h-[min(320px,50vh)]",children:ir.map(M=>e.jsxs(Ld,{children:[e.jsx(Od,{children:M.label}),M.events.map(W=>e.jsx(st,{value:W.event,className:"font-mono",children:W.event},W.event))]},M.id))})]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2 max-lg:gap-1 lg:h-11",children:[e.jsxs(B,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-lg px-3 text-xs max-lg:h-7 max-lg:px-2 max-lg:text-2xs",onClick:()=>h(new Date().toISOString()),children:[e.jsx(ts,{className:"mr-1.5 size-3.5 max-lg:mr-1 max-lg:size-3"}),"Refresh sample"]}),e.jsx(Wt,{delayDuration:150,children:e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsxs(B,{type:"button",size:"sm",className:"h-8 rounded-full px-3 text-xs max-lg:h-7 max-lg:px-2 max-lg:text-2xs",onClick:F,disabled:j,"data-testid":"button-webhooks-se
318nd-event",children:[C?e.jsx(Ve,{className:"mr-1.5 size-3.5 animate-spin max-lg:mr-1 max-lg:size-3"}):e.jsx(Rr,{className:"mr-1.5 size-3.5 max-lg:mr-1 max-lg:size-3"}),"Send test event"]})})}),L?e.jsx(os,{className:"max-w-xs text-xs leading-relaxed",children:L}):null]})})]})]}),E?e.jsx("p",{className:Pa,children:E.description}):null]}),q||R?e.jsxs("div",{className:"space-y-1",children:[q?e.jsxs("p",{className:"text-xs text-amber-700 max-lg:text-2xs max-lg:leading-snug dark:text-amber-300",children:["This endpoint is not subscribed to ",e.jsx("span",{className:"font-mono",children:i}),", so a live event would not be delivered."]}):null,R?e.jsx("p",{className:"text-xs text-amber-700 max-lg:text-2xs max-lg:leading-snug dark:text-amber-300",children:"This endpoint is disabled or auto-paused, so a live event would not be delivered."}):null]}):null,x?null:e.jsx("p",{className:Pa,children:"Select a saved endpoint to send from GEN Health. Copy cURL to POST to a custom URL."}),e.jsxs("div",{className:"rounded-lg border border-subtle bg-surface-sunken p-3 max-lg:p-2",children:[e.jsx("p",{className:"mb-2 text-3xs font-semibold uppercase tracking-[0.22em] text-content-tertiary max-lg:mb-1.5",children:"Headers to verify"}),e.jsxs("div",{className:"space-y-1 font-mono text-xs text-slate-700 max-lg:text-2xs dark:text-slate-200",children:[e.jsx("p",{children:"Content-Type: application/json"}),e.jsxs("p",{children:["X-Webhook-Event: ",v.event]}),e.jsxs("p",{className:"break-all",children:["X-Webhook-Signature: ",g||"<enter signing secret>"]})]}),p?e.jsx("p",{className:"mt-2 text-xs text-amber-700 max-lg:text-2xs dark:text-amber-300",children:p}):null]}),e.jsxs("div",{className:"grid gap-3 max-lg:gap-2 lg:grid-cols-2",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5 max-lg:space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-800 max-lg:text-2xs dark:text-slate-100",children:"Simulated payload"}),e.jsxs(B,{type:"button",size:"sm",variant:"outline",className:"h-7 rounded-lg px-2.5 text-xs max-lg:h-6 max-lg:px-2 max-lg:text-2xs",onClick:()=>w(k),children:[e.jsx(ms,{className:"mr-1.5 size-3.5 max-lg:mr-1 max-lg:size-3"}),"Copy"]})]}),e.jsx("pre",{className:il,children:k})]}),e.jsxs("div",{className:"min-w-0 space-y-1.5 max-lg:space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-800 max-lg:text-2xs dark:text-slate-100",children:"Replay with cURL"}),e.jsxs(B,{type:"button",size:"sm",variant:"outline",className:"h-7 rounded-lg px-2.5 text-xs max-lg:h-6 max-lg:px-2 max-lg:text-2xs",onClick:()=>w(P),children:[e.jsx(ms,{className:"mr-1.5 size-3.5 max-lg:mr-1 max-lg:size-3"}),"Copy"]})]}),e.jsx("pre",{className:il,children:P})]})]})]})}xc.propTypes={clientId:Ne.string,endpoints:Ne.arrayOf(Ne.object),onSendEvent:Ne.func};function Dp(t){return String(t||"").split(/[\n,]/).map(s=>s.trim()).filter(Boolean)}function na(t){if(!t)return"â";if(t instanceof Date)return t.toLocaleString();if(t!=null&&t.toDate)return t.toDate().toLocaleString();if(t!=null&&t.seconds)return new Date(t.seconds*1e3).toLocaleString();if(t!=null&&t._seconds)return new Date(t._seconds*1e3).toLocaleString();if(typeof t=="string"||typeof t=="number"){const s=new Date(t);if(!Number.isNaN(s.getTime()))return s.toLocaleString()}return"â"}function pc(t){return t.prefix?`${t.prefix}â¢â¢â¢â¢â¢â¢â¢â¢`:"â"}const $p=[{header:"Name",csvValue:t=>t.name||""},{header:"Key",csvValue:t=>pc(t)},{header:"Type",csvValue:t=>t.typeLabel||""},{header:"Created",csvValue:t=>na(t.createdAt)},{header:"Status",csvValue:t=>t.statusLabel||""}],Bp=[{header:"Type",csvValue:t=>t.typeLabel||""},{header:"Endpoint / path",csvValue:t=>t.actualPath||t.name||""},{header:"API version",csvValue:t=>t.apiVersion||""},{header:"API key",csvValue:t=>t.apiKeyName||t.apiKeyPrefix||""},{header:"Method",csvValue:t=>t.method||"â"},{header:"Status",csvValue:t=>t.statusLabel||""},{header:"Time",csvValue:t=>na(t.createdAt)}],ll=200,Bn=1e4,Vp=[{id:"overview",label:"Overview",icon:xn},{id:"api-keys",label:"API keys",icon:Rs},{id:"webhooks",label:"Webhooks",icon:Ms},{id:"analytics",label:"Analytics",icon:po},{id:"request-log",label:"Request Log",icon:Ua}],qp=[{id:"server",label:"Server"},{id:"storefront",label:"Storefront"}],Hp=[{id:"active",label:"Active"},{id:"revoked",label:"Revoked"},{id:"legacy",label:"Legacy"}],Wp=[{id:"incoming",label:"API requests"},{id:"webhook",label:"Webhooks"},{id:"hosted-checkout",label:"Hosted Checkout"}],Gp=[{id:"success",label:"Success"},{id:"requires_action",label:"Warning"},{id:"error",label:"Error"},{id:"unknown",label:"Unknown"}];function Aa(t){return String(t||"").trim().toLowerCase()}function ol(t){if(!t)return 0;if(typeof t=="number")return t;if(t!=null&&t.seconds)return t.seconds*1e3;if(t!=null&&t._seconds)return t._seconds*1e3;if(typeof t=="string"){const s=new Date(t).getTime();return Number.isNaN(s)?0:s}return 0}function Vn(t){const s=Number(t);return!Number.isFinite(s)||s<=0?"â":s<1e3?`${Math.round(s)} ms`:`${(s/1e3).toFixed(1)} s`}function cl(t){return Number.isFinite(t)?`${Math.round(t)}%`:"â"}function Ia(t){if(t==null||t==="")return"";if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}try{return JSON.stringify(t,null,2)}catch{return String(t)}}function br(t){const s=Number(t);return s>=500?"error":s>=400?"requires_action":s>=200&&s<300?"success":"unknown"}function yr(t){return t==="delivered"?"success":t==="failed"?"error":"unknown"}function dl(t=[],s=[]){const a=t.map(n=>
318({id:`incoming-${n.id}`,rawId:n.id,type:n.source==="hosted-checkout"?"hosted-checkout":"incoming",typeLabel:n.source==="hosted-checkout"?"Hosted Checkout":"API request",actualPath:n.source==="hosted-checkout"?n.endpoint||"Hosted Checkout failure":n.requestPath||n.path||n.endpoint||"Unknown path",apiVersion:n.apiVersion||null,apiKeyId:n.apiKeyId||null,apiKeyName:n.apiKeyName||"",apiKeyPrefix:n.apiKeyPrefix||"",name:n.source==="hosted-checkout"?n.endpoint||"Hosted Checkout failure":n.requestPath||n.path||n.endpoint||"Request",method:n.source==="hosted-checkout"?"Checkout":n.method||"",statusCode:n.responseStatusCode,statusTone:br(n.responseStatusCode),statusLabel:n.source==="hosted-checkout"?"Payment failed":n.responseStatusCode?String(n.responseStatusCode):"Unknown",durationMs:Number(n.durationMs)||0,createdAt:n.createdAt||null,timestamp:ol(n.createdAt),log:n})),i=s.map(n=>({id:`webhook-${n.id}`,rawId:n.id,type:"webhook",typeLabel:"Webhook",actualPath:n.eventName||n.endpointName||n.webhookUrl||"Webhook delivery",apiVersion:null,apiKeyId:null,apiKeyName:"",apiKeyPrefix:"",name:n.eventName||n.webhookUrl||"Webhook delivery",method:`${Number(n.attempts)||0} attempts`,statusCode:n.responseStatusCode,statusTone:yr(n.deliveryStatus),statusLabel:n.deliveryStatus||"Unknown",durationMs:0,createdAt:n.createdAt||null,timestamp:ol(n.createdAt),log:n}));return[...a,...i].sort((n,r)=>r.timestamp-n.timestamp)}function Ys({tone:t,label:s}){return e.jsx(De,{className:K(gn(t||"unknown"),"max-lg:px-1.5 max-lg:text-3xs"),children:s})}function gc({children:t,label:s="More information"}){return e.jsx(Wt,{delayDuration:150,children:e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":s,className:"inline-flex shrink-0 items-center justify-center rounded-full p-0.5 text-slate-400 transition-colors hover:text-slate-700 dark:hover:text-slate-200",children:e.jsx(Ds,{className:"size-3.5 max-lg:size-3"})})}),e.jsx(os,{className:"max-w-xs text-xs leading-relaxed",children:t})]})})}const ml={success:"bg-emerald-500",requires_action:"bg-amber-500",error:"bg-red-500",unknown:"bg-slate-300 dark:bg-slate-600"};function Ra({label:t,value:s,hint:a,tone:i}){return e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-content-tertiary max-lg:text-2xs",children:[e.jsx("span",{children:t}),a?e.jsx(gc,{label:`${t} info`,children:a}):null]}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 max-lg:mt-0.5 max-lg:gap-1",children:[i?e.jsx("span",{className:K("size-1.5 rounded-full",ml[i]||ml.unknown)}):null,e.jsx("span",{className:"text-base font-semibold text-content-primary max-lg:text-sm",children:s})]})]})}function Qs({icon:t,label:s,description:a,external:i=!1,onClick:n}){return e.jsxs("button",{type:"button",onClick:n,className:"flex w-full items-center gap-3 border-t border-subtle px-4 py-3 text-left transition-colors max-lg:gap-2 max-lg:px-2.5 max-lg:py-2 first:border-t-0 hover:bg-slate-50 dark:hover:bg-slate-800/50",children:[e.jsx(t,{className:"size-4 shrink-0 text-slate-400 max-lg:size-3.5"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-content-primary max-lg:text-xs",children:s}),e.jsx("span",{className:"block truncate text-xs text-content-tertiary max-lg:text-2xs",children:a})]}),i?e.jsx(Da,{className:"size-3.5 shrink-0 text-slate-400 max-lg:size-3"}):e.jsx(Hd,{className:"size-4 shrink-0 text-slate-400 max-lg:size-3.5"})]})}function La({label:t,value:s,sub:a}){return e.jsxs("div",{className:"bg-surface-raised p-4 max-lg:p-2.5",children:[e.jsx("p",{className:"text-xs font-medium text-content-tertiary max-lg:text-2xs",children:t}),e.jsx("p",{className:"mt-1.5 text-xl font-semibold tabular-nums text-content-primary max-lg:mt-1 max-lg:text-base",children:s}),a?e.jsx("p",{className:"mt-0.5 text-2xs text-content-tertiary max-lg:text-3xs",children:a}):null]})}function Kp({changed:t,saving:s,onSave:a,onDiscard:i,accentColor:n,saveLabel:r}){return t?e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 max-lg:gap-1",children:[e.jsx(B,{t
318ype:"button",size:"sm",variant:"outline",onClick:i,disabled:s,className:"h-7 px-2.5 text-xs max-lg:px-2 max-lg:text-2xs",children:"Discard"}),e.jsxs(B,{type:"button",size:"sm",onClick:a,disabled:s,"aria-label":r,className:"h-7 px-2.5 text-xs text-white max-lg:px-2 max-lg:text-2xs hover:opacity-90",style:{backgroundColor:n},children:[s?e.jsx($e,{size:"xs",className:"mr-1"}):null,"Save"]})]}):null}function ul({checked:t,disabled:s=!1,id:a,info:i,label:n,onCheckedChange:r,saving:l=!1,children:c=null}){const u=()=>{s||r(!t)};return e.jsx("div",{role:"button",tabIndex:s?-1:0,"aria-pressed":t,"aria-disabled":s,onClick:m=>{m.target.closest("button, input, label")||u()},onKeyDown:m=>{m.key!=="Enter"&&m.key!==" "||(m.preventDefault(),u())},className:K("overflow-hidden rounded-xl border border-subtle bg-slate-50/60 transition-colors dark:bg-slate-900/20","hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-slate-400 dark:hover:bg-slate-900 dark:focus-visible:ring-slate-500",s?"cursor-not-allowed opacity-70":"cursor-pointer",t&&"bg-slate-50/70 dark:bg-slate-900"),children:e.jsxs("div",{className:"flex min-h-[5rem] items-center gap-3 p-3 max-lg:min-h-0 max-lg:gap-2 max-lg:p-2",children:[e.jsx(Me,{id:a,checked:t,disabled:s,onClick:m=>m.stopPropagation(),onCheckedChange:m=>r(!!m),className:"size-5 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx(oe,{htmlFor:a,className:"cursor-pointer text-sm font-medium text-content-primary max-lg:text-xs",children:n}),e.jsx(gc,{label:`${n} info`,children:i}),l?e.jsx(Ve,{className:"size-3.5 animate-spin text-content-tertiary max-lg:size-3","aria-label":"Saving"}):null]}),c?e.jsx("div",{className:"mt-3 max-lg:mt-2",children:c}):null]})]})})}function Yp({clientId:t=null,headerActionsSlot:s=null}){var Xr,Zr,ei,ti,si,ai,ni,ri,ii,li,oi,ci,di,mi;const a=iu(),{confirmAction:i,confirmDialog:n}=Md(),{userDoc:r,userType:l}=Se(),c=l==="Super Admin",{branding:u}=Ce(),m=t||(r==null?void 0:r.clientId),h=(u==null?void 0:u.accentColor)||je,g=lu(m),[y,p]=o.useState(!0),[d,x]=o.use
318State(!1),[f,C]=o.useState(!1),[N,v]=o.useState(!1),[k,P]=o.useState(!1),[A,E]=o.useState("overview"),[z,q]=o.useState(!1),[R,O]=o.useState([]),[j,L]=o.useState([]),[b,w]=o.useState(null),[F,M]=o.useState([]),[W,H]=o.useState([]),[ae,xe]=o.useState(!1),[Ae,se]=o.useState(!1),[Z,fe]=o.useState(""),[J,ge]=o.useState(""),[ye,Re]=o.useState([]),[G,U]=o.useState([]),[V,D]=o.useState(""),[T,$]=o.useState([]),[S,Q]=o.useState([]),[Y,de]=o.useState(null),[ve,Ee]=o.useState(!1),[Oe,nt]=o.useState("server"),[ze,pt]=o.useState(null),[Bt,Gt]=o.useState(!1),[cs,X]=o.useState(""),[We,ct]=o.useState(!1),[gt,_t]=o.useState(!1),[dt,et]=o.useState(""),[Rt,rt]=o.useState(!1),[Lt,ee]=o.useState(""),[Ye,ht]=o.useState(!1);o.useEffect(()=>{if(!m){p(!1);return}const _=he(ce,"Clients",m),te=qe(_,ne=>{const le=ne.exists()?ne.data():null;ct((le==null?void 0:le.skipOnboardingForApiPatients)===!0);const Te=String((le==null?void 0:le.patientSourceField)||"").trim();et(Te),rt(!!Te),ee(Te),p(!1)},ne=>{console.error("Error loading client API section:",ne),I.error("Unable to load API settings. Please try again."),p(!1)});return()=>te()},[m]),o.useEffect(()=>{pt(null),Ee(!1)},[m]),o.useEffect(()=>{if(!m){O([]),de(null);return}async function _(){var te,ne;try{x(!0);const le=await a("listApiKeys",{clientId:m}),Te=Array.isArray((te=le==null?void 0:le.data)==null?void 0:te.apiKeys)?le.data.apiKeys:[];O(Te),de(((ne=le==null?void 0:le.data)==null?void 0:ne.legacyApiKey)||null)}catch(le){console.error("Error loading API keys:",le),I.error(le.message||"Unable to load API keys. Please try again.")}finally{x(!1)}}_()},[m,a]),o.useEffect(()=>{if(!m){L([]),w(null);return}async function _(){var te;try{C(!0);const[ne,le]=await Promise.all([a("listStorefrontKeys",{clientId:m}),a("getStorefrontReadiness",{clientId:m})]);L(Array.isArray((te=ne==null?void 0:ne.data)==null?void 0:te.storefrontKeys)?ne.data.storefrontKeys:[]),w((le==null?void 0:le.data)||null)}catch(ne){console.error("Error loading storefront settings:",ne),I.error(ne.message||"Unable to load storefront settings. Please try again.")}finally{C(!1)}}_()},[m,a]);const Qe=o.useMemo(()=>m?sr(ar.MAIN,`/${m}/api-docs?tab=api`):"",[m]),He=dt.trim()!==Lt,re=o.useCallback(async()=>{var _,te;if(m)try{xe(!0);const ne=await a("listClientApiLogs",{clientId:m,limit:ll});M(Array.isArray((_=ne==null?void 0:ne.data)==null?void 0:_.requestLogs)?ne.data.requestLogs:[]),H(Array.isArray((te=ne==null?void 0:ne.data)==null?void 0:te.webhookLogs)?ne.data.webhookLogs:[]),se(!0)}catch(ne){console.error("Error loading API logs:",ne),I.error(ne.message||"Unable to load API logs. Please try again.")}finally{xe(!1)}},[m,a]);o.useEffect(()=>{(A==="analytics"||A==="request-log")&&re()},[A,re]),o.useEffect(()=>{M([]),H([]),se(!1),fe("")},[m]);const pe=o.useMemo(()=>{const _=R.map(le=>({id:`server-${le.id}`,keyId:le.id,type:"server",typeLabel:"Server",name:le.name||"Untitled key",prefix:le.apiKeyPrefix||"",status:"active",statusLabel:"Active",createdAt:le.createdAt||null,source:le})),te=Y?[{id:"legacy",keyId:"legacy",type:"server",typeLabel:"Server",name:"Legacy API key",prefix:Y.apiKeyPrefix||"",status:"legacy",statusLabel:"Legacy",createdAt:Y.apiKeyCreatedAt||null,source:Y}]:[],ne=j.map(le=>({id:`storefront-${le.id}`,keyId:le.id,type:"storefront",typeLabel:"Storefront",name:le.name||"Untitled key",prefix:le.keyPrefix||"",status:String(le.status||"active").toLowerCase(),statusLabel:le.status||"Active",createdAt:le.createdAt||null,allowedOrigins:le.allowedOrigins||[],source:le}));return[..._,...te,...ne]},[R,Y,j]),me=o.useMemo(()=>{const _=Aa(J);return pe.filter(te=>ye.length>0&&!ye.includes(te.type)||G.length>0&&!G.includes(te.status)?!1:_?[te.name,te.prefix,te.typeLabel,te.statusLabel,...te.allowedOrigins||[]].some(ne=>Aa(ne).includes(_)):!0)},[pe,J,G,ye]),ie=o.useMemo(()=>dl(F,W),[F,W]),_e=o.useCallback(async()=>{var le,Te;const _=await a("listClientApiLogs",{clientId:m,limit:Bn}),te=Array.isArray((le=_==null?void 0:_.data)==null?void 0:le.requestLogs)?_.data.requestLogs:[],ne=Array.isArray((Te=_==null?void 0:_.data)==null?void 0:Te.webhookLogs)?_.data.webhookLogs:[];return{rows:dl(te,ne),truncated:te.length>=Bn||ne.length>=Bn}},[m,a]),kt=o.useMemo(()=>{const _=Aa(V);return ie.filter(te=>{var ne,le,Te,Yt;return T.length>0&&!T.includes(te.type)||S.length>0&&!S.includes(te.statusTone)?!1:_?[te.typeLabel,te.actualPath,te.name,te.method,te.apiVersion,te.apiKeyName,te.apiKeyPrefix,te.statusLabel,(ne=te.log)==null?void 0:ne.endpointName,(le=te.log)==null?void 0:le.eventName,(Te=te.log)==null?void 0:Te.webhookUrl,(Yt=te.log)==null?void 0:Yt.errorMessage].some(Je=>Aa(Je).includes(_)):!0})},[ie,V,S,T]),ke=o.useMemo(()=>kt.find(_=>_.id===Z)||null,[kt,Z]);function Kt(_){fe(_),Gt(!0)}const Ct=o.useMemo(()=>{const _=F.length,te=F.filter(Je=>br(Je.responseStatusCode)==="success").length,ne=_?F.reduce((Je,Vt)=>Je+(Number(Vt.durationMs)||0),0)/_:0,le=W.filter(Je=>yr(Je.deliveryStatus)==="success").length,Te=W.filter(Je=>yr(Je.deliveryStatus)==="error").length,Yt=new Map;return F.forEach(Je=>{const Vt=[Je.apiVersion,Je.requestPath||Je.endpoint||"Unknown path"].filter(
318Boolean).join(" · "),ps=Yt.get(Vt)||{endpoint:Vt,count:0,success:0,duration:0};ps.count+=1,ps.duration+=Number(Je.durationMs)||0,br(Je.responseStatusCode)==="success"&&(ps.success+=1),Yt.set(Vt,ps)}),{totalRequests:_,successRate:_?te/_*100:NaN,averageDuration:ne,webhookCount:W.length,deliveredWebhooks:le,failedWebhooks:Te,topEndpoints:Array.from(Yt.values()).sort((Je,Vt)=>Vt.count-Je.count).slice(0,6)}},[F,W]),Ac=[{id:"type",header:"Type",width:"14%",minWidth:120,renderCell:_=>e.jsx(Ys,{tone:_.type==="webhook"?"event":"info",label:_.typeLabel}),skeletonClassName:"w-20 rounded-full"},{id:"actualPath",header:"Endpoint / path",width:"34%",minWidth:220,renderCell:_=>{var te,ne;return e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-mono text-xs text-content-primary max-lg:text-2xs",title:_.actualPath,children:_.actualPath}),e.jsx("p",{className:"mt-0.5 truncate text-2xs text-content-tertiary max-lg:text-3xs",children:_.type==="incoming"?[_.method||"UNKNOWN",_.apiVersion?`${_.apiVersion} API`:"Version not recorded"].join(" · "):((te=_.log)==null?void 0:te.endpointName)||((ne=_.log)==null?void 0:ne.webhookUrl)||"Configured webhook endpoint"})]})},skeletonClassName:"w-40"},{id:"apiKey",header:"API key",width:"20%",minWidth:150,renderCell:_=>_.type==="incoming"?e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-300",children:_.apiKeyName||(_.apiKeyId?`Key ${_.apiKeyId.slice(0,8)}`:"Not recorded")}),_.apiKeyPrefix?e.jsxs("p",{className:"truncate font-mono text-2xs text-content-tertiary max-lg:text-3xs",children:[_.apiKeyPrefix,"â¢â¢â¢â¢"]}):null]}):e.jsx("span",{className:"text-xs text-slate-400 max-lg:text-2xs dark:text-slate-500",children:"â"}),skeletonClassName:"w-24"},{id:"status",header:"Status",width:"14%",minWidth:110,renderCell:_=>e.jsx(Ys,{tone:_.statusTone,label:_.statusLabel}),skeletonClassName:"w-16 rounded-full"},{id:"createdAt",header:"Time",width:"18%",minWidth:145,renderCell:_=>e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:na(_.createdAt)}),skeletonClassName:"w-24"}];async function Bs(){var _,te;if(m)try{x(!0);const ne=await a("listApiKeys",{clientId:m});O(Array.isArray((_=ne==null?void 0:ne.data)==null?void 0:_.apiKeys)?ne.data.apiKeys:[]),de(((te=ne==null?void 0:ne.data)==null?void 0:te.legacyApiKey)||null)}catch(ne){console.error("Error refreshing API keys:",ne),I.error(ne.message||"Unable to refresh API keys. Please try again.")}finally{x(!1)}}async function Vs(){var _;if(m)try{C(!0);const[te,ne]=await Promise.all([a("listStorefrontKeys",{clientId:m}),a("getStorefrontReadiness",{clientId:m})]);L(Array.isArray((_=te==null?void 0:te.data)==null?void 0:_.storefrontKeys)?te.data.storefrontKeys:[]),w((ne==null?void 0:ne.data)||null)}catch(te){console.error("Error refreshing storefront state:",te),I.error(te.message||"Unable to refresh storefront settings. Please try again.")}finally{C(!1)}}function Gr(_){const te=new Date().toLocaleString([],{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});return _==="storefront"?`Storefront key ${te}`:`API key ${te}`}async function Ic(_=""){var ne;if(!m)return;const te=String(_||Gr("server")).trim();if(!te){I.error("Enter an API key name");return}try{v(!0);const le=await a("generateApiKey",{clientId:m,name:te});pt({value:((ne=le==null?void 0:le.data)==null?void 0:ne.apiKey)||"",name:te,kind:"server"}),Ee(!1),I.success("API key generated"),await Bs()}catch(le){console.error("Error generating API key:",le),I.error(le.message||"Unable to generate API key. Please try again.")}finally{v(!1)}}async function Rc(_,te){if(!m||!_||_==="legacy")return;const ne=window.prompt("Rename API key",te||"");if(ne===null)return;const le=ne.trim();if(!le){I.error("Enter an API key name");return}try{v(!0),await a("updateApiKeyName",{clientId:m,keyId:_,name:le}),I.success("API key renamed"),await Bs()}catch(Te){console.error("Error renaming API key:",Te),I.error(Te.message||"Unable to rename API key. Please try again.")}finally{v(!1)}}async function Lc(_,te){var le;if(!(!m||!await i({title:`Regenerate "${te}
318"?`,description:"The current key stops working the moment this completes. Every integration using it fails until it is given the new key.",confirmLabel:"Regenerate key",tone:"destructive",confirmationText:te})))try{v(!0);const Te=await a("regenerateApiKey",{clientId:m,keyId:_});pt({value:((le=Te==null?void 0:Te.data)==null?void 0:le.apiKey)||"",name:te,kind:"server"}),I.success("API key regenerated"),await Bs()}catch(Te){console.error("Error regenerating API key:",Te),I.error(Te.message||"Unable to regenerate API key. Please try again.")}finally{v(!1)}}async function Oc(_,te){if(!(!m||!await i({title:`Revoke "${te}"?`,description:"The key is destroyed. Every integration using it fails immediately, and it cannot be brought back â a new key has to be issued.",confirmLabel:"Revoke key",tone:"destructive",confirmationText:te})))try{v(!0),await a("revokeApiKey",{clientId:m,keyId:_}),I.success("API key revoked"),await Bs()}catch(le){console.error("Error revoking API key:",le),I.error(le.message||"Unable to revoke API key. Please try again.")}finally{v(!1)}}async function Mc(){if(!(!m||!await i({title:"Revoke the legacy API key?",description:"The legacy key is destroyed. Anything still authenticating with it fails immediately and cannot be restored.",confirmLabel:"Revoke legacy key",tone:"destructive",confirmationText:"REVOKE"})))try{v(!0),await a("revokeApiKey",{clientId:m}),I.success("Legacy API key revoked"),await Bs()}catch(te){console.error("Error revoking legacy API key:",te),I.error(te.message||"Unable to revoke legacy API key. Please try again.")}finally{v(!1)}}async function Fc(_=""){var ne;if(!m)return;const te=String(_||Gr("storefront")).trim();if(!te){I.error("Enter a storefront key name");return}try{P(!0);const le=await a("generateStorefrontKey",{clientId:m,name:te,allowedOrigins:[]});pt({value:((ne=le==null?void 0:le.data)==null?void 0:ne.storefrontKey)||"",name:te,kind:"storefront"}),Ee(!1),I.success("Storefront key generated"),await Vs()}catch(le){console.error("Error generating storefront key:",le),I.error(le.message||"Unable to generate storefront key. Please try again.")}finally{P(!1)}}async function zc(_,te){if(!m||!_)return;const ne=window.prompt("Rename storefront key",te||"");if(ne===null)return;const le=ne.trim();if(!le){I.error("Enter a storefront key name");return}try{P(!0),await a("updateStorefrontKeyName",{clientId:m,keyId:_,name:le}),I.success("Storefront key renamed"),await Vs()}catch(Te){console.error("Error renaming storefront key:",Te),I.error(Te.message||"Unable to rename storefront key. Please try again.")}finally{P(!1)}}async function _c(_,te){var le;if(!(!m||!await i({title:`Regenerate "${te}"?`,description:"The current storefront key stops working the moment this completes. Every embed using it breaks until it is updated.",confirmLabel:"Regenerate key",tone:"destructive",confirmationText:te})))try{P(!0);const Te=await a("regenerateStorefrontKey",{clientId:m,keyId:_});pt({value:((le=Te==null?void 0:Te.data)==null?void 0:le.storefrontKey)||"",name:te,kind:"storefront"}),I.success("Storefront key regenerated"),await Vs()}catch(Te){console.error("Error regenerating storefront key:",Te),I.error(Te.message||"Unable to regenerate storefront key. Please try again.")}finally{P(!1)}}async function Uc(_,te){if(!(!m||!await i({title:`Revoke "${te}
318"?`,description:"The key is destroyed. Hosted embeds and SDK mounts using it stop working immediately and cannot be restored.",confirmLabel:"Revoke key",tone:"destructive",confirmationText:te})))try{P(!0),await a("revokeStorefrontKey",{clientId:m,keyId:_}),I.success("Storefront key revoked"),await Vs()}catch(le){console.error("Error revoking storefront key:",le),I.error(le.message||"Unable to revoke storefront key. Please try again.")}finally{P(!1)}}async function Dc(_,te){if(m)try{P(!0),await a("updateStorefrontKeyOrigins",{clientId:m,keyId:_,allowedOrigins:Dp(te)}),I.success("Allowed origins updated"),await Vs()}catch(ne){console.error("Error updating storefront origins:",ne),I.error(ne.message||"Unable to update allowed origins. Please try again.")}finally{P(!1)}}async function $c(_){try{await navigator.clipboard.writeText(_),I.success("Copied")}catch{I.error("Copy failed")}}async function Kr(_,te){_&&(await $c(_),X(te),setTimeout(()=>X(""),1500))}async function Bc(_){if(!m)return;const te=!!_,ne=We;ct(te);try{_t(!0),await a("updateClientDeveloperSettings",{clientId:m,skipOnboardingForApiPatients:te}),I.success("API patient onboarding updated")}catch(le){console.error("Error updating API patient onboarding setting:",le),ct(ne),I.error("Unable to update API patient onboarding. Please try again.")}finally{_t(!1)}}async function Vc(){if(!m)return;const _=dt.trim();try{ht(!0),await a("updateClientDeveloperSettings",{clientId:m,patientSourceField:_||null}),et(_),rt(!!_),ee(_),I.success("Patient source field saved")}catch(te){console.error("Error saving patient source field:",te),I.error("Unable to save patient source field. Please try again.")}finally{ht(!1)}}async function qc(_){if(!m)return;const te=!!_;if(rt(te),te){et(Te=>Te||Lt||"");return}const ne=dt,le=Lt;if(et(""),!!le)try{ht(!0),await a("updateClientDeveloperSettings",{clientId:m,patientSourceField:null}),ee(""),I.success("Patient source field disabled")}catch(Te){console.error("Error disabling patient source field:",Te),rt(!0),et(ne),I.error("Unable to disable patient source field. Please try again.")}finally{ht(!1)}}if(!m)return null;const Yr=(b==null?void 0:b.isReady)===!0,Hc=g.endpoints.filter(_=>_.enabled).length,yn=g.endpoints.length>0,Qr=pe.length,Jr=e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{if(!Qe)return;const _=A==="webhooks"?"webhooks":"v2-api";window.open(Qe.replace("tab=api",`tab=${_}`),"_blank","noopener,noreferrer")},className:"h-8 shrink-0 gap-1.5 rounded-full px-3 text-xs max-lg:h-7 max-lg:gap-1 max-lg:px-2 max-lg:text-2xs",children:[e.jsx(Da,{className:"size-3.5 max-lg:size-3"}),e.jsx("span",{className:"max-sm:hidden",children:"Documentation"})]});return e.jsxs(e.Fragment,{children:[e.jsx("div",{id:"client-api",className:"scroll-mt-24",children:e.jsxs(Fd,{value:A,onValueChange:E,className:"space-y-4 max-lg:space-y-2.5",children:[s?Wc.createPortal(Jr,s):e.jsx("div",{className:"flex justify-end",children:Jr}),e.jsx(zd,{className:"grid h-auto w-full grid-cols-2 gap-1 border border-slate-200 bg-white p-1 max-lg:flex max-lg:w-full max-lg:justify-start max-lg:overflow-x-auto max-lg:p-0.5 max-lg:[&>*]:shrink-0 dark:border-slate-700 dark:bg-slate-900 sm:grid-cols-5",style:{"--tabs-active-color":h},children:Vp.map(_=>{const te=_.icon;return e.jsxs(_d,{value:_.id,className:"h-8 w-full justify-center gap-1.5 px-2 text-content-tertiary shadow-none max-lg:h-7 max-lg:w-auto max-lg:gap-1 max-lg:px-2 max-lg:text-2xs hover:text-slate-800 data-[state=active]:shadow-none dark:hover:text-slate-200",children:[e.jsx(te,{className:"size-3.5 shrink-0 max-lg:size-3"}),e.jsx("span",{className:"truncate",children:_.label})]},_.id)})}),e.jsx(qs,{value:"overview",className:"mt-0",children:e.jsxs(tt,{id:"client-api-overview",title:"Overview",description:"Developer setup status for this client.",icon:xn,accentColor:h,bodyClassName:"p-0",children:[e.jsxs("div",{className:"grid gap-4 px-4 py-4 max-lg:gap-2 max-lg:px-2.5 max-lg:py-2.5 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Ra,{label:"API keys",value:String(Qr),hint:"Active server and storefront keys for this client."}),e.jsx(Ra,{label:"Webhooks",value:yn?String(g.endpoints.length):"Not set",tone
318:yn?"success":"unknown",hint:yn?`${Hc} enabled of ${g.endpoints.length} endpoint${g.endpoints.length===1?"":"s"}.`:"Add an endpoint to receive signed event deliveries."}),e.jsx(Ra,{label:"Storefront",value:Yr?"Ready":"Needs setup",tone:Yr?"success":"requires_action",hint:"Hosted checkout and SDK readiness, authenticated with X-Storefront-Key."}),e.jsx(Ra,{label:"Recent activity",value:String(ie.length),hint:"Incoming requests and webhook deliveries currently loaded."})]}),e.jsxs("div",{className:"border-t border-subtle",children:[e.jsx("div",{className:"px-4 py-3 max-lg:px-2.5 max-lg:py-2",children:e.jsx("h3",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Quick links"})}),e.jsxs("div",{className:"border-t border-subtle",children:[e.jsx(Qs,{icon:Rs,label:"Manage API keys",description:"Create, regenerate, and revoke keys.",onClick:()=>E("api-keys")}),e.jsx(Qs,{icon:Ms,label:"Configure webhooks",description:"Endpoint, signing secret, and subscribed events.",onClick:()=>E("webhooks")}),e.jsx(Qs,{icon:Ua,label:"Request log",description:"Inspect recent API, webhook, and Hosted Checkout failure activity.",onClick:()=>E("request-log")}),e.jsx(Qs,{icon:Da,label:"API reference",description:"Endpoints, authentication, and examples.",external:!0,onClick:()=>Qe&&window.open(Qe,"_blank","noopener,noreferrer")}),e.jsx(Qs,{icon:Da,label:"Hosted checkout & SDK",description:"Embed checkout and mount the SDK.",external:!0,onClick:()=>Qe&&window.open(Qe.replace("tab=api","tab=hosted"),"_blank","noopener,noreferrer")})]})]})]})}),e.jsx(qs,{value:"api-keys",className:"mt-0",children:e.jsxs(tt,{id:"client-api-keys",title:"API keys",icon:Rs,accentColor:h,filteredCount:me.length,totalCount:Qr,search:{placeholder:"Search keys",value:J,onChange:ge,testId:"input-client-api-keys-search"},filters:[{id:"type",filters:qp,activeFilters:ye,onFilterChange:Re,defaultLabel:"Type",branding:u},{id:"status",filters:Hp,activeFilters:G,onFilterChange:U,defaultLabel:"Status",branding:u}],actions:e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 max-lg:flex-nowrap max-lg:gap-1",children:[e.jsx(Cm,{feature:"api-keys",tenantSlug:u==null?void 0:u.businessName,view:{getRows:()=>me},allData:{mode:"client",getRows:()=>pe},columns:$p,testId:"button-export-api-keys"}),e.jsxs(B,{size:"sm",onClick:()=>{nt("server"),Ee(!0)},className:"h-8 shrink-0 gap-1.5 rounded-full px-3 text-xs text-white max-lg:h-7 max-lg:gap-1 max-lg:px-2 max-lg:text-2xs hover:opacity-90",style:{backgroundColor:h},children:[e.jsx(ot,{className:"size-3.5 max-lg:size-3"}),"Create key"]})]}),loading:d||f,bodyClassName:"p-0",children:[e.jsx("div",{className:"border-b border-subtle px-4 py-2 text-xs text-content-tertiary max-lg:px-2.5 max-lg:py-1.5 max-lg:text-2xs max-lg:leading-snug",children:"Server keys authenticate backend calls. Storefront keys authenticate hosted checkout and SDK embeds. Full keys are shown only once, at creation."}),d||f?e.jsx("div",{className:"flex items-center justify-center px-3 py-10 max-lg:py-6",children:e.jsx(Ve,{className:"size-4 animate-spin text-blue-600 max-lg:size-3.5"})}):e.jsxs(la,{children:[e.jsx(oa,{children:e.jsxs(At,{children:[e.jsx(Be,{className:"h-9 px-4 text-xs max-lg:px-2",children:"Name"}),e.jsx(Be,{className:"h-9 px-4 text-xs max-lg:px-2",children:"Key"}),e.jsx(Be,{className:"h-9 px-4 text-xs max-lg:px-2",children:"Type"}),e.jsx(Be,{className:"h-9 px-4 text-xs max-lg:px-2",children:"Created"}),e.jsx(Be,{className:"h-9 px-4 text-xs max-lg:px-2",children:"Status"}),e.jsx(Be,{className:"h-9 w-10 px-4 text-right text-xs max-lg:px-2",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs(ca,{children:[me.length===0?e.jsx(At,{children:e.jsx(Ie,{colSpan:6,className:"px-4 py-10 text-center text-xs text-content-tertiary max-lg:px-2 max-lg:py-6",children:pe.length===0?"No API keys yet. Create your first key to start integrating.":"No keys match the current filters."})}):null,me.map(_=>{var Vt,ps;const te=_.status==="legacy",ne=_.type==="storefront",le=_.status==="revoked",Te=ne?`sf-${_.keyId}`:_.keyId,Yt=ne?(Vt=_.source)==null?void 0:Vt.storefrontKey:(ps=_.source)==null?void 0:ps.apiKey,Je=(_.allowedOrigins||[]).length;return e.jsxs(At,{children:[e.jsx(Ie,{className:"px-4 py-3 max-lg:px-2 max-lg:py-1.5",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-content-primary max-lg:text-xs",children:_.name}),ne?e.jsx("p",{className:K("mt-0.5 text-xs max-lg:text-2xs",Je===0?"text-amber-600 dar
318k:text-amber-300":"text-content-tertiary"),children:Je===0?"No allowed origins":`${Je} allowed origin${Je===1?"":"s"}`}):null]})}),e.jsx(Ie,{className:"px-4 py-3 font-mono text-xs text-content-tertiary max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs",children:pc(_)}),e.jsx(Ie,{className:"px-4 py-3 max-lg:px-2 max-lg:py-1.5",children:e.jsx(De,{variant:"outline",className:"text-3xs max-lg:px-1.5 max-lg:py-0",children:_.typeLabel})}),e.jsx(Ie,{className:"px-4 py-3 text-xs text-content-tertiary max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs",children:na(_.createdAt)}),e.jsx(Ie,{className:"px-4 py-3 max-lg:px-2 max-lg:py-1.5",children:e.jsx(Ys,{tone:_.status,label:_.statusLabel})}),e.jsx(Ie,{className:"px-4 py-3 text-right max-lg:px-2 max-lg:py-1.5",children:e.jsxs(Ud,{children:[e.jsx(Dd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"size-7 max-lg:size-6","aria-label":`Actions for ${_.name}`,disabled:N||k,children:e.jsx(ou,{className:"size-4 max-lg:size-3.5"})})}),e.jsxs($d,{align:"end",className:"w-44",children:[c&&Yt?e.jsxs(e.Fragment,{children:[e.jsxs(Hs,{onClick:()=>Kr(Yt,Te),children:[cs===Te?e.jsx(Ze,{className:"mr-2 size-3.5"}):e.jsx(ms,{className:"mr-2 size-3.5"}),"Copy key"]}),e.jsx(Bd,{})]}):null,te?null:e.jsxs(Hs,{disabled:ne?k:N,onClick:()=>ne?zc(_.keyId,_.name):Rc(_.keyId,_.name),children:[e.jsx(zt,{className:"mr-2 size-3.5"}),"Rename"]}),ne?e.jsxs(Hs,{disabled:k||le,onClick:()=>{const ui=window.prompt("Enter allowed origins, comma separated",(_.allowedOrigins||[]).join(", "));ui!==null&&Dc(_.keyId,ui)},children:[e.jsx(zt,{className:"mr-2 size-3.5"}),"Edit origins"]}):null,te?null:e.jsxs(Hs,{disabled:ne?k||le:N,onClick:()=>ne?_c(_.keyId,_.name):Lc(_.keyId,_.name),children:[e.jsx(ts,{className:"mr-2 size-3.5"}),"Regenerate"]}),e.jsxs(Hs,{className:"text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400",disabled:ne?k||le:N,onClick:()=>{if(ne){Uc(_.keyId,_.name);return}if(te){Mc();return}Oc(_.keyId,_.name)},children:[e.jsx(bt,{className:"mr-2 size-3.5"}),"Revoke"]})]})]})})]},_.id)})]})]}),e.jsx("div",{className:"border-t border-subtle px-4 py-4 max-lg:px-2.5 max-lg:py-2.5",children:e.jsxs("div",{className:"grid gap-3 max-lg:gap-2 lg:grid-cols-2",children:[e.jsx(ul,{id:"skip-onboarding-api-patients",checked:We,disabled:y||gt,saving:gt,onCheckedChange:_=>Bc(!!_),label:"Skip account setup",info:"When enabled, patients created through the API do not have to complete account setup before using the portal. Use this only when your API payload already collects the required onboarding details."}),e.jsx(ul,{id:"patient-source-field-enabled",checked:Rt,disabled:y||Ye,saving:Ye,onCheckedChange:_=>qc(!!_),label:"Use source custom field",info:"Maps a patient custom field into the Patients page Source column. For example, entering source reads each patient customFields.source value before falling back to API.",children:Rt?e.jsxs("div",{className:"flex flex-wrap items-end gap-2 max-lg:flex-nowrap max-lg:gap-1.5",onClick:_=>_.stopPropagation(),onKeyDown:_=>_.stopPropagation(),children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{htmlFor:"patient-source-field",className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Custom field key"}),e.jsx(be,{id:"patient-source-field",value:dt,onChange:_=>et(_.target.value),placeholder:"e.g. source",className:"h-8 max-w-xs rounded-lg border-subtle text-xs max-lg:h-7",disabled:y||Ye})]}),e.jsx(Kp,{changed:He,saving:Ye,onSave:Vc,onDiscard:()=>et(Lt),accentColor:h,saveLabel:"Save patient source field"})]}):null})]})})]})}),e.jsx(qs,{value:"webhooks",className:"mt-0",children:e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsx(uc,{store:g}),e.jsx(tt,{id:"client-webhooks-simulator",title:"Webhook simulator",description:"Generate a signed sample payload, replay it with cURL, or send it to a saved endpoint.",icon:Ms,accentColor:h,bodyClassName:"p-4 sm:p-5",children:e.jsx(xc,{clientId:m,endpoints:g.endpoints,onSendEvent:g.sendEvent})})]})}),e.jsx(qs,{value:"analytics",className:"mt-0",children:e.jsxs(tt,{id:"client-api-analytics",title:"Analytics",description:`Aggregated from the most recent ${ll} saved API and webhook log entries for this client.`,icon:po,accentColor:h,actions:e.jsxs(B,{type:"button",size:"sm",variant:"outline",onClick:re,disabled:ae,className:"h-8 gap-1.5 rounded-full px-3 text-xs max-lg:h-7 max-lg:gap-1 max-lg:px-2 max-lg:text-2xs",children:[ae?e.jsx($e,{size:"xs"}):e.jsx(ts,{className:"size-3"}),"Refresh"]}),bodyClassName:"p-0",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-px border-b border-subtle bg-slate-200 dark:bg-slate-700 xl:grid-cols-4",children:[e.jsx(La,{label:"Requests",value:String(Ct.totalRequests)}),e.jsx(La,{label:"Success rate",value:cl(Ct.successRate)}),e.jsx(La,{label:"Avg duration",value:Vn(Ct.averageDuration)}),e.jsx(La,{label:"Webhooks",value:String(Ct.webhookCount),sub:`${Ct.deliveredWebhooks} delivered · ${Ct.failedWebhooks} failed`})]}),e.jsx("div",{className:"border-b border-subtle px-4 py-3 max-lg:px-2.5 max-lg:py-2",children:e.jsx("h3",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Top endpoints"})}),ae&&!Ae?e.jsx("div",{className:"flex items-center justify-center px-3 py-10 max-lg:py-6",children:e.jsx(Ve,{className:"size-4 animate-spin text-blue-600 max-lg:size-3.5"})}):e.jsxs(la,{children:[e.jsx(oa,{children:e.jsxs(At,{children:[e.jsx(Be,{className:"h-9 px-4 text-xs max-lg:px-2",children:"Endpoint"}),e.jsx(Be,{className:"h-9 px-4 text-xs max-lg:px-2",children:"Requests"}),e.jsx(Be,{className:"h-9 px-4 text-xs max-lg:px-2",children:"Success"}),e.jsx(Be,{className:"h-9 px-4 text-xs max-lg:px-2",children:"Avg duration"})]})}),e.jsxs(ca,{children:[Ct.topEndpoints.length===0?e.jsx(At,{children:e.jsx(Ie,{colSpan:4,className:"px-4 py-10 text-center text-xs text-content-tertiary max-lg:px-2 max-lg:py-6",children:"No request activity has been logged yet."})}):null,Ct.topEndpoints.map(_=>e.jsxs(At,{children:[e.jsx(Ie,{className:"px-4 py-3 font-mono text-xs text-slate-700 max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs dark:text-slate-300",children:_.endpoint}),e.jsx(Ie,{className:"px-4 py-3 text-xs tabular-nums text-content-secondary max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs",children:_.count}),e.jsx(Ie,{className:"px-4 py-3 text-xs tabular-nums text-content-secondary max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs",children:cl(_.success/_.count*100)}),e.jsx(Ie,{className:"px-4 py-3 text-xs tabular-nums text-content-secondary max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs",children:Vn(_.duration/_.count)})]},_.endpoint))]})]})]})}),e.jsx(qs,{value:"request-log",className:"mt-0",children:e.jsx($s,{id:"client-api-request-log",title:"Request log",tooltipDescription:"Covers server-side API calls, webhook deliveries, and Hosted Checkout payment failures for this client. Successful Hosted Checkout payments appear under Orders, not here.",description:"Server-side API calls, webhook deliveries, and Hosted Checkout payment failures for this client. Select a row for details.",icon:Ua,accentColor:h,filteredCount:kt.length,totalCount:ie.length,search:{placeholder:"Search logs",value:V,onChange:D,testId:"input-client-api-request-log-search"},filters:[{id:"type",filters:Wp,activeFilters:T,onFilterChange:$,defaultLabel:"Type",branding:u},{id:"status",filters:Gp,activeFilters:S,onFilterChange:Q,defaultLabel:"Status",branding:u}],actions:e.jsx("div",{className:"flex flex-wrap items-center justify-end gap-2 max-lg:flex-nowrap max-lg:gap-1",children:e.jsxs(B,{type:"button",size:"sm",variant:"outline",onClick:re,disabled:ae,className:"h-8 gap-1.5 rounded-full px-3 text-xs max-lg:h-7 max-lg:gap-1 max-lg:px-2 max-lg:text-2xs",children:[ae?e.jsx($e,{size:"xs"}):e.jsx(ts,{className:"size-3"}),"Refresh"]})}),loading:ae&&!Ae,surfaceBodyClassName:"p-0",columns:Ac,rows:kt,rowKey:"id",rowClick:_=>Kt(_.id),rowClassName:_=>Bt&&(ke==null?void 0:ke.id)===_.id?"bg-surface-sunken":"",rowTestId:_=>`row-client-api-request-log-${_.id}`,tableLabel:"Client API request log table",tableTestId:"table-client-api-request-log",emptyMessage:ie.length===0?"N
318o API, webhook, or Hosted Checkout failure activity has been logged yet.":"No logs match the current filters.",csvExport:{feature:"api-request-logs",tenantSlug:u==null?void 0:u.businessName,view:{getRows:()=>kt},allData:{mode:"client",getRows:_e},columns:Bp,testId:"button-export-api-request-logs"}})})]})}),e.jsx(zp,{open:z,onOpenChange:q,clientId:m,apiKey:(ze==null?void 0:ze.value)||"",shareableDocsUrl:Qe}),e.jsx(at,{open:ve,onOpenChange:Ee,title:"Create API key",description:"Choose a key type.",mobileCompactHeaderRow:!0,mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",footerClassName:"max-[1024px]:gap-1.5 max-[1024px]:px-3 max-[1024px]:py-2.5",contentClassName:"max-w-lg",bodyClassName:"p-4 max-[1024px]:px-3 max-[1024px]:py-2.5 sm:p-5",footer:e.jsx(B,{type:"button",variant:"outline",className:"rounded-full",onClick:()=>Ee(!1),children:"Cancel"}),children:e.jsx($t,{className:"bg-surface-raised p-3 max-lg:p-2",children:e.jsx("div",{className:K("grid gap-3 max-lg:gap-2","sm:grid-cols-2"),children:[{id:"server",label:"Regular API key",description:"Private key for backend systems.",action:()=>Ic(),saving:N},{id:"storefront",label:"Storefront key",description:"Public key for checkout embeds.",action:()=>Fc(),saving:k}].map(_=>e.jsxs("button",{type:"button",onClick:()=>{nt(_.id),_.action()},disabled:N||k,className:"flex min-h-32 flex-col items-start justify-between gap-4 rounded-lg border border-subtle px-4 py-4 text-left transition-colors max-lg:min-h-0 max-lg:gap-2.5 max-lg:px-2.5 max-lg:py-2.5 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-60 dark:hover:bg-slate-900/40",children:[e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-content-primary max-lg:text-xs",children:_.label}),e.jsx("span",{className:"mt-2 block text-xs leading-relaxed text-content-tertiary max-lg:mt-1 max-lg:text-2xs max-lg:leading-snug",children:_.description})]}),e.jsxs("span",{className:"inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-xs font-medium text-white max-lg:h-7 max-lg:gap-1 max-lg:px-2.5 max-lg:text-2xs",style:{backgroundColor:h},children:[_.saving||Oe===_.id&&(N||k)?e.jsx(Ve,{className:"size-3.5 animate-spin max-lg:size-3"}):e.jsx(ot,{className:"size-3.5 max-lg:size-3"}),"Generate"]})]},_.id))})})}),e.jsx(at,{open:!!ze,onOpenChange:_=>{_||pt(null)},title:"Copy your key now",description:"For security, this is the only time the full key is shown. Store it somewhere safe.",mobileCompactHeaderRow:!0,mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",bodyClassName:"max-[1024px]:px-3 max-[1024px]:py-2.5",footerClassName:"max-[1024px]:gap-1.5 max-[1024px]:px-3 max-[1024px]:py-2.5",footer:e.jsx(B,{type:"submit",form:"client-api-section-form-2",className:"rounded-full",children:"Done"}),children:e.jsx("form",{id:"client-api-section-form-2",className:us,onSubmit:xs(()=>pt(null)),children:e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[ze!=null&&ze.name?e.jsxs("p",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:["Key ",e.jsx("span",{className:"font-medium text-slate-700 dark:text-slate-200",children:ze.name})]}):null,e.jsxs("div",{className:"flex items-center gap-1.5 max-lg:gap-1",children:[e.jsx(be,{readOnly:!0,value:(ze==null?void 0:ze.value)||"",onFocus:_=>_.target.select(),className:"h-9 flex-1 rounded-lg font-mono text-xs max-lg:h-8"}),e.jsx(B,{type:"button",variant:"outline",className:"h-9 shrink-0 gap-1.5 rounded-lg px-3 text-xs max-lg:h-8 max-lg:gap-1 max-lg:px-2 max-lg:text-2xs",onClick:()=>Kr((ze==null?void 0:ze.value)||"","revealed"),children:cs==="revealed"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"size-3.5 max-lg:size-3"})," Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(ms,{className:"size-3.5 max-lg:size-3"})," Copy"]})})]})]})})}),e.jsx(Vd,{open:Bt,onOpenChange:Gt,children:e.jsx(qd,{side:"right",accessibleTitle:`Log detail${ke!=null&&ke.name?`: ${ke.name}`:""}`,className:"flex w-[min(38rem,96vw)] max-w-none flex-col gap-0 p-0 max-lg:w-[min(38rem,100vw)]",children:ke?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border-b border-subtle px-5 py-4 pr-12 max-lg:px-3 max-lg:py-2.5 max-lg:pr-11",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 max-lg:gap-1.5",children:[e.jsx(Ys,{tone:ke.type==="webhook"?"event":"info",label:ke.typeLabel}),e.jsx(Ys,{tone:ke.statusTone,label:ke.statusLabel})]}),e.jsx("p",{className:"mt-2 break-all font-mono text-xs text-content-secondary max-lg:mt-1.5 max-lg:text-2xs",children:ke.actualPath||ke.name})]}),e.jsxs("div",{className:"flex-1 space-y-4 overflow-auto px-5 py-4 max-lg:space-y-2.5 max-lg:px-3 max-lg:py-2.5",children:[e.jsxs("div",{className:"grid gap-2 text-xs max-lg:gap-1.5 max-lg:text-2xs",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:gap-2",children:[e.jsx("span",{className:"text-content-tertiary",children:"Time"}),e.jsx("span",{className:"font-medium text-content-primary",children:na(ke.createdAt)})]}),ke.type==="incoming"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:gap-2",children:[e.jsx("span",{className:"text-content-tertiary",children:"API version"}),e.jsx("span",{className:"font-medium text-content-primary",children:ke.apiVersion||"Not recorded"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:gap-2",children:[e.jsx("span",{className:"text-content-tertiary",children:"API key"}),e.jsxs("span",{className:"text-right font-medium text-content-primary",children:[ke.apiKeyName||(ke.apiKeyId?`Key ${ke.apiKeyId.slice(0,8)}`:"Not recorded"),ke.apiKeyPrefix?e.jsxs("span",{className:"ml-1 font-mono text-2xs text-content-tertiary",children:["(",ke.apiKeyPrefix,"â¢â¢â¢â¢)"]}):null]})]})]}):null,ke.type==="incoming"?e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:gap-2",children:[e.jsx("span",{className:"text-content-tertiary",children:"Duration"}),e.jsx("span",{className:"font-medium text-content-primary",children:Vn(ke.durationMs)})]}):null,(Xr=ke.log)!=null&&Xr.webhookUrl?e.jsxs("div",{className:"space-y-1 pt-1",children:[e.jsx("span",{className:"text-content-tertiary",children:"Webhook URL"}),e.jsx("p",{className:"break-all font-mono text-xs text-content-primary",children:ke.log.webhookUrl})]}):null]}),(Zr=ke.log)!=null&&Zr.errorMessage?e.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 p-2.5 text-xs text-red-700 max-lg:p-2 max-lg:text-2xs dark:border-red-800 dark:bg-red-900/20 dark:text-red-300",children:ke.log.errorMessage}):null,Ia(((ei=ke.log)==null?void 0:ei.requestBodyJson)||((ti=ke.log)==null?void 0:ti.requestBodyString)||((si=ke.log)==null?void 0:si.payload))?e.jsxs("div",{className:"space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Request"}),e.jsx("pre",{className:"max-h-72 overflow-auto rounded-lg bg-slate-950 p-3 text-2xs leading-relaxed text-slate-100 max-lg:max-h-52 max-lg:p-2 max-lg:text-3xs max-lg:leading-snug",children:Ia(((ai=ke.log)==null?void 0:ai.requestBodyJson)||((ni=ke.log)==null?void 0:ni.requestBodyString)||((ri=ke.log)==null?void 0:ri.payload))})]}):null,Ia(((ii=ke.log)==null?void 0:ii.responseBodyJson)||((li=ke.log)==null?void 0:li.responseBodyString)||((oi=ke.log)==null?void 0:oi.response))?e.jsxs("div",{className:"space-y-1.5 max-lg:space-y-1",children:[e.jsx(oe,{className:"text-xs font-medium text-slate-700 max-lg:text-2xs dark:text-slate-200",children:"Response"}),e.jsx("pre",{className:"max-h-72 overflow-auto rounded-lg bg-slate-950 p-3 text-2xs leading-relaxed text-slate-100 max-lg:max-h-52 max-lg:p-2 max-lg:text-3xs max-lg:leading-snug",children:Ia(((ci=ke.log)==null?void 0:ci.responseBodyJson)||((di=ke.log)==null?void 0:di.responseBodyString)||((mi=ke.log)==null?void 0:mi.response))})]}):null]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-5 text-center max-lg:px-3",children:[e.jsx(Ua,{className:"size-8 text-slate-300 max-lg:size-6 dark:text-slate-600"}),e.jsx("p",{className:"mt-2 text-sm font-medium text-content-primary max-lg:mt-1.5 max-lg:text-xs",children:"No log selected"})]})})}),n]})}function Qp(t){const{userDoc:s,tenantPreviewRequestContext:a}=Se(),i=t.clientId||(s==null?void 0:s.clientId)||"",n=JSON.stringify([i,s==null?void 0:s.id,a==null?void 0:a.previewRuntimeId]);return e.jsx(Yp,{...t},n)}const Jp=go("manageClient");async function qr(t,s){const a=Ls.currentUser;if(!a)throw new Error("Not authenticated");const i=await a.getIdToken(),n=await fetch(Jp,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({action:t,...s})}),r=await n.json().catch(()=>({}));if(!n.ok||(r==null?void 0:r.success)===!1)throw new Error((r==null?void 0:r.error)||"Request failed");return(r==null?void 0:r.data)||{}}function Xp({clientId:t,channel:s="all",limit:a=50,cursor:i=null}){return qr("listClientCommunicationLogs",{clientId:t,channel:s,limit:a,cursor:i})}function Zp({clientId:t,channel:s,logId:a}){return qr("getClientCommunicationLog",{clientId:t,channel:s,logId:a})}function hc({clientId:t,logId:s}){return qr("resendClientCommunicationLog",{clientId:t,logId:s})}const eg={queued:"pending",accepted:"pending",sending:"processing",received:"delivered",undelivered:"failed",skipped:"inactive"};function fc(t){const s=String(t||"").trim().toLowerCase();return eg[s]||s||"unknown"}function ma(t){const s=String(t||"").trim().replace(/[_-]+/g," ");return s?s.charAt(0).toUpperCase()+s.slice(1):"â"}
318function tg(t){return t?new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"â"}function sg(t){if(!t)return"â";const s=new Date(t),a=s.getFullYear()===new Date().getFullYear();return s.toLocaleString(void 0,{month:"short",day:"numeric",...a?{}:{year:"numeric"},hour:"numeric",minute:"2-digit"})}function qn(t={}){return t.recipientEmail||t.recipientPhone||"â"}function ag(t=""){const s=String(t||""),a='<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">';return/<html[\s>]/i.test(s)?s:`<!doctype html><html><head>${a}</head><body style="margin:0;background:#ffffff;">${s}</body></html>`}function ng({label:t,children:s}){return e.jsx(Wt,{delayDuration:150,children:e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex size-5 shrink-0 items-center justify-center rounded-full text-slate-400 transition hover:text-slate-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-300 dark:hover:text-slate-200","aria-label":t,children:e.jsx(Ds,{className:"size-3.5","aria-hidden":!0})})}),e.jsx(os,{className:"max-w-xs text-xs leading-relaxed",children:s})]})})}function Oa({label:t,children:s}){return e.jsxs("div",{className:"min-w-0",children:[e.jsx("dt",{className:"text-3xs font-medium uppercase tracking-wide text-content-tertiary",children:t}),e.jsx("dd",{className:"mt-0.5 truncate text-xs text-content-primary",children:s??e.jsx("span",{className:"text-slate-400 dark:text-slate-500",children:"â"})})]})}function rg({open:t,onOpenChange:s,clientId:a,logRef:i,accentColor:n="#2563eb",onResent:r}){const[l,c]=o.useState(null),[u,m]=o.useState(!1),[h,g]=o.useState(""),[y,p]=o.useState(!1),d=(i==null?void 0:i.id)||null,x=(i==null?void 0:i.channel)||"email";o.useEffect(()=>{if(!t||!a||!d)return;let P=!1;return m(!0),g(""),c(null),Zp({clientId:a,channel:x,logId:d}).then(A=>{P||c((A==null?void 0:A.record)||null)}).catch(A=>{P||g(A.message||"Unable to load this message.")}).finally(()=>{P||m(!1)}),()=>{P=!0}},[x,a,d,t]);const f=o.useCallback(async()=>{if(!(!a||!d)){p(!0);try{await hc({clientId:a,logId:d}),I.success("Email queued to send again"),r==null||r(),s(!1)}catch(P){I.error(P.message||"Unable to resend this email.")}finally{p(!1)}}},[a,d,s,r]),C=o.useMemo(()=>(l==null?void 0:l.channel)==="email"?ag(l.html):null,[l]),N=(l==null?void 0:l.direction)==="inbound",v=((l==null?void 0:l.channel)||x)!=="sms",k=!!(l!=null&&l.canResend);return e.jsxs(at,{open:t,onOpenChange:s,title:(i==null?void 0:i.subject)||(x==="sms"?"Text message":"Email"),description:e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[N?e.jsx(Jo,{className:"size-3.5 text-emerald-600 dark:text-emerald-400","aria-hidden":!0}):e.jsx(du,{className:"size-3.5 text-slate-400 dark:text-slate-500","aria-hidden":!0}),N?"Received from":"Sent to"," ",(l==null?void 0:l.recipientName)||(i==null?void 0:i.recipientName)||(l==null?void 0:l.recipientEmail)||(l==null?void 0:l.recipientPhone)||"recipient"," · ",tg((l==null?void 0:l.createdAt)??(i==null?void 0:i.createdAt))]}),contentClassName:v?"h-[min(88vh,46rem)] max-h-[calc(100dvh-1rem)] w-full max-w-3xl":"max-h-[calc(100dvh-1rem)] w-full max-w-lg",bodyClassName:`flex min-h-0 flex-col overflow-hidden p-0 max-[1024px]:p-0${v?" flex-1":""}`,contentTestId:"dialog-client-communication-log",footer:e.jsxs("div",{className:"flex w-full items-center justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",className:"rounded-full",onClick:()=>s(!1),children:"Close"}),k?e.jsx(ng,{label:"About sending again",children:"Sends this exact message again to the same address. Nothing is re-rendered, so the recipient gets a copy of what is shown here."}):null,k?e.jsxs(B,{type:"button",className:"rounded-full text-white hover:opacity-90",style:{backgroundColor:n},onClick:f,disabled:y||u,children:[y?e.jsx(Ve,{className:"mr-1.5 size-3.5 animate-spin","aria-hidden":!0}):e.jsx(ts,{className:"mr-1.5 size-3.5","aria-hidden":!0}),"Send again"]}):null]}),children:[e.jsxs("dl",{className:"grid shrink-0 grid-cols-2 gap-x-4 gap-y-2 border-b border-subtle px-4 py-2.5 sm:grid-cols-4",children:[e.jsx(Oa,{label:"From",children:l==null?void 0:l.from}),e.jsx(Oa,{label:"To",children:(l==null?void 0:l.to)||(i==null?void 0:i.recipientEmail)||(i==null?void 0:i.recipientPhone)}),e.jsx(Oa,{label:"Type",children:ma((l==null?void 0:l.type)||(i==null?void 0:i.type))}),e.jsx(Oa,{label:"Status",children:l?e.jsx(Bo,{status:fc(l.status),label:ma(l.status)}):null})]}),l!=null&&l.errorMessage?e.jsx("p",{className:"shrink-0 border-b border-red-200 bg-red-50 px-4 py-2 text-xs text-red-700 dark:border-red-900/60 dark:bg-red-950/40 dark:text-red-300",children:l.errorMessage}):null,e.jsx("div",{className:`flex min-h-0 flex-col overflow-hidden bg-surface-sunken p-3${v?" flex-1":""}`,children:u?e.jsxs("div",{className:"space-y-2 p-1",children:[e.jsx(ue,{className:"h-4 w-2/3"}),e.jsx(ue,{className:"h-4 w-1/2"}),e.jsx(ue,{className:"h-48 w-full"})]}):h?e.jsx("p",{className:"p-4 text-sm text-red-600 dark:text-red-400",children:h}):(l==null?void 0:l.channel)==="sms"?e.jsx("div",{className:"overflow-y-auto rounded-lg border border-subtle bg-surface-raised p-4",children:e.jsx("p",{className:"whitespace-pre-wrap text-sm text-slate-800 dark:text-slate-200",children:l.body||"This message had no text content."})}):e.jsx("iframe",{title:`Email preview: ${(l==null?void 0:l.subject)||"message"}`,className:"h-full w-full flex-1 rounded-lg border border-subtle bg-surface-raised","data-testid":"iframe-client-communication-log-preview",sandbox:"",referrerPolicy:"no-referrer",srcDoc:C||"",style:{colorScheme:"light"}})})]})}const ig=50,lg=[{id:"all",label:"Email and SMS"},{id:"email",label:"Email only"},{id:"sms",label:"SMS only"}];function xl(t,s){const a=new Map;return t.forEach(i=>
318{const n=s(i);n&&a.set(n,(a.get(n)||0)+1)}),Array.from(a.entries()).sort(([i],[n])=>i.localeCompare(n)).map(([i,n])=>({id:i,label:ma(i),count:n}))}function og(){const{userDoc:t,clientData:s}=Se(),{branding:a}=Ce(),i=(t==null?void 0:t.clientId)||(s==null?void 0:s.id)||null,n=(a==null?void 0:a.accentColor)||(s==null?void 0:s.accentColor)||je,[r,l]=o.useState([]),[c,u]=o.useState("all"),[m,h]=o.useState(!0),[g,y]=o.useState(!1),[p,d]=o.useState(""),[x,f]=o.useState(""),[C,N]=o.useState([]),[v,k]=o.useState([]),[P,A]=o.useState(null),E=o.useRef(null),z=o.useRef(!1),q=o.useRef(0),R=o.useCallback(async({append:J=!1}={})=>{if(!i){l([]),h(!1);return}const ge=q.current+1;q.current=ge,J?y(!0):h(!0),d("");try{const ye=await Xp({clientId:i,channel:c,limit:ig,cursor:J?E.current:null});if(q.current!==ge)return;const Re=(ye==null?void 0:ye.rows)||[];E.current=(ye==null?void 0:ye.nextCursor)||null,z.current=!!(ye!=null&&ye.hasMore&&(ye!=null&&ye.nextCursor)),l(G=>{if(!J)return Re;const U=new Set(G.map(V=>`${V.channel}:${V.id}`));return[...G,...Re.filter(V=>!U.has(`${V.channel}:${V.id}`))]})}catch(ye){if(q.current!==ge)return;d(ye.message||"Unable to load communications."),J||l([])}finally{q.current===ge&&(h(!1),y(!1))}},[c,i]);o.useEffect(()=>{E.current=null,z.current=!1,R()},[R]);const O=o.useCallback(()=>{!z.current||g||m||R({append:!0})},[R,m,g]),j=o.useCallback(()=>{E.current=null,z.current=!1,R()},[R]),L=o.useCallback(async J=>{try{await hc({clientId:i,logId:J.id}),I.success("Email queued to send again"),j()}catch(ge){I.error(ge.message||"Unable to resend this email.")}},[i,j]),b=o.useMemo(()=>xl(r,J=>J.status),[r]),w=o.useMemo(()=>xl(r,J=>J.type),[r]),F=o.useMemo(()=>{const J=x.trim().toLowerCase();return r.filter(ge=>C.length&&!C.includes(ge.status)||v.length&&!v.includes(ge.type)?!1:J?[ge.recipientName,ge.recipientEmail,ge.recipientPhone,ge.subject,ge.type].filter(Boolean).some(ye=>String(ye).toLowerCase().includes(J)):!0)},[r,x,C,v]),{sortedData:M,sortKey:W,sortDirection:H,handleSort:ae}=Ur(F,"createdAt","desc"),xe=!!x.trim()||C.length>0||v.length>0||c!=="all",Ae=o.useCallback(()=>{f(""),N([]),k([]),u("all")},[]),se=o.useMemo(()=>[{id:"createdAt",header:"When",sortKey:"createdAt",minWidth:150,fixedWidth:!0,csvValue:J=>J.createdAt?new Date(J.createdAt).toISOString():"",renderCell:J=>e.jsx("span",{className:"block truncate text-xs tabular-nums text-content-secondary max-lg:text-2xs",children:sg(J.createdAt)})},{id:"channel",header:"Channel",sortKey:"channel",minWidth:96,fixedWidth:!0,csvValue:J=>`${J.channel==="sms"?"SMS":"Email"} (${J.direction})`,renderCell:J=>{const ge=J.channel==="sms"?pa:Ar;return e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-slate-700 max-lg:text-2xs dark:text-slate-300",children:[e.jsx(ge,{className:"size-3.5 shrink-0 text-slate-400 dark:text-slate-500","aria-hidden":!0}),J.channel==="sms"?"SMS":"Email",J.direction==="inbound"?e.jsx(Jo,{className:"size-3 shrink-0 text-emerald-600 dark:text-emerald-400","aria-label":"Received from patient"}):null]})}},{id:"recipient",header:"Recipient",minWidth:220,csvValue:J=>[J.recipientName,qn(J)].filter(Boolean).join(" â "),renderCell:J=>e.jsx(_r,{primary:J.recipientName||qn(J),secondary:J.recipientName?qn(J):J.recipientType||"",highlight:x})},{id:"subject",header:"Subject",minWidth:260,csvValue:J=>J.subject||"",renderCell:J=>e.jsx("span",{className:"block truncate text-xs text-content-secondary max-lg:text-2xs",children:J.subject})},{id:"type",header:"Type",sortKey:"type",minWidth:150,hideOnMobile:!0,csvValue:J=>J.type||"",renderCell:J=>e.jsx("span",{className:"block truncate text-xs text-content-tertiary max-lg:text-2xs",children:ma(J.type)})},{id:"status",header:"Status",sortKey:"status",minWidth:110,fixedWidth:!0,align:"center",headerClassName:"text-center",csvValue:J=>J.status||"",renderCell:J=>e.jsx(Bo,{status:fc(J.status),label:ma(J.status)})}],[x]),Z=o.useMemo(()=>[cu({id:"channel",filters:lg,value:c,onChange:u,defaultLabel:"Email and SMS"}),b.length>1?{id:"status",filters:b,activeFilters:C,onFilterChange:N,defaultLabel:"All statuses"}:null,w.length>1?{id:"type",filters:w,activeFilters:v,onFilterChange:k,defaultLabel:"All types",searchable:!0}
318:null].filter(Boolean),[c,C,b,v,w]),fe=o.useCallback(J=>[{label:"View message",icon:xo,onSelect:()=>A(J)},...J.canResend?[{label:"Send again",icon:ts,onSelect:()=>L(J)}]:[]],[L]);return e.jsxs(e.Fragment,{children:[e.jsx($s,{id:"client-communication-logs",title:"Communications",tooltipDescription:"Newest first. Open a row to see the message exactly as it was delivered, and to send an email again.",icon:ho,accentColor:n,actions:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"h-8 rounded-full text-xs max-lg:h-7 max-lg:px-2 max-lg:text-2xs",onClick:j,disabled:m,children:[e.jsx(ts,{className:`mr-1.5 size-3.5 ${m?"animate-spin":""}`,"aria-hidden":!0}),"Refresh"]}),search:{value:x,onChange:f,placeholder:"Search recipient or subjectâ¦"},filters:Z,hasActiveFilters:xe,onClearFilters:Ae,filteredCount:F.length,totalCount:r.length,error:p,columns:se,rows:M,rowKey:J=>`${J.channel}:${J.id}`,rowClick:J=>A(J),rowKeyboardAccessible:!0,rowAriaLabel:J=>`Open ${J.channel==="sms"?"text message":"email"}: ${J.subject}`,contextMenuActions:fe,onEndReached:O,loading:m,loadingMore:g,skeletonRowCount:8,emptyMessage:xe?"No messages match these filters.":"No messages yet.",tableLabel:"Communication logs table",csvExport:{feature:"communication-logs",view:{getRows:()=>M,label:"Export what's in the table"},testId:"button-export-communication-logs"},maxHeight:620,sortKey:W,sortDirection:H,onSort:ae,compactDensity:!0}),e.jsx(rg,{open:!!P,onOpenChange:J=>{J||A(null)},clientId:i,logRef:P,accentColor:n,onResent:j})]})}const cn=15,cg=1440,dg={patientPaymentCompletedAllAdmins:{email:!1},patientPaymentCompletedResponsibleStaff:{email:!1},patientMessageReceived:{email:!1,sms:!1,throttleMinutes:cn}},mg=[{key:"patientPaymentCompletedAllAdmins",label:"Patient payment completed â all Client Admins"},{key:"patientPaymentCompletedResponsibleStaff",label:"Patient payment completed â responsible staff"},{key:"patientMessageReceived",label:"Patient messages",throttle:!0,supportsSms:!0}],ug={patientPaymentCompletedAllAdmins:"Email every active Client Admin when a patient order is paid.",patientPaymentCompletedResponsibleStaff:"Email the manual-invoice creator and the staff member who authorized a queued prescription payment prompt.",patientMessageReceived:"Account defaults for patient inbox alerts. Active Client Admins and Client Staff can override these in their personal notification preferences."};function bc(t,s=cn){const a=Number(t);return!Number.isFinite(a)||a<=0?s:Math.min(Math.round(a),cg)}function ra(t={}){return Object.entries(dg).reduce((s,[a,i])=>{const n=(t==null?void 0:t[a])||{},r={email:n.email===!0,...a==="patientMessageReceived"?{sms:n.sms===!0}:{}};return typeof i.throttleMinutes=="number"&&(r.throttleMinutes=bc(n.throttleMinutes,i.throttleMinutes)),s[a]=r,s},{})}function pl(t){return ug[t]||"Controls client admin email for this event."}const xg=[{key:"email",label:"Email"},{key:"sms",label:"SMS"}],pg=K("h-7 w-14 shrink-0 rounded-md border border-subtle bg-surface-raised px-1.5 text-center text-xs text-content-primary shadow-none","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:cursor-not-allowed disabled:opacity-50","max-lg:h-6 max-lg:w-12 max-lg:text-2xs");function gg(t){return t.email&&t.sms?"Follows the patient message default until you change it.":t.email?"Email follows the patient message default until you change it.":t.sms?"SMS follows the patient message default until you change it.":null}function yc({idPrefix:t,staffConfig:s=null,patientConfig:a=null,disabled:i=!1,control:n="checkbox",description:r,onSaveField:l}){const c=xu({staffConfig:s,patientConfig:a}),[u,m]=o.useState(null),h=c.throttleMinutes;o.useEffect(()=>{m(null)},[h]);const g=()=>{if(u===null)return;const p=Ho(u,or);m(null),p!==h&&(l==null||l("throttleMinutes",p))},y=gg(c.follows);return e.jsx("div",{className:"px-4 py-3 max-lg:px-2.5 max-lg:py-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 max-lg:gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Staff conversations"}),r?e.jsx("p",{className:"mt-0.5 text-xs leading-5 text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:r}):null,y?e.jsx("p",{className:"mt-0.5 text-xs leading-5 text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:y}):null,e.jsxs("div",{className:"mt-2 flex flex-nowrap items-center gap-1.5 max-lg:mt-1.5",children:[e.jsx("label",{htmlFor:`${t}-throttle`,className:"whitespace-nowrap text-xs text-content-tertiary max-lg:text-2xs",children:"At most once every"}),e.jsx("input",{id:`${t}-throttle`,type:"number",min:1,max:1440,value:u??h,disabled:i,onChange:p=>m(p.target.value),onBlur:g,className:pg}),e.jsx("span",{className:"whitespace-nowrap text-xs text-content-tertiary max-lg:text-2xs",children:"minutes per conversation"})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-4 max-lg:gap-3",children:xg.map(p=>{const d=`${t}-${p.key}`,x=c[p.key]===!0,f=`${p.label} default for staff conversations`;return n==="switch"?e.jsxs("div",{className:"flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx(oe,{htmlFor:d,className:"text-xs text-content-tertiary max-lg:text-2xs",children:p.label}),e.jsx(it,{id:d,checked:x,disabled:i,onCheckedChange:C=>l==null?void 0:l(p.key,C===!0),"aria-label":f})]},p.key):e.jsxs("label",{className:"inline-flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:p.label}),e.jsx(Me,{checked:x,disabled:i,onCheckedChange:C=>l==null?void 0:l(p.key,C===!0),className:"size-6","aria-label":f})]},p.key)})})]})})}function Hn(t,s){return JSON.stringify(t)===JSON.stringify(s)}function Ma({children:t}){return t?e.jsx("p",{className:"mt-0.5 text-xs leading-5 text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:t}):null}function hg({clientId:t,accentColor:s="#2563eb",canEdit:a=!0}){const[i,n]=o.useState(!0),[r,l]=o.useState(!1),[c,u]=o.useState(ra()),[m,h]=o.use
318State(aa()),[g,y]=o.useState(null),[p,d]=o.useState(null),[x,f]=o.useState(null),C=o.useRef(g),N=o.useRef(p),v=o.useRef(!1);o.useEffect(()=>{C.current=g},[g]),o.useEffect(()=>{N.current=p},[p]),o.useEffect(()=>{if(!t){n(!1);return}const j=qe(he(ce,"Clients",t),L=>{var M;if(v.current)return;const b=L.exists()?L.data():{},w=ra(b==null?void 0:b.clientNotifications),F=aa(b==null?void 0:b.patientNotifications);u(w),h(F),y(w),d(F),f(((M=b==null?void 0:b.clientNotifications)==null?void 0:M.staffMessageReceived)??null),n(!1)},L=>{console.error("Error loading client admin notification settings:",L),I.error("Unable to load notification settings."),n(!1)});return()=>j()},[t]);const k=o.useCallback(async(j,L)=>{if(!(!t||!a))try{l(!0),await Fe(he(ce,"Clients",t),{[`clientNotifications.${j}`]:L[j],updatedAt:Pe()}),y(L),I.success("Notification settings updated")}catch(b){console.error("Error saving client admin notification settings:",b),I.error("Unable to save notification settings."),u(C.current||ra())}finally{l(!1)}},[a,t]),P=o.useCallback(async j=>{if(!(!t||!a))try{l(!0),await Fe(he(ce,"Clients",t),{patientNotifications:j,updatedAt:Pe()}),d(j),I.success("Patient email setting updated")}catch(L){console.error("Error saving patient email notification setting:",L),I.error("Unable to save patient email setting."),h(N.current||aa())}finally{l(!1)}},[a,t]),A=o.useCallback(j=>{if(!a||r)return;const L={...m,[Ti]:j===!0};if(Hn(L,N.current)){h(L);return}h(L),P(L)},[a,m,P,r]),E=o.useCallback((j,L)=>{a&&u(b=>{const w={...b,[j]:L((b==null?void 0:b[j])||{})};return Hn(w,C.current)||k(j,w),w})},[a,k]),z=o.useCallback(async(j,L)=>{if(!t||!a)return;const b=x;f(w=>({...w&&typeof w=="object"?w:{},[j]:L}));try{l(!0),await Fe(he(ce,"Clients",t),{[`${cr.tenantClientStaffMessage}.${j}`]:L,updatedAt:Pe()}),I.success("Notification settings updated")}catch(w){console.error("Error saving staff conversation alert defaults:",w),I.error("Unable to save notification settings."),f(b)}finally{l(!1)}},[a,t,x]),q=o.useCallback((j,L)=>{a&&(v.current=!0,u(b=>({...b,[j]:{...(b==null?void 0:b[j])||{},throttleMinutes:L}})))},[a]),R=o.useCallback(j=>{a&&u(L=>{const b=(L==null?void 0:L[j])||{},w=bc(b.throttleMinutes,cn),F={...L,[j]:{...b,throttleMinutes:w}};return v.current=!1,Hn(F,C.current)||k(j,F),F})},[a,k]);if(!t)return null;const O=(m==null?void 0:m[Ti])===!0;return e.jsx(tt,{id:"client-account-notifications",title:"Account defaults",description:"Tenant-wide defaults for patient inbox alerts, staff conversation alerts, and payment notifications.",icon:Us,accentColor:s,loading:i,bodyClassName:"divide-y divide-slate-200 bg-surface-raised dark:divide-slate-700",children:i?e.jsxs("div",{className:"grid gap-2 p-4 max-lg:p-2.5",children:[e.jsx(ue,{className:"h-12 w-full rounded-lg max-lg:h-10"}),e.jsx(ue,{className:"h-12 w-full rounded-lg max-lg:h-10"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-3 max-lg:gap-2 max-lg:px-2.5 max-lg:py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(oe,{htmlFor:"client-disable-patient-emails",className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Disable patient emails and SMS"}),e.jsx(Ma,{children:"When on, patients get no emails or text messages from GEN Health, such as visit confirmations, reminders, message alerts, or order updates. Sign-in links, password resets, and verification codes still send. Staff and providers still get their alerts."})]}),e.jsx(it,{id:"client-disable-patient-emails",checked:O,disabled:!a||r,onCheckedChange:A,"aria-label":"Disable all patient emails and SMS for this client"})]}),mg.map(j=>{const L=(c==null?void 0:c[j.key])||{},b=L.email===!0,w=L.sms===!0,F=!a||r,M=j.supportsSms?b||w:b,W=(ae=!b)=>{F||E(j.key,xe=>({...xe,email:ae===!0}))},H=(ae=!w)=>{F||E(j.key,xe=>({...xe,sms:ae===!0}))};return j.supportsSms?e.jsx("div",{className:"px-4 py-3 max-lg:px-2.5 max-lg:py-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 max-lg:gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:j.label}),e.jsx(Ma,{children:pl(j.key)}),j.key==="patientMessageReceived"?e.jsx(Ma,{children:Wo}):null,j.throttle&&M?e.jsxs("div",{className:"mt-2 flex flex-nowrap items-center gap-1.5 max-lg:mt-1.5",children:[e.jsx("label",{htmlFor:`throttle-${j.key}`,className:"whitespace-nowrap text-xs text-content-tertiary max-lg:text-2xs",children:"At most once every"}),e.jsx("input",{id:`throttle-${j.key}`,type:"number",min:1,max:1440,value:L.throttleMinutes??cn,disabled:!a,onChange:ae=>q(j.key,ae.target.value),onBlur:()=>R(j.key),className:"h-7 w-14 shrink-0 rounded-md border border-subtle bg-surface-raised px-1.5 text-center text-xs text-content-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 max-lg:h-6 max-lg:w-12","aria-label":`Throttle minutes for ${j.label}`}),e.jsx("span",{className:"whitespace-nowrap text-xs text-content-tertiary max-lg:text-2xs",children:"minutes"})]}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-4 max-lg:gap-3",children:[e.jsxs("label",{className:"inline-flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:"Email"}),e.jsx(Me,{checked:b,disabled:F,onCheckedChange:ae=>W(ae),className:"size-6","aria-label":`Email default for ${j.label}`})]}),e.jsxs("label",{className:"inline-flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:"SMS"}),e.jsx(Me,{checked:w,disabled:F,onCheckedChange:ae=>H(ae),className:"size-6","aria-label":`SMS default for ${j.label}`})]})]})]})},j.key):e.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-3 max-lg:gap-2 max-lg:px-2.5 max-lg:py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(oe,{htmlFor:`client-notification-${j.key}`,className:"text-sm font-medium text-content-primary max-lg:text-xs",children:j.label}),e.jsx(Ma,{children:pl(j.key)})]}),e.jsx(it,{id:`client-notification-${j.key}`,checked:b,disabled:F,onCheckedChange:ae=>W(ae),"aria-label":`Email for ${j.label}`})]},j.key)}),e.jsx(yc,{idPrefix:"client-staff-message",staffConfig:x,patientConfig:c==null?void 0:c.patientMessageReceived,disabled:!a||r,description:"Account defaults for team channels, direct messages, and announcements. Client Admins and Client Staff can override these in their personal notification preferences.",onSaveField:z})]})})}const fg=["gfe_only","gfe_prescribe","affiliate"];function bg(t){const s=String(t||"").trim().toLowerCase();return fg.includes(s)?s:"gfe_only"}function yg(){const{userDoc:t,clientData:s}=Se(),{branding:a}=Ce(),i=(t==null?void 0:t.clientId)||(s==null?void 0:s.id)||null,n=(a==null?void 0:a.accentColor)||(s==null?void 0:s.accentColor)||(s==null?void 0:s.primaryColor)||je;return!i||!s?null:e.jsx(qo,{entity:s,entityType:"client",entityId:i,entityLabel:"client",accentColor:n,canEditBilling
318Contact:!0,canEditPaymentMethods:!0,platformBilling:s==null?void 0:s.platformBilling})}function vg(){const{userDoc:t}=Se(),s=t==null?void 0:t.clientId;return s?e.jsx(uu,{scopeType:"client",scopeId:s,tileColumns:4,hideWhen:a=>bg(a==null?void 0:a.model)==="affiliate"}):null}function Ng(){var l,c;const{userDoc:t,clientData:s}=Se(),{branding:a}=Ce(),i=(t==null?void 0:t.clientId)||(s==null?void 0:s.id)||null,n=(a==null?void 0:a.accentColor)||(s==null?void 0:s.accentColor)||(s==null?void 0:s.primaryColor)||je,r=ra(s==null?void 0:s.clientNotifications).patientMessageReceived;return i?e.jsxs("div",{className:"grid gap-4 max-lg:gap-2",children:[e.jsx(hg,{clientId:i,accentColor:n,canEdit:!0}),e.jsx(So,{userId:t==null?void 0:t.id,userDoc:t,clientData:s,tenantPatientMessageConfig:r,accentColor:n,title:"Your delivery preferences",description:"Override account defaults for patient inbox alerts sent to you.",canEdit:!0}),e.jsx(Eo,{userId:t==null?void 0:t.id,tenantStaffConfig:(l=s==null?void 0:s.clientNotifications)==null?void 0:l.staffMessageReceived,tenantPatientConfig:(c=s==null?void 0:s.clientNotifications)==null?void 0:c.patientMessageReceived,accentColor:n,canEdit:!0})]}):null}function jg(t){return e.jsx("div",{className:"space-y-6 max-lg:space-y-3",children:t})}const gl=[{id:"account",title:"Account settings",items:[{slug:"overview",aliases:["account","account-billing","billing"],title:"Account and billing",description:"Plan details, primary billing contact, and account payment method.",icon:ga,renderContent:()=>e.jsx(yg,{})},{slug:"notifications",aliases:["alerts"],title:"Notifications",description:"Account defaults and personal delivery preferences for patient inbox alerts and payment notifications.",icon:Us,renderContent:()=>e.jsx(Ng,{})},{slug:"payments",aliases:["payment-processor","shipping"],title:"Payments",description:"Patient checkout processor, API keys, instructions, and default shipping price.",icon:Vl,renderContent:()=>jg(e.jsxs("div",{className:"grid gap-4 max-lg:gap-2",children:[e.jsx(vg,{}),e.jsx(Qu,{}),e.jsx(Ju,{}),e.jsx(Yu,{})]}))},{slug:"orders",title:"Orders",description:"Create optional order statuses for your team to use during fulfillment.",icon:fo,renderContent:()=>e.jsx(Xu,{})},{slug:"branding",title:"Branding",description:"Business brand assets, colors, typography, themes, and custom portal domain.",icon:Ja,renderContent:()=>e.jsx(Rp,{})},{slug:"patient-experience",title:"Portal experience",description:"Patient portal navigation, dashboard modules, checkout flow order, and notifications.",icon:Wd,renderContent:()=>e.jsx(oc,{})},{slug:"security",title:"Security",description:"Configure MFA requirements for users logging in under this client.",icon:Lr,renderContent:()=>e.jsx(Fp,{tenantType:"client"})},{slug:"logs",aliases:["communications"],title:"Logs",description:"Email and SMS history for your patients and team.",icon:ho,renderContent:()=>e.jsx(og,{})},{slug:"developers",title:"Developers",description:"API keys, logs, webhook subscriptions, and implementation references.",icon:Rs,renderContent:t=>e.jsx(Qp,{headerActionsSlot:t==null?void 0:t.headerActionsSlot})}]}];function kg({embedded:t=!1,embeddedPath:s=null,onEmbeddedNavigate:a=null}){const{clientData:i,userDoc:n,userType:r}=Se(),l=Bl(n),c=o.useMemo(()=>{const u=Ts(r,"Client Admin")&&l==="Client"?gl.map(h=>h.id==="account"?{...h,items:[...h.items,{slug:"staff-permissions",title:"Staff permissions",description:"Role permissions and staff catalog visibility.",icon:Ir,renderContent:()=>e.jsx(Wu,{})}]}:h):gl;if(!Jl(i==null?void 0:i.model))return u;const m=new Set(["overview","payments","orders","patient-experience"]);return u.map(h=>({...h,items:h.items.filter(g=>!m.has(g.slug))}))},[i==null?void 0:i.model,r,l]);return e.jsx(To,{groups:c,embedded:t,embeddedPath:s,onEmbeddedNavigate:a})}function wg({embedded:t=!1,embeddedPath:s=null,onEmbeddedNavigate:a=null}){var p,d;const i=$l(),n=Gc(),{userDoc:r,clientData:l}=Se(),{branding:c}=Ce(),u=(c==null?void 0:c.accentColor)||(l==null?void 0:l.accentColor)||(l==null?void 0:l.primaryColor)||je,m=s||i.pathname,h=Pm(m),g=o.useMemo(()=>ra(l==null?void 0:l.clientNotifications).patientMessageReceived,[l==null?void 0:l.clientNotifications]),y=x=>{if(t&&a){a(x);return}n(x)};return h&&h!=="notifications"?(y(`${An}/notifications`),null):h?e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsx(Go,{title:"Notifications",description:"Choose how you want to be alerted about patient messages and staff conversations.",backOnClick:t?void 0:()=>y(An),backLabel:"Back to settings"}),e.jsx(So,{userId:r==null?void 0:r.id,userDoc:r,clientData:l,tenantPatientMessageConfig:g,accentColor:u,title:"Patient message alerts",description:"Control email and SMS alerts for your client inbox.",canEdit:!0}),e.jsx(Eo,{userId:r==null?void 0:r.id,tenantStaffConfig:(p=l==null?void 0:l.clientNotifications)==null?void 0:p.staffMessageReceived,tenantPatientConfig:(d=l==null?void 0:l.clientNotifications)==null?void 0:d.patientMessageReceived,accentColor:u,canEdit:!0})]}):e.jsx(xt,{className:"overflow-hidden rounded-xl border border-subtle bg-surface-raised dark:bg-slate-900/60",children:e.jsxs("button",{type:"button",onClick:()=>y(`${An}/notifications`),className:"flex w-full items-start gap-3 p-4 text-left transition-colors max-lg:gap-2 max-lg:p-2.5 hover:bg-slate-50 dark:hover:bg-slate-900",children:[e.jsx(Us,{className:"mt-0.5 size-5 text-content-tertiary max-lg:size-4"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-content-primary max-lg:text-xs",children:"Notifications"}),e.jsx("span",{className:"mt-1 block text-xs text-content-tertiary max-lg:text-2xs",children:"Choose how you want to be alerted about patient messages and staff conversations."})]})]})})}function Cg(){const{userDoc:t,providerNetwork:s}=Se(),{branding:a}=Ce(),i=(t==null?void 0:t.providerNetworkId)||(s==null?void 0:s.id)||null,n=(a==null?void 0:a.accentColor)||(s==null?void 0:s.accentColor)||(s==null?void 0:s.primaryColor)||je;return!i||!s?null:e.jsx(qo,{entity:s,entityType:"providerNetwork",entityId:i,entityLabel:"provider network",accentColor:n,canEditBilling
318Contact:!0,canEditPaymentMethods:!0,platformBilling:s==null?void 0:s.platformBilling})}const Sg=go("manageClient"),Eg="Patients receive text messages from this phone number when messaging is enabled.";function Tg({viewerUserType:t=null}){const{userDoc:s}=Se(),{branding:a}=Ce(),i=s==null?void 0:s.clientId,n=t||(s==null?void 0:s.userType)||"",r=bo(n,["Client Admin","Super Admin"]),l=(a==null?void 0:a.accentColor)||je,[c,u]=o.useState(!0),[m,h]=o.useState(null),[g,y]=o.useState({name:"",status:"active",timezone:""}),[p,d]=o.useState(null),[x,f]=o.useState(null);o.useEffect(()=>{if(!i){u(!1);return}const k=qe(he(ce,"Clients",i),P=>{if(!P.exists()){u(!1);return}const A=P.data(),E={name:A.name||"",status:A.status||"active",timezone:A.timezone||""};y(E),d(E),f(A.twilioMessaging||null),u(!1)},P=>{console.error("Error loading organization overview:",P),I.error("Unable to load organization details."),u(!1)});return()=>k()},[i]);async function C(k,P){if(!i)return!1;try{return h(k),await Fe(he(ce,"Clients",i),{[k]:P,updatedAt:Pe()}),d(A=>({...A,[k]:P})),I.success("Organization details updated"),!0}catch(A){return console.error(`Error updating ${k}:`,A),I.error("Unable to update organization details. Please try again."),y(E=>({...E,[k]:p==null?void 0:p[k]})),!1}finally{h(null)}}async function N(){if(!i||!r)return!1;const k=String(g.name||"").trim();if(!k)return I.error("Business entity name is required"),y(P=>({...P,name:(p==null?void 0:p.name)||""})),!1;try{h("name");const P=Ls.currentUser;if(!P)throw new Error("Not authenticated");const A=await P.getIdToken(),E=await fetch(Sg,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`},body:JSON.stringify({action:"updateClient",clientId:i,name:k,status:g.status||"active"})}),z=await E.json().catch(()=>({}));if(!E.ok||z.success===!1)throw new Error(z.error||"Unable to update business entity name.");return d(q=>({...q,name:k})),y(q=>({...q,name:k})),I.success("Business entity name updated"),!0}catch(P){return console.error("Error updating business entity name:",P),I.error(P.message||"Unable to update business entity name. Please try again."),y(A=>({...A,name:(p==null?void 0:p.name)||""})),!1}finally{h(null)}}function v(k){y(P=>({...P,[k]:p==null?void 0:p[k]}))}return i?e.jsxs("div",{className:"space-y-6 max-lg:space-y-3",children:[e.jsx(tt,{id:"client-organization-details",title:"Organization details",description:"Legal business identity and scheduling timezone.",icon:ga,accentColor:l,loading:c,bodyClassName:"p-5 max-lg:p-2.5",children:c?e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 max-lg:gap-2.5",children:[e.jsx(ue,{className:"h-10 w-full max-lg:h-8"}),e.jsx(ue,{className:"h-10 w-full max-lg:h-8"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2 md:items-start max-lg:gap-2.5",children:[e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsxs("div",{className:"flex min-h-5 items-center",children:[e.jsx(oe,{htmlFor:"organization-business-entity-name",className:"text-xs text-content-secondary max-lg:text-2xs",children:"Business entity name"}),r&&g.name!==(p==null?void 0:p.name)&&e.jsxs("div",{className:"ml-auto flex gap-1",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5",onClick:N,disabled:m==="name",style:{color:l},children:m==="name"?e.jsx($e,{size:"xs"}):e.jsx(Ze,{className:"size-3"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5 text-red-600 hover:bg-red-50 hover:text-red-700",onClick:()=>v("name"),disabled:m==="name",children:e.jsx(Ft,{className:"size-3"})})]})]}),e.jsx(be,{id:"organization-business-entity-name",name:"name",value:g.name,onChange:k=>y(P=>({...P,name:k.target.value})),disabled:!r||m==="name",className:`text-sm ${r?"":"bg-slate-100 dark:bg-slate-700"}`})]}),e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{htmlFor:"organization-timezone",className:"text-sm font-medium max-lg:text-xs",children:"Timezone"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:"Patient-facing schedules and communications use this timezone when available."})]}),g.timezone!==(p==null?void 0:p.timezone)&&e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{t
318ype:"button",size:"icon",variant:"ghost",className:"size-5",onClick:()=>C("timezone",g.timezone),disabled:m==="timezone",style:{color:l},children:m==="timezone"?e.jsx($e,{size:"xs"}):e.jsx(Ze,{className:"size-3"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-5 text-red-600 hover:bg-red-50 hover:text-red-700",onClick:()=>v("timezone"),disabled:m==="timezone",children:e.jsx(Ft,{className:"size-3"})})]})]}),e.jsxs(yt,{value:g.timezone||"__unset__",onValueChange:k=>y(P=>({...P,timezone:k==="__unset__"?"":k})),children:[e.jsx(vt,{id:"organization-timezone",className:"text-sm",children:e.jsx(Nt,{placeholder:"Select client timezone"})}),e.jsxs(jt,{children:[e.jsx(st,{value:"__unset__",children:"No timezone selected"}),yo.map(k=>e.jsx(st,{value:k.value,children:k.label},k.value))]})]})]})]})}),e.jsx(tt,{id:"client-messaging-number",title:"Messaging number",description:Eg,icon:gu,accentColor:l,loading:c,bodyClassName:"p-5 max-lg:p-2.5",children:c?e.jsx(ue,{className:"h-16 w-full rounded-lg max-lg:h-12"}):e.jsx(pu,{twilioMessaging:x,accentColor:l,editable:!1,bare:!0})})]}):null}const hl={name:"Network name",displayName:"Display name",timezone:"Timezone",supportEmail:"Support email"};function Pg(){const{currentUser:t,providerNetwork:s,userDoc:a}=Se(),{branding:i}=Ce(),n=s==null?void 0:s.id,[r,l]=o.useState(!0),[c,u]=o.useState({name:"",displayName:"",timezone:"",supportEmail:""}),[m,h]=o.useState(null),[g,y]=o.useState(null),p=o.useRef(!1),d=(i==null?void 0:i.accentColor)||je;o.useEffect(()=>{if(!n){l(!1);return}const v=he(ce,"ProviderNetworks",n),k=qe(v,P=>{if(P.exists()){const A=P.data(),E={name:A.name||"",displayName:A.displayName||A.companyName||"",timezone:A.timezone||"",supportEmail:A.supportEmail||""};u(E),h(E)}l(!1)},P=>{console.error("Error fetching provider network business details:",P),I.error("Unable to load business details. Please try again."),l(!1)});return()=>k()},[n]),o.useEffect(()=>{if(r||!n||p.current||c.supportEmail)return;async function v(){try{const k=String((a==null?void 0:a.email)||(t==null?void 0:t.email)||"").trim();if(!k)return;await Fe(he(ce,"ProviderNetworks",n),{supportEmail:k,updatedAt:Pe()}),u(P=>({...P,supportEmail:k})),h(P=>({...P,supportEmail:k})),I.info("Support Email auto-populated from your admin account.")}catch(k){console.error("Error auto-populating support email:",k)}finally{p.current=!0}}v()},[t==null?void 0:t.email,r,n,c.supportEmail,a==null?void 0:a.email]);async function x(v,k){if(n)try{y(v),await Fe(he(ce,"ProviderNetworks",n),{[v]:k,updatedAt:Pe()}),h(P=>({...P,[v]:k})),I.success(`${hl[v]||v} updated`)}catch(P){console.error(`Error updating ${v}:`,P),I.error(`Unable to update ${(hl[v]||v).toLowerCase()}. Please try again.`),u(A=>({...A,[v]:m[v]}))}finally{y(null)}}function f(v){u(k=>({...k,[v]:m[v]}))}function C(v){const{name:k,value:P}=v.target;u(A=>({...A,[k]:P}))}function N(v){return c[v]===(m==null?void 0:m[v])?null:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-6 max-[1024px]:h-6 max-[1024px]:w-6",onClick:()=>{if(v==="supportEmail"){const k=String(c.supportEmail||"").trim();if(k&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){I.error("Please enter a valid email address.");return}x("supportEmail",k);return}x(v,c[v])},disabled:g===v,style:{color:d},children:g===v?e.jsx(Ve,{className:"size-4 animate-spin max-lg:size-3.5"}):e.jsx(Ze,{className:"size-4 max-lg:size-3.5"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-6 text-red-600 hover:text-red-700 hover:bg-red-50 max-[1024px]:h-6 max-[1024px]:w-6",onClick:()=>f(v),disabled:g===v,children:e.jsx(Ft,{className:"size-4 max-lg:size-3.5"})})]})}return!r&&!n?null:e.jsxs(xt,{id:"network-business-details",className:"rounded-xl border border-subtle dark:bg-slate-800 overflow-hidden w-full flex flex-col scroll-mt-24",children:[e.jsx("div",{className:"bg-surface-sunken border-b border-subtle p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx("div",{className:"p-1.5 rounded-lg max-lg:p-1",style:{backgroundColor:d},children:e.jsx(ga,{className:"size-4 text-white max-lg:size-3.5"})}),e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Business Details"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Network identity, timezone, and support contact"})]})]})}),e.jsx("div",{className:"p-5 flex-1 max-lg:p-3",children:r?e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 max-lg:gap-2 md:grid-cols-2",children:[e.jsx(ue,{className:"h-16 w-full max-lg:h-12"}),e.jsx(ue,{className:"h-16 w-full max-lg:h-12"})]}),e.jsx(ue,{className:"h-16 w-full max-lg:h-12"}),e.jsx(ue,{className:"h-16 w-full max-lg:h-12"})]}):e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 max-lg:gap-2 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 max-lg:space-y-1",children:[e.jsxs("div",{className:"flex min-h-6 items-center justify-between max-lg:min-h-5",children:[e.jsx(Or,{htmlFor:"network-name",className:"max-lg:text-xs",children:"Network Name"}),N("name")]}),e.jsx(be,{id:"network-name",name:"name",type:"text",placeholder:"e.g., Regional Provider Network",value:c.name,onChange:C})]}),e.jsxs("div",{className:"space-y-2 max-lg:space-y-1",children:[e.jsxs("div",{className:"flex min-h-6 items-center justify-between max-lg:min-h-5",children:[e.jsx(oe,{htmlFor:"network-display-name",className:"max-lg:text-xs",children:"Display Name"}),N("displayName")]}),e.jsx(be,{id:"network-display-name",name:"displayName",placeholder:"Optional public-facing name",value:c.displayName,onChange:C})]})]}),e.jsxs("div",{className:"space-y-3 max-lg:space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1 max-lg:space-y-0.5",children:[e.jsx(oe,{htmlFor:"network-timezone",className:"max-lg:text-xs",children:"Timezone"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:"All network hours and schedules use this timezone."})]}),N("timezone")]}),e.jsxs(yt,{value:c.timezone,onValueChange:v=>u(k=>({...k,timezone:v})),children:[e.jsx(vt,{id:"network-timezone",className:"w-full",children:e.jsx(Nt,{placeholder:"Select network timezone"})}),e.jsx(jt,{children:yo.map(v=>e.jsx(st,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-3 max-lg:space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1 max-lg:space-y-0.5",children:[e.jsx(oe,{htmlFor:"network-support-email",className:"text-sm font-medium max-lg:text-xs",children:"Support Email"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:"This email will be visible to end-users as the reply-to contact for branded emails."})]}),N("supportEmail")]}),e.jsx(be,{id:"network-support-email",name:"supportEmail",type:"email",placeholder:"[email protected]",value:c.supportEmail,onChange:C})]})]})})]})}function Ag({providerNetworkId:t,accentColor:s,canEdit:a=!0}){const{providerNetwork:i}=Se(),{branding:n}=Ce(),r=t||(i==null?void 0:i.id),l=s||(n==null?void 0:n.accentColor)||je,[c,u]=o.useState(!0),[m,h]=o.use
318State({...fi}),[g,y]=o.useState({...fi}),[p,d]=o.useState(!1),x=!Gd(m,g);o.useEffect(()=>{if(!r){u(!1);return}const N=he(ce,"ProviderNetworks",r),v=qe(N,k=>{if(k.exists()){const P=bi(k.data());h(P),y(P)}u(!1)},k=>{console.error("Error fetching provider network clinic address:",k),I.error("Unable to load business address. Please try again."),u(!1)});return()=>v()},[r]);function f(){h(g)}async function C(){if(!r||!a)return;const{error:N,address:v}=Qd(m);if(N){I.error(N);return}try{d(!0),await Fe(he(ce,"ProviderNetworks",r),{address:v,updatedAt:Pe()}),y(bi({address:v})),I.success("Business address updated")}catch(k){console.error("Error updating business address:",k),I.error("Unable to update business address. Please try again.")}finally{d(!1)}}return!c&&!r?null:e.jsxs(xt,{id:"network-business-address",className:"rounded-xl border border-subtle dark:bg-slate-800 overflow-hidden w-full flex flex-col scroll-mt-24",children:[e.jsx("div",{className:"bg-surface-sunken border-b border-subtle p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 max-lg:flex-nowrap max-lg:gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 max-lg:gap-1.5",children:[e.jsx("div",{className:"p-1.5 rounded-lg shrink-0 max-lg:p-1",style:{backgroundColor:l},children:e.jsx(Kd,{className:"size-4 text-white max-lg:size-3.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Business address"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Physical location used when registering providers with OnlyScripts."})]})]}),x&&a?e.jsxs("div",{className:"flex gap-1 shrink-0",children:[e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-6 max-[1024px]:h-6 max-[1024px]:w-6",onClick:C,disabled:p,style:{color:l},"aria-label":"Save business address",children:p?e.jsx(Ve,{className:"size-4 animate-spin max-lg:size-3.5"}):e.jsx(Ze,{className:"size-4 max-lg:size-3.5"})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"size-6 text-red-600 hover:text-red-700 hover:bg-red-50 max-[1024px]:h-6 max-[1024px]:w-6",onClick:f,disabled:p,"aria-label":"Discard business address changes",children:e.jsx(Ft,{className:"size-4 max-lg:size-3.5"})})]}):null]})}),e.jsx("div",{className:"p-5 flex-1 max-lg:p-3",children:c?e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsx(ue,{className:"h-10 w-full max-lg:h-9"}),e.jsx(ue,{className:"h-10 w-full max-lg:h-9"}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 max-lg:gap-2 sm:grid-cols-3",children:[e.jsx(ue,{className:"h-10 w-full max-lg:h-9"}),e.jsx(ue,{className:"h-10 w-full max-lg:h-9"}),e.jsx(ue,{className:"h-10 w-full max-lg:h-9"})]})]}):e.jsx(Yd,{idPrefix:"network-clinic",value:m,onChange:h,disabled:!a||p,requiredFields:["street1","city","state","zip"],cityStateZipClassName:"grid gap-3 max-lg:gap-2 sm:grid-cols-3"})})]})}function Ig(){const t=[];for(let s=0;s<24;s++)for(let a=0;a<60;a+=15){const i=s.toString().padStart(2,"0"),n=a.toString().padStart(2,"0"),r=`${i}:${n}`,l=s===0?12:s>12?s-12:s,c=s<12?"AM":"PM",u=`${l}:${n} ${c}`;t.push({value:r,label:u})}return t}function dn({value:t,onChange:s,disabled:a,className:i,ariaLabel:n,testId:r}){const l=Ig();return e.jsxs(yt,{value:t,onValueChange:s,disabled:a,children:[e.jsx(vt,{className:`h-9 text-sm max-lg:h-8 ${i||""}`,"aria-label":n,"data-testid":r,children:e.jsx(Nt,{})}),e.jsx(jt,{className:"max-h-[300px]",children:l.map(c=>e.jsx(st,{value:c.value,className:"text-sm",children:c.label},c.value))})]})}function Rg({open:t,onOpenChange:s,onSave:a,timezone:i}){const{branding:n}=Ce(),r=(n==null?void 0:n.accentColor)||je,[l,c]=o.useState([]),[u,m]=o.useState("09:00"),[h,g]=o.useState("17:00"),[y,p]=o.useState(!1),[d,x]=o.use
318State(!1),f=async()=>{if(l.length===0){I.error("Please select at least one date");return}if(!y&&(!u||!h)){I.error("Please set both start and end times");return}if(!i){I.error("No timezone configured for this network. Go to Network Settings and set a timezone first.");return}try{x(!0);const C=l.map(N=>({startAt:vi(N,y?"00:00":u,i),endAt:vi(N,y?"23:59":h,i),unavailable:y}));await a(C),c([]),m("09:00"),g("17:00"),p(!1),s(!1)}catch(C){console.error("Error adding exceptions:",C)}finally{x(!1)}};return e.jsx(io,{open:t,onOpenChange:s,children:e.jsxs(lo,{className:`${Xd} max-w-5xl`,"data-testid":ys("dialog","schedule","add-exception"),children:[e.jsxs(oo,{className:`${Zd} max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2`,children:[e.jsx(co,{className:"font-display text-xl max-[1024px]:text-base max-[1024px]:leading-tight",children:"Add Schedule Exception"}),e.jsx(mo,{className:"max-[1024px]:text-2xs max-[1024px]:leading-snug",children:"Select the dates to override and set custom hours or mark as unavailable"})]}),e.jsx("div",{className:`${em} max-[1024px]:px-2 max-[1024px]:py-2`,children:e.jsx(xt,{className:`${tm} overflow-hidden bg-surface-raised p-0`,children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2",children:[e.jsxs("section",{className:"px-5 py-4 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{className:"text-sm font-medium mb-3 block text-content-primary max-lg:mb-1.5 max-lg:text-xs",children:"Select dates"}),e.jsx("p",{className:"text-xs text-content-tertiary mb-2 max-lg:mb-1 max-lg:text-2xs",children:"Click dates to select or deselect"}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-subtle bg-surface-raised p-2 max-lg:p-1.5 sm:flex sm:justify-center sm:p-4",children:e.jsx("div",{className:"[&_.rdp-day_button]:cursor-pointer",children:e.jsx(wm,{mode:"multiple",selected:l.map(C=>new Date(C+"T00:00:00")),onSelect:C=>{c(C?C.map(N=>{const v=N.getFullYear(),k=String(N.getMonth()+1).padStart(2,"0"),P=String(N.getDate()).padStart(2,"0");return`${v}-${k}-${P}`}):[])},className:"rounded-md"})})}),l.length>0&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-2 max-lg:mt-2 max-lg:gap-1.5",children:l.sort().map(C=>e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 border rounded-full text-sm max-lg:gap-1 max-lg:px-2 max-lg:py-0.5 max-lg:text-2xs",style:{backgroundColor:`${r}15`,color:r,borderColor:`${r}40`},children:[new Date(C).toLocaleDateString("en-US",{month:"short",day:"numeric"}),e.jsx("button",{type:"button",onClick:()=>c(N=>N.filter(v=>v!==C)),"aria-label":`Remove ${C} exception date`,"data-testid":ys("button","schedule","remove-exception-date",C),style:{color:r},onMouseEnter:N=>{N.currentTarget.style.opacity="0.7"},onMouseLeave:N=>{N.currentTarget.style.opacity="1"},children:e.jsx(Ft,{className:"size-3"})})]},C))})]}),e.jsxs("section",{className:"border-t border-subtle px-5 py-4 max-lg:px-3 max-lg:py-2.5 sm:px-6 lg:border-l lg:border-t-0",children:[e.jsx(oe,{className:"text-sm font-medium mb-3 block text-content-primary max-lg:mb-1.5 max-lg:text-xs",children:"Which hours are you free?"}),e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-lg bg-surface-sunken p-3 max-lg:gap-2 max-lg:p-2",children:[e.jsx(it,{checked:y,onCheckedChange:p,className:"data-[state=checked]:!bg-[var(--accent-color)]",style:{"--accent-color":r}}),e.jsx(oe,{className:"text-sm text-content-primary cursor-pointer max-lg:text-xs",children:"Mark unavailable (All day)"})]}),!y&&e.jsxs("div",{className:"space-y-3 max-lg:space-y-1.5",children:[e.jsx(oe,{className:"text-xs text-content-secondary max-lg:text-2xs",children:"Time range"}),e.jsxs("div",{className:"flex flex-col gap-3 max-lg:gap-1.5 sm:flex-row sm:items-center",children:[e.jsx(dn,{value:u,onChange:m,className:"flex-1",ariaLabel:"Exception start time",testId:ys("select","schedule","exception-start-time")}),e.jsx("span",{className:"text-sm text-content-tertiary max-lg:text-xs",children:"-"}),e.jsx(dn,{value:h,onChange:g,className:"flex-1",ariaLabel:"Exception end time",testId:ys("select","schedule","exception-end-time")})]})]})]})]})]})})}),e.jsxs(sm,{className:`${am} flex-col-reverse gap-3 max-[1024px]:gap-1.5 max-[1024px]:pt-2.5 sm:flex-row sm:justify-end`,children:[e.jsx(B,{variant:"outline",onClick:()=>s(!1),disabled:d,className:"rounded-full",children:"Close"}),e.jsx(B,{onClick:f,disabled:d||l.length===0,className:"rounded-full text-white",style:{backgroundColor:r,"--hover-bg":`${r}dd`},onMouseEnter:C=>{C.currentTarget.style.backgroundColor=`${r}dd`},onMouseLeave:C=>{C.currentTarget.style.backgroundColor=r},children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"size-4 mr-2 animate-spin"}),"Saving..."]}):"Save override"})]})]})})}function Lg({schedule:t,exceptions:s,onUpdateSchedule:a,onAddException:i,onDeleteException:n,loading:r=!1,title:l="Availability",description:c="Manage your weekly schedule and exceptions",timezone:u=null,showTimezoneLabel:m=!1}){const{branding:h}
318=Ce(),g=(h==null?void 0:h.accentColor)||je,[y,p]=o.useState(null),[d,x]=o.useState(!1),f=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];async function C(v){const k={...t,[v]:{...t[v],enabled:!t[v].enabled}};p(v);try{await a(k)}finally{p(null)}}async function N(v,k,P){const A={...t,[v]:{...t[v],[k]:P}};p(v);try{await a(A)}finally{p(null)}}return e.jsxs(e.Fragment,{children:[e.jsxs(xt,{className:"rounded-xl border border-subtle dark:bg-slate-800 overflow-hidden h-full w-full flex flex-col","data-testid":ys("section","settings","schedule-manager"),children:[e.jsx("div",{className:"bg-surface-sunken border-b border-subtle p-3 max-lg:p-2",children:e.jsx("div",{className:"flex items-center justify-between gap-3 max-lg:gap-1.5",children:e.jsxs("div",{className:"flex items-center gap-2 max-lg:min-w-0 max-lg:gap-1.5",children:[e.jsx("div",{className:"p-1.5 rounded-lg max-lg:p-1",style:{backgroundColor:g},children:e.jsx(Er,{className:"size-4 max-lg:size-3.5",style:{color:"#ffffff"}})}),e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:l}),e.jsxs("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:[c,m&&u&&e.jsxs("span",{className:"ml-2 font-medium",children:["(",Jd(u),")"]})]})]})]})})}),e.jsx("div",{className:"p-4 flex-1 max-lg:p-2.5",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 max-lg:gap-2.5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 max-lg:mb-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Default Weekly Schedule"}),e.jsx("p",{className:"text-xs text-content-tertiary mt-0.5 max-lg:text-2xs max-lg:leading-tight",children:"Set your regular hours"})]}),e.jsx("div",{className:"space-y-2 max-lg:space-y-1",children:r?[...Array(7)].map((v,k)=>e.jsxs("div",{className:"flex items-center gap-3 py-1.5 max-lg:gap-2 max-lg:py-1",children:[e.jsxs("div",{className:"flex items-center gap-2 w-28 max-lg:w-24 max-lg:gap-1.5",children:[e.jsx(ue,{className:"h-5 w-9 rounded-full"}),e.jsx(ue,{className:"h-3 w-16"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-1 max-lg:gap-1.5",children:[e.jsx(ue,{className:"h-9 flex-1 max-lg:h-8"}),e.jsx(ue,{className:"h-3 w-2"}),e.jsx(ue,{className:"h-9 flex-1 max-lg:h-8"})]})]},k)):f.map(v=>{var k,P;return e.jsxs("div",{className:"flex items-center gap-3 py-1.5 max-lg:gap-2 max-lg:py-1",children:[e.jsxs("div",{className:"flex items-center gap-2 w-28 max-lg:w-24 max-lg:gap-1.5",children:[e.jsx(it,{checked:((k=t==null?void 0:t[v])==null?void 0:k.enabled)??!1,onCheckedChange:()=>C(v),disabled:y===v,className:"data-[state=checked]:!bg-[var(--accent-color)] scale-90",style:{"--accent-color":g}}),e.jsx(oe,{className:"text-xs font-medium capitalize text-content-primary cursor-pointer max-lg:truncate max-lg:text-2xs",children:v})]}),(P=t==null?void 0:t[v])!=null&&P.enabled?e.jsxs("div",{className:"flex items-center gap-2 flex-1 max-lg:gap-1.5",children:[e.jsx(dn,{value:t[v].startTime,onChange:A=>N(v,"startTime",A),disabled:y===v,className:"flex-1",ariaLabel:`${v} start time`,testId:ys("select","schedule",v,"start-time")}),e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:"-"}),e.jsx(dn,{value:t[v].endTime,onChange:A=>N(v,"endTime",A),disabled:y===v,className:"flex-1",ariaLabel:`${v} end time`,testId:ys("select","schedule",v,"end-time")}),y===v&&e.jsx(Ve,{className:"size-3 animate-spin flex-shrink-0",style:{color:g}})]}):e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:"Unavailable"})]},v)})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 max-lg:mb-1.5 max-lg:flex-nowrap max-lg:gap-2",children:[e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Schedule Exceptions"}),e.jsx("p",{className:"text-xs text-content-tertiary mt-0.5 max-lg:text-2xs max-lg:leading-tight",children:"Override specific dates"})]}),e.jsxs(B,{size:"sm",onClick:()=>x(!0),disabled:r,className:"h-8 text-xs text-white hover:opacity-95 max-lg:shrink-0 max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",style:{backgroundColor:g},children:[e.jsx(ot,{className:"size-3 mr-1"}),"Add"]})]}),r?e.jsx("div",{className:"space-y-2 max-lg:space-y-1",children:Array.from({length:4}).map((v,k)=>e.jsx(ue,{className:"h-14 w-full rounded-lg max-lg:h-10"},k))}):!s||s.length===0?e.jsx("div",{className:"text-center py-12 text-xs text-content-tertiary border border-dashed border-subtle rounded-lg max-lg:py-6 max-lg:text-2xs",children:"No exceptions added yet"}):e.jsx("div",{className:"space-y-2 max-h-[320px] overflow-y-auto max-lg:max-h-56 max-lg:space-y-1",children:s.sort((v,k)=>{var E,z,q,R;const P=((z=(E=v.startAt)==null?void 0:E.toMillis)==null?void 0:z.call(E))??new Date(v.date||0).getTime(),A=((R=(q=k.startAt)==null?void 0:q.toMillis)==null?void 0:R.call(q))??new Date(k.date||0).getTime();return P-A}).map(v=>{const k=v.startAt&&u?Tn(v.startAt,u,"MMM d, yyyy"):v.date?new Date(v.date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â",P=v.unavailable?"Unavailable":v.startAt&&v.endAt&&u?`${Tn(v.startAt,u,"h:mm a")} â ${Tn(v.endAt,u,"h:mm a")}`:`${yi(v.startTime)} â ${yi(v.endTime)}`;return e.jsxs("div",{className:"flex items-start justify-between p-2 bg-surface-sunken border border-subtle rounded-lg hover:bg-slate-100 dar
318k:hover:bg-slate-800 transition-colors max-lg:p-1.5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs font-medium text-content-primary truncate max-lg:text-2xs max-lg:leading-tight",children:k}),e.jsx("p",{className:"text-xs text-content-secondary truncate max-lg:text-3xs max-lg:leading-tight",children:P})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>n(v.id),className:"text-red-600 hover:text-red-700 dark:text-red-400 size-6 p-0 flex-shrink-0 max-[1024px]:h-6 max-[1024px]:w-6 max-[1024px]:px-0",children:e.jsx(Ft,{className:"size-3"})})]},v.id)})})]})]})})]}),e.jsx(Rg,{open:d,onOpenChange:x,onSave:i,timezone:u})]})}function Og(){const{userDoc:t}=Se(),s=t==null?void 0:t.providerNetworkId,{networkTimezone:a}=hu(),[i,n]=o.useState([]),[r,l]=o.useState(!1),[c,u]=o.useState({sunday:{enabled:!1,startTime:"09:00",endTime:"17:00"},monday:{enabled:!1,startTime:"09:00",endTime:"17:00"},tuesday:{enabled:!1,startTime:"09:00",endTime:"17:00"},wednesday:{enabled:!1,startTime:"09:00",endTime:"17:00"},thursday:{enabled:!1,startTime:"09:00",endTime:"17:00"},friday:{enabled:!1,startTime:"09:00",endTime:"17:00"},saturday:{enabled:!1,startTime:"09:00",endTime:"17:00"}});o.useEffect(()=>{if(!s)return;l(!0);
318const y=Xe(ce,"ProviderNetworks",s,"Hours"),p=qe(y,d=>{const x=d.docs.map(N=>({id:N.id,...N.data()})),f=x.find(N=>N.id==="default");f&&u(f.schedule||c);const C=x.filter(N=>N.id!=="default");n(C),l(!1)},d=>{console.error("Error loading hours:",d),l(!1)});return()=>p()},[s]);async function m(y){try{const p=he(ce,"ProviderNetworks",s,"Hours","default");await nr(p,{schedule:y,updatedAt:Pe()},{merge:!0})}catch(p){throw console.error("Error saving schedule:",p),I.error("Unable to save schedule. Please try again."),p}}async function h(y){try{const p=y.map(d=>{const x=`exception_${d.startAt.toMillis()}_${Date.now()}`,f=he(ce,"ProviderNetworks",s,"Hours",x);return nr(f,{startAt:d.startAt,endAt:d.endAt,unavailable:d.unavailable,createdAt:Pe()})});await Promise.all(p),I.success(`${y.length} exception${y.length>1?"s":""} added`)}catch(p){throw console.error("Error adding exceptions:",p),I.error("Unable to add exceptions. Please try again."),p}}async function g(y){try{await jm(he(ce,"ProviderNetworks",s,"Hours",y)),I.success("Exception removed")}catch(p){console.error("Error removing exception:",p),I.error("Unable to remove exception. Please try again.")}}return s?e.jsx(Lg,{schedule:c,exceptions:i,onUpdateSchedule:m,onAddException:h,onDeleteException:g,loading:r,title:"Network Hours",description:"Manage the operating hours for your provider network",timezone:a,showTimezoneLabel:!0}):e.jsx(xt,{className:"rounded-xl border border-subtle p-12 max-lg:p-6 dark:bg-slate-800",children:e.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-lg:gap-1.5",children:[e.jsx("div",{className:"rounded-full bg-slate-100 p-3 max-lg:p-2 dark:bg-slate-700",children:e.jsx(Er,{className:"size-6 text-slate-400 max-lg:size-5 dark:text-slate-500"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-semibold text-content-primary max-lg:text-sm",children:"No Network Associated"}),e.jsx("p",{className:"mt-1 text-sm text-content-secondary max-lg:mt-0.5 max-lg:text-xs",children:"You need to be associated with a provider network to manage hours."})]})]})})}const fl={networks:0,clients:0,networkAdmins:0,clientAdmins:0,clientStaff:0,patients:0,providers:0,providerDelegates:0},Mg=({userType:t})=>{const{userDoc:s,userType:a}=Se(),{branding:i}=Ce(),n=t||a,r=n==="Super Admin",l=Ts(n,"Client Admin"),c=Ts(n,"Provider Network Admin"),u=Ts(n,"Provider"),m=(i==null?void 0:i.accentColor)||je,h=!!s,g=(s==null?void 0:s.clientId)||null,y=(s==null?void 0:s.providerNetworkId)||null,[p,d]=o.useState(()=>({...fl}));o.useEffect(()=>{if(!h)return;(async()=>{const C={...fl};try{if(r){const[N,v,k]=await Promise.all([Qt(Xe(ce,"ProviderNetworks")),Qt(Xe(ce,"Clients")),Qt(mt(Xe(ce,"Users"),Ue("userType","in",Et(["Provider Network Admin"]))))]);C.networks=N.data().count,C.clients=v.data().count,C.networkAdmins=k.data().count}if((r||l)&&(r||g)){const N=r?mt(Xe(ce,"Users"),Ue("userType","in",Et(["Client Admin"]))):mt(Xe(ce,"Users"),Ue("userType","in",Et(["Client Admin"])),Ue("clientId","==",g)),v=r?mt(Xe(ce,"Users"),Ue("userType","in",Et(["Client Staff"]))):mt(Xe(ce,"Users"),Ue("userType","in",Et(["Client Staff"])),Ue("clientId","==",g)),k=r?mt(Xe(ce,"Users"),Ue("userType","==","Patient")):mt(Xe(ce,"Users"),Ue("userType","==","Patient"),Ue("clientId","==",g)),[P,A,E]=await Promise.all([Qt(N),Qt(v),Qt(k)]);C.clientAdmins=P.data().count,C.clientStaff=A.data().count,C.patients=E.data().count}if((r||c||u)&&(r||c&&y||g)){const N=r?mt(Xe(ce,"Users"),Ue("userType","in",Et(["Provider"]))):c&&y?mt(Xe(ce,"Users"),Ue("userType","in",Et(["Provider"])),Ue("providerNetworkId","==",y)):mt(Xe(ce,"Users"),Ue("userType","in",Et(["Provider"])),Ue("clientId","==",g)),v=r?mt(Xe(ce,"Users"),Ue("userType","in",Et(["Provider Delegate"]))):c&&y?mt(Xe(ce,"Users"),Ue("userType","in",Et(["Provider Delegate"])),Ue("providerNetworkId","==",y)):mt(Xe(ce,"Users"),Ue("userType","in",Et(["Provider Delegate"])),Ue("clientId","==",g)),[k,P]=await Promise.all([Qt(N),Qt(v)]);C.providers=k.data().count,C.providerDelegates=P.data().count}if(c&&y){const N=mt(Xe(ce,"Users"),Ue("userType","in",Et(["Provider Network Admin"])),Ue("providerNetworkId","==",y)),v=await Qt(N);C.networkAdmins=v.data().count}d(C)}catch(N){console.error("Error fetching counts:",N)}})()},[h,g,y,r,l,c,u]);const x=r?nm:m;return e.jsxs("div",{className:"space-y-10 max-lg:space-y-4",children:[e.jsxs("div",{className:`grid gap-4 max-lg:gap-2 ${r?"md:grid-cols-4":c||l?"md:grid-cols-3":"md:grid-cols-2"}`,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(Jt,{icon:Pn,value:p.networks,label:"Provider Networks",accentColor:x}),e.jsx(Jt,{icon:ga,value:p.clients,label:"Clients",accentColor:x}),e.jsx(Jt,{icon:Pn,value:p.networkAdmins,label:"Network Admins",accentColor:x})]}),(r||l)&&e.jsxs(e.Fragment,{children:[e.jsx(Jt,{icon:Lr,value:p.clientAdmins,label:"Client Admins",accentColor:x}),e.jsx(Jt,{icon:rm,value:p.clientStaff,label:"Client Staff",accentColor:x}),e.jsx(Jt,{icon:Ni,value:p.patients,label:"Patients",accentColor:x})]}),c&&e.jsx(Jt,{icon:Pn,value:p.networkAdmins,label:"Network Admins",accentColor:x}),(r||c||u)&&e.jsxs(e.Fragment,{children:[e.jsx(Jt,{icon:im,value:p.providers,label:"Providers",accentColor:x}),e.jsx(Jt,{icon:Ni,value:p.providerDelegates,label:"Provider Delegates",accentColor:x})]})]}),l?e.jsx(Tg,{}):null,c?e.jsxs("div",{className:"space-y-6 max-lg:space-y-3",children:[e.jsx(Pg,{}),e.jsx(Ag,{}),e.jsx(Og,{})]}):null]})};function bn({title:t,description:s,actions:a=null,children:i,className:n=""}){return e.jsxs("section",{className:K("overflow-hidden rounded-xl border border-subtle bg-surface-sunken",n),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-subtle p-3 max-lg:gap-2 max-lg:p-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:t}),e.jsx("p",{className:"mt-1 text-xs text-content-tertiary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:s})]}),a?e.jsx("div",{className:"flex shrink-0 items-center gap-1.5 max-lg:gap-1",children:a}):null]}),e.jsx("div",{className:"p-3 max-lg:p-2",children:i})]})}function Fg({accentColor:t,children:s}){return e.jsx(tt,{id:"provider-network-operations-settings",title:"Operations settings",description:"Manage scheduling, review windows, and network-wide workflow controls.",icon:vo,accentColor:t,bodyClassName:"p-4 sm:p-5",children:e.jsx("div",{className:"grid gap-3 max-lg:gap-1.5 lg:grid-cols-2",children:s})})}function zg({providerNetworkId:t,accentColor:s}){const{providerNetwork:a}=Se(),{branding:i}=Ce(),n=t||(a==null?void 0:a.id),r=s||(i==null?void 0:i.accentColor)||je,[l,c]=o.useState(!0),[u,m]=o.useState(!1),[h,g]=o.useState(0),[y,p]=o.use
318State(0),[d,x]=o.useState("0");o.useEffect(()=>{if(!n){c(!1);return}const k=qe(he(ce,"ProviderNetworks",n),P=>{var E;if(!P.exists()){c(!1);return}const A=((E=P.data())==null?void 0:E.minAdvanceBookingHours)??0;g(A),p(A),x(String(A)),c(!1)},P=>{console.error("Failed to load scheduling rules settings",P),I.error("Unable to load scheduling rules. Please try again."),c(!1)});return()=>k()},[n]);const f=o.useMemo(()=>h!==y,[h,y]);function C(k){const P=k.target.value;x(P);const A=parseFloat(P);!Number.isNaN(A)&&A>=0&&g(A)}function N(){g(y),x(String(y))}async function v(){if(!n)return;const k=parseFloat(d);if(Number.isNaN(k)||k<0){I.error("Enter a valid number of hours (0 or more).");return}try{m(!0),await Fe(he(ce,"ProviderNetworks",n),{minAdvanceBookingHours:k,updatedAt:Pe()}),g(k),p(k),x(String(k)),I.success("Scheduling rules updated")}catch(P){console.error("Failed saving scheduling rules",P),I.error("Unable to update scheduling rules. Please try again."),g(y),x(String(y))}finally{m(!1)}}return n?e.jsx(bn,{title:"Scheduling rules",description:"Set the minimum advance notice required before a patient can book a telehealth visit.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:N,disabled:!f||u,children:"Discard"}),e.jsxs(B,{type:"button",size:"sm",onClick:v,disabled:!f||u,className:"text-white hover:opacity-95",style:{backgroundColor:r},children:[u?e.jsx($e,{size:"sm",label:"Saving scheduling rules",className:"mr-1.5 max-lg:mr-1"}):null,u?"Saving":"Save"]})]}),children:l?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"h-10 w-full rounded-lg"}),e.jsx(ue,{className:"h-4 w-3/4"})]}):e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Minimum advance booking time"}),e.jsx("p",{className:"mt-0.5 text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"Patients cannot book with less than this amount of notice. Set to 0 to allow immediate booking."})]}),e.jsxs("div",{className:"flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx(be,{type:"number",min:"0",step:"0.5",value:d,onChange:C,className:"w-28 max-lg:w-20","aria-label":"Minimum advance booking hours"}),e.jsx("span",{className:"text-sm text-content-secondary max-lg:text-xs",children:"hours"})]})]})}):null}const Hr=300*1e3,vc=Hr,Nc=3600*1e3,Ba=Hr/6e4,Va=vc/6e4,qa=Nc/6e4;function _g(t){const s=Number(t);return Number.isFinite(s)?Math.min(Nc,Math.max(vc,Math.round(s))):null}function Ug(t){var a;return(_g((a=t==null?void 0:t.providerNoShowPolicy)==null?void 0:a.graceMs)??Hr)/6e4}function bl(t){return Number(t)===Ba}function yl(t){const s=Number(t);return Number.isInteger(s)&&s>=Va&&s<=qa}function Dg({providerNetworkId:t,accentColor:s}){const{providerNetwork:a}=Se(),{branding:i}=Ce(),n=t||(a==null?void 0:a.id),r=s||(i==null?void 0:i.accentColor)||je,[l,c]=o.useState(!0),[u,m]=o.useState(!1),[h,g]=o.useState(Ba),[y,p]=o.useState(Ba),[d,x]=o.use
318State(String(Ba));o.useEffect(()=>{if(!n){c(!1);return}const k=qe(he(ce,"ProviderNetworks",n),P=>{if(!P.exists()){c(!1);return}const A=Ug(P.data());g(A),p(A),x(String(A)),c(!1)},P=>{console.error("Failed to load provider no-show settings",P),I.error("Unable to load no-show settings. Please try again."),c(!1)});return()=>k()},[n]);const f=o.useMemo(()=>h!==y,[h,y]);function C(k){const P=k.target.value;x(P);const A=parseInt(P,10);yl(A)&&g(A)}function N(){g(y),x(String(y))}async function v(){var P,A;if(!n)return;const k=parseInt(d,10);if(!yl(k)){I.error(`Enter a whole number between ${Va} and ${qa} minutes.`);return}try{m(!0),await Fe(he(ce,"ProviderNetworks",n),{providerNoShowPolicy:bl(k)?Co():{graceMs:k*6e4,updatedAt:Pe(),updatedBy:((P=Ls.currentUser)==null?void 0:P.uid)||null,updatedByEmail:((A=Ls.currentUser)==null?void 0:A.email)||null},updatedAt:Pe()}),g(k),p(k),x(String(k)),I.success("No-show grace period updated")}catch(E){console.error("Failed saving provider no-show settings",E),I.error("Unable to update no-show settings. Please try again."),g(y),x(String(y))}finally{m(!1)}}return n?e.jsx(bn,{title:"Provider no-show",description:"Set how long to wait after a scheduled video visit before flagging the provider as a no-show.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:N,disabled:!f||u,children:"Discard"}),e.jsxs(B,{type:"button",size:"sm",onClick:v,disabled:!f||u,className:"text-white hover:opacity-95",style:{backgroundColor:r},children:[u?e.jsx($e,{size:"sm",label:"Saving provider no-show settings",className:"mr-1.5 max-lg:mr-1"}):null,u?"Saving":"Save"]})]}),children:l?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"h-10 w-full rounded-lg"}),e.jsx(ue,{className:"h-4 w-3/4"})]}):e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Grace period"}),e.jsxs("p",{className:"mt-0.5 text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:["Flags the visit and notifies subscribed systems without changing visit status. Allowed range: ",Va,"â",qa," minutes."]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 max-lg:gap-1.5",children:[e.jsx(be,{type:"number",min:Va,max:qa,step:"1",value:d,onChange:C,className:"w-28 max-lg:w-20","aria-label":"Provider no-show grace period in minutes"}),e.jsx("span",{className:"text-sm text-content-secondary max-lg:text-xs",children:"minutes"}),bl(h)?e.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-2xs",children:"Using the platform default"}):null]})]})}):null}function hs(t={}){return xm(t)}function $g(t){if(!t)return null;if(typeof(t==null?void 0:t.toDate)=="function")return t.toDate().toLocaleString();const s=new Date(t);return Number.isNaN(s.getTime())?null:s.toLocaleString()}function Bg({providerNetworkId:t,accentColor:s}){const{userDoc:a,providerNetwork:i}=Se(),{branding:n}=Ce(),r=t||(a==null?void 0:a.providerNetworkId)||(i==null?void 0:i.id)||null,l=s||(n==null?void 0:n.accentColor)||(i==null?void 0:i.accentColor)||je,[c,u]=o.useState(!0),[m,h]=o.useState(!1),[g,y]=o.useState(ba),[p,d]=o.useState(ba),[x,f]=o.useState({updatedAt:null,updatedByEmail:null}),[C,N]=o.useState(!1);o.useEffect(()=>{if(!r){u(!1);return}return qe(he(ce,"ProviderNetworks",r),O=>{var b;const j=O.exists()?((b=O.data())==null?void 0:b.prescriptionReviewQueue)||{}:{},L=hs(j);y(L),d(L),f({updatedAt:j.updatedAt||null,updatedByEmail:j.updatedByEmail||null}),u(!1)},O=>{console.error("Failed to load prescription review queue settings",O),I.error("Unable to load prescription review queue settings."),u(!1)})},[r]);const v=o.useMemo(()=>JSON.stringify(hs(g))!==JSON.stringify(hs(p)),[p,g]),k=o.useMemo(()=>lm(g.unit),[g.unit]),P=o.useMemo(()=>om(g.value,g.unit),[g.unit,g.value]),A=o.useMemo(()=>cm(P),[P]),E=$g(x.updatedAt);function z(O,j){y(L=>{const b={...L,[O]:j};return O==="unit"?hs(b):b})}async function q(O){var b,w;if(!r)return;const j=hs(O),L=j.reviewWindowMs===ba.reviewWindowMs;h(!0);try{await Fe(he(ce,"ProviderNetworks",r),{prescriptionReviewQueue:L?Co():{reviewWindowMs:j.reviewWindowMs,updatedAt:Pe(),updatedBy:((b=Ls.currentUser)==null?void 0:b.uid)||null,updatedByEmail
318:((w=Ls.currentUser)==null?void 0:w.email)||null},updatedAt:Pe()}),y(j),d(j),I.success(L?"Prescription review queue restored to the two-hour default":"Prescription review queue settings saved")}catch(F){un(F,{area:"prescribing",surface:"frontend/src/pages/settings/SettingsProviderNetworkAdminView/SettingsOperations/components/PrescriptionReviewQueueCard.jsx",operation:"frontend/src/pages/settings/SettingsProviderNetworkAdminView/SettingsOperations/components/PrescriptionReviewQueueCard.jsx:123"}),console.error("Failed to save prescription review queue settings",F),I.error("Unable to save prescription review queue settings.")}finally{h(!1),N(!1)}}function R(){const O=hs(g);if(O.reviewWindowMs<um){N(!0);return}q(O)}return r?e.jsxs(e.Fragment,{children:[e.jsx(bn,{title:"Prescription review queue",description:"Set how long queued prescriptions remain editable before automatic pharmacy submission.",className:"lg:col-span-2",actions:e.jsxs(e.Fragment,{children:[e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>y(ba),disabled:c||m,"data-testid":"button-network-prescription-review-window-default",children:[e.jsx(No,{className:"mr-1 size-3.5 max-lg:size-3"}),"Default"]}),e.jsxs(B,{type:"button",size:"sm",onClick:R,disabled:c||m||!v,className:"text-white hover:opacity-95",style:{backgroundColor:l},"data-testid":"button-network-prescription-review-window-save",children:[m?e.jsx($e,{size:"sm",label:"Saving prescription review queue",className:"mr-1"}):e.jsx(mm,{className:"mr-1 size-3.5 max-lg:size-3"}),m?"Saving":"Save"]})]}),children:c?e.jsx("div",{className:"flex min-h-24 items-center justify-center max-lg:min-h-16",children:e.jsx($e,{size:"lg",label:"Loading prescription review queue",className:"text-content-tertiary"})}):e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[minmax(0,1fr)_10rem]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{htmlFor:"prescriptionReviewWindowValue",className:"text-xs font-semibold text-content-primary",children:"Review window"}),e.jsx(be,{id:"prescriptionReviewWindowValue",type:"number",min:k.min,max:k.max,value:g.value,onChange:O=>z("value",O.target.value),"data-testid":"input-network-prescription-review-window-value"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{htmlFor:"prescriptionReviewWindowUnit",className:"text-xs font-semibold text-content-primary",children:"Unit"}),e.jsxs(yt,{value:dm(g.unit),onValueChange:O=>z("unit",O),children:[e.jsx(vt,{id:"prescriptionReviewWindowUnit","data-testid":"select-network-prescription-review-window-unit",children:e.jsx(Nt,{})}),e.jsxs(jt,{children:[e.jsx(st,{value:"minutes",children:"Minutes"}),e.jsx(st,{value:"hours",children:"Hours"})]})]})]})]}),e.jsxs("div",{className:"space-y-1 text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:[e.jsxs("p",{children:["Current setting: ",A,". Allowed range is 1 minute to 24 hours."]}),e.jsx("p",{children:E?`Last updated ${E}${x.updatedByEmail?` by ${x.updatedByEmail}`:""}.`:"Using the default two-hour review window."})]})]})}),e.jsx(_s,{open:C,onOpenChange:N,title:"Use a short review window?",description:`You are saving a ${A} review window. Windows under 5 minutes are intended for testing only and may cause prescriptions to auto-send before providers can review them.`,confirmLabel:"Save anyway",onConfirm:()=>q(hs(g)),tone:"warning",busy:m})]}):null}const Vg=300*1e3,Ha=new Map;function qg(t,s){return`${t}:${s?"all":"active"}`}function jc(){Ha.clear()}Tu(jc);function Hg(t,s){const a=Ha.get(t);if(a&&Date.now()-a.at<Vg)return a.promise;const i=Eu({includeArchived:s}).catch(n=>{throw Ha.delete(t),n});return Ha.set(t,{at:Date.now(),promise:i}),i}function kc({providerNetworkId:t,includeArchived:s=!1,enabled:a=!0}={}){const i=String(t||"").trim(),[n,r]=o.useState({options:[],tenantCount:0,complete:!0}),[l,c]=o.useState(!1),[u,m]=o.useState(null),[h,g]=o.useState(0),y=o.useCallback(()=>{jc(),g(p=>p+1)},[]);return o.useEffect(()=>{if(!a||!i){c(!1);return}let p=!0;return c(!0),m(null),Hg(qg(i,s),s).then(d=>{p&&r({options:d.options,tenantCount:d.tenantCount,complete:d.complete})}).catch(d=>{p&&(r({options:[],tenantCount:0,complete:!0}),m((d==null?void 0:d.message)||"Unable to load patient field options"))}).finally(()=>{p&&c(!1)}),()=>{p=!1}},[a,s,i,h]),{...n,loading:l,error:u,reload:y}}const vl=new Map(Qo.map(t=>[t.value,t.label])),Wg=new Map(Su.map(t=>[t.value,t.label])),Gg=new Set(["rows","address","file"]);function Kg(t){return t.type==="provider_network"?"Network":t.label||(t.type==="business"?"A business":"A client")}function Yg(t){return Gg.has(t.valueType)?"Providers will see this read-only â this field type is collected on forms only.":t.anyProviderEditable?"":"Providers will see this read-only until the definition allows provider editing."}function Qg({option:t,selected:s}){const a=Yg(t),i=t.conflict?[...new Set(t.scopes.map(r=>vl.get(r.valueType)||r.valueType))]:[],n=`patient-field-option-${t.key}`;return e.jsxs("label",{htmlFor:n,className:K("flex cursor-pointer items-start gap-2 rounded-lg border p-2.5 transition",s?"border-default bg-surface-muted":"border-subtle bg-surface-raised hover:border-default"),children:[e.jsx(Ka,{value:t.key,id:n,className:"mt-1 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-sm font-medium text-content-primary",children:t.label}),e.jsx(De,{variant:"outline",className:"text-2xs",children:vl.get(t.valueType)||t.valueType}),t.scopes.map(r=>e.jsx(De,{variant:"secondary",className:"text-2xs",children:Kg(r)},`${r.type}:${r.id}`))]}),t.description?e.jsx("span",{className:"mt-1 block text-xs text-content-tertiary",children:t.description}):null,i.length>0?e.jsxs("span",{className:"mt-1 flex items-start gap-1 text-xs text-amber-700 dark:text-amber-300",children:[e.jsx(jo,{className:"mt-0.5 size-3 shrink-0","aria-hidden":!0}),`Typed differently across tenants (${i.join(", ")}). Each patient gets their own tenant's control.`]}):null,a?e.jsx("span",{className:"mt-1 block text-xs text-amber-700 dark:text-amber-300",children:a}):null]})]})}
318function Jg({open:t,onOpenChange:s,draft:a,onDraftChange:i,onSave:n,saving:r=!1,providerNetworkId:l,existingKeys:c=[]}){const{branding:u}=Ce(),m=(u==null?void 0:u.accentColor)||je,h=(a==null?void 0:a._isNew)===!0,[g,y]=o.useState(""),[p,d]=o.useState(!1),[x,f]=o.useState(""),{options:C,tenantCount:N,complete:v,loading:k,error:P,reload:A}=kc({providerNetworkId:l,includeArchived:!0,enabled:t});o.useEffect(()=>{t||(y(""),f(""))},[t]),o.useEffect(()=>{var w,F;if(!x)return;const b=C.find(M=>M.key===x);b&&(f(""),i({...a,patientFieldKey:b.key,patientFieldId:((w=b.scopes[0])==null?void 0:w.fieldId)||"",patientFieldLabel:b.label,patientFieldScopeType:((F=b.scopes[0])==null?void 0:F.type)||null}))},[a,i,C,x]);const E=o.useMemo(()=>new Set(c.filter(b=>b!==(a==null?void 0:a.patientFieldKey))),[a==null?void 0:a.patientFieldKey,c]),z=o.useMemo(()=>{const b=g.trim().toLowerCase();return C.filter(w=>!E.has(w.key)).filter(w=>w.anyActive===!0).filter(w=>b?`${w.label} ${w.key} ${w.description||""}`.toLowerCase().includes(b):!0)},[E,C,g]),q=o.useMemo(()=>{const b=new Map;return z.forEach(w=>{const F=w.group||"operational";b.has(F)||b.set(F,[]),b.get(F).push(w)}),[...b.entries()]},[z]),R=C.find(b=>b.key===(a==null?void 0:a.patientFieldKey))||null;function O(b){i({...a,...b})}function j(b){var F,M;const w=C.find(W=>W.key===b);w&&O({patientFieldKey:w.key,patientFieldId:((F=w.scopes[0])==null?void 0:F.fieldId)||"",patientFieldLabel:w.label,patientFieldScopeType:((M=w.scopes[0])==null?void 0:M.type)||null})}function L(){const b=yu(a,(a==null?void 0:a.order)??0);if(!b){I.error("Choose a patient data field before saving.");return}n(b)}return a?e.jsxs(e.Fragment,{children:[e.jsx(at,{open:t,onOpenChange:s,title:h?"Add patient data field":"Edit patient data field",description:"Providers fill these in chart review Step 2. Answers are saved on the patient, not on the chart review.",contentClassName:"max-w-xl",mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",footerClassName:"max-[1024px]:px-3 max-[1024px]:pt-2.5 max-[1024px]:gap-1.5",bodyClassName:"max-[1024px]:p-2",footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",className:"rounded-full",onClick:()=>s(!1),children:"Cancel"}),e.jsx(B,{type:"submit",form:"patient-field-question-form",className:"rounded-full text-white",style:{backgroundColor:m},disabled:r,children:r?"Savingâ¦":"Save question"})]}),children:e.jsx("form",{id:"patient-field-question-form",className:us,onSubmit:xs(L,{disabled:r}),children:e.jsxs($t,{className:"overflow-hidden bg-surface-raised p-0",children:[e.jsxs("section",{className:"space-y-2 px-5 py-4 max-lg:space-y-1.5 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx(oe,{htmlFor:"patient-field-question-search",className:"max-lg:text-xs",children:"Patient data field"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"rounded-full max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",onClick:()=>d(!0),children:[e.jsx(ot,{className:"mr-1 size-3.5 max-lg:size-3"}),"Create a new field"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(pn,{className:"pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-content-tertiary","aria-hidden":!0}),e.jsx(be,{id:"patient-field-question-search",value:g,onChange:b=>y(b.target.value),placeholder:"Search fields",className:"pl-8",autoComplete:"off"})]}),k?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ue,{className:"h-14 w-full"}),e.jsx(ue,{className:"h-14 w-full"})]}):P?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:P}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"rounded-full",onClick:A,children:"Try again"})]}):q.length===0?e.jsx("p",{className:"text-xs text-content-tertiary",children:C.every(b=>b.anyActive!==!0)?"No active patient data fields are defined yet. Use Create a new field to add one.":"No fields match this search, or every match is already on the list."}):e.jsx(Ga,{value:a.patientFieldKey||"",onValueChange:j,className:"max-h-72 space-y-3 overflow-y-auto pr-1",children:q.map(([b,w])=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-2xs font-semibold uppercase tracking-wide text-content-tertiary",children:Wg.get(b)||b}),w.map(F=>e.jsx(Qg,{option:F,selected:F.key===a.patientFieldKey},F.key))]},b))}),v?null:e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-300",children:`Only the first ${N} clients and businesses were scanned. A field defined beyond that is not listed â create it on the network instead.`})]}),e.jsxs("section",{className:"grid gap-4 border-t border-subtle px-5 py-4 max-lg:gap-2 max-lg:px-3 max-lg:py-2.5 sm:grid-cols-2 sm:px-6",children:[e.jsxs("div",{className:"space-y-1 max-lg:space-y-0.5",children:[e.jsx("p",{className:"text-xs font-medium text-content-secondary",children:"Selected"}),e.jsx("p",{className:"text-sm text-content-primary max-lg:text-xs",children:(R==null?void 0:R.label)||a.patientFieldLabel||"Nothing selected yet"})]}),e.jsxs("div",{className:"space-y-3 max-lg:space-y-1.5",children:[e.jsxs("label",{htmlFor:"patient-field-question-required",className:"flex items-center gap-2 text-sm text-content-secondary max-lg:gap-1.5 max-lg:text-xs",children:[e.jsx(Me,{id:"patient-field-question-required",checked:a.required,onCheckedChange:b=>O({required:b===!0})}),"Required"]}),e.jsxs("label",{htmlFor:"patient-field-question-enabled",className:"flex items-center gap-2 text-sm text-content-secondary max-lg:gap-1.5 max-lg:text-xs",children:[e.jsx(Me,{id:"patient-field-question-enabled",checked:a.enabled,onCheckedChange:b=>O({enabled:b===!0})}),"Enabled"]})]})]})]})})}),e.jsx(Cu,{open:p,onOpenChange:d,definition:null,onSaved:b=>{var F;const w=((F=b==null?void 0:b.field)==null?void 0:F.key)||"";A(),w&&f(w)}})]}):null}const Xg=[vs.SHORT_TEXT,vs.LONG_TEXT,vs.SINGLE_SELECT,vs.MULTI_SELECT,vs.YES_NO,vs.ACKNOWLEDGMENT],Zg=new Map(Qo.map(t=>[t.value,t.label])),eh=new Set(["rows","address","file"]);function th(t){return t==="provider_network"?"Network":t==="business"?"Business":t==="client"?"Client":""}function Wn(t=0){return{id:`opt_${`${Date.now()}_${t}`}`,label:"",value:""}}function sh({question:t,onEdit:s,onRemove:a,disabled:i}){const{attributes:n,listeners:r,setNodeRef:l,transform:c,transition:u,isDragging:m}=fn({id:t.id}),h={transform:hn.Transform.toString(c),transition:u};return e.jsxs("div",{ref:l,style:h,className:K("flex items-start gap-3 rounded-xl border border-subtle bg-surface-raised dark:bg-slate-900/40 p-3","max-lg:gap-2 max-lg:p-2",m&&"relative z-raised shadow-lg",!t.enabled&&"opacity-70"),children:[e.jsx("button",{type:"button",className:"mt-0.5 inline-flex size-7 shrink-0 items-center justify-center rounded-md text-content-tertiary hover:text-slate-700 disabled:opacity-50 max-lg:size-6 dark:hover:text-slate-200",disabled:i,"aria-label":`Reorder ${t.label||"question"}`,...n,...r,children:e.jsx(ha,{className:"size-4 max-lg:size-3.5"})}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-1 max-lg:space-y-0.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 max-lg:gap-1",children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:t.label||"Untitled question"}),e.jsx(De,{variant:"outline",className:"text-2xs max-lg:px-1.5 max-lg:text-3xs",children:Ko(t.type)}),t.required?e.jsx(De,{className:"bg-red-100 text-red-800 hover:bg-red-100 max-lg:px-1.5 max-lg:text-3xs dark:bg-red-950/50 dark:text-red-200",children:"Required"}):e.jsx(De,{variant:"secondary",className:"max-lg:px-1.5 max-lg:text-3xs",children:"Optional"}),t.enabled?null:e.jsx(De,{variant:"secondary",className:"max-lg:px-1.5 max-lg:text-3xs",children:"Disabled"})]}),dr(t.type)?e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-snug",children:t.options.map(g=>
318g.label).filter(Boolean).join(" · ")||"No options configured"}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"size-8 max-[1024px]:h-8 max-[1024px]:w-8",disabled:i,onClick:()=>s(t),"aria-label":"Edit question",children:e.jsx(zt,{className:"size-4 max-lg:size-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"size-8 text-red-600 hover:text-red-700 max-[1024px]:h-8 max-[1024px]:w-8 dark:text-red-400",disabled:i,onClick:()=>a(t.id),"aria-label":"Remove question",children:e.jsx(bt,{className:"size-4 max-lg:size-3.5"})})]})]})}function ah({question:t,option:s,onEdit:a,onRemove:i,disabled:n}){const{attributes:r,listeners:l,setNodeRef:c,transform:u,transition:m,isDragging:h}=fn({id:t.id}),g={transform:hn.Transform.toString(u),transition:m},y=(s==null?void 0:s.label)||t.patientFieldLabel||t.patientFieldKey,p=(s==null?void 0:s.valueType)||null,d=s?[...new Set(s.scopes.map(C=>C.type))]:[t.patientFieldScopeType].filter(Boolean),x=!!s&&(eh.has(s.valueType)||s.anyProviderEditable!==!0),f=!!s&&s.anyActive!==!0;return e.jsxs("div",{ref:c,style:g,className:K("flex items-start gap-3 rounded-xl border border-subtle bg-surface-raised p-3","max-lg:gap-2 max-lg:p-2",h&&"relative z-raised shadow-lg",!t.enabled&&"opacity-70"),children:[e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"mt-0.5 size-7 shrink-0 text-content-tertiary max-lg:size-6",disabled:n,"aria-label":`Reorder ${y}`,...r,...l,children:e.jsx(ha,{className:"size-4 max-lg:size-3.5"})}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-1 max-lg:space-y-0.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 max-lg:gap-1",children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:y}),p?e.jsx(De,{variant:"outline",className:"text-2xs max-lg:px-1.5 max-lg:text-3xs",children:Zg.get(p)||p}):null,d.map(C=>e.jsx(De,{variant:"secondary",className:"max-lg:px-1.5 max-lg:text-3xs",children:th(C)},C)),t.required?e.jsx(De,{className:"bg-red-100 text-red-800 hover:bg-red-100 max-lg:px-1.5 max-lg:text-3xs dark:bg-red-950/50 dark:text-red-200",children:"Required"}):e.jsx(De,{variant:"secondary",className:"max-lg:px-1.5 max-lg:text-3xs",children:"Optional"}),t.enabled?null:e.jsx(De,{variant:"secondary",className:"max-lg:px-1.5 max-lg:text-3xs",children:"Disabled"}),f?e.jsx(De,{className:"bg-amber-100 text-amber-800 hover:bg-amber-100 max-lg:px-1.5 max-lg:text-3xs dark:bg-amber-950/50 dark:text-amber-200",children:"Archived"}):x?e.jsx(De,{className:"bg-amber-100 text-amber-800 hover:bg-amber-100 max-lg:px-1.5 max-lg:text-3xs dark:bg-amber-950/50 dark:text-amber-200",children:"Read-only in charting"}):null]}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-snug",children:t.patientFieldKey})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"size-8 max-[1024px]:size-8",disabled:n,onClick:()=>a(t),"aria-label":"Edit patient data field",children:e.jsx(zt,{className:"size-4 max-lg:size-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"size-8 text-red-600 hover:text-red-700 max-[1024px]:size-8 dark:text-red-400",disabled:n,onClick:()=>i(t.id),"aria-label":"Remove patient data field",children:e.jsx(bt,{className:"size-4 max-lg:size-3.5"})})]})]})}function nh({open:t,onOpenChange:s,onChoose:a}){return e.jsx(at,{open:t,onOpenChange:s,title:"Add question",description:"Pick what the provider is being asked for.",contentClassName:"max-w-md",children:e.jsxs("div",{className:"space-y-2 p-1",children:[e.jsx(B,{type:"button",variant:"outline",className:"h-auto w-full justify-start whitespace-normal rounded-xl px-4 py-3 text-left",onClick:()=>a("patient_field"),"aria-label":"Add a patient data field",children:e.jsxs("span",{className:"block",children:[e.jsx("span",{className:"block text-sm font-medium text-content-primary",children:"Patient data field"}),e.jsx("span",{className:"block text-xs text-content-tertiary",children:"An existing patient data field, prefilled and saved back onto the patient record."})]})}
318),e.jsx(B,{type:"button",variant:"outline",className:"h-auto w-full justify-start whitespace-normal rounded-xl px-4 py-3 text-left",onClick:()=>a("decision"),"aria-label":"Add a decision question",children:e.jsxs("span",{className:"block",children:[e.jsx("span",{className:"block text-sm font-medium text-content-primary",children:"Decision question"}),e.jsx("span",{className:"block text-xs text-content-tertiary",children:"A free-form or multiple-choice answer recorded on the chart review decision."})]})})]})})}function rh({open:t,onOpenChange:s,draft:a,onDraftChange:i,onSave:n,saving:r}){const{branding:l}=Ce(),c=(l==null?void 0:l.accentColor)||je,u=dr(a==null?void 0:a.type);function m(d){i({...a,...d})}function h(d,x){const f=[...a.options||[]];f[d]={...f[d],...x},m({options:f})}function g(){m({options:[...a.options||[],Wn((a.options||[]).length)]})}function y(d){m({options:(a.options||[]).filter((x,f)=>f!==d)})}function p(){const d=ju(a,a.order??0);if(!d){I.error("Enter a question label and valid options before saving.");return}n(d)}return a?e.jsx(at,{open:t,onOpenChange:s,title:a._isNew?"Add decision question":"Edit decision question",description:"Providers answer these in chart review Step 2 before recording a decision.",contentClassName:"max-w-xl",mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",footerClassName:"max-[1024px]:px-3 max-[1024px]:pt-2.5 max-[1024px]:gap-1.5",bodyClassName:"max-[1024px]:px-2 max-[1024px]:py-2",footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",className:"rounded-full",onClick:()=>s(!1),children:"Cancel"}),e.jsx(B,{type:"submit",form:"decision-questions-manager-form",className:"rounded-full text-white",style:{backgroundColor:c},disabled:r,children:r?"Savingâ¦":"Save question"})]}),children:e.jsx("form",{id:"decision-questions-manager-form",className:us,onSubmit:xs(p,{disabled:r}),children:e.jsxs($t,{className:"overflow-hidden bg-surface-raised p-0",children:[e.jsxs("section",{className:"space-y-2 px-5 py-4 max-lg:space-y-1.5 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"decision-question-label",className:"max-lg:text-xs",children:"Question"}),e.jsx(Is,{id:"decision-question-label",value:a.label,onChange:d=>m({label:d.target.value}),placeholder:"What should the provider answer?",rows:3})]}),e.jsxs("section",{className:"grid gap-4 border-t border-subtle px-5 py-4 max-lg:gap-2 max-lg:px-3 max-lg:py-2.5 sm:grid-cols-2 sm:px-6",children:[e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsx(oe,{className:"max-lg:text-xs",children:"Type"}),e.jsxs(yt,{value:a.type,onValueChange:d=>{const x={type:d};dr(d)&&!(a.options||[]).length&&(x.options=[Wn(0),Wn(1)]),m(x)},children:[e.jsx(vt,{children:e.jsx(Nt,{})}),e.jsx(jt,{children:Xg.map(d=>e.jsx(st,{value:d,children:Ko(d)},d))})]})]}),e.jsxs("div",{className:"space-y-3 pt-6 max-lg:space-y-1.5 max-lg:pt-0",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-700 max-lg:gap-1.5 max-lg:text-xs dark:text-slate-300",children:[e.jsx(Me,{checked:a.required,onCheckedChange:d=>m({required:d===!0})}),"Required"]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-700 max-lg:gap-1.5 max-lg:text-xs dark:text-slate-300",children:[e.jsx(Me,{checked:a.enabled,onCheckedChange:d=>m({enabled:d===!0})}),"Enabled"]})]})]}),u?e.jsxs("section",{className:"space-y-2 border-t border-subtle px-5 py-4 max-lg:space-y-1.5 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(oe,{className:"max-lg:text-xs",children:"Answer options"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"rounded-full max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",onClick:g,children:[e.jsx(ot,{className:"mr-1 size-3.5 max-lg:size-3"}),"Add option"]})]}),e.jsx("div",{className:"space-y-2 max-lg:space-y-1.5",children:(a.options||[]).map((d,x)=>e.jsxs("div",{className:"flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx(be,{value:d.label,onChange:f=>h(x,{label:f.target.value}),placeholder:`Option ${x+1}`,"aria-label":`Option ${x+1}`}
318),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 max-lg:size-8",onClick:()=>y(x),"aria-label":"Remove option",children:e.jsx(bt,{className:"size-4 max-lg:size-3.5"})})]},d.id||x))})]}):null]})})}):null}function ih({decisionQuestions:t=[],onPersist:s,patientFieldQuestions:a=[],onPersistPatientFields:i,providerNetworkId:n="",disabled:r=!1,saving:l=!1}){const c=Mr(Fr(zr,{activationConstraint:{distance:6}})),[u,m]=o.useState(!1),[h,g]=o.useState(null),[y,p]=o.useState(!1),[d,x]=o.useState(!1),[f,C]=o.useState(null),N=o.useMemo(()=>Li(t),[t]),v=o.useMemo(()=>Oi(a),[a]),{options:k}=kc({providerNetworkId:n,includeArchived:!0,enabled:v.length>0}),P=o.useMemo(()=>new Map(k.map(H=>[H.key,H])),[k]),A=o.useCallback(async H=>{const ae=Li(H);await s(ae)},[s]),E=o.useCallback(async H=>{const ae=Oi(H);await(i==null?void 0:i(ae))},[i]),z=o.useCallback(async H=>{const{active:ae,over:xe}=H;if(!xe||ae.id===xe.id)return;const Ae=N.findIndex(Z=>Z.id===ae.id),se=N.findIndex(Z=>Z.id===xe.id);Ae<0||se<0||await A(rr(N,Ae,se))},[A,N]),q=o.useCallback(async H=>{const{active:ae,over:xe}=H;if(!xe||ae.id===xe.id)return;const Ae=v.findIndex(Z=>Z.id===ae.id),se=v.findIndex(Z=>Z.id===xe.id);Ae<0||se<0||await E(rr(v,Ae,se))},[v,E]),R=()=>{g({...Nu(N.length),_isNew:!0}),m(!0)},O=()=>{C({...vu(v.length),_isNew:!0}),x(!0)},j=H=>{p(!1),H==="patient_field"?O():R()},L=H=>{g({...H,options:(H.options||[]).map(ae=>({...ae})),_isNew:!1}),m(!0)},b=H=>{C({...H,_isNew:!1}),x(!0)},w=async H=>{const ae=h._isNew?[...N,H]:N.map(xe=>xe.id===H.id?H:xe);await A(ae),m(!1),g(null)},F=async H=>{const ae=f._isNew?[...v,H]:v.map(xe=>xe.id===H.id?H:xe);await E(ae),x(!1),C(null)},M=async H=>{await A(N.filter(ae=>ae.id!==H))},W=async H=>{await E(v.filter(ae=>ae.id!==H))};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle pb-2 max-lg:gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("h3",{className:"truncate text-xs font-semibold uppercase tracking-wide text-content-tertiary",children:"Chart review decision questions"}),e.jsx(Wt,{delayDuration:150,children:e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsx("button",{type:"button",tabIndex:-1,"aria-label":"Chart review decision questions details",className:"inline-flex size-4 shrink-0 items-center justify-center rounded-full text-slate-400 transition hover:text-slate-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-300 dark:hover:text-slate-200",children:e.jsx(Ds,{className:"size-3.5","aria-hidden":!0})})}),e.jsx(os,{className:"max-w-xs text-xs leading-relaxed",children:"Custom provider-facing questions shown in Step 2 before approve, defer, or deny. Decision question answers are saved on the chart review; patient data field answers are saved on the patient record."})]})})]}),e.jsxs(B,{type:"button",size:"sm",variant:"outline",className:"shrink-0 rounded-full max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",disabled:r||l,onClick:()=>p(!0),children:[e.jsx(ot,{className:"mr-1.5 size-4 max-lg:mr-1 max-lg:size-3"}),"Add question"]})]}),e.jsxs("div",{className:"mt-3 space-y-4 max-lg:mt-2 max-lg:space-y-3",children:[e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsx("p",{className:"text-2xs font-semibold uppercase tracking-wide text-content-tertiary",children:"Patient data fields"}),v.length===0?e.jsx("p",{className:"text-xs text-content-tertiary",children:"No patient data fields configured."}):e.jsx(tn,{sensors:c,collisionDetection:sn,onDragEnd:H=>{q(H)},children:e.jsx(an,{items:v.map(H=>H.id),strategy:nn,children:e.jsx("div",{className:"space-y-2 max-lg:space-y-1.5",children:v.map(H=>e.jsx(ah,{question:H,option:P.get(H.patientFieldKey)||null,disabled:r||l,onEdit:b,onRemove:W},H.id))})})})]}),e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsx("p",{className:"text-2xs font-semibold uppercase tracking-wide text-content-tertiary",children:"Decision questions"}),N.length===0?e.jsx("p",{className:"text-xs text-content-tertiary",children:"No custom decision questions configured."}):e.jsx(tn,{sensors:c,collisionDetection:sn,onDragEnd:H=>{z(H)},children:e.jsx(an,{items:N.map(H=>H.id),strategy:nn,children:e.jsx("div",{className:"space-y-2 max-lg:space-y-1.5",children:N.map(H=>e.jsx(sh,{question:H,disabled:r||l,onEdit:L,onRemove:M},H.id))})})})]})]}),e.jsx(nh,{open:y,onOpenChange:p,onChoose:j}),e.jsx(Jg,{open:d,onOpenChange:H=>{x(H),H||C(null)},draft:f,onDraftChange:C,onSave:H=>{F(H)},saving:l,providerNetworkId:n,existingKeys:v.map(H=>H.patientFieldKey)}),e.jsx(rh,{open:u,onOpenChange:H=>{m(H),H||g(null)},draft:h,onDraftChange:g,onSave:H=>{w(H)},saving:l})]})}function zs({label:t,hint:s}){return s?e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsx("button",{type:"button",tabIndex:-1,"aria-label":`${t} details`,className:"inline-flex size-4 shrink-0 items-center justify-center rounded-full text-slate-400 transition hover:text-slate-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-300 dark:hover:text-slate-200",children:e.jsx(Ds,{className:"size-3.5","aria-hidden":!0})})}),e.jsx(os,{className:"max-w-xs text-xs leading-relaxed",children:s})]}):null}function vr({id:t,title:s,hint:a,checked:i,onCheckedChange:n,disabled:r=!1,badge:l=null,trailing:c=null,children:u=null,className:m="",testId:h}){return e.jsxs("div",{className:K("border-b border-slate-100 py-2.5 last:border-b-0 max-lg:py-2 dark:border-slate-800",m),"data-testid":h,children:[e.jsxs("div",{className:"flex items-center gap-3 max-lg:gap-2",children:[e.jsx(it,{id:t,checked:i,onCheckedChange:n,disabled:r,className:"shrink-0"}),e.jsxs("label",{htmlFor:t,className:"flex min-w-0 flex-1 cursor-pointer items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-sm font-medium text-content-primary max-lg:text-xs",children:s}),e.jsx(zs,{label:s,hint:a}),l]}),c]}),i&&u?e.jsx("div",{className:"mt-2 pl-14 max-lg:mt-1.5 max-lg:pl-11",children:u}):null]})}function Wa({id:t,label:s,hint:a,checked:i,onChange:n,disabled:r=!1,accentColor:l}){return e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsx("button",{type:"button",id:t,"aria-pressed":i,disabled:r,onClick:()=>n(!i),className:K("inline-flex shrink-0 items-center rounded-full border px-2.5 py-0.5 text-2xs font-medium transition max-lg:px-2 max-lg:text-3xs","disabled:cursor-not-allowed disabled:opacity-60",i?"border-transparent text-white":"border-subtle bg-surface-raised text-content-secondary hover:border-slate-300 hover:text-slate-900 dark:hover:text-slate-100"),style:i?{backgroundColor:l}:void 0,children:s})}),e.jsx(os,{className:"max-w-xs text-xs leading-relaxed",children:a})]})}function Nr({title:t,hint:s,trailing:a=null}){return e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle pb-2 max-lg:gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("h3",{className:"truncate text-xs font-semibold uppercase tracking-wide text-content-tertiary",children:t}),e.jsx(zs,{label:t,hint:s})]}),a]})}const Gn="DISABLE",lh=[{id:ft.SIGN_FIRST,label:"Sign, then prescribe",hint:"Providers approve the chart before they can send or queue a prescription."},{id:ft.SIGN_TOGETHER,label:"Sign and prescribe together",hint:"Providers can complete attestations and send or queue the prescription in one step. Clinical approval is still recorded. Provider Delegates still need a Provider approval first."},{id:ft.PRESCRIBE_FIRST,label:"Prescribe, then sign",hint:"Providers can send or queue a prescription before signing. The chart stays open until they sign."}],oh={[ft.SIGN_FIRST]:"Prescription sign-off set to sign, then prescribe",[ft.SIGN_TOGETHER]:"Prescription sign-off set to sign and prescribe together",[ft.PRESCRIBE_FIRST]:"Prescription sign-off set to prescribe, then sign"};function ch(t){return{prescribeBeforeSignoff:t===ft.PRESCRIBE_FIRST,approveAndPrescribeTogether:t===ft.SIGN_TOGETHER}}function Ut({id:t,title:s,hint:a,checked:i,onCheckedChange:n,disabled:r=!1,badge:l=null,children:c=null}){return e.jsxs("div",{className:"border-b border-subtle py-2.5 last:border-b-0 max-lg:py-2",children:[e.jsxs("div",{className:"flex items-center gap-3 max-lg:gap-2",children:[e.jsx(Me,{id:t,checked:i,onCheckedChange:n,disabled:r,className:"size-5 shrink-0"}),e.jsxs("label",{htmlFor:t,className:"flex min-w-0 flex-1 cursor-pointer items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-sm font-medium text-content-primary max-lg:text-xs",children:s}),e.jsx(zs,{label:s,hint:a}),l]})]}),i&&c?e.jsx("div",{className:"mt-2 pl-8 max-lg:mt-1.5 max-lg:pl-7",children:c}):null]})}function dh({section:t,meta:s,saving:a,accentColor:i,prescriptionAlwaysVisible:n,prescriptionSignoffMode:r,progressNotesSection:l,progressNotesMeta:c,onEnabledChange:u,onAlwaysVisibleChange:m,onSignoffModeChange:h,onProgressNotesEnabledChange:g}){const{attributes:y,listeners:p,setNodeRef:d,transform:x,transition:f,isDragging:C}=fn({id:t.key}),N=t.enabled!==!1;return e.jsxs("div",{ref:d,style:{transform:hn.Transform.toString(x),transition:f},className:K("flex items-center gap-2 border-b border-subtle py-2 last:border-b-0 max-lg:gap-1.5 max-lg:py-1.5",t.key===Zt.PRESCRIPTION&&"flex-wrap",C&&"relative z-raised bg-surface-raised shadow-sm"),children:[e.jsx(B,{t
318ype:"button",variant:"ghost",size:"icon",className:"size-6 min-h-6 min-w-6 shrink-0 cursor-grab rounded text-content-tertiary hover:text-content-primary active:cursor-grabbing","aria-label":`Drag to reorder ${s.label}`,disabled:a,...y,...p,children:e.jsx(ha,{className:"size-4","aria-hidden":!0})}),e.jsx(Me,{id:`operations-charting-section-${t.key}`,checked:N,onCheckedChange:v=>u(t.key,v===!0),disabled:a,className:"size-5 shrink-0"}),e.jsxs("label",{htmlFor:`operations-charting-section-${t.key}`,className:"flex min-w-0 flex-1 cursor-pointer items-center gap-1.5",children:[e.jsx("span",{className:K("truncate text-sm font-medium max-lg:text-xs",N?"text-content-primary":"text-content-tertiary"),children:s.label}),e.jsx(zs,{label:s.label,hint:s.description})]}),N&&t.key===Zt.REVIEW&&l?e.jsx(Wa,{id:"operations-charting-progress-notes",label:c.label,hint:c.description,checked:l.enabled!==!1,onChange:g,disabled:a,accentColor:i}):null,N&&t.key===Zt.PRESCRIPTION?e.jsxs("div",{className:"flex min-w-0 flex-col items-end gap-1.5 max-lg:w-full max-lg:pl-8",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1.5 max-lg:gap-1",children:[e.jsx(Wa,{id:"operations-charting-prescription-always-visible",label:"Always visible",hint:`Providers can open the prescription section before Step 2 approval.${r===ft.SIGN_TOGETHER||r===ft.PRESCRIBE_FIRST?" Kept on while an unlocked prescribe mode is enabled.":" Final prescribing still requires an approved decision."}`,checked:n===!0||r===ft.SIGN_TOGETHER||r===ft.PRESCRIBE_FIRST,onChange:m,disabled:a||r===ft.SIGN_TOGETHER||r===ft.PRESCRIBE_FIRST,accentColor:i}),e.jsx("div",{role:"radiogroup","aria-label":"Prescription sign-off order",className:"flex flex-wrap items-center justify-end gap-1.5 max-lg:gap-1",children:lh.map(v=>e.jsx(Wa,{id:`operations-charting-signoff-${v.id}`,label:v.label,hint:v.hint,checked:r===v.id,onChange:()=>h(v.id),disabled:a,accentColor:i},v.id))})]}),r===ft.PRESCRIBE_FIRST?e.jsx("p",{className:"max-w-sm text-right text-2xs leading-relaxed text-content-tertiary",children:"The chart stays open after dispatch until the prescriber signs to close the encounter. Deny and defer are unavailable once a prescription is sent. EMR delivery waits for the signature."}):null]}):null]})}function mh({providerNetworkId:t,accentColor:s}){const{userDoc:a,providerNetwork:i}=Se(),{branding:n}=Ce(),r=t||(a==null?void 0:a.providerNetworkId)||(i==null?void 0:i.id),l=s||(n==null?void 0:n.accentColor)||(i==null?void 0:i.accentColor)||je,[c,u]=o.useState(!0),[m,h]=o.useState({allowSelfReduction:!1,enforceLicensure:!0,syncVisitClaiming:!1,syncVisitProviderIds:[],visitNotifications:!1,visitNotificationRules:[],requireProductFormCoverage:!0,legitScriptEnabled:!1,hideVoidActionFromProviders:!1,hideLastProviderColumn:!1,chartingWorkflow:rn}),[g,y]=o.useState(!1),[p,d]=o.useState(""),[x,f]=o.useState(new Set),[C,N]=o.useState(!1),[v,k]=o.useState(""),[P,A]=o.useState(!1),[E,z]=o.useState(!0);o.useEffect(()=>{if(!r){u(!1);return}let S=!1;const Q=qe(he(ce,"ProviderNetworks",r),Y=>{var Ee,Oe,nt,ze;if(S)return;const de=Y.exists()?Y.data()||{}:{},ve=mr(de.chartingWorkflow);h({allowSelfReduction:de.allowProviderAvailabilitySelfReduction===!0,enforceLicensure:fu(de),syncVisitClaiming:((Ee=de.syncVisitClaiming)==null?void 0:Ee.enabled)===!0,syncVisitProviderIds:Array.isArray((Oe=de.syncVisitClaiming)==null?void 0:Oe.providerIds)?de.syncVisitClaiming.providerIds:[],visitNotifications:((nt=de.visitNotifications)==null?void 0:nt.enabled)===!0,visitNotificationRules:Array.isArray((ze=de.visitNotifications)==null?void 0:ze.rules)?de.visitNotifications.rules:[],requireProductFormCoverage:de.requireProductFormCoverage!==!1,legitScriptEnabled:de.legitScriptEnabled===!0,hideVoidActionFromProviders:de.hideVoidActionFromProviders===!0,hideLastProviderColumn:de.hideLastProviderColumn===!0,chartingWorkflow:ve}),d(ve.approveButtonText),y(!!ve.approveButtonText),u(!1)},Y=>{console.error("Failed to load operations controls",Y),I.error("Unable to load operations controls. Please try again."),S||u(!1)});return()=>{S=!0,Q()}},[r]),o.useEffect(()=>{if(!r){A(!1),z(!1);return}let S=!1;return z(!0),pm({providerNetworkId:r}).then(Q=>{if(S)return;const Y=Array.isArray(Q==null?void 0:Q.pharmacies)?Q.pharmacies:[];A(bu(Y))}).catch(Q=>{console.error("Failed to load pharmacy capability for prescribe-by-product",Q),S||A(!1)}).finally(()=>{S||z(!1)}),()=>{S=!0}},[r]);function q(S,Q){f(Y=>{const de=new Set(Y);return Q?de.add(S):de.delete(S),de})}async function R(S,Q,Y,de,ve=Y){if(!r||x.has(S))return;const Ee=m[S];h(Oe=>({...Oe,[S]:ve})),q(S,!0);try{await Fe(he(ce,"ProviderNetworks",r),{[Q]:Y,updatedAt:Pe()}),I.success(de)}catch(Oe){console.error(`Failed to save ${S}`,Oe),h(nt=>({...nt,[S]:Ee})),I.error(`Unable to update ${de.toLowerCase()}.`)}finally{q(S,!1)}}async function O(S,Q,Y="charting-sections"){if(!r||x.has(Y))return;const de=m.chartingWorkflow,ve=mr(S);h(Ee=>({...Ee,chartingWorkflow:ve})),q(Y,!0);try{await Fe(he(ce,"ProviderNetworks",r),{chartingWorkflow:Yo(ve),updatedAt:Pe()}),I.success(Q)}catch(Ee){console.error("Failed to save charting workflow",Ee),h(Oe=>({...Oe,chartingWorkflow:de})),I.error(`Unable to update ${Q.toLowerCase()}.`)}finally{q(Y,!1)}}async function j(S,Q,Y){await O({...m.chartingWorkflow,[S]:Q},Y,`charting-${S}`)}async function L(S){await O({...J,decisionQuestions:S},"Chart review decision questions updated","charting-decisionQuestions")}async function b(S){await O({...J,patientFieldQuestions:S},"Chart review patient data fields updated","charting-patientFieldQuestions")}function w(S){const Q=S(J.sections);O({...J,sections:Q},"Visit charting section settings updated")}function F(S,Q){w(Y=>In(Y,S,{enabled:Q}))}function M(S){w(Q=>In(Q,Zt.PRESCRIPTION,{alwaysVisible:S}))}function W(S){const Q=m.chartingWorkflow,Y=ch(S);Q.prescribeBeforeSignoff===Y.prescribeBeforeSignoff&&Q.approveAndPrescribeTogether===Y.approveAndPrescribeTogether||O({...Q,...Y},oh[S]||"Prescription sign-off updated","charting-signoff-mode")}function H(S){w(Q=>In(Q,Zt.PROGRESS_NOTES,{enabled:S}))}function ae(S){const{active:Q,over:Y}=S;!Y||Q.id===Y.id||w(de=>
318wu(de,Q.id,Y.id))}async function xe(S){if(!r||x.has("enforceLicensure"))return;const Q=m.enforceLicensure;q("enforceLicensure",!0);try{const Y=(a==null?void 0:a.fullName)||(a==null?void 0:a.displayName)||(a==null?void 0:a.email)||null,de=km(ce);de.update(he(ce,"ProviderNetworks",r),{enforceProviderStateLicensure:S,enforceProviderStateLicensureUpdatedAt:Pe(),enforceProviderStateLicensureUpdatedBy:(a==null?void 0:a.id)||null,enforceProviderStateLicensureUpdatedByName:Y,updatedAt:Pe()}),de.set(he(Xe(ce,"AuditLogs")),{type:"provider_network_policy",action:"state_licensure_enforcement_changed",userId:(a==null?void 0:a.id)||null,userType:(a==null?void 0:a.userType)||null,scopeKey:`providerNetwork:${r}`,metadata:{field:"enforceProviderStateLicensure",previousValue:Q,newValue:S,providerNetworkId:r,actorName:Y},timestamp:Pe()}),await de.commit(),h(ve=>({...ve,enforceLicensure:S})),I.success(S?"State licensure enforcement enabled":"State licensure enforcement disabled")}catch(Y){console.error("Failed to save state licensure enforcement",Y),I.error("Unable to update state licensure enforcement.")}finally{q("enforceLicensure",!1)}}function Ae(S){if(S){xe(!0);return}k(""),N(!0)}async function se(){v.trim().toUpperCase()===Gn&&(N(!1),await xe(!1))}function Z(S){y(S),S||j("approveButtonText","","Step 2 approve button text reset")}function fe(){if(!g)return;const S=p.trim().slice(0,50);d(S),S||y(!1),j("approveButtonText",S,S?"Step 2 approve button text updated":"Step 2 approve button text reset")}const J=m.chartingWorkflow,ge=J.sections||rn.sections,ye=o.useMemo(()=>ge.filter(S=>S.key!==Zt.PROGRESS_NOTES),[ge]),Re=ge.find(S=>S.key===Zt.PROGRESS_NOTES),G=Mi[Zt.PROGRESS_NOTES],U=ge.find(S=>S.key===Zt.PRESCRIPTION),V=o.useMemo(()=>ye.map(S=>S.key),[ye]),D=Mr(Fr(zr,{activationConstraint:{distance:6}}));if(!r)return null;const T=x.size>0,$=m.enforceLicensure?null:e.jsx(De,{className:"shrink-0 border-amber-200 bg-amber-100 text-amber-900 hover:bg-amber-100 max-lg:px-1.5 max-lg:text-3xs dark:border-amber-800 dark:bg-amber-950/60 dark:text-amber-200",children:"Override active"});return e.jsxs(Wt,{delayDuration:150,children:[e.jsx(bn,{title:"Operations controls",description:"Network-wide policies and charting controls. Every change saves automatically.",className:"lg:col-span-2",actions:T?e.jsx($e,{label:"Saving operations settings",className:"text-content-tertiary"}):null,children:c?e.jsx("div",{className:"space-y-2",children:Array.from({length:8}).map((S,Q)=>e.jsx(ue,{className:"h-9 w-full rounded-lg"},Q))}):e.jsxs("div",{className:"space-y-5 max-lg:space-y-3.5",children:[e.jsxs("div",{className:"grid gap-x-8 sm:grid-cols-2",children:[e.jsx(Ut,{id:"operations-allow-self-reduction",checked:m.allowSelfReduction,onCheckedChange:S=>void R("allowSelfReduction","allowProviderAvailabilitySelfReduction",S===!0,"Provider availability reduction settings updated"),disabled:x.has("allowSelfReduction"),title:"Allow provider availability reductions",hint:"Providers can reduce or remove their own hours without approval."}),e.jsx(Ut,{id:"operations-enforce-licensure",checked:m.enforceLicensure,onCheckedChange:Ae,disabled:x.has("enforceLicensure"),title:"Require patient-state licensure",hint:"Require providers to hold an active license in the patient's state.",badge:$}),e.jsx(Ut,{id:"operations-sync-claiming",checked:m.syncVisitClaiming,onCheckedChange:S=>void R("syncVisitClaiming","syncVisitClaiming",{enabled:S===!0,providerIds:m.syncVisitProviderIds},"Sync visit claiming settings updated",S===!0),disabled:x.has("syncVisitClaiming"),title:"Enable network sync-visit claiming",hint:"Allow selected in-network providers to claim eligible sync visits."}),e.jsx(Ut,{id:"operations-visit-notifications",checked:m.visitNotifications,onCheckedChange:S=>void R("visitNotifications","visitNotifications",{enabled:S===!0,rules:m.visitNotificationRules},"Visit notification settings updated",S===!0),disabled:x.has("visitNotifications"),title:"Enable visit notifications",hint:"Send the configured visit reminder email and text messages."}),(a==null?void 0:a.providerNetworkId)===r&&Ts(a==null?void 0:a.userType,"Provider Network Admin")?e.jsx(Ut,{id:"operations-legitscript",checked:m.legitScriptEnabled,onCheckedChange:S=>void R("legitScriptEnabled","legitScriptEnabled",S===!0,"LegitScript approval visibility updated"),disabled:x.has("legitScriptEnabled"),title:"Show LegitScript approval",hint:"Mark protocols as approved or not approved. Linked clients see the same status on their products."}):null,e.jsx(Ut,{id:"operations-product-form-coverage",checked:m.requireProductFormCoverage,onCheckedChange:S=>void R("requireProductFormCoverage","requireProductFormCoverage",S===!0,"Product form coverage settings updated"),disabled:x.has("requireProductFormCoverage"),title:"Require product form coverage",hint:"Only offer products with an applicable intake form."}
318),e.jsx(Ut,{id:"operations-hide-provider-void",checked:m.hideVoidActionFromProviders,onCheckedChange:S=>void R("hideVoidActionFromProviders","hideVoidActionFromProviders",S===!0,"Provider void settings updated"),disabled:x.has("hideVoidActionFromProviders"),title:"Hide void action from providers",hint:"Remove the Void button from the provider async visits queue. Provider Network Admins can still void."}),e.jsx(Ut,{id:"operations-hide-last-provider-column",checked:m.hideLastProviderColumn,onCheckedChange:S=>void R("hideLastProviderColumn","hideLastProviderColumn",S===!0,"Last provider column settings updated"),disabled:x.has("hideLastProviderColumn"),title:"Hide last provider column",hint:"Hide Last Provider for all roles in visit tables and CSV column exports."}),P?e.jsx(Ut,{id:"operations-prescribe-by-product",checked:J.prescribeByProduct===!0,onCheckedChange:S=>void j("prescribeByProduct",S===!0,"Prescribe-by-product setting updated"),disabled:x.has("charting-prescribeByProduct")||E,title:"Prescribe by product",hint:"Providers pick a product first in charting Step 3 and form-request prescribing, from both the client's own products and the provider network's. OnlyScripts-tied products can be sent; custom or untied products are save-only."}):null,e.jsx(Ut,{id:"operations-combine-attestations",checked:J.combineAttestations,onCheckedChange:S=>void j("combineAttestations",S===!0,"Attestation settings updated"),disabled:x.has("charting-combineAttestations"),title:"Combine attestations",hint:"Use one statement when providers record a visit decision."}),e.jsx(Ut,{id:"operations-custom-approve-button",checked:g,onCheckedChange:Z,disabled:x.has("charting-approveButtonText"),title:"Use custom Step 2 approve text",hint:"Rename the approve button providers see in Step 2 of charting.",children:e.jsx(be,{value:p,onChange:S=>d(S.target.value.slice(0,50)),onBlur:fe,maxLength:50,placeholder:"e.g. Approve care plan","aria-label":"Custom Step 2 approve button text"})})]}),e.jsxs("div",{children:[e.jsx(Nr,{title:"Visit charting sections",hint:"Control which charting sections providers see and the order they appear in Visit Charting. Drag rows to reorder, and use the pills for each section's options."}),e.jsx(tn,{sensors:D,collisionDetection:sn,onDragEnd:ae,children:e.jsx(an,{items:V,strategy:nn,children:ye.map(S=>{const Q=Mi[S.key]||{label:S.key,description:"Charting section."};return e.jsx(dh,{section:S,meta:Q,accentColor:l,saving:x.has("charting-sections")||x.has("charting-signoff-mode"),prescriptionAlwaysVisible:U==null?void 0:U.alwaysVisible,prescriptionSignoffMode:ku(J),progressNotesSection:Re,progressNotesMeta:G,onEnabledChange:F,onAlwaysVisibleChange:M,onSignoffModeChange:W,onProgressNotesEnabledChange:H},S.key)})})})]}),e.jsx(ih,{decisionQuestions:J.decisionQuestions,onPersist:L,patientFieldQuestions:J.patientFieldQuestions,onPersistPatientFields:b,providerNetworkId:r,disabled:!r,saving:x.has("charting-decisionQuestions")||x.has("charting-patientFieldQuestions")})]})}),e.jsx(_s,{open:C,onOpenChange:S=>{S||k(""),N(S)},title:"Turn off the license check?",description:"Providers could treat patients in states where they are not licensed. Other access and safety checks stay on, and this change is logged.",confirmLabel:"Turn off check",tone:"destructive",confirmDisabled:v.trim().toUpperCase()!==Gn,onConfirm:se,children:e.jsxs("div",{className:"space-y-2 max-lg:space-y-1.5",children:[e.jsxs("label",{htmlFor:"operations-disable-licensure-confirmation",className:"text-sm font-medium text-content-primary max-lg:block max-lg:text-xs",children:["Type ",Gn," to confirm"]}),e.jsx(be,{id:"operations-disable-licensure-confirmation",value:v,onChange:S=>k(S.target.value),autoComplete:"off"})]})})]})}function uh(t={}){const s=[t.firstName,t.lastName].filter(Boolean).join(" ").trim();return t.fullName||t.displayName||s||t.email||"Unnamed provider"}function xh(t,s){return t.enabled===s.enabled&&JSON.stringify([...t.providerIds].sort())===JSON.stringify([...s.providerIds].sort())}function ph({providerNetworkId:t,accentColor:s,showMasterToggle:a=!0}){const{userDoc:i,providerNetwork:n}=Se(),{branding:r}=Ce(),l=t||(n==null?void 0:n.id),c=s||(r==null?void 0:r.accentColor)||je,[u,m]=o.useState(!0),[h,g]=o.useState(!1),[y,p]=o.use
318State({enabled:!1,providerIds:[]}),[d,x]=o.useState({enabled:!1,providerIds:[]}),[f,C]=o.useState([]),[N,v]=o.useState(!0),[k,P]=o.useState("");o.useEffect(()=>{if(!l){m(!1);return}const b=qe(he(ce,"ProviderNetworks",l),w=>{const F=Pu(w.exists()?w.data():null);p(F),x(F),m(!1)},w=>{console.error("Failed to load sync visit claiming setting",w),I.error("Unable to load the sync visit claiming setting. Please try again."),m(!1)});return()=>b()},[l]),o.useEffect(()=>{if(!l){v(!1);return}let b=!1;async function w(){try{v(!0);const F=await wo(mt(Xe(ce,"Users"),Ue("userType","in",Et(["Provider"])),Ue("providerNetworkId","==",l),Ue("status","==","active")));if(b)return;const M=F.docs.map(W=>{const H=W.data()||{};return{id:W.id,name:uh(H),email:H.email||"",active:!0}});M.sort((W,H)=>W.name.localeCompare(H.name)),C(M)}catch(F){console.error("Failed to load network providers for sync visit claiming",F),b||I.error("Unable to load network providers. Please try again.")}finally{b||v(!1)}}return w(),()=>{b=!0}},[l]);const A=o.useMemo(()=>new Set(f.map(b=>b.id)),[f]),E=o.useMemo(()=>{const b=y.providerIds.filter(w=>!A.has(w));return[...f,...b.map(w=>({id:w,name:"Former provider",email:w,active:!1}))]},[f,y.providerIds,A]),z=o.useMemo(()=>{const b=k.trim().toLowerCase();return b?E.filter(w=>w.name.toLowerCase().includes(b)||w.email.toLowerCase().includes(b)||String(w.id||"").toLowerCase().includes(b)):E},[E,k]),q=o.useMemo(()=>!xh(y,d),[y,d]),R=y.providerIds.length;function O(b,w){p(F=>({...F,providerIds:w?Array.from(new Set([...F.providerIds,b])):F.providerIds.filter(M=>M!==b)}))}async function j(){if(!(!l||h))try{g(!0),await Fe(he(ce,"ProviderNetworks",l),{syncVisitClaiming:{enabled:y.enabled,providerIds:y.providerIds},syncVisitClaimingUpdatedAt:Pe(),syncVisitClaimingUpdatedBy:(i==null?void 0:i.id)||null,updatedAt:Pe()}),x(y),I.success("Sync visit claiming settings updated")}catch(b){console.error("Failed saving sync visit claiming settings",b),I.error("Unable to update sync visit claiming settings. Please try again."),p(d)}finally{g(!1)}}function L(){p(d)}return l?e.jsxs(xt,{className:"overflow-hidden rounded-xl border border-subtle dark:bg-slate-800",children:[e.jsx("div",{className:"border-b border-subtle bg-surface-sunken p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:flex-nowrap max-lg:gap-1.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 max-lg:gap-1.5",children:[e.jsx("div",{className:"rounded-lg p-1.5 max-lg:p-1",style:{backgroundColor:c},children:e.jsx(Bu,{className:"size-4 text-white max-lg:size-3.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Sync visit claiming"}),e.jsx("p",{className:"truncate text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Allow selected providers to claim eligible network sync visits"})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2 max-lg:gap-1",children:[a&&(u?e.jsxs(e.Fragment,{children:[e.jsx(ue,{className:"h-4 w-8"}),e.jsx(ue,{className:"h-6 w-11 rounded-full"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-medium text-slate-700 max-lg:text-3xs dark:text-slate-300",children:y.enabled?"On":"Off"}),e.jsx(it,{checked:y.enabled,onCheckedChange:b=>p(w=>({...w,enabled:b})),disabled:h,"aria-label":"Allow providers to claim network sync visits",className:"data-[state=checked]:!bg-[var(--accent-color)]",style:{"--accent-color":c}})]})),!u&&q&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",size:"sm",onClick:L,disabled:h,className:"max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:"Discard"}),e.jsx(B,{size:"sm",onClick:j,disabled:h,className:"max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:h?e.jsx(Ve,{className:"size-4 animate-spin max-lg:size-3.5"}):"Save"})]})]})]})}),e.jsx("div",{className:"space-y-3 p-4 max-lg:space-y-2 max-lg:p-2.5",children:u?e.jsxs(e.Fragment,{children:[e.jsx(ue,{className:"h-12 w-full max-lg:h-10"}),e.jsx(ue,{className:"h-4 w-3/4"})]}):e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:y.enabled?"":"pointer-events-none opacity-50",children:[e.jsx("p",{className:"text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"Granted providers see a Network Visits list on their Visits page and can claim same-network sync visits that have not started, subject to the patient-state licensure policy above. Claiming transfers the visit, its order, and its chart review to them; the previous provider is notified."}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 max-lg:mt-2 max-lg:flex-nowrap max-lg:gap-2",children:[e.jsxs("div",{className:"relative min-w-0 flex-1 sm:max-w-xs",children:[e.jsx(pn,{className:"pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-slate-400 max-lg:left-2 max-lg:size-3","aria-hidden":!0}),e.jsx(be,{value:k,onChange:b=>P(b.target.value),placeholder:"Search providersâ¦","aria-label":"Search providers",className:"h-8 pl-8 text-xs max-lg:h-7 max-lg:pl-7 dark:border-slate-600 dar
318k:bg-slate-700"})]}),e.jsxs("span",{className:"shrink-0 text-xs text-content-tertiary max-lg:text-3xs",children:[R," granted"]})]}),e.jsx("div",{className:"mt-2 max-h-64 overflow-y-auto rounded-lg border border-subtle max-lg:mt-1.5 max-lg:max-h-52",children:N?e.jsx("div",{className:"space-y-2 p-3 max-lg:space-y-1.5 max-lg:p-2",children:Array.from({length:3}).map((b,w)=>e.jsx(ue,{className:"h-8 w-full max-lg:h-7"},w))}):z.length===0?e.jsx("p",{className:"p-4 text-center text-xs text-content-tertiary max-lg:p-2.5 max-lg:text-2xs",children:E.length===0?"No active providers in this network yet.":"No providers match your search."}):e.jsx("ul",{className:"divide-y divide-slate-100 dark:divide-slate-700/60",children:z.map(b=>{const w=y.providerIds.includes(b.id);return e.jsx("li",{children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-3 px-3 py-2 hover:bg-slate-50 max-lg:gap-2 max-lg:px-2 max-lg:py-1.5 dark:hover:bg-slate-700/30",children:[e.jsx(Me,{checked:w,disabled:h||!b.active&&!w,onCheckedChange:F=>O(b.id,F===!0),"aria-label":`Allow ${b.name} to claim network sync visits`}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-content-primary max-lg:text-xs max-lg:leading-tight",children:b.name}),b.email&&e.jsx("span",{className:"block truncate text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:b.email})]}),!b.active&&e.jsx(De,{className:"shrink-0 border-subtle bg-slate-100 text-content-secondary hover:bg-slate-100 max-lg:px-1.5 max-lg:text-3xs dark:bg-slate-700",children:"Inactive"})]})},b.id)})})})]}),!y.enabled&&e.jsx("div",{className:"absolute inset-0 z-raised flex items-center justify-center rounded-lg bg-slate-100/70 px-6 text-center max-lg:px-3 dark:bg-slate-900/70",children:e.jsxs("p",{className:"text-sm font-medium text-slate-700 max-lg:text-xs max-lg:leading-snug dark:text-slate-200",children:["Providers only see their own schedule. Turn this on to grant network visit claiming.",R>0?" Your saved provider selection is preserved.":""]})})]})})]}):null}const gh=[...ko].sort((t,s)=>t.value.localeCompare(s.value));function Js(t){return ln(t).map(s=>({...s,states:[...s.states],visitTypes:[...s.visitTypes]}))}function hh(t,s){return JSON.stringify(ln(t))!==JSON.stringify(ln(s))}function fh({rule:t,index:s,accentColor:a,categoryOptions:i,saving:n,onChange:r,onRemove:l}){const[c,u]=o.useState(""),m=t.visitTypes.includes(Ws);function h(x){r({...t,states:t.states.includes(x)?t.states.filter(f=>f!==x):[...t.states,x].sort()})}function g(x){r({...t,visitTypes:x?[Ws]:[]})}function y(x,f){const C=String(x||"").trim().toLowerCase().replace(/\s+/g,"");if(!C)return;let N=t.visitTypes.filter(v=>v!==Ws);f?N.includes(C)||(N=[...N,C]):N=N.filter(v=>v!==C),r({...t,visitTypes:N})}function p(){const x=String(c||"").trim().toLowerCase().replace(/\s+/g,"");if(!x)return;const f=Array.from(new Set([...t.visitTypes.filter(C=>C!==Ws),x]));r({...t,visitTypes:f}),u("")}const d=t.visitTypes.filter(x=>x!==Ws&&!i.some(f=>f.value===x));return e.jsxs("div",{className:"rounded-xl border border-subtle p-4 max-lg:p-2.5",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:["Rule ",s+1]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:n,className:"h-8 rounded-full px-2.5 text-xs max-lg:h-7 max-lg:px-2 max-lg:text-2xs",children:[e.jsx(bt,{className:"mr-1 size-3.5"}),"Remove"]})]}),e.jsxs("div",{className:"space-y-4 max-lg:space-y-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-slate-700 dark:text-slate-300",children:"States"}),e.jsx("div",{className:"grid grid-cols-8 gap-1.5 max-lg:gap-1 sm:grid-cols-10 md:grid-cols-12 lg:grid-cols-[repeat(17,minmax(0,1fr))]",children:gh.map(x=>{const f=t.states.includes(x.value);return e.jsx("button",{type:"button",title:x.label,onClick:()=>h(x.value),disabled:n,"aria-pressed":f,className:K("h-8 rounded-md border text-xs font-semibold transition-colors max-lg:h-7 max-lg:text-2xs",f?"text-white shadow-sm":"border-subtle bg-surface-raised dark:bg-slate-900/40 text-content-secondary hover:border-slate-300 hover:bg-slate-50 dark:hover:border-slate-600 dar
318k:hover:bg-slate-800",n&&"cursor-not-allowed opacity-60"),style:f?{backgroundColor:a,borderColor:a}:void 0,children:x.value},x.value)})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-slate-700 dark:text-slate-300",children:"Visit types"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-700 dark:text-slate-300",children:[e.jsx(Me,{checked:m,onCheckedChange:x=>g(x===!0),disabled:n}),"All visit types"]}),!m&&i.map(x=>e.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-700 dark:text-slate-300",children:[e.jsx(Me,{checked:t.visitTypes.includes(x.value),onCheckedChange:f=>y(x.value,f===!0),disabled:n}),x.label]},x.value)),!m&&d.map(x=>e.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-700 dark:text-slate-300",children:[e.jsx(Me,{checked:t.visitTypes.includes(x),onCheckedChange:f=>y(x,f===!0),disabled:n}),x]},x)),!m&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx(be,{value:c,onChange:x=>u(x.target.value),placeholder:"Custom visit type",disabled:n,className:"h-8 max-w-xs text-xs"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:p,disabled:n||!c.trim(),className:"h-8 rounded-full px-3 text-xs",children:"Add type"})]})]})]})]})]})}function bh({providerNetworkId:t,accentColor:s}){const{providerNetwork:a}=Se(),{branding:i}=Ce(),n=t||(a==null?void 0:a.id),r=s||(i==null?void 0:i.accentColor)||je,[l,c]=o.useState(!0),[u,m]=o.useState(!1),[h,g]=o.useState([]),[y,p]=o.useState([]),[d,x]=o.use
318State([]);o.useEffect(()=>{if(!n){c(!1);return}c(!0);const A=he(ce,"ProviderNetworks",n,"Settings",Fi),E=Xe(ce,"ProviderNetworks",n,"Categories"),z=qe(A,R=>{var j;const O=Js(R.exists()?(j=R.data())==null?void 0:j.rules:[]);g(O),p(O),c(!1)},R=>{console.error("Failed to load Beluga sync visit policy",R),I.error("Unable to load Beluga sync visit policy. Please try again."),c(!1)}),q=qe(E,R=>{const O=R.docs.map(j=>{const L=j.data()||{},b=String(L.name||j.id||"").trim();return b?{value:b.toLowerCase().replace(/\s+/g,""),label:b}:null}).filter(Boolean).sort((j,L)=>j.label.localeCompare(L.label));x(O)},R=>{console.error("Failed to load Beluga visit type categories",R)});return()=>{z(),q()}},[n]);const f=o.useMemo(()=>hh(h,y),[h,y]);function C(){g(Js(y))}function N(){g(A=>[...A,Au(A.length)])}function v(A,E){g(z=>z.map((q,R)=>R===A?E:q))}function k(A){g(E=>E.filter((z,q)=>q!==A))}async function P(){if(n)try{m(!0);const A=ln(h);await nr(he(ce,"ProviderNetworks",n,"Settings",Fi),{rules:A,updatedAt:Pe()},{merge:!0}),g(Js(A)),p(Js(A)),I.success("Beluga sync visit policy updated")}catch(A){console.error("Failed saving Beluga sync visit policy",A),I.error("Unable to update Beluga sync visit policy. Please try again."),g(Js(y))}finally{m(!1)}}return n?e.jsxs(xt,{className:"overflow-hidden rounded-xl border border-subtle dark:bg-slate-800",children:[e.jsx("div",{className:"border-b border-subtle bg-surface-sunken p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:flex-nowrap max-lg:gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 max-lg:min-w-0 max-lg:gap-1.5",children:[e.jsx("div",{className:"rounded-lg p-1.5 max-lg:p-1",style:{backgroundColor:r},children:e.jsx(on,{className:"size-4 text-white max-lg:size-3.5"})}),e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Beluga Sync Visit Policy"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Configure which patient states and Beluga visit types require live video visits."})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 max-lg:shrink-0 max-lg:gap-1",children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:!f||u,className:"h-8 px-2.5 text-xs max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:"Discard"}),e.jsx(B,{type:"button",size:"sm",onClick:P,disabled:!f||u,className:"h-8 px-2.5 text-xs text-white hover:opacity-95 max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",style:{backgroundColor:r},children:u?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"mr-1.5 size-3.5 animate-spin max-lg:mr-1 max-lg:size-3"}),"Saving"]}):"Save"})]})]})}),e.jsx("div",{className:"space-y-3 p-4 max-lg:space-y-2 max-lg:p-2.5",children:l?e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"h-24 w-full rounded-xl"}),e.jsx(ue,{className:"h-24 w-full rounded-xl"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs",children:"Empty policy means async visits unless a product explicitly requires sync."}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:N,disabled:u,className:"h-8 rounded-full px-3 text-xs max-lg:h-7 max-lg:px-2 max-lg:text-2xs",children:[e.jsx(ot,{className:"mr-1 size-3.5"}),"Add rule"]})]}),h.length===0?e.jsx("p",{className:"rounded-xl border border-dashed border-subtle px-4 py-6 text-sm text-content-tertiary",children:"No sync visit rules configured yet."}):e.jsx("div",{className:"space-y-3",children:h.map((A,E)=>e.jsx(fh,{rule:A,index:E,accentColor:r,categoryOptions:d,saving:u,onChange:z=>v(E,z),onRemove:()=>k(E)},A.id||E))})]})})]}):e.jsx(xt,{className:"overflow-hidden rounded-xl border border-subtle dark:bg-slate-800",children:e.jsx("div",{className:"border-b border-subtle bg-surface-sunken p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center gap-2 max-lg:min-w-0 max-lg:gap-1.5",children:[e.jsx("div",{className:"rounded-lg bg-slate-100 p-1.5 text-content-tertiary max-lg:p-1 dark:bg-slate-700",children:e.jsx(on,{className:"size-4 max-lg:size-3.5"})}),e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Beluga Sync Visit Policy"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Select a provider network to manage Beluga live-visit requirements."})]})]})})})}const Nl=[...ko].sort((t,s)=>t.value.localeCompare(s.value));function yh(t,s){return JSON.stringify(t)!==JSON.stringify(s)}function vh({providerNetworkId:t,accentColor:s}){const{providerNetwork:a}=Se(),{branding:i}=Ce(),n=t||(a==null?void 0:a.id),r=s||(i==null?void 0:i.accentColor)||je,[l,c]=o.useState(!0),[u,m]=o.useState(!1),[h,g]=o.useState(ji),[y,p]=o.use
318State(ji);o.useEffect(()=>{let N=!1;if(!n){c(!1);return}c(!0);const v=qe(he(ce,"ProviderNetworks",n),async k=>{try{if(!k.exists()){N||c(!1);return}const P=k.data()||{},A=gm(P),E=A===null?await hm(n):ki(A);if(N)return;g(E),p(E),c(!1)}catch(P){console.error("Failed resolving sync visit state settings snapshot",P),N||(I.error("Unable to load sync visit state settings. Please try again."),c(!1))}},k=>{console.error("Failed to load sync visit state settings",k),I.error("Unable to load sync visit state settings. Please try again."),N||c(!1)});return()=>{N=!0,v()}},[n]);const d=o.useMemo(()=>yh(h,y),[h,y]);function x(N){g(v=>v.includes(N)?v.filter(k=>k!==N):[...v,N].sort())}function f(){g(y)}async function C(){if(n)try{m(!0);const N=ki(h);await Fe(he(ce,"ProviderNetworks",n),{syncVisitStates:N,updatedAt:Pe()}),g(N),p(N),I.success("Sync visit state settings updated")}catch(N){console.error("Failed saving sync visit state settings",N),I.error("Unable to update sync visit state settings. Please try again."),g(y)}finally{m(!1)}}return n?e.jsxs(xt,{className:"overflow-hidden rounded-xl border border-subtle dark:bg-slate-800",children:[e.jsx("div",{className:"border-b border-subtle bg-surface-sunken p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:flex-nowrap max-lg:gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 max-lg:min-w-0 max-lg:gap-1.5",children:[e.jsx("div",{className:"rounded-lg p-1.5 max-lg:p-1",style:{backgroundColor:r},children:e.jsx(on,{className:"size-4 text-white max-lg:size-3.5"})}),e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Telehealth Visit States"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Choose the patient states that require telehealth video or phone visits."})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 max-lg:shrink-0 max-lg:gap-1",children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:f,disabled:!d||u,className:"h-8 px-2.5 text-xs max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:"Discard"}),e.jsx(B,{type:"button",size:"sm",onClick:C,disabled:!d||u,className:"h-8 px-2.5 text-xs text-white hover:opacity-95 max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",style:{backgroundColor:r},children:u?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"mr-1.5 size-3.5 animate-spin max-lg:mr-1 max-lg:size-3"}),"Saving"]}):"Save"})]})]})}),e.jsx("div",{className:"space-y-3 p-4 max-lg:space-y-2 max-lg:p-2.5",children:l?e.jsx("div",{className:"grid grid-cols-8 gap-1.5 max-lg:gap-1 sm:grid-cols-10 md:grid-cols-12 lg:grid-cols-[repeat(17,minmax(0,1fr))]",children:Array.from({length:51}).map((N,v)=>e.jsx(ue,{className:"h-8 rounded-md max-lg:h-7"},v))}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-content-tertiary max-lg:flex-nowrap max-lg:gap-2 max-lg:text-3xs max-lg:leading-tight",children:[e.jsx("span",{className:"max-lg:min-w-0",children:"Click a state to toggle telehealth visit requirement."}),e.jsxs("span",{className:"font-medium text-slate-700 max-lg:shrink-0 dark:text-slate-300",children:[h.length," of ",Nl.length," selected"]})]}),e.jsx("div",{className:"grid grid-cols-8 gap-1.5 max-lg:gap-1 sm:grid-cols-10 md:grid-cols-12 lg:grid-cols-[repeat(17,minmax(0,1fr))]",children:Nl.map(N=>{const v=h.includes(N.value);return e.jsx("button",{type:"button",title:N.label,onClick:()=>x(N.value),disabled:u,"aria-pressed":v,className:K("h-8 rounded-md border text-xs font-semibold transition-colors","max-lg:h-7 max-lg:text-2xs","focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-offset-white dark:focus:ring-offset-slate-800",v?"text-white shadow-sm":"border-subtle bg-surface-raised dark:bg-slate-900/40 text-content-secondary hover:border-slate-300 hover:bg-slate-50 dark:hover:border-slate-600 dark:hover:bg-slate-800",u&&"cursor-not-allowed opacity-60"),style:v?{backgroundColor:r,borderColor:r,"--tw-ring-color":`${r}60`}:{"--tw-ring-color":`${r}60`},children:N.value},N.value)})})]})})]}):e.jsx(xt,{className:"overflow-hidden rounded-xl border border-subtle dark:bg-slate-800",children:e.jsx("div",{className:"border-b border-subtle bg-surface-sunken p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center gap-2 max-lg:min-w-0 max-lg:gap-1.5",children:[e.jsx("div",{className:"rounded-lg bg-slate-100 p-1.5 text-content-tertiary max-lg:p-1 dark:bg-slate-700",children:e.jsx(on,{className:"size-4 max-lg:size-3.5"})}),e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Telehealth Visit States"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Select a provider network to manage which states require live visits."})]})]})})})}function Nh({providerNetworkId:t,accentColor:s}){const{providerNetwork:a}=Se(),i=t||(a==null?void 0:a.id),[n,r]=o.useState(!!i),[l,c]=o.useState(!1);return o.useEffect(()=>{if(!i){r(!1),c(!1);return}r(!0);const u=qe(he(ce,"ProviderNetworks",i),m=>{var g;const h=m.exists()?(g=m.data())==null?void 0:g.apiAdapterKey:null;c(Iu(h)),r(!1)},()=>{c(!1),r(!1)});return()=>u()},[i]),n?e.jsx(ue,{className:"h-40 w-full rounded-xl"}):l?e.jsx(bh,{providerNetworkId:i,accentColor:s}):e.jsx(vh,{providerNetworkId:i,accentColor:s})}const jh=[{id:"before_24h_patient_email",trigger:"beforeVisitStart",offsetMinutes:-1440,audience:"patient",channels:{email:!0,sms:!1},templateKey:"visitReminderPatient",enabled:!0},{id:"before_24h_provider_email",trigger:"beforeVisitStart",offsetMinutes:-1440,audience:"provider",channels:{email:!0,sms:!1},templateKey:"visitReminderProvider",enabled:!0},{id:"before_1h_patient_email",trigger:"beforeVisitStart",offsetMinutes:-60,audience:"patient",channels:{email:!0,sms:!1},templateKey:"visitReminderPatient",enabled:!0},{id:"before_1h_provider_email",trigger:"beforeVisitStart",offsetMinutes:-60,audience:"provider",channels:{email:!0,sms:!1},templateKey:"visitReminderProvider",enabled:!0},{id:"before_5m_patient",trigger:"beforeVisitStart",offsetMinutes:-5,audience:"patient",channels:{email:!0,sms:!0},templateKey:"visitReminderPatient",enabled:!0},{id:"before_5m_provider",trigger:"beforeVisitStart",offsetMinutes:-5,audience:"provider",channels:{email:!0,sms:!0},templateKey:"visitReminderProvider",enabled:!0}],kh=["minutes","hours","days"],wh={minutes:[5,10,15,30,45],hours:[1,2,4,6,12,24],days:[1,2,3,7]};function mn(){return jh.map(t=>({...t,channels:{...t.channels}}))}function Kn(t,s,a){const i=Number.isFinite(Number(s))?Math.max(0,Number(s)):0,r=Math.max(1,Math.round(i*(a==="days"?1440:a==="hours"?60:1)));return t==="afterVisitEnd"?r:-r}function Fa(t){const s=Math.abs(Number(t)||0);return s?s%1440===0&&s>=1440?{amount:s/1440,unit:"days"}:s%60===0&&s>=60?{amount:s/60,unit:"hours"}:{amount:s,unit:"minutes"}:{amount:30,unit:"minutes"}}function Ch(t,s){const a=s.indexOf(t);
318return a<0?s[0]:s[(a+1)%s.length]}function Sh(t){if(!t||typeof t!="object")return{enabled:!1,rules:mn()};const s=Array.isArray(t.rules)&&t.rules.length?t.rules.map((a,i)=>{var h,g;const n=a.trigger==="afterVisitEnd"?"afterVisitEnd":"beforeVisitStart",r=a.audience==="provider"?"provider":"patient",l=n==="afterVisitEnd"?60:-60,c=Number(a.offsetMinutes);let m=Number.isFinite(c)?Math.round(c):l;return m===0&&(m=l),m=n==="afterVisitEnd"?Math.abs(m):-Math.abs(m),{id:a.id||`rule_${i}_${Date.now()}`,trigger:n,offsetMinutes:m,audience:r,channels:{email:!!((h=a==null?void 0:a.channels)!=null&&h.email),sms:!!((g=a==null?void 0:a.channels)!=null&&g.sms)},templateKey:r==="provider"?"visitReminderProvider":"visitReminderPatient",enabled:a.enabled!==!1}}):mn();return{enabled:t.enabled===!0,rules:s}}function Eh(t){return t==="afterVisitEnd"?"After Visit End":"Before Visit Start"}function Th(t){return t==="provider"?"Provider":"Patient"}function Ph(t,s){const a=t==="days"?"Day":t==="hours"?"Hour":"Minute",i=`${a}s`;return s===1?a:i}function Ah(t){return{borderColor:`${t}66`,backgroundColor:`${t}1A`,color:t}}function Yn(t){return"inline-flex h-8 items-center justify-center rounded-full border px-3 text-xs font-medium transition-colors max-lg:h-7 max-lg:px-2 max-lg:text-3xs"}function jl(t){return t?"inline-flex size-8 items-center justify-center rounded-full border border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 max-lg:size-7 dark:border-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300":"inline-flex size-8 items-center justify-center rounded-full border border-subtle bg-surface-raised text-content-tertiary hover:bg-slate-50 max-lg:size-7 dark:hover:bg-slate-800"}function Ih({providerNetworkId:t,accentColor:s,showMasterToggle:a=!0}){const{providerNetwork:i}=Se(),{branding:n}=Ce(),r=t||(i==null?void 0:i.id),l=s||(n==null?void 0:n.accentColor)||je,[c,u]=o.useState(!0),[m,h]=o.useState(!1),[g,y]=o.useState({enabled:!1,rules:mn()}),[p,d]=o.useState({enabled:!1,rules:mn()});o.useEffect(()=>{if(!r){u(!1);return}const O=he(ce,"ProviderNetworks",r),j=qe(O,L=>{var w;if(!L.exists()){u(!1);return}const b=Sh((w=L.data())==null?void 0:w.visitNotifications);y(b),d(b),u(!1)},L=>{console.error("Failed to load visit notifications settings",L),I.error("Unable to load visit notification settings. Please try again."),u(!1)});return()=>j()},[r]);const x=o.useMemo(()=>JSON.stringify(g)!==JSON.stringify(p),[g,p]);async function f(){if(r)try{h(!0),await Fe(he(ce,"ProviderNetworks",r),{visitNotifications:g,updatedAt:Pe()}),d(g),I.success("Visit notification settings updated")}catch(O){console.error("Failed saving visit notification settings",O),I.error("Unable to update visit notification settings. Please try again."),y(p)}finally{h(!1)}}function C(){y(p)}function N(O,j){y(L=>{const b=[...L.rules];return b[O]=j(b[O]),{...L,rules:b}})}function v(){const O=`custom_${Date.now()}`;y(j=>({...j,rules:[...j.rules,{id:O,trigger:"beforeVisitStart",offsetMinutes:-30,audience:"patient",channels:{email:!0,sms:!1},templateKey:"visitReminderPatient",enabled:!0}]}))}function k(O){y(j=>({...j,rules:j.rules.filter((L,b)=>b!==O)}))}function P(O){N(O,j=>({...j,enabled:!j.enabled}))}function A(O){N(O,j=>{const L=j.trigger==="afterVisitEnd"?"beforeVisitStart":"afterVisitEnd",b=Fa(j.offsetMinutes);return{...j,trigger:L,offsetMinutes:Kn(L,b.amount,b.unit)}})}function E(O,j){N(O,L=>{const b=Fa(L.offsetMinutes),w=Number.parseInt(String(j),10),F=Number.isFinite(w)&&w>0?w:1;return{...L,offsetMinutes:Kn(L.trigger,F,b.unit)}})}function z(O){N(O,j=>{const L=Fa(j.offsetMinutes),b=Ch(L.unit,kh),w=wh[b]||[1],F=w.includes(L.amount)?L.amount:w[0];return{...j,offsetMinutes:Kn(j.trigger,F,b)}})}function q(O){N(O,j=>{const L=j.audience==="provider"?"patient":"provider";return{...j,audience:L,templateKey:L==="provider"?"visitReminderProvider":"visitReminderPatient"}})}function R(O,j){N(O,L=>{var b;return{...L,channels:{...L.channels||{},[j]:!((b=L==null?void 0:L.channels)!=null&&b[j])}}})}return e.jsxs(xt,{className:"rounded-xl border border-subtle dark:bg-slate-800 overflow-hidden h-full w-full flex flex-col",children:[e.jsx("div",{className:"bg-surface-sunken border-b border-subtle p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:flex-nowrap max-lg:gap-1.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 max-lg:gap-1.5",children:[e.jsx("div",{className:"rounded-lg p-1.5 max-lg:p-1",style:{backgroundColor:l},children:e.jsx(Us,{className:"size-4 text-white max-lg:size-3.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Visit Notifications"}),e.jsx("p",{className:"truncate text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Configure pre/post visit reminders by audience and channel"})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2 max-lg:gap-1",children:[a?e.jsx("div",{className:"flex items-center gap-2 max-lg:gap-1",children:c?e.jsxs(e.Fragment,{children:[e.jsx(ue,{className:"h-4 w-8"}),e.jsx(ue,{className:"h-6 w-11 rounded-full"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-medium text-slate-700 max-lg:text-3xs dark:text-slate-300",children:g.enabled?"On":"Off"}),e.jsx(it,{checked:g.enabled,onCheckedChange:O=>y(j=>({...j,enabled:O})),className:"data-[state=checked]:!bg-[var(--accent-color)]",style:{"--accent-color":l}})]})}):null,!c&&x?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",size:"sm",onClick:C,disabled:m,className:"max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:"Discard"}),e.jsx(B,{size:"sm",onClick:f,disabled:m,className:"max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:m?e.jsx(Ve,{className:"size-4 animate-spin max-lg:size-3.5"}):"Save"})]}):null]})]})}),e.jsx("div",{className:"p-4 space-y-3 overflow-y-auto max-lg:space-y-2 max-lg:p-2.5",children:e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:!c&&!g.enabled?"pointer-events-none opacity-50":"",children:[e.jsx("div",{className:"rounded-lg border border-subtle overflow-hidden max-lg:min-w-0",children:e.jsxs(la,{children:[e.jsx(oa,{children:e.jsxs(At,{className:"hover:bg-transparent dark:border-slate-700 bg-slate-50/70 dark:bg-slate-800/50",children:[e.jsx(Be,{className:"text-xs py-2 w-[90px]",children:"Status"}),e.jsx(Be,{className:"text-xs py-2 w-[170px]",children:"Trigger"}),e.jsx(Be,{className:"text-xs py-2 min-w-[220px]",children:"Timing"}),e.jsx(Be,{className:"text-xs py-2 w-[130px]",children:"Audience"}),e.jsx(Be,{className:"text-xs py-2 w-[80px] text-center",children:"Email"}),e.jsx(Be,{className:"text-xs py-2 w-[80px] text-center",children:"SMS"}),e.jsx(Be,{className:"text-xs py-2 w-[70px] text-right",children:"Action"})]})}),e.jsx(ca,{children:c?Array.from({length:4}).map((O,j)=>e.jsxs(At,{className:"dark:border-slate-700",children:[e.jsx(Ie,{className:"py-2",children:e.jsx(ue,{className:"h-6 w-10 rounded-full"})}),e.jsx(Ie,{className:"py-2",children:e.jsx(ue,{className:"h-8 w-32 rounded-full"})}),e.jsx(Ie,{className:"py-2",children:e.jsx(ue,{className:"h-8 w-44 rounded-full"})}),e.jsx(Ie,{className:"py-2",children:e.jsx(ue,{className:"h-8 w-24 rounded-full"})}),e.jsx(Ie,{className:"py-2 text-center",children:e.jsx(ue,{className:"mx-auto
318size-8 rounded-full"})}),e.jsx(Ie,{className:"py-2 text-center",children:e.jsx(ue,{className:"mx-auto size-8 rounded-full"})}),e.jsx(Ie,{className:"py-2 text-right",children:e.jsx(ue,{className:"ml-auto size-7 rounded-full"})})]},`loading-${j}`)):g.rules.map((O,j)=>{var w,F,M,W;const L=Fa(O.offsetMinutes),b=Ah(l);return e.jsxs(At,{className:"dark:border-slate-700 hover:bg-slate-50/60 dark:hover:bg-slate-700/30",children:[e.jsx(Ie,{className:"py-2",children:e.jsx("div",{className:"flex items-center",children:e.jsx(it,{checked:!!O.enabled,onCheckedChange:()=>P(j),"aria-label":`Toggle status for rule ${j+1}`,className:"data-[state=checked]:!bg-[var(--accent-color)]",style:{"--accent-color":l}})})}),e.jsx(Ie,{className:"py-2",children:e.jsx("button",{type:"button",onClick:()=>A(j),className:Yn(),style:b,children:Eh(O.trigger)})}),e.jsx(Ie,{className:"py-2",children:e.jsxs("div",{className:"flex items-center gap-2 max-lg:gap-1.5",children:[e.jsx("input",{type:"text",min:"1",step:"1",inputMode:"numeric",value:L.amount,onChange:H=>E(j,H.target.value),className:"h-8 w-16 rounded-md border border-subtle bg-surface-raised px-2 text-center text-xs font-medium text-slate-700 outline-none transition-colors focus:border-[var(--accent-color)] focus:ring-2 focus:ring-slate-300 max-lg:w-14 dark:text-slate-100 dark:focus:ring-slate-500",style:{"--accent-color":l},"aria-label":`Timing amount for rule ${j+1}`}),e.jsx("button",{type:"button",onClick:()=>z(j),className:Yn(),style:b,title:"Click to cycle unit",children:Ph(L.unit,L.amount)})]})}),e.jsx(Ie,{className:"py-2",children:e.jsx("button",{type:"button",onClick:()=>q(j),className:Yn(),style:b,children:Th(O.audience)})}),e.jsx(Ie,{className:"py-2 text-center",children:e.jsx("button",{type:"button","aria-label":`Toggle email channel for rule ${j+1}`,onClick:()=>R(j,"email"),className:jl(!!((w=O.channels)!=null&&w.email)),children:(F=O.channels)!=null&&F.email?e.jsx(Ze,{className:"size-4"}):e.jsx(Ft,{className:"size-4"})})}),e.jsx(Ie,{className:"py-2 text-center",children:e.jsx("button",{type:"button","aria-label":`Toggle sms channel for rule ${j+1}`,onClick:()=>R(j,"sms"),className:jl(!!((M=O.channels)!=null&&M.sms)),children:(W=O.channels)!=null&&W.sms?e.jsx(Ze,{className:"size-4"}):e.jsx(Ft,{className:"size-4"})})}),e.jsx(Ie,{className:"py-2 text-right",children:e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"size-7 text-red-600 hover:text-red-700 hover:bg-red-50 max-[1024px]:h-7 max-[1024px]:w-7 max-[1024px]:min-h-7 max-[1024px]:min-w-7",onClick:()=>k(j),disabled:g.rules.length<=1,children:e.jsx(bt,{className:"size-4 max-lg:size-3.5"})})})]},O.id)})})]})}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3 max-lg:mt-1.5 max-lg:gap-2",children:[e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-snug",children:"Click trigger/unit pills and type the timing amount. Reminder jobs are created when a visit is confirmed (no backfill for historical visits)."}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:v,disabled:c,className:"h-8 shrink-0 px-2.5 text-xs max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:[e.jsx(ot,{className:"mr-1.5 size-3.5 max-lg:mr-1 max-lg:size-3"}),"Add Rule"]})]})]}),!c&&!g.enabled&&e.jsx("div",{className:"absolute inset-0 z-raised flex items-center justify-center rounded-lg bg-slate-100/70 px-6 text-center max-lg:px-3 dark:bg-slate-900/70",children:e.jsx("p",{className:"text-sm font-medium text-slate-700 max-lg:text-xs max-lg:leading-snug dark:text-slate-200",children:"All visit-related emails and text messages are disabled."})})]})})]})}const Rh=K("h-7 w-14 shrink-0 rounded-md border border-subtle bg-surface-raised px-1.5 text-center text-xs text-content-primary shadow-none","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:cursor-not-allowed disabled:opacity-50","max-lg:h-6 max-lg:w-12 max-lg:text-2xs"),Lh=[{key:"email",label:"Email"},{key:"sms",label:"SMS"}];function za({children:t}){return t?e.jsx("p",{className:"mt-0.5 text-xs leading-5 text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:t}):null}function Oh(){var xe,Ae,se,Z,fe,J,ge,ye,Re,G,U;const{providerNetwork:t,userDoc:s}=Se(),{branding:a}=Ce(),i=(a==null?void 0:a.accentColor)||je,n=!!(s!=null&&s.providerNetworkId),r=(t==null?void 0:t.id)||null,l=(Ae=(xe=t==null?void 0:t.providerNotifications)==null?void 0:xe.queuedPrescriptionRequest)==null?void 0:Ae.email,c=(se=t==null?void 0:t.providerNotifications)==null?void 0:se[Ci],u=c==null?void 0:c.email,m=c==null?void 0:c.sms,h=c==null?void 0:c.throttleMinutes,g=(fe=(Z=t==null?void 0:t.providerNotifications)==null?void 0:Z.staffMessageReceived)==null?void 0:fe.email,y=(ge=(J=t==null?void 0:t.providerNotifications)==null?void 0:J.staffMessageReceived)==null?void 0:ge.sms,p=(Re=(ye=t==null?void 0:t.providerNotifications)==null?void 0:ye.staffMessageReceived)==null?void 0:Re.throttleMinutes,d=(U=(G=t==null?void 0:t.providerNotifications)==null?void 0:G.messageEscalation)==null?void 0:U.email,[x,f]=o.useState(null),[C,N]=o.useState(!0),[v,k]=o.useState(()=>Si()),P=o.useRef(v),[A,E]=o.useState(!0),[z,q]=o.useState(!1),[R,O]=o.useState(()=>ya()),j=o.useRef(R);o.useEffect(()=>{if(!r){E(!0);return}const V=ya(l===void 0?void 0:{queuedPrescriptionRequest:{email:l}});O(V),j.current=V;const D=Si({email:u,sms:m,throttleMinutes:h});k(D),P.current=D,f({...typeof g=="boolean"?{email:g}:{},...typeof y=="boolean"?{sms:y}:{},...p!=null?{throttleMinutes:p}:{}}),N(d!==!1),E(!1)},[r,l,u,m,h,g,y,p,d]);const L=o.useCallback(async(V,D,T)=>{if(r)try{q(!0),await Fe(he(ce,"ProviderNetworks",r),{[V]:D,updatedAt:Pe()}),I.success("Notification settings updated")}catch($){console.error("Error saving provider notification settings:",$),I.error("Unable to save notification settings."),T==null||T()}finally{q(!1)}},[r]),b=o.useCallback((V,D)=>
318{if(!r||z)return;const T=x;f($=>({...$||{},[V]:D})),L(`${cr.tenantProviderStaffMessage}.${V}`,D,()=>f(T))},[r,L,z,x]),w=o.useCallback(V=>{if(!r||z)return;const D=V===!0;if(D===C)return;const T=C;N(D),L(cr.tenantMessageEscalationEmail,D,()=>N(T))},[C,r,L,z]),F=o.useCallback(async(V,D)=>{if(r)try{q(!0),await Fe(he(ce,"ProviderNetworks",r),{[`providerNotifications.${Ci}.${V}`]:D,updatedAt:Pe()}),P.current={...P.current,[V]:D},I.success("Notification settings updated")}catch(T){console.error("Error saving patient message alert defaults:",T),I.error("Unable to save notification settings."),k(P.current)}finally{q(!1)}},[r]),M=o.useCallback((V,D)=>{var $;if(!r||z)return;const T=D===!0;k(S=>({...S,[V]:T})),T!==(($=P.current)==null?void 0:$[V])&&F(V,T)},[r,F,z]),W=o.useCallback(()=>{var D;if(!r||z)return;const V=Ho(v.throttleMinutes,or);k(T=>({...T,throttleMinutes:V})),V!==((D=P.current)==null?void 0:D.throttleMinutes)&&F("throttleMinutes",V)},[v.throttleMinutes,r,F,z]),H=o.useCallback(async(V,D)=>{if(r)try{q(!0),await Fe(he(ce,"ProviderNetworks",r),{[`providerNotifications.${V}.email`]:D,updatedAt:Pe()}),j.current={...j.current||ya(),[V]:{email:D}},I.success("Notification settings updated")}catch(T){console.error("Error saving provider notification settings:",T),I.error("Unable to save notification settings."),O(j.current||ya())}finally{q(!1)}},[r]),ae=o.useCallback((V,D)=>{var S,Q;if(!r||z)return;const T=D===!0,$=T===((Q=(S=j.current)==null?void 0:S[V])==null?void 0:Q.email);O(Y=>({...Y,[V]:{email:T}})),!$&&H(V,T)},[r,H,z]);return!r&&!n?null:e.jsxs("div",{children:[e.jsx(tt,{id:"provider-network-provider-notifications",title:"Provider notifications",icon:Us,accentColor:i,loading:A,bodyClassName:"divide-y divide-subtle bg-surface-raised",children:A?e.jsx("div",{className:"grid gap-2 p-4 max-lg:p-2.5",children:e.jsx(ue,{className:"h-12 w-full rounded-lg max-lg:h-10"})}):e.jsxs(e.Fragment,{children:[Em.map(V=>{var $;const D=(($=R==null?void 0:R[V.key])==null?void 0:$.email)===!0,T=!r||z;return e.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-3 max-lg:gap-2 max-lg:px-2.5 max-lg:py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(oe,{htmlFor:`provider-notification-${V.key}`,className:"text-sm font-medium text-content-primary max-lg:text-xs",children:V.label}),e.jsx(za,{children:Tm(V.key)})]}),e.jsx(it,{id:`provider-notification-${V.key}`,checked:D,disabled:T,onCheckedChange:S=>ae(V.key,S),"aria-label":`Email for ${V.label}`})]},V.key)}),e.jsxs("div",{className:"px-4 py-3 max-lg:px-2.5 max-lg:py-2",children:[e.jsx("span",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Patient messages"}),e.jsx(za,{children:"Default SMS and email pointer alerts for providers, delegates, and admins when a patient message reaches them. Until you set email here, a provider is emailed (at most every 30 minutes) only when the patient addressed that provider: a direct message, the provider's own thread, or a provider-team message from a patient in their care. Other patient messages send no email by default. Each person can override this on their profile. Alerts never include the patient's name or the message."}),e.jsx("div",{className:"mt-2 grid gap-2 sm:grid-cols-2",children:Lh.map(V=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(oe,{htmlFor:`provider-notification-patient-message-${V.key}`,className:"text-xs font-medium text-content-primary max-lg:text-2xs",children:V.label}),e.jsx(it,{id:`provider-notification-patient-message-${V.key}`,checked:(v==null?void 0:v[V.key])===!0,disabled:!r||z,onCheckedChange:D=>M(V.key,D),"aria-label":`${V.label} for patient messages`})]},V.key))}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-content-primary max-lg:text-2xs",children:[e.jsx("label",{htmlFor:"provider-notification-patient-message-throttle",className:"whitespace-nowrap",children:"At most once every"}),e.jsx("input",{id:"provider-notification-patient-message-throttle",type:"number",min:1,max:1440,value:(v==null?void 0:v.throttleMinutes)??or,disabled:!r||z,onCh
318ange:V=>k(D=>({...D,throttleMinutes:V.target.value})),onBlur:W,className:Rh}),e.jsx("span",{className:"whitespace-nowrap",children:"minutes per conversation"})]})]}),e.jsx(yc,{idPrefix:"provider-notification-staff-message",staffConfig:x,patientConfig:v,control:"switch",disabled:!r||z,description:"Default alerts for team channels, direct messages, and announcements. Each person can override this on their profile.",onSaveField:b}),e.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-3 max-lg:gap-2 max-lg:px-2.5 max-lg:py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(oe,{htmlFor:"provider-notification-message-escalation",className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Escalations"}),e.jsx(za,{children:"Email the provider team when a conversation is escalated to them. On by default. Each person can override this on their profile. Muted conversations send no escalation email."}),e.jsx(za,{children:Wo})]}),e.jsx(it,{id:"provider-notification-message-escalation",checked:C,disabled:!r||z,onCheckedChange:w,"aria-label":"Email for escalations"})]})]})}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-content-secondary max-lg:mt-1.5 max-lg:text-2xs max-lg:leading-snug",children:"Providers always see the in-app alert. These controls cover email and SMS only."})]})}const Mh=[{value:"step_by_step",title:"Step-by-step visit workflow",description:"Providers move through clinical review, evaluation, attestation, and prescribing one step at a time. This is the default."},{value:"single_scroll",title:"Single-scroll visit workflow",description:"All charting steps are stacked on one scrollable page so providers can review and document without switching steps."}];function Fh({providerNetworkId:t,accentColor:s,showToggleOptions:a=!0}){const{providerNetwork:i}=Se(),{branding:n}=Ce(),r=t||(i==null?void 0:i.id),l=s||(n==null?void 0:n.accentColor)||je,[c,u]=o.useState(!0),[m,h]=o.useState(!1),[g,y]=o.useState(!1),[p,d]=o.useState(""),[x,f]=o.useState(rn),[C,N]=o.useState(rn);o.useEffect(()=>{if(!r){u(!1);return}const z=qe(he(ce,"ProviderNetworks",r),q=>{var O;if(!q.exists()){u(!1);return}const R=mr((O=q.data())==null?void 0:O.chartingWorkflow);f(R),N(R),u(!1)},q=>{console.error("Failed to load charting workflow settings",q),I.error("Unable to load charting settings. Please try again."),u(!1)});return()=>z()},[r]);const v=o.useMemo(()=>x.layout!==C.layout||x.hideProgressNotes!==C.hideProgressNotes||x.combineAttestations!==C.combineAttestations||x.combinedAttestationHtml!==C.combinedAttestationHtml||x.hideSoap!==C.hideSoap||x.approveButtonText!==C.approveButtonText||JSON.stringify(x.sections)!==JSON.stringify(C.sections),[x,C]);function k(){d(x.combinedAttestationHtml||""),y(!0)}function P(){f(z=>({...z,combinedAttestationHtml:p})),y(!1)}async function A(){if(r)try{h(!0),await Fe(he(ce,"ProviderNetworks",r),{chartingWorkflow:Yo(x),updatedAt:Pe()}),N(x),I.success("Charting settings updated")}catch(z){console.error("Failed saving charting workflow settings",z),I.error("Unable to update charting settings. Please try again."),f(C)}finally{h(!1)}}function E(){f(C)}return r?e.jsxs(xt,{className:"overflow-hidden rounded-xl border border-subtle dark:bg-slate-800",children:[e.jsx("div",{className:"border-b border-subtle bg-surface-sunken p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:flex-nowrap max-lg:gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 max-lg:min-w-0 max-lg:gap-1.5",children:[e.jsx("div",{className:"rounded-lg p-1.5 max-lg:p-1",style:{backgroundColor:l},children:e.jsx(fm,{className:"size-4 text-white max-lg:size-3.5"})}),e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Visit Charting"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Control how providers move through and document the visit charting workspace."})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 max-lg:shrink-0 max-lg:gap-1",children:[e.jsx(B,{t
318ype:"button",variant:"outline",size:"sm",onClick:E,disabled:!v||m,className:"h-8 px-2.5 text-xs max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:"Discard"}),e.jsx(B,{type:"button",size:"sm",onClick:A,disabled:!v||m,className:"h-8 px-2.5 text-xs text-white hover:opacity-95 max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",style:{backgroundColor:l},children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"mr-1.5 size-3.5 animate-spin max-lg:mr-1 max-lg:size-3"}),"Saving"]}):"Save"})]})]})}),e.jsx("div",{className:"space-y-3 p-4 max-lg:space-y-2 max-lg:p-2.5",children:c?e.jsxs(e.Fragment,{children:[e.jsx(ue,{className:"h-24 w-full max-lg:h-20"}),e.jsx(ue,{className:"h-12 w-full max-lg:h-10"}),e.jsx(ue,{className:"h-12 w-full max-lg:h-10"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-lg border border-subtle bg-surface-raised p-4 max-lg:p-2.5",children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Charting layout"}),e.jsx("p",{className:"mt-0.5 text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"Choose whether providers work through the visit one step at a time or on a single scrollable page."}),e.jsx("div",{className:"mt-3 space-y-2 max-lg:mt-2 max-lg:space-y-1.5",children:Mh.map(z=>{const q=x.layout===z.value;return e.jsxs("button",{type:"button",onClick:()=>f(R=>({...R,layout:z.value})),className:`flex w-full items-start gap-3 rounded-lg border p-3 text-left transition max-lg:gap-2 max-lg:p-2 ${q?"border-slate-300 bg-slate-50 dark:border-slate-500 dark:bg-slate-800":"border-slate-200 bg-white hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:hover:bg-slate-800"}`,style:q?{borderColor:l}:void 0,children:[e.jsx("span",{className:"mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border",style:{borderColor:q?l:"#cbd5e1"},"aria-hidden":!0,children:q?e.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:l}}):null}),e.jsxs("span",{className:"space-y-0.5",children:[e.jsx("span",{className:"block text-sm font-medium text-content-primary max-lg:text-xs",children:z.title}),e.jsx("span",{className:"block text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:z.description})]})]},z.value)})})]}),a?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-lg border border-subtle bg-surface-raised p-4 max-lg:gap-2 max-lg:p-2.5",children:[e.jsx(Me,{checked:x.hideProgressNotes,onCheckedChange:z=>f(q=>({...q,hideProgressNotes:z===!0})),className:"mt-0.5 shrink-0","aria-label":"Hide progress notes on the clinical review step"}),e.jsxs("span",{className:"space-y-1 max-lg:space-y-0.5",children:[e.jsx("span",{className:"block text-sm font-medium text-content-primary max-lg:text-xs",children:"Hide progress notes on the clinical review step"}),e.jsx("span",{className:"block text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"When enabled, the first charting step shows only the intake and form review content. The progress note editor and the inline add-progress-note actions are removed."})]})]}),e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-subtle bg-surface-raised p-4 max-lg:gap-2 max-lg:p-2.5",children:[e.jsxs("label",{className:"flex min-w-0 flex-1 cursor-pointer items-start gap-3 max-lg:gap-2",children:[e.jsx(Me,{checked:x.combineAttestations,onCheckedChange:z=>f(q=>({...q,combineAttestations:z===!0})),className:"mt-0.5 shrink-0","aria-label":"Combine attestations into a single statement"}),e.jsxs("span",{className:"space-y-1 max-lg:space-y-0.5",children:[e.jsx("span",{className:"block text-sm font-medium text-content-primary max-lg:text-xs",children:"Combine attestations into a single statement"}),e.jsx("span",{className:"block text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"When enabled, the attestation text appears under Visit Decision and recording a decision acknowledges the attestations."})]})]}
318),x.combineAttestations?e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:k,className:"size-8 shrink-0 rounded-full max-[1024px]:h-8 max-[1024px]:w-8","aria-label":"Edit combined attestation statement",children:e.jsx(zt,{className:"size-4 max-lg:size-3.5"})}):null]}),e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-lg border border-subtle bg-surface-raised p-4 max-lg:gap-2 max-lg:p-2.5",children:[e.jsx(Me,{checked:x.hideSoap,onCheckedChange:z=>f(q=>({...q,hideSoap:z===!0})),className:"mt-0.5 shrink-0","aria-label":"Hide SOAP evaluation"}),e.jsxs("span",{className:"space-y-1 max-lg:space-y-0.5",children:[e.jsx("span",{className:"block text-sm font-medium text-content-primary max-lg:text-xs",children:"Hide SOAP evaluation"}),e.jsx("span",{className:"block text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"When enabled, SOAP generation is disabled for this network and the charting evaluation step is hidden."})]})]})]}):null,!a&&x.combineAttestations?e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-subtle bg-surface-raised p-4 max-lg:flex-nowrap max-lg:gap-2 max-lg:p-2.5",children:[e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Combined attestation statement"}),e.jsx("p",{className:"mt-0.5 text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"Edit the statement providers acknowledge when recording a decision."})]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:k,className:"shrink-0 rounded-full max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:[e.jsx(zt,{className:"mr-1.5 size-3.5 max-lg:mr-1 max-lg:size-3","aria-hidden":!0}),"Edit"]})]}):null]})}),e.jsx(at,{open:g,onOpenChange:y,title:"Combined attestation statement",description:"Write the statement providers will acknowledge when recording a visit decision.",contentClassName:"max-w-3xl",bodyClassName:"!p-0",mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",footerClassName:"max-[1024px]:px-3 max-[1024px]:pt-2.5 max-[1024px]:gap-1.5",footer
318:e.jsxs("div",{className:"flex w-full justify-end gap-2 max-lg:gap-1.5",children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>y(!1),children:"Cancel"}),e.jsx(B,{type:"button",size:"sm",onClick:P,className:"text-white",style:{backgroundColor:l},children:"Save statement"})]}),children:e.jsx("div",{className:"px-5 py-3 max-lg:px-2 max-lg:py-2",children:e.jsx($t,{className:"space-y-3 overflow-hidden border-0 bg-surface-raised p-4 shadow-none max-lg:space-y-2 max-lg:p-2.5",children:e.jsx(Ru,{value:p,onChange:d,placeholder:"Write the attestation providers acknowledge when approving, deferring, or denying a visit",className:"min-h-[280px] max-lg:min-h-[200px] sm:min-h-[360px]"})})})})]}):null}function zh(){const{branding:t}=Ce(),s=(t==null?void 0:t.accentColor)||je;return e.jsxs("div",{className:"space-y-6 max-lg:space-y-3",children:[e.jsxs(Fg,{accentColor:s,children:[e.jsx(zg,{}),e.jsx(Dg,{}),e.jsx(Bg,{}),e.jsx(mh,{})]}),e.jsx(ph,{showMasterToggle:!1}),e.jsx(Nh,{}),e.jsx(Ih,{showMasterToggle:!1}),e.jsx(Oh,{}),e.jsx(Fh,{showToggleOptions:!1}),e.jsx(zo,{})]})}const Wr={timeoutMs:15e3,timeoutMessage:"Messaging policy request timed out. Try again."};function _h(){return rs("manageMessaging",{action:"getMessagingPolicy"},Wr)}function kl(t=null){return rs("manageMessaging",{action:"listMessagingPolicyClients",...t?{cursor:t}:{}},Wr)}function Uh(t){return rs("manageMessaging",{action:"updateMessagingPolicy",...t},Wr)}function Dh(t,s){const a=[],i=new Map;return[...Array.isArray(t)?t:[],...Array.isArray(s)?s:[]].forEach(n=>{const r=typeof(n==null?void 0:n.id)=="string"?n.id.trim():"";if(!r)return;const l={...n,id:r},c=i.get(r);c===void 0?(i.set(r,a.length),a.push(l)):a[c]={...a[c],...l}}),a}const ua=["Provider Network Admin","Provider","Provider Delegate"],jr={groupChatEnabled:!0,directMessagingEnabled:!1,allowedDirectRecipientUserTypes:[...ua],patientMessaging:{providerTeamEnabled:!0,individualProviderEnabled:!1}};function wt(t){var i,n;const s=t&&typeof t=="object"?t:{},a=Array.isArray(s.allowedDirectRecipientUserTypes)?s.allowedDirectRecipientUserTypes.filter(r=>bo(r,ua)):jr.allowedDirectRecipientUserTypes;return{groupChatEnabled:s.groupChatEnabled!==!1,directMessagingEnabled:s.directMessagingEnabled===!0,allowedDirectRecipientUserTypes:ua.filter(r=>a.includes(r)),patientMessaging:{providerTeamEnabled:((i=s.patientMessaging)==null?void 0:i.providerTeamEnabled)!==!1,individualProviderEnabled:((n=s.patientMessaging)==null?void 0:n.individualProviderEnabled)===!0}}}function $h(t){return Array.isArray(t)?t.reduce((s,a)=>{const i=String((a==null?void 0:a.clientId)||(a==null?void 0:a.id)||"").trim();return i&&(s[i]=a!=null&&a.policy?wt(a.policy):wt(a)),s},{}):!t||typeof t!="object"?{}:Object.entries(t).reduce((s,[a,i])=>{const n=String(a||"").trim();return n&&(s[n]=i&&typeof i=="object"?wt(i):null),s},{})}function wl(t){const s=t!=null&&t.data&&typeof t.data=="object"?t.data:t||{};return{aiDraftsEnabled:s.aiDraftsEnabled===!0,deliveryMode:sa(s.deliveryMode),defaultClientPolicy:wt(s.defaultClientPolicy),clientPolicies:$h(s.clientPolicies)}}function Cl(t){const s=t!=null&&t.data&&typeof t.data=="object"?t.data:t||{};return{clients:(Array.isArray(s.clients)?s.clients:[]).map(i=>{const n=typeof(i==null?void 0:i.id)=="string"?i.id.trim():"";return n?{id:n,displayName:i.displayName||null,name:i.name||null,businessName:i.businessName||null,legalName:i.legalName||null,messagingPolicyRelationship:i.messagingPolicyRelationship==="additional"?"additional":"primary",messagingPolicyOverride:i.messagingPolicyOverride?wt(i.messagingPolicyOverride):null}:null}).filter(Boolean),hasMore:s.hasMore===!0,nextCursor:typeof s.nextCursor=="string"&&s.nextCursor?s.nextCursor:null}}function fs(t){const s=wt(t);return{...s,allowedDirectRecipientUserTypes:[...s.allowedDirectRecipientUserTypes],patientMessaging:{...s.patientMessaging}}}function Bh(t,s){return!t&&!s?!0:!t||!s?!1:JSON.stringify(wt(t))===JSON.stringify(wt(s))}function Vh(t={},s={},a=new Set){const i=new Set([...Object.keys(t),...Object.keys(s)]);return Object.fromEntries([...i].filter(n=>
318!Bh(t[n],s[n])).map(n=>{const r=t[n]?wt(t[n]):null;return[n,r&&a.has(n)?{patientMessaging:r.patientMessaging}:r]}))}function Sl({aiDraftsEnabled:t,deliveryMode:s,defaultClientPolicy:a,clientPolicies:i}){const n=Object.fromEntries(Object.entries(i||{}).sort(([r],[l])=>r.localeCompare(l)).map(([r,l])=>[r,l?wt(l):null]));return JSON.stringify({aiDraftsEnabled:t===!0,deliveryMode:sa(s),defaultClientPolicy:wt(a),clientPolicies:n})}function qh(t){return t.displayName||t.name||t.businessName||t.legalName||"Unnamed client"}function El(t){return Object.fromEntries((Array.isArray(t)?t:[]).map(s=>[s.id,s.messagingPolicyOverride?fs(s.messagingPolicyOverride):null]))}function Tl(t,s){const a={...t||{}};return Object.entries(s||{}).forEach(([i,n])=>{Object.prototype.hasOwnProperty.call(a,i)||(a[i]=n?fs(n):null)}),a}function Pl({idPrefix:t,policy:s,onChange:a,disabled:i=!1,accentColor:n}){const r=(u,m)=>a({...s,[u]:m}),l=(u,m)=>{const h=s.allowedDirectRecipientUserTypes||[],g=m?[...new Set([...h,u])]:h.filter(y=>y!==u);r("allowedDirectRecipientUserTypes",ua.filter(y=>g.includes(y)))},c=s.directMessagingEnabled&&s.allowedDirectRecipientUserTypes.length===0;return e.jsxs(e.Fragment,{children:[e.jsx(vr,{id:`${t}-group-chat`,title:"Shared team chat",hint:"Lets the client use its shared internal thread with this provider network.",checked:s.groupChatEnabled,onCheckedChange:u=>r("groupChatEnabled",u===!0),disabled:i}),e.jsx(vr,{id:`${t}-direct-messaging`,title:"Direct staff messages",hint:"Lets client staff start a private internal conversation with selected network roles. Pick the roles they can reach below.",checked:s.directMessagingEnabled,onCheckedChange:u=>r("directMessagingEnabled",u===!0),disabled:i,children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 max-lg:gap-1",children:[ua.map(u=>e.jsx(Wa,{id:`${t}-${u.toLowerCase().replaceAll(" ","-")}`,label:u,hint:`Client staff can start a direct conversation with ${u} users in this network.`,checked:s.allowedDirectRecipientUserTypes.includes(u),onChange:m=>l(u,m),disabled:i,accentColor:n},u)),c?e.jsx("span",{className:"text-2xs text-red-700 max-lg:text-3xs dark:text-red-300",role:"alert",children:"Pick at least one role."}):null]})})]})}function Al({rows:t=3}){return e.jsx("div",{className:"space-y-2",children:Array.from({length:t}).map((s,a)=>e.jsx(ue,{className:"h-9 w-full rounded-lg"},a))})}function Il({message:t,onRetry:s}){return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-lg border border-red-200 bg-red-50 p-3 text-xs text-red-800 max-lg:gap-2 max-lg:p-2 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-200",role:"alert",children:[e.jsx("span",{children:t}),e.jsx(B,{type:"button",size:"sm",variant:"outline",onClick:s,className:"max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:"Try again"})]})}function Hh({providerNetworkId:t,accentColor:s}){const{userDoc:a,providerNetwork:i}=Se(),{branding:n}=Ce(),r=t||(a==null?void 0:a.providerNetworkId)||(i==null?void 0:i.id)||null,l=s||(n==null?void 0:n.accentColor)||je,[c,u]=o.useState(!0),[m,h]=o.useState(!0),[g,y]=o.useState(!1),[p,d]=o.useState(!1),[x,f]=o.useState(""),[C,N]=o.useState(""),[v,k]=o.useState(""),[P,A]=o.useState(0),[E,z]=o.useState(0),[q,R]=o.useState(null),[O,j]=o.useState([]),[L,b]=o.useState(null),[w,F]=o.useState(!1),M=o.useRef(0),[W,H]=o.useState({aiDraftsEnabled:!1,deliveryMode:wi.FULL_TEXT,defaultClientPolicy:fs(jr),clientPolicies:{}}),[ae,xe]=o.useState({aiDraftsEnabled:!1,deliveryMode:wi.FULL_TEXT,defaultClientPolicy:fs(jr),clientPolicies:{}});o.useEffect(()=>{if(!r){u(!1),R(null);return}let D=!1;async function T(){u(!0),R(null),f("");try{const $=await _h();if(($==null?void 0:$.success)===!1)throw new Error($.error||"Unable to load messaging policy.");const S=wl($);if(D)return;H(S),xe(S),R(r)}catch($){if(D)return;console.error("Failed to load messaging policy settings",$),f(($==null?void 0:$.message)||"Unable to load messaging policy. Try again.")}finally{D||u(!1)}}return T(),()=>{D=!0}},[r,P]),o.useEffect(()=>{const D=M.current+1;if(M.current=D,j([]),b(null),F(!1),N(""),k(""),!r||q!==r){h(!!(r&&!x));return}let T=!1;async function $(){h(!0);try{const S=await kl();if(T||M.current!==D)return;const Q=Cl(S),Y=El(Q.clients);j(Q.clients),b(Q.nextCursor),F(Q.hasMore),xe(de=>({...de,clientPolicies:{...de.clientPolicies,...Y}})),H(de=>({...de,clientPolicies:Tl(de.clientPolicies,Y)}))}catch(S){if(T||M.current!==D)return;console.error("Failed to load linked clients for messaging policy",S),N("Unable to load linked clients. Try again.")}finally{!T&&M.current===D&&h(!1)}}return $(),()=>{T=!0,M.current===D&&(M.current+=1)}},[E,q,x,r]);async function Ae(){if(!L||!w||g||p)return;const D=M.current;y(!0),k("");try{const T=await kl(L);if(M.current!==D)return;const $=Cl(T),S=El($.clients);j(Q=>Dh(Q,$.clients)),b($.nextCursor),F($.hasMore),xe(Q=>({...Q,clientPolicies:{...Q.clientPolicies,...S}})),H(Q=>({...Q,clientPolicies:Tl(Q.clientPolicies,S)}))}catch(T){if(M.current!==D)return;console.error("Failed to load more linked clients for messaging policy",T),k("Unable to load more linked clients.")}finally{M.current===D&&y(!1)}}const se=o.useMemo(()=>Sl(W)!==Sl(ae),[ae,W]),Z=o.useMemo(()=>new Set(O.filter(D=>D.messagingPolicyRelationship==="additional").map(D=>D.id)),[O]),fe=o.useMemo(()=>[W.defaultClientPolicy,...Object.entries(W.clientPolicies||{}).filter(([T])=>!Z.has(T)).map(([,T])=>T)].some(T=>(T==null?void 0:T.directMessagingEnabled)&&T.allowedDirectRecipientUserTypes.length===0),[Z,W]),J=se&&!p&&!c&&!m&&!g&&!fe;function ge(D){H(T=>({...T,defaultClientPolicy:wt(D)}))}function ye(D,T){H($=>({...$,clientPolicies:{...$.clientPolicies,[D]:T==="custom"?fs($.defaultClientPolicy):null}}))}function Re(D,T){H($=>({...$,clientPolicies:{...$.clientPolicies,[D]:wt(T)}}))}function G(){H({aiDraftsEnabled:ae.aiDraftsEnabled===!0,deliveryMode:sa(ae.deliveryMode),defaultClientPolicy:fs(ae.defaultClientPolicy),clientPolicies:Object.fromEntries(Object.entries(ae.clientPolicies||{}).map(([D,T])=>[D,T?fs(T):null]))})}async function U(){if(!J)return;const D={aiDraftsEnabled:W.aiDraftsEnabled===!0,deliveryMode:sa(W.deliveryMode),defaultClientPolicy:wt(W.defaultClientPolicy),clientPolicies:Vh(W.clientPolicies,ae.clientPolicies,Z)};try{d(!0);const T=await Uh(D);if((T==null?void 0:T.success)===!1)throw new Error(T.error||"Unable to update messaging policy.");const $=wl(T),S={aiDraftsEnabled:$.aiDraftsEnabled,deliveryMode:$.deliveryMode,defaultClientPolicy:$.defaultClientPolicy,clientPolicies:{...W.clientPolicies,...$.clientPolicies}};H(S),xe(S),I.success("Messaging policy updated")}catch(T){console.error("Failed to save messaging policy settings",T),I.error((T==null?void 0:T.message)||"Unable to update messaging policy. Please try again.")}finally{d(!1)}}if(!r)return null;const V=!m&&!C?`${O.length} linked ${O.length===1?"client":"clients"}`:"";return e.jsx(Wt,{delayDuration:150,children:e.jsx(tt,{id:"settings-messaging-policy",title:"Messaging policy",tooltipDescription:"Sets which conversations linked clients can start with this network, which network roles they can reach, and whether staff drafts may use the approved AI model. Disabled options block new sends while existing history stays readable.",icon:pa,accentColor:l,bodyClassName:"p-4 max-lg:p-2.5 sm:p-5",actions:e.jsxs("div",{className:"flex shrink-0 items-center gap-2 max-lg:gap-1",children:[e.jsx(B,{t
318ype:"button",variant:"outline",size:"sm",onClick:G,disabled:!se||p||c,"data-testid":"button-messaging-policy-discard",className:"rounded-full max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",children:"Discard"}),e.jsx(B,{type:"button",size:"sm",onClick:U,disabled:!J,style:{backgroundColor:l},className:"rounded-full text-white hover:opacity-95 max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs","data-testid":"button-messaging-policy-save",children:p?e.jsx(Ve,{className:"size-4 animate-spin max-lg:size-3.5","aria-label":"Saving messaging policy"}):"Save"})]}),children:e.jsxs("div",{className:"space-y-5 max-lg:space-y-3.5",children:[e.jsxs("section",{"aria-labelledby":"messaging-policy-default-title",children:[e.jsx(Nr,{title:"Network default",hint:"Applies to every linked client unless that client has a custom policy below."}),c?e.jsx("div",{className:"mt-3 max-lg:mt-2",children:e.jsx(Al,{})}):x?e.jsx("div",{className:"mt-3 max-lg:mt-2",children:e.jsx(Il,{message:x,onRetry:()=>A(D=>D+1)})}):e.jsxs(e.Fragment,{children:[e.jsx("span",{id:"messaging-policy-default-title",className:"sr-only",children:"Network default messaging policy"}),e.jsx(vr,{id:"messaging-policy-ai-drafts",title:"AI-assisted staff drafts",hint:"Consent to bounded recent message text being sent to the approved drafting model. Drafts are never sent automatically, and linked clients must separately consent.",checked:W.aiDraftsEnabled,onCheckedChange:D=>H(T=>({...T,aiDraftsEnabled:D===!0})),disabled:p}),e.jsxs("div",{className:"border-b border-subtle py-2.5 last:border-b-0 max-lg:py-2",children:[e.jsxs("div",{className:"flex items-center gap-3 max-lg:gap-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[e.jsx(oe,{htmlFor:"messaging-policy-delivery-mode",className:"truncate text-sm font-medium text-content-primary max-lg:text-xs",children:"Patient text notifications"}),e.jsx(zs,{label:"Patient text notifications",hint:"Applies on top of each linked client's own Patient text notifications setting and cannot loosen it. A provider can still switch a single message to Full text. Prescription messages, attachments, and visit-charting messages stay secure."})]}),e.jsxs(yt,{value:W.deliveryMode,onValueChange:D=>H(T=>({...T,deliveryMode:sa(D)})),disabled:p,children:[e.jsx(vt,{id:"messaging-policy-delivery-mode",className:"h-8 w-36 shrink-0 text-xs max-lg:h-7 max-lg:w-32","aria-describedby":"messaging-policy-delivery-mode-option","data-testid":"select-messaging-policy-delivery-mode",children:e.jsx(Nt,{})}),e.jsx(jt,{className:"max-h-[min(320px,50vh)]",children:Ps.map(D=>e.jsx(st,{value:D.key,children:D.label},D.key))})]})]}),e.jsx("p",{id:"messaging-policy-delivery-mode-option",className:"mt-1.5 text-2xs leading-snug text-content-tertiary",children:(Ps.find(D=>D.key===W.deliveryMode)||Ps[0]).description})]}),e.jsx(Pl,{idPrefix:"messaging-policy-default",policy:W.defaultClientPolicy,onChange:ge,disabled:p,accentColor:l})]})]}),e.jsxs("section",{"aria-labelledby":"messaging-policy-clients-title",children:[e.jsx(Nr,{title:"Linked-client overrides",hint:"Primary links can customize all messaging controls. Additional links inherit patient destinations from the primary network and cannot be overridden here.",trailing:V?e.jsx("span",{className:"shrink-0 text-2xs text-content-tertiary max-lg:text-3xs",children:V}):null}),e.jsx("span",{id:"messaging-policy-clients-title",className:"sr-only",children:"Linked-client messaging overrides"}),m?e.jsx("div",{className:"mt-3 max-lg:mt-2",children:e.jsx(Al,{})}):C?e.jsx("div",{className:"mt-3 max-lg:mt-2",children:e.jsx(Il,{message:C,onRetry:()=>z(D=>D+1)})}):O.length===0?e.jsx("p",{className:"mt-3 text-xs text-content-tertiary max-lg:mt-2",children:"No linked clients are available for an override."}):e.jsxs(e.Fragment,{children:[O.map(D=>{var de;const T=((de=W.clientPolicies)==null?void 0:de[D.id])||null,$=!!T,S=D.messagingPolicyRelationship==="primary",Q=`messaging-policy-mode-${D.id}`,Y=qh(D);return e.jsxs("article",{className:"border-b border-slate-100 py-2.5 last:border-b-0 max-lg:py-2 dark:border-slate-800","data-testid":`row-messaging-policy-client-${D.id}`,children:[e.jsxs("div",{className:"flex items-center gap-3 max-lg:gap-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-sm font-medium text-content-primary max-lg:text-xs",children:Y}),e.jsx("span",{className:"shrink-0 rounded-full bg-slate-100 px-2 py-0.5 text-3xs font-medium uppercase tracking-wide text-content-secondary max-lg:px-1.5 dark:bg-slate-700",children:S?"Primary":"Additional"}),e.jsx(zs,{label:Y,hint:S?$?"A custom policy replaces the network default for this client.":"This client follows the network default above. Switch to a custom policy to diverge.":"This network is an additional link for this client. Patient access is controlled by the primary network in the Client profile."})]}),e.jsxs(oe,{htmlFor:Q,className:"sr-only",children:["Policy mode for ",Y]}
318),e.jsxs(yt,{value:$?"custom":"inherit",onValueChange:ve=>ye(D.id,ve),disabled:!S||c||!!x||p,children:[e.jsx(vt,{id:Q,"aria-label":`Policy mode for ${Y}`,className:"h-8 w-36 shrink-0 text-xs max-lg:h-7 max-lg:w-32",children:e.jsx(Nt,{})}),e.jsxs(jt,{children:[e.jsx(st,{value:"inherit",children:"Inherit default"}),e.jsx(st,{value:"custom",children:"Custom policy"})]})]})]}),S&&$?e.jsx("div",{className:"mt-1 pl-3 max-lg:pl-2",children:e.jsx(Pl,{idPrefix:`messaging-policy-client-${D.id}`,policy:T,onChange:ve=>Re(D.id,ve),disabled:p,accentColor:l})}):null]},D.id)}),e.jsx(Lu,{hasMore:w,loading:g,disabled:p,error:v,onLoadMore:Ae,label:"Loading linked clientsâ¦"})]}),!c&&!x&&fe?e.jsx("p",{className:"mt-3 text-xs text-red-700 max-lg:mt-2 max-lg:text-2xs max-lg:leading-snug dark:text-red-300",role:"alert",children:"Select at least one direct-message recipient role before saving a policy with direct messaging enabled."}):null]})]})})})}function Wh(){const{branding:t}=Ce(),s=(t==null?void 0:t.accentColor)||je;return e.jsx(Ou,{surface:"page",accentColor:s,canManage:!0,testIdScope:"settings"})}function Gh(){return e.jsxs("div",{className:"space-y-6 max-lg:space-y-3",children:[e.jsx(Hh,{}),e.jsx(Wh,{})]})}function Kh({networkId:t,savedSlug:s="",onSaved:a}){const[i,n]=o.useState(null),[r,l]=o.useState(!1),[c,u]=o.useState(""),m=o.useRef(null),h=i??s,g=h!==s,y=s?sr(ar.MAIN,`/${s}/clients/api`):"",p=s?sr(ar.MAIN,`/login?networkBrand=${encodeURIComponent(s)}`):"";async function d(x){var f;if(x.preventDefault(),!r){if(h.length>80||h&&!/^[a-z0-9-]+$/.test(h)){u("Use up to 80 lowercase letters, numbers, and dashes."),(f=m.current)==null||f.focus();return}l(!0),u("");try{const C=await rs("setProviderNetworkBrandingSlug",{networkId:t,slug:h},{timeoutMs:15e3,timeoutMessage:"Saving took too long. Check your connection and try again."});a(C.data.slug||""),n(null),Pt.success(h?"Branding slug saved":"Branding slug removed")}catch(C){u(C.message||"Unable to save. Try again."),requestAnimationFrame(()=>{var N;return(N=m.current)==null?void 0:N.focus()})}finally{l(!1)}}}return e.jsxs("form",{onSubmit:d,className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Or,{htmlFor:"network-docs-slug",optional:!0,children:"Branding slug"}),e.jsxs(Wl,{children:[e.jsx(Gl,{asChild:!0,children:e.jsx(B,{type:"button",variant:"ghost",size:"icon","aria-label":"Branding slug links and information",children:e.jsx(Ds,{className:"size-4","aria-hidden":"true"})})}),e.jsxs(Kl,{accessibleLabel:"Branding slug links",align:"start",className:"w-80 max-w-[calc(100vw-2rem)] space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your slug applies your network branding to these public pages."}),s?e.jsx("dl",{className:"space-y-3 text-sm",children:[["API docs",y],["Login",p]].map(([x,f])=>e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:x}),e.jsx("dd",{children:e.jsx(B,{asChild:!0,variant:"link",className:"h-auto max-w-full whitespace-normal break-all p-0 text-left",children:e.jsx("a",{href:f,target:"_blank",rel:"noreferrer",children:f})})})]},x))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Save a branding slug to create your links."}),g&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Links update after you save."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing or clearing the slug disables the previous branded links."})]})]})]}),e.jsx(be,{ref:m,id:"network-docs-slug",value:h,onChange:x=>{n(x.target.value.toLowerCase().trim()),u("")},placeholder:"e.g. my-network",autoComplete:"off",spellCheck:!1,disabled:r,error:c,"aria-describedby":"network-docs-slug-help"}),e.jsx("p",{id:"network-docs-slug-help",className:"text-xs text-muted-foreground",children:"Use the info icon to view your branded links."})]}),(g||r)&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{type:"submit",disabled:r,children:[r&&e.jsx($e,{size:"xs"})," Save slug"]}),e.jsx(B,{type:"button",variant:"outline",disabled:r,onClick:()=>{n(null),u("")},children:"Discard"})]})]})}
318const Yh=Fo({manageFunctionName:"manageProviderNetwork",idField:"network_id",tenantKey:"ProviderNetwork"}),Qh=Mo({manageFunctionName:"manageProviderNetwork",idField:"network_id",tenantKey:"ProviderNetwork"}),Jh="mx-auto aspect-square w-full max-w-[11rem] shrink-0 max-lg:max-w-[8rem]",Xh="min-h-0 w-full flex-1";function Zh(){const{providerNetwork:t,userDoc:s}=Se(),{branding:a}=Ce(),i=(t==null?void 0:t.id)||(s==null?void 0:s.providerNetworkId),[n,r]=o.useState(!0),[l,c]=o.useState({brandingSlug:"",name:"",displayName:"",iconUrl:"",logoUrl:"",logoDisplaySize:"medium",accentColor:je,secondaryColor:"",backgroundColor:"",sidebarHeaderBackgroundColor:"",logoWhiteBackground:!1,timezone:"",headerFont:null,supportEmail:"",customDomain:null,emailDomain:null}),[u,m]=o.useState(!1),[h,g]=o.useState(null),[y,p]=o.useState(null),[d,x]=o.useState(null),[f,C]=o.useState(null),[N,v]=o.useState(null),k=(a==null?void 0:a.accentColor)||l.accentColor||je;Rm(l),Oo({formData:l,originalData:h,enabled:!n&&!!h,onSave:(j,L)=>{const b=_o(j,L);if(b!==null)return b!==L&&c(w=>w[j]===b?w:{...w,[j]:b}),A(j,b,{silent:!0})}});function P(j){return{name:"Network name",displayName:"Display name",iconUrl:"Network icon",logoUrl:"Network logo",logoDisplaySize:"Logo size",accentColor:"Primary color",secondaryColor:"Secondary color",backgroundColor:"Background color",sidebarHeaderBackgroundColor:"Side menu header color",logoWhiteBackground:"Logo background setting",timezone:"Timezone",headerFont:"Header font"}[j]||j}o.useEffect(()=>{if(!i){r(!1);return}const j=he(ce,"ProviderNetworks",i),L=qe(j,b=>{if(b.exists()){const w=b.data(),F={brandingSlug:w.brandingSlug||"",name:w.name||"",displayName:w.displayName||w.companyName||"",iconUrl:w.iconUrl||"",logoUrl:w.logoUrl||"",logoDisplaySize:w.logoDisplaySize||"medium",accentColor:w.accentColor||w.primaryColor||je,secondaryColor:w.secondaryColor||"",backgroundColor:w.backgroundColor||"",sidebarHeaderBackgroundColor:w.sidebarHeaderBackgroundColor||"",logoWhiteBackground:w.logoWhiteBackground||!1,timezone:w.timezone||"",headerFont:w.headerFont||null,supportEmail:w.supportEmail||"",customDomain:w.customDomain||null,emailDomain:w.emailDomain||null};c(F),g(F),p(w.iconUrl||null),x(w.logoUrl||null)}r(!1)},b=>{console.error("Error fetching provider network:",b),I.error("Unable to load branding data. Please try again."),r(!1)});return()=>L()},[i]);async function A(j,L,b={}){const{silent:w=!1}=b;if(!i)return!1;try{v(j);const F=he(ce,"ProviderNetworks",i),M={[j]:L,updatedAt:Pe()};return j==="accentColor"&&(M.primaryColor=L),await Fe(F,M),g(W=>({...W,[j]:L})),j==="headerFont"&&so(L||null),w||I.success(`${P(j)} updated`),!0}catch(F){return console.error(`Error updating ${j}:`,F),I.error(`Unable to update ${P(j).toLowerCase()}. Please try again.`),c(M=>({...M,[j]:h[j]})),!1}finally{v(null)}}function E(j){c(L=>({...L,...Uo(L,j)}))}async function z(){u||(await Promise.all(ao.map(j=>Xa(j.value))),m(!0))}async function q(j){const L=j==="__default__"?null:j;(L??null)!==((h==null?void 0:h.headerFont)??null)&&(c(b=>({...b,headerFont:L})),L&&Xa(L),await A("headerFont",L,{silent:!0}))}async function R(j,L){try{C(j);const w=(await Qa({file:L,brandType:"providerNetwork",brandId:i,assetRole:j==="iconUrl"?"icon":"logo"})).logoUrl;if(j==="iconUrl"?p(w):x(w),c(M=>({...M,[j]:w})),await A(j,w)===!1)throw new Error("Unable to save image. Please retry.")}catch(b){throw console.error(`Error uploading ${j}:`,b),I.error(b.message||`Unable to upload ${P(j).toLowerCase()}. Please try again.`),b}finally{C(null)}}async function O(j){j==="iconUrl"?p(null):x(null),c(L=>({...L,[j]:""})),await A(j,"")}return!n&&!i?e.jsx(tt,{id:"network-branding",title:"Branding",description:"Customize your network logo, colors, and fonts.",icon:Ja,accentColor:k,bodyClassName:"p-6 max-lg:p-3",children:e.jsx("div",{className:"text-center py-12 text-content-tertiary max-lg:py-6",children:e.jsx("p",{className:"text-sm max-lg:text-xs",children:"No provider network associated with your account"})})}):e.jsxs("div",{className:"space-y-6 scroll-mt-24 max-lg:space-y-3",children:[e.jsx(tt,{id:"network-branding",title:"Branding",description:"Customize your network logo, colors, and fonts.",icon:Ja,accentColor:k,bodyClassName:"p-5 flex-1 max-lg:p-3",children:n?e.jsxs("div",{className:"space-y-4 max-lg:space-y-2.5",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-6 max-lg:gap-2.5 md:grid-cols-3 md:items-start",children:[e.jsx(ue,{className:"h-52 w-full rounded-xl max-lg:h-40"}),e.jsx(ue,{className:"h-52 w-full rounded-xl max-lg:h-40 md:col-span-2"})]}),e.jsx(ue,{className:"h-10 w-full max-lg:h-9"}),e.jsx(ue,{className:"h-32 w-full rounded-lg max-lg:h-24"})]}):e.jsxs("div",{className:"space-y-6 max-lg:space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-6 max-lg:gap-2.5 md:grid-cols-3 md:items-start",children:[e.jsx("div",{className:"md:col-span-1",children:e.jsx(Os,{label:"Icon",description:"Used for the browser favicon and square brand placements. Upload a square crop.",cropTitle:"Crop
318Network Icon",cropDescription:"Position the image inside a square frame for favicon and other compact brand slots.",previewUrl:y,aspect:1,uploading:f==="iconUrl",accentColor:l.accentColor,onUpload:j=>R("iconUrl",j),onRemove:()=>O("iconUrl"),previewFrameClassName:Jh,previewImageClassName:"h-full w-full",dropzoneClassName:"h-44 max-lg:h-32",changeLabel:"Change Icon",emptyLabel:"Click or drag to upload icon"})}),e.jsx("div",{className:"md:col-span-2",children:e.jsx(Os,{label:"Logo",description:"Used in provider-facing pages and communications. Upload a wide 3:1 crop.",cropTitle:"Crop Network Logo",cropDescription:"Position the image inside a wide 3:1 frame for provider branding and email headers.",previewUrl:d,aspect:3,uploading:f==="logoUrl",accentColor:l.accentColor,onUpload:j=>R("logoUrl",j),onRemove:()=>O("logoUrl"),previewFrameClassName:Xh,previewImageClassName:"h-full w-full",dropzoneClassName:"aspect-[3/1] min-h-0",changeLabel:"Change Logo",emptyLabel:"Click or drag to upload logo",containerClassName:"p-3 max-lg:p-2",showLightBackgroun
318d:l.logoWhiteBackground,secondaryActionLabel:`Size: ${Zl(l.logoDisplaySize)}`,onSecondaryAction:()=>{const j=Xl(l.logoDisplaySize);c(L=>({...L,logoDisplaySize:j})),A("logoDisplaySize",j)},onToggleLightBackground:d||l.logoUrl?()=>{const j=!l.logoWhiteBackground;c(L=>({...L,logoWhiteBackground:j})),A("logoWhiteBackground",j)}:void 0})})]}),e.jsx(Kh,{networkId:i,savedSlug:(h==null?void 0:h.brandingSlug)||"",onSaved:j=>{c(L=>({...L,brandingSlug:j})),g(L=>({...L,brandingSlug:j}))}},i),e.jsx(Po,{value:l.headerFont,savingField:N,onValueChange:q,onOpenChange:j=>{j&&z()}}),e.jsx(Ao,{formData:l,savingField:N,lightenColor:eo,onPrimaryColorChange:E,onSecondaryColorChange:j=>c(L=>({...L,secondaryColor:j})),onBackgroundColorChange:j=>c(L=>({...L,backgroundColor:j})),onSidebarHeaderColorChange:j=>c(L=>({...L,sidebarHeaderBackgroundColor:j}))})]})}),n?e.jsx(en,{id:"network-domain-management",accentColor:k,loading:!0,children:e.jsx(ue,{className:"h-40 w-full rounded-xl max-lg:h-24"})}):e.jsx(en,{id:"network-domain-management",accentColor:k,description:"Point a branded portal subdomain to this network login and send patient email from your own domain.",howItWorks:!0,children:e.jsx(tc,{tenantId:i,customDomain:l.customDomain,emailDomain:l.emailDomain,accentColor:k,customDomainApi:Yh,emailDomainApi:Qh,testIdPrefix:"network-domain"})})]})}const ef=[{value:"0",label:"Disabled"},{value:"15",label:"15 minutes"},{value:"30",label:"30 minutes"},{value:"60",label:"1 hour"},{value:"120",label:"2 hours"},{value:"240",label:"4 hours"}],Rl={client:{collection:"Clients",idField:"clientId",label:"client",testPrefix:"client"},business:{collection:"Businesses",idField:"businessId",label:"business",testPrefix:"business"},providerNetwork:{collection:"ProviderNetworks",idField:"providerNetworkId",label:"provider network",testPrefix:"provider-network"}};function tf(t,{clientData:s,businessData:a,providerNetwork:i}){return t==="client"?s:t==="business"?a:i}function sf({tenantType:t="providerNetwork",tenantId:s=null,tenantData:a=null,showInactivityLogout:i=!1}){var L,b;const{userDoc:n,providerNetwork:r,clientData:l,businessData:c}=Se(),u=Rl[t]||Rl.providerNetwork,m=s||(n==null?void 0:n[u.idField])||null,h=a||tf(t,{clientData:l,businessData:c,providerNetwork:r})||{},g=Ro(t),y=Za(h,"staff"),p=Za(h,"patient"),d=no(h),x=((b=(L=h==null?void 0:h.security)==null?void 0:L.inactivityLogout)==null?void 0:b.timeoutMinutes)||0,f=o.useMemo(()=>({staff:y,patient:p,timeoutMinutes:String(x)}),[y,p,x]),[C,N]=o.useState({staff:f.staff,patient:f.patient}),[v,k]=o.useState(f.timeoutMinutes),[P,A]=o.useState(()=>new Set),E=w=>P.has(w),z=P.has("mfa-staff")||P.has("mfa-patient");o.useEffect(()=>{z||N({staff:f.staff,patient:f.patient})},[f.staff,f.patient,z]),o.useEffect(()=>{k(f.timeoutMinutes)},[f.timeoutMinutes]);async function q(w,F){if(!m)return I.error("Unable to update security settings",{description:`Missing ${u.label} record.`}),!1;A(M=>new Set(M).add(F));try{return await Fe(he(ce,u.collection,m),{...w,updatedAt:Pe()}),I.success("Security settings updated"),!0}catch(M){return I.error("Unable to update security settings",{description:M.message||"Please try again."}),!1}finally{A(M=>{const W=new Set(M);return W.delete(F),W})}}async function R(w,F){const M=C[w]===!0,W={...C,[w]:F};N(W),await q(ro({audience:w,nextValue:F,currentSecurity:Lo(W)}),`mfa-${w}`)||N(ae=>({...ae,[w]:M}))}async function O(w){const F=v;k(w);const M=Number(w);await q({"security.inactivityLogout.timeoutMinutes":Number.isFinite(M)&&M>0?M:0},"timeout")||k(F)}const j=`${u.testPrefix}-inactivity`;return e.jsxs(xt,{className:"overflow-hidden border border-subtle dark:bg-slate-800",children:[e.jsx("div",{className:"border-b border-subtle bg-surface-sunken p-4 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center gap-2 max-lg:min-w-0 max-lg:gap-1.5",children:[e.jsx(Ir,{className:"size-4 text-content-tertiary max-lg:size-3.5","aria-hidden":"true"}),e.jsxs("div",{className:"max-lg:min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Security"}),e.jsxs("p",{className:"text-xs text-content-secondary max-lg:text-3xs max-lg:leading-tight",children:["Controls apply to users logging in under this ",u.label,"."]})]})]})}),e.jsxs("div",{className:"space-y-4 p-4 max-lg:space-y-2.5 max-lg:p-2.5",children:[d&&g.length>1?e.jsx("p",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-bg)] p-3 text-xs leading-relaxed text-[var(--status-info-text)] max-lg:p-2.5 max-lg:text-2xs","data-testid":"text-settings-security-mfa-legacy-note",children:Io}):null,g.map(w=>{const F=`${u.testPrefix}-mfa-${w.audience}`;
318return e.jsxs("div",{className:"flex items-start gap-4 rounded-lg border border-subtle bg-surface-raised p-4 max-lg:gap-2 max-lg:p-2.5",children:[e.jsx(it,{id:F,checked:C[w.audience]===!0,disabled:E(`mfa-${w.audience}`),onCheckedChange:M=>R(w.audience,M),"aria-label":`Toggle ${w.label.toLowerCase()}`,className:"mt-0.5 shrink-0","data-testid":w.testId}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-1 max-lg:space-y-0.5",children:[e.jsx(oe,{htmlFor:F,className:"text-sm font-medium text-content-primary max-lg:text-xs",children:w.label}),e.jsxs("p",{className:"text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:[w.description," Users set up and verify with an email code or an authenticator app."]})]})]},w.audience)}),i?e.jsxs("div",{className:"grid gap-3 rounded-lg border border-subtle bg-surface-raised p-4 max-lg:gap-2 max-lg:p-2.5 sm:grid-cols-[1fr_220px] sm:items-center",children:[e.jsxs("div",{className:"space-y-1 max-lg:space-y-0.5",children:[e.jsx(oe,{htmlFor:j,className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"Timed logout after inactivity"}),e.jsx("p",{className:"text-xs text-content-secondary max-lg:text-2xs max-lg:leading-snug",children:"Activity in any open tab keeps the session active."})]}),e.jsxs(yt,{value:v,onValueChange:O,disabled:E("timeout"),children:[e.jsx(vt,{id:j,className:"max-lg:h-9","aria-label":"Timed logout after inactivity","data-testid":"select-settings-security-inactivity",children:e.jsx(Nt,{})}),e.jsx(jt,{children:ef.map(w=>e.jsx(st,{value:w.value,children:w.label},w.value))})]})]}):null]})]})}const Ll="border-subtle bg-surface-raised shadow-sm transition-[border-color,box-shadow] duration-150 placeholder:text-slate-400 hover:border-slate-300 focus-visible:border-slate-400 focus-visible:ring-2 focus-visible:ring-slate-200/90 focus-visible:ring-offset-0 dark:text-slate-100 dark:placeholder:text-slate-500 dark:hover:border-slate-500 dark:focus-visible:border-slate-500 dark:focus-visible:ring-slate-600/35",Ol="text-xs font-medium text-content-secondary max-lg:text-2xs",af="text-xs leading-relaxed text-content-tertiary max-lg:text-2xs max-lg:leading-snug";function nf({name:t,url:s}){if(!t.trim())return"Endpoint name is required.";if(!s.trim())return"Endpoint URL is required.";let a;try{a=new URL(s.trim())}catch{return"Enter a valid URL."}return a.protocol!=="https:"?"Endpoint URL must use HTTPS.":""}function wc({open:t,onClose:s,endpoint:a=null,onSubmit:i}){const{branding:n}=Ce(),r=(n==null?void 0:n.accentColor)||je,l=!!a,[c,u]=o.useState(""),[m,h]=o.useState(""),[g,y]=o.useState(""),[p,d]=o.useState(!1);o.useEffect(()=>{t&&(u((a==null?void 0:a.name)||""),h((a==null?void 0:a.url)||""),y(""),d(!1),requestAnimationFrame(()=>{var f;(f=document.getElementById("developers-endpoint-name"))==null||f.focus()}))},[t,a]);async function x(f){var N;(N=f==null?void 0:f.preventDefault)==null||N.call(f);const C=nf({name:c,url:m});if(C){y(C);return}y(""),d(!0);try{await i({name:c.trim(),url:m.trim()}),s()}catch(v){y(v.message||"Unable to save endpoint. Please try again.")}finally{d(!1)}}return e.jsx(at,{open:t,onOpenChange:f=>{!f&&!p&&s()},title:l?"Edit endpoint":"Add endpoint",description:l?"Update the destination for this webhook endpoint.":"Receive signed network events at an HTTPS URL you control.",contentClassName:"max-w-lg",contentTestId:"dialog-developers-endpoint",mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",footerClassName:"max-[1024px]:px-3 max-[1024px]:pt-2.5 max-[1024px]:gap-1.5",footer
318:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",className:"min-h-10 rounded-lg max-[1024px]:min-h-8",onClick:s,disabled:p,"data-testid":"button-developers-endpoint-cancel",children:"Cancel"}),e.jsxs(B,{type:"submit",form:"developers-endpoint-form",className:"min-h-10 rounded-lg text-white hover:opacity-95 max-[1024px]:min-h-8",style:{backgroundColor:r},disabled:p||!c.trim()||!m.trim(),"data-testid":"button-developers-endpoint-save",children:[p?e.jsx(Ve,{className:"mr-1.5 size-4 animate-spin max-lg:mr-1 max-lg:size-3.5"}):null,l?"Save changes":"Create endpoint"]})]}),children:e.jsxs("form",{id:"developers-endpoint-form",onSubmit:x,noValidate:!0,children:[e.jsxs("div",{className:"rounded-xl border border-slate-200/90 bg-surface-raised shadow-sm dark:border-slate-700",children:[e.jsxs("div",{className:"space-y-1.5 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:[e.jsx(oe,{htmlFor:"developers-endpoint-name",className:Ol,children:"Name"}),e.jsx(be,{id:"developers-endpoint-name",value:c,onChange:f=>u(f.target.value),placeholder:"e.g. Production CRM",autoComplete:"off",maxLength:120,className:K("h-11 max-lg:h-10",Ll),"data-testid":"input-developers-endpoint-name"})]}),e.jsxs("div",{className:"space-y-1.5 border-t border-slate-200/90 px-5 py-4 max-lg:space-y-1 max-lg:px-3 max-lg:py-2.5 dark:border-slate-700/90 sm:px-6",children:[e.jsx(oe,{htmlFor:"developers-endpoint-url",className:Ol,children:"URL"}),e.jsx(be,{id:"developers-endpoint-url",type:"url",value:m,onChange:f=>h(f.target.value),placeholder:"e.g. https://example.com/webhooks/gen-health",autoComplete:"off",inputMode:"url",className:K("h-11 font-mono text-sm max-lg:h-10",Ll),"data-testid":"input-developers-endpoint-url"}),e.jsx("p",{className:af,children:"Must be HTTPS and publicly reachable."})]})]}),g?e.jsx("p",{className:"mt-3 text-xs text-red-600 max-lg:mt-2 max-lg:text-2xs max-lg:leading-snug dark:text-red-400",role:"alert",children:g}):null]})})}wc.propTypes={open:Ne.bool.isRequired,onClose:Ne.func.isRequired,endpoint:Ne.object,onSubmit:Ne.func.isRequired};function Cc({open:t,onClose:s,secret:a="",endpointName:i="",rotated:n=!1}){const{branding:r}=Ce(),l=(r==null?void 0:r.accentColor)||je,[c,u]=o.useState(!1);o.useEffect(()=>{t&&u(!1)},[t]);async function m(){try{await navigator.clipboard.writeText(a),u(!0),I.success("Signing secret copied to clipboard")}catch{I.error("Unable to copy. Select the secret and copy it manually.")}}return e.jsx(at,{open:t,onOpenChange:h=>{h||s()},preventOutsideDismiss:!0,title:n?"New signing secret":"Signing secret",description:i?`Use this secret to verify webhook signatures from ${i}.`:"Use this secret to verify webhook signatures.",contentClassName:"max-w-lg",contentTestId:"dialog-developers-secret",mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",footerClassName:"max-[1024px]:px-3 max-[1024px]:pt-2.5 max-[1024px]:gap-1.5",footer
318:e.jsx(B,{type:"button",className:"min-h-10 rounded-lg text-white hover:opacity-95 max-[1024px]:min-h-8",style:{backgroundColor:l},onClick:s,"data-testid":"button-developers-secret-done",children:"Done"}),children:e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-200/80 bg-amber-50/90 px-3 py-2.5 text-xs text-amber-800 max-lg:gap-1.5 max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs max-lg:leading-snug dark:border-amber-800/60 dark:bg-amber-950/40 dark:text-amber-300",children:[e.jsx(jo,{className:"mt-0.5 size-3.5 shrink-0 max-lg:size-3","aria-hidden":!0}),e.jsxs("span",{children:["This secret is shown only once and cannot be retrieved later.",n?" The previous secret is already invalid.":""," Store it securely now."]})]}),e.jsx("div",{className:"rounded-xl border border-slate-200/90 bg-surface-raised shadow-sm dark:border-slate-700",children:e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 max-lg:gap-1.5 max-lg:px-2.5 max-lg:py-2",children:[e.jsx("code",{className:"min-w-0 flex-1 select-all break-all font-mono text-sm text-content-primary max-lg:text-2xs max-lg:leading-snug","data-testid":"input-developers-secret-value",children:a}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1.5 px-3 text-xs max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:gap-1 max-[1024px]:px-2 max-[1024px]:text-2xs",onClick:m,"aria-label":"Copy signing secret","data-testid":"button-developers-copy-secret",children:[c?e.jsx(Ze,{className:"size-3.5"}):e.jsx(ms,{className:"size-3.5"}),c?"Copied":"Copy"]})]})})]})})}Cc.propTypes={open:Ne.bool.isRequired,onClose:Ne.func.isRequired,secret:Ne.string,endpointName:Ne.string,rotated:Ne.bool};const ws="providerNetworkWebhookEndpoints",Ml="providerNetworkWebhookSubscriptions",_a="providerNetworkWebhookDeliveries";function Sc(t){if(!t)return null;if(typeof t=="number")return Number.isFinite(t)?t>1e12?t:t*1e3:null;if(typeof t=="string"){const s=Date.parse(t);return Number.isFinite(s)?s:null}if(typeof t=="object"){if(typeof t.toMillis=="function")return t.toMillis();const s=t._seconds??t.seconds;if(Number.isFinite(s)){const a=t._nanoseconds??t.nanoseconds??0;return s*1e3+Math.floor(a/1e6)}}return null}function Zs(t){const s=Sc(t);return s?new Date(s).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"â"}function kr(t){const s=Sc(t);if(!s)return"â";const a=Date.now()-s;if(a<0)return Zs(t);if(a<6e4)return"Just now";const i=Math.floor(a/6e4);if(i<60)return`${i}m ago`;const n=Math.floor(i/60);if(n<24)return`${n}h ago`;const r=Math.floor(n/24);return r<7?`${r}d ago`:new Date(s).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Fl(t){if(!t)return"â";try{const s=new URL(t),a=s.pathname==="/"?"":s.pathname,i=a.length>28?`${a.slice(0,25)}â¦`:a;return`${s.host}${i}`}catch{return String(t)}}function rf(){const[t,s]=o.useState([]),[a,i]=o.useState(5),[n,r]=o.useState(!0),[l,c]=o.useState(""),u=o.useCallback(async({silent:d=!1}={})=>{d||r(!0);try{const x=await Ot(ws,{method:"GET",requireAuth:!0});s(Array.isArray(x.endpoints)?x.endpoints:[]),Number.isFinite(x.maxActiveEndpoints)&&i(x.maxActiveEndpoints),c("")}catch(x){c(x.message||"Unable to load webhook endpoints.")}finally{r(!1)}},[]);o.useEffect(()=>{u()},[u]);const m=o.useCallback(async({name:d,url:x})=>{const f=await Ot(ws,{method:"POST",body:{name:d,url:x},requireAuth:!0});return await u({silent:!0}),f},[u]),h=o.useCallback(async(d,x)=>{const f=await Ot(ws,{method:"PATCH",path:`/${d}`,body:x,requireAuth:!0});return s(C=>C.map(N=>N.endpointId===d?f.endpoint||{...N,...x}:N)),f},[]),g=o.useCallback(async d=>{const x=await Ot(ws,{method:"DELETE",path:`/${d}`,requireAuth:!0});return s(f=>f.filter(C=>C.endpointId!==d)),x},[]),y=o.useCallback(async d=>{const x=await Ot(ws,{method:"POST",path:`/${d}/rotations`,requireAuth:!0});return await u({silent:!0}),x},[u]),p=o.useCallback(async d=>await Ot(ws,{method:"POST",path:`/${d}/tests`,requireAuth:!0}),[]);return{endpoints:t,maxActiveEndpoints:a,loading:n,error:l,refresh:u,createEndpoint:m,updateEndpoint:h,deleteEndpoint:g,rotateSecret:y,sendTest:p}}function lf(){const[t,s]=o.useState([]),[a,i]=o.useState([]),[n,r]=o.useState(!0),[l,c]=o.useState(""),u=o.useCallback(async()=>{r(!0);try{const h=await Ot(Ml,{method:"GET",requireAuth:!0});s(Array.isArray(h.events)?h.events:[]),i(Array.isArray(h.catalog)?h.catalog:[]),c("")}catch(h){c(h.message||"Unable to load event subscriptions.")}finally{r(!1)}},[]);o.useEffect(()=>{u()},[u]);const m=o.useCallback(async h=>{const g=await Ot(Ml,{method:"PUT",body:{events:h},requireAuth:!0});return s(Array.isArray(g.events)?g.events:h),g},[]);return{events:t,catalog:a,loading:n,error:l,refresh:u,saveEvents:m}}function Qn({endpointId:t,status:s,limit:a,cursor:i}){const n=new URLSearchParams;return t&&n.set("endpointId",t),s&&n.set("status",s),n.set("limit",String(a)),i&&n.set("cursor",i),`?${n.toString()}`}function of({endpointId:t="",status:s="",limit:a=50}={}){const[i,n]=o.useState([]),[r,l]=o.useState(""),[c,u]=o.useState(!0),[m,h]=o.use
318State(!1),[g,y]=o.useState(""),p=o.useRef(0),d=o.useCallback(async({silent:N=!1}={})=>{const v=++p.current;N||u(!0);try{const k=await Ot(_a,{method:"GET",path:Qn({endpointId:t,status:s,limit:a}),requireAuth:!0});if(v!==p.current)return;n(Array.isArray(k.deliveries)?k.deliveries:[]),l(k.nextCursor||""),y("")}catch(k){if(v!==p.current)return;y(k.message||"Unable to load deliveries.")}finally{v===p.current&&u(!1)}},[t,s,a]);o.useEffect(()=>{d()},[d]);const x=o.useCallback(async()=>{if(!r||m)return;const N=p.current;h(!0);try{const v=await Ot(_a,{method:"GET",path:Qn({endpointId:t,status:s,limit:a,cursor:r}),requireAuth:!0});if(N!==p.current)return;const k=Array.isArray(v.deliveries)?v.deliveries:[];n(P=>{const A=new Set(P.map(E=>E.deliveryId));return[...P,...k.filter(E=>!A.has(E.deliveryId))]}),l(v.nextCursor||"")}catch(v){if(N!==p.current)return;y(v.message||"Unable to load more deliveries.")}finally{h(!1)}},[t,s,a,r,m]),f=o.useCallback(async N=>{const v=await Ot(_a,{method:"POST",path:`/${N}/replays`,requireAuth:!0});return await d({silent:!0}),v},[d]);return{exportRows:o.useCallback(()=>Mu(N=>Ot(_a,{method:"GET",path:Qn({endpointId:t,status:s,limit:100,cursor:N}),requireAuth:!0}),{rowsKey:"deliveries",idKey:"deliveryId"}),[t,s]),deliveries:i,nextCursor:r,loading:c,loadingMore:m,error:g,refresh:d,loadMore:x,replayDelivery:f}}const Jn="max-lg:px-1.5 max-lg:text-3xs";function cf(t){return t.status==="paused"?t.pausedReason==="auto_failure"?e.jsx(De,{className:K(ds("amber"),Jn),children:"Auto-paused"}):e.jsx(De,{className:K(ds("slate"),Jn),children:"Paused"}):e.jsx(De,{className:K(gn(t.status||"active"),Jn),children:"Active"})}function Ec({endpoints:t,maxActiveEndpoints:s,loading:a,error:i,createEndpoint:n,updateEndpoint:r,deleteEndpoint:l,rotateSecret:c,sendTest:u}){var xe,Ae;const{branding:m}=Ce(),h=(m==null?void 0:m.accentColor)||je,[g,y]=o.useState({open:!1,endpoint:null}),[p,d]=o.useState({open:!1,secret:"",endpointName:"",rotated:!1}),[x,f]=o.useState(null),[C,N]=o.useState(null),[v,k]=o.useState(!1),P=t.filter(se=>se.status==="active").length,A=P>=s,{sortedData:E,sortKey:z,sortDirection:q,handleSort:R}=Ur(t,"name","asc");async function O(se){var fe;if(g.endpoint){await r(g.endpoint.endpointId,se),I.success("Endpoint updated");return}const Z=await n(se);I.success("Endpoint created"),d({open:!0,secret:Z.secret||"",endpointName:((fe=Z.endpoint)==null?void 0:fe.name)||se.name,rotated:!1})}async function j(se){N(se.endpointId);const Z=I.loading(`Sending test to ${se.name}...`);try{const fe=await u(se.endpointId);I.dismiss(Z);const J=Number.isFinite(fe.durationMs)?` · ${fe.durationMs}ms`:"";I.success(`Test delivered (HTTP ${fe.statusCode}${J})`)}catch(fe){I.dismiss(Z);const J=Number.isFinite(fe==null?void 0:fe.statusCode)?` (HTTP ${fe.statusCode})`:"";I.error(`Test failed${J}`,{description:fe.message||"The receiver did not accept the request."})}finally{N(null)}}async function L(se){const Z=se.status==="paused"?"active":"paused";N(se.endpointId);try{await r(se.endpointId,{status:Z}),I.success(Z==="paused"?"Endpoint paused":"Endpoint re-enabled")}catch(fe){I.error(fe.message||"Unable to update endpoint status.")}finally{N(null)}}async function b(){if(!x)return;const{type:se,endpoint:Z}=x;k(!0);try{if(se==="rotate"){const fe=await c(Z.endpointId);f(null),d({open:!0,secret:fe.secret||"",endpointName:Z.name,rotated:!0})}else se==="delete"&&(await l(Z.endpointId),f(null),I.success("Endpoint deleted"))}catch(fe){I.error(fe.message||"Request failed. Please try again.")}finally{k(!1)}}function w(se){const Z=C===se.endpointId;return[{id:"edit",label:"Edit",icon:zt,onSelect:()=>y({open:!0,endpoint:se})},{id:"send-test",label:"Send test",icon:Z?e.jsx($e,{size:"sm"}):Rr,disabled:Z,onSelect:()=>j(se)},{id:"toggle-status",label:se.status==="paused"?"Re-enable":"Pause",icon:se.status==="paused"?uo:Vo,disabled:Z||se.status==="paused"&&A,disabledTooltip:se.status==="paused"&&A?`Limit of ${s} active endpoints reached.`:void 0,onSelect:()=>L(se)},{id:"rotate-secret",label:"Rotate secret",icon:Rs,disabled:Z,onSelect:()=>f({type:"rotate",endpoint:se})},{id:"delete",label:"Delete",icon:bt,danger:!0,disabled:Z,onSelect:()=>f({type:"delete",endpoint:se})}]}const F=e.jsxs(B,{size:"sm",className:"h-8 text-xs text-white hover:opacity-95 max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-3xs",style:{backgroundColor:h},disabled:A||a,onClick:()=>y({open:!0,endpoint:null}),"data-testid":"button-developers-add-endpoint",children:[e.jsx(ot,{className:"mr-1 size-3"}),"Add endpoint"]}),M=A?e.jsx(Wt,{delayDuration:150,children:e.jsxs(is,{children:[e.jsx(ls,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:F})}),e.jsxs(os,{className:"max-w-xs text-xs",children:["Limit of ",s," active endpoints reached. Pause or delete one to add another."]})]})}):F,W={id:"developers-endpoints",title:"Webhook endpoints",icon:Ms,accentColor:h,countLabel:a?"":`${P} of ${s} active · HTTPS URLs only`,actions:M,error:i},H=[{id:"name",csvValue:se=>`${se.name} · ${Fl(se.url)}`,header:"Name",sortKey:"name",minWidth:200,renderCell:se=>e.jsx(_r,{primary:se.name,secondary:Fl(se.url)}),skeletonClassName:"w-36"},{id:"status",csvValue:se=>se.status==="paused"?se.pausedReason==="auto_failure"?"Auto-paused":"Paused":"Active",header:"Status",sortKey:"status",minWidth:110,renderCell:cf,skeletonClassName:"w-20 rounded-full"},{id:"secret",header:"Secret",hideOnMobile:!0,minWidth:130,renderCell:se=>e.jsxs("span",{className:"font-mono text-xs text-content-secondary max-lg:text-3xs",children:["â¢â¢â¢â¢ ",se.secretLast4||"????",e.jsxs("span",{className:"ml-1.5 text-slate-400 max-lg:ml-1 dark:text-slate-500",children:["v",se.secretVersion??1]})]}),skeletonClassName:"w-20"},{id:"health",csvValue:se=>`${se.totalDeliveries||0} sent · ${se.consecutiveFailures||0} failing · Last delivery ${kr(se.lastDeliveryAt)}`,header:"Health",hideOnMobile:!0,minWidth:190,renderCell:se=>{const Z=se.consecutiveFailures||0;return e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("p",{className:"truncate text-xs text-slate-700 max-lg:text-3xs max-lg:leading-tight dark:text-slate-300",children:[se.totalDeliveries||0," sent ·"," ",e.jsxs("span",{className:K(Z>0&&"font-semibold text-red-600 dark:text-red-400"),children:[Z," failing"]})]}),e.jsxs("p",{className:"truncate text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:["Last delivery ",kr(se.lastDeliveryAt)]})]})},skeletonClassName:"w-28"},{id:"actions",header:"Actions",align:"center",minWidth:64,renderCell:se=>e.jsx($o,{actions:w(se),label:`Open actions for ${se.name||"endpoint"}`,testId:`menu-developers-endpoint-${se.endpointId}-actions`}),skeletonClassName:"w-7 rounded-md"}],ae=!a&&t.length===0;return e.jsxs(e.Fragment,{children:[ae?e.jsx(tt,{...W,children:e.jsxs("div",{className:"px-6 py-12 text-center max-lg:px-3 max-lg:py-6","data-testid":"section-developers-endpoints-empty",children:[e.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"No endpoints yet"}),e.jsx("p",{className:"mt-1 text-xs text-content-tertiary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:"Add an HTTPS endpoint to start receiving signed network events."}),e.jsxs(B,{size:"sm",className:"mt-4 h-8 text-xs text-white hover:opacity-95 max-lg:mt-2.5 max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",style:{backgroundColor:h},onClick:()=>y({open:!0,endpoint:null}),"data-testid":"button-developers-add-endpoint-empty",children:[e.jsx(ot,{className:"mr-1 size-3"}),"Add endpoint"]})]})}):e.jsx($s,{...W,columns:H,rows:E,csvExport:{feature:"webhook-endpoints",disabled:a},rowKey:"endpointId",rowTestId:se=>`row-developers-endpoint-${se==null?void 0:se.endpointId}`,contextMenuActions:w,loading:a,skeletonRowCount:3,tableLabel:"Webhook endpoints table",tableTestId:"table-developers-endpoints",sortKey:z,sortDirection:q,onSort:R}),e.jsx(wc,{open:g.open,endpoint:g.endpoint,onClose:()=>y({open:!1,endpoint:null}),onSubmit:O}),e.jsx(Cc,{open:p.open,secret:p.secret,endpointName:p.endpointName,rotated:p.rotated,onClose:()=>d({open:!1,secret:"",endpointName:"",rotated:!1})}),e.jsx(_s,{open:!!x,onOpenChange:se=>{!se&&!v&&f(null)},title:(x==null?void 0:x.type)==="rotate"?"Rotate signing secret?":"Delete endpoint?",description:(x==null?void 0:x.type)==="rotate"?`The current secret for ${((xe=x==null?void 0:x.endpoint)==null?void 0:xe.name)||"this endpoint"} stops working immediately. Deliveries signed with the old secret will fail verification until you install the new one.`:`${((Ae=x==null?void 0:x.endpoint)==null?void 0:Ae.name)||"This endpoint"} stops receiving events immediately. This cannot be undone.`,confirmLabel:(x==null?void 0:x.type)==="rotate"?"Rotate secret":"Delete",onConfirm:b,tone:(x==null?void 0:x.type)==="delete"?"destructive":"default",accentColor:h,busy:v,confirmTestId:"button-developers-endpoint-confirm"})]})}Ec.propTypes={endpoints:Ne.arrayOf(Ne.object).isRequired,maxActiveEndpoints:Ne.number.isRequired,loading:Ne.bool.isRequired,error:Ne.string,createEndpoint:Ne.func.isRequired,updateEndpoint:Ne.func.isRequired,deleteEndpoint:Ne.func.isRequired,rotateSecret:Ne.func.isRequired,sendTest:Ne.func.isRequired};const zl={"visit.created":"A new visit was scheduled or started.","visit.updated":"A visit's details or status changed (includes changed_fields).","visit.completed":"A visit was completed and charted.","visit.cancelled":"A visit was cancelled.","visit.canceled":"A visit was cancelled.","provider.created":"A provider joined the network.","provider.updated":"A provider's profile or status changed.","provider.deactivated":"A provider was deactivated.","client.created":"A client was added to the network.","client.updated":"A client's details or status changed.","prescription.created":"A prescription was created during charting.","prescription.sent":"A prescription was sent to the pharmacy.","prescription.updated":"A prescription's status changed.","prescription.failed":"A prescription submission failed."},df={created:"was created",updated:"was updated",deleted:"was deleted",completed:"was completed",cancelled:"was cancelled",canceled:"was cancelled",failed:"failed",sent:"was sent",paused:"was paused",deactivated:"was deactivated",activated:"was activated"};function mf(t){if(zl[t])return zl[t];const[s="record",a=""]=String(t||"").split("."),i=df[a];return i?`A ${s} ${i}.`:`A ${s} ${a} event occurred.`}function uf(t,s){if(t.size!==s.size)return!1;for(const a of t)if(!s.has(a))return!1;return!0}function xf(){const{branding:t}=Ce(),s=(t==null?void 0:t.accentColor)||je,{events:a,catalog:i,loading:n,error:r,saveEvents:l}=lf(),[c,u]=o.useState(()=>
318new Set),[m,h]=o.useState(!1);o.useEffect(()=>{u(new Set(a))},[a]);const g=o.useMemo(()=>{const N=new Map;return i.forEach(v=>{const k=v.category||"Other";N.has(k)||N.set(k,[]),N.get(k).push(v.event)}),Array.from(N.entries()).map(([v,k])=>({category:v,events:k}))},[i]),y=o.useMemo(()=>new Set(a),[a]),p=!uf(c,y);function d(N,v){u(k=>{const P=new Set(k);return v?P.add(N):P.delete(N),P})}function x(N,v){u(k=>{const P=new Set(k);return N.forEach(A=>{v?P.add(A):P.delete(A)}),P})}async function f(){h(!0);try{await l(Array.from(c)),I.success("Event subscriptions updated")}catch(N){I.error(N.message||"Unable to update event subscriptions.")}finally{h(!1)}}function C(){u(new Set(a))}return e.jsxs(xt,{className:"overflow-hidden rounded-xl border border-subtle dark:bg-slate-800","data-testid":"section-developers-subscriptions",children:[e.jsx("div",{className:"border-b border-subtle bg-surface-sunken p-3 max-lg:p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 max-lg:flex-nowrap max-lg:gap-1.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 max-lg:gap-1.5",children:[e.jsx("div",{className:"shrink-0 rounded-lg p-1.5 max-lg:p-1",style:{backgroundColor:s},children:e.jsx(fo,{className:"size-4 text-white max-lg:size-3.5","aria-hidden":!0})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Event subscriptions"}),e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:"Network-wide: every active endpoint receives the same selected events."})]})]}),p?e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 max-lg:gap-1",children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:m,className:"h-8 px-2.5 text-xs max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs","data-testid":"button-developers-subscriptions-discard",children:"Discard"}),e.jsx(B,{type:"button",size:"sm",onClick:f,disabled:m,className:"h-8 px-2.5 text-xs text-white hover:opacity-95 max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",style:{backgroundColor:s},"data-testid":"button-developers-subscriptions-save",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"mr-1.5 size-3.5 animate-spin max-lg:mr-1 max-lg:size-3"}),"Saving"]}):"Save"})]}):null]})}),e.jsx("div",{className:"space-y-4 p-4 max-lg:space-y-2.5 max-lg:p-2.5",children:n?e.jsxs(e.Fragment,{children:[e.jsx(ue,{className:"h-24 w-full max-lg:h-20"}),e.jsx(ue,{className:"h-24 w-full max-lg:h-20"})]}):r?e.jsx("p",{className:"text-sm text-red-600 max-lg:text-xs dark:text-red-400",children:r}):g.length===0?e.jsx("p",{className:"text-sm text-content-tertiary max-lg:text-xs",children:"No events available yet."}):g.map(N=>{const v=N.events.every(k=>c.has(k));return e.jsxs("div",{className:"overflow-hidden rounded-lg border border-subtle",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle bg-surface-sunken px-3 py-2 max-lg:gap-2 max-lg:px-2 max-lg:py-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-800 max-lg:text-2xs dark:text-slate-100",children:N.category}),e.jsx("button",{type:"button",onClick:()=>x(N.events,!v),className:"text-xs font-medium text-content-tertiary transition-colors hover:text-slate-700 max-lg:shrink-0 max-lg:text-3xs dark:hover:text-slate-200","data-testid":`button-developers-subscriptions-${N.category.toLowerCase()}-select-all`,children:v?"Clear all":"Select all"})]}),e.jsx("div",{className:"divide-y divide-slate-200 bg-surface-raised dark:divide-slate-700",children:N.events.map(k=>e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 px-3 py-2.5 transition-colors hover:bg-slate-50 max-lg:gap-2 max-lg:px-2 max-lg:py-1.5 dark:hover:bg-slate-800/60",children:[e.jsx(Me,{checked:c.has(k),onCheckedChange:P=>d(k,P===!0),"aria-label":`Subscribe to ${k}`,className:"mt-0.5","data-testid":`input-developers-event-${k}`}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-mono text-xs font-medium text-content-primary max-lg:text-2xs max-lg:leading-tight",children:k}),e.jsx("span",{className:"block text-xs text-content-tertiary max-lg:text-3xs max-lg:leading-tight",children:mf(k)})]})]},k))})]},N.category)})})]})}const wr={pending:"Pending",published:"Published",delivered:"Delivered",failed:"Failed",skipped_paused:"Skipped (paused)"},pf=["delivered","failed","pending","published","skipped_paused"],gf=["delivered","failed","
318skipped_paused"];function hf(t){return t==="delivered"?ds("green"):t==="pending"||t==="published"?ds("yellow"):t==="skipped_paused"?ds("slate"):gn(t)}function Cr({status:t}){return e.jsx(De,{className:K(hf(t),"max-lg:px-1.5 max-lg:text-3xs"),children:wr[t]||t||"Unknown"})}Cr.propTypes={status:Ne.string};function _l(t){return Number.isFinite(t)?t>=200&&t<300?"text-emerald-600 dark:text-emerald-400":t>=400?"text-red-600 dark:text-red-400":"text-content-secondary":"text-slate-400 dark:text-slate-500"}function Ul(t){return(t==null?void 0:t.kind)==="event"&&gf.includes(t==null?void 0:t.status)}function Tt({label:t,children:s}){return e.jsxs("div",{className:"flex items-start justify-between gap-4 px-4 py-2.5 max-lg:gap-2 max-lg:px-2.5 max-lg:py-1.5",children:[e.jsx("dt",{className:"shrink-0 text-xs font-medium text-content-tertiary max-lg:text-3xs",children:t}),e.jsx("dd",{className:"min-w-0 text-right text-xs text-content-primary max-lg:text-3xs",children:s})]})}Tt.propTypes={label:Ne.string.isRequired,children:Ne.node};function Tc({endpoints:t}){const{branding:s}=Ce(),a=(s==null?void 0:s.accentColor)||je,[i,n]=o.useState([]),[r,l]=o.useState([]),[c,u]=o.useState(null),[m,h]=o.useState(!1),{deliveries:g,exportRows:y,nextCursor:p,loading:d,loadingMore:x,error:f,refresh:C,loadMore:N,replayDelivery:v}=of({endpointId:i[0]||"",status:r[0]||""}),k=o.useMemo(()=>{const R={};return(t||[]).forEach(O=>{R[O.endpointId]=O.name}),R},[t]),P=i.length>0||r.length>0;async function A(){if(!(!c||!Ul(c)||m)){h(!0);try{await v(c.deliveryId),I.success("Replay queued"),u(null)}catch(R){I.error(R.message||"Unable to replay this delivery.")}finally{h(!1)}}}const E=[{id:"event",csvValue:R=>R.kind==="ping"?"Ping":R.event||"",header:"Event",minWidth:190,renderCell:R=>e.jsx(_r,{primary:R.kind==="ping"?"Ping":R.event||"â",secondary:[R.eventId,R.replayOf?"replay":""].filter(Boolean).join(" · ")}),skeletonClassName:"w-32"},{id:"endpoint",csvValue:R=>k[R.endpointId]||R.endpointId||"",header:"Endpoint",hideOnMobile:!0,minWidth:150,renderCell:R=>e.jsx("span",{className:"block truncate text-xs text-content-secondary max-lg:text-3xs",children:k[R.endpointId]||R.endpointId||"â"}),skeletonClassName:"w-24"},{id:"status",csvValue:R=>wr[R.status]||R.status||"",header:"Status",minWidth:110,renderCell:R=>e.jsx(Cr,{status:R.status}),skeletonClassName:"w-20 rounded-full"},{id:"attempts",csvValue:R=>`${R.attempts??0} of ${R.maxAttempts??"â"}`,header:"Attempts",hideOnMobile:!0,align:"center",minWidth:90,renderCell:R=>e.jsxs("span",{className:"text-xs tabular-nums text-content-secondary max-lg:text-3xs",children:[R.attempts??0," of ",R.maxAttempts??"â"]}),skeletonClassName:"w-12"},{id:"lastAttempt",csvValue:R=>Zs(R.lastAttemptAt||R.createdAt),header:"Last attempt",hideOnMobile:!0,minWidth:120,renderCell:R=>e.jsx("span",{className:"text-xs text-content-secondary max-lg:text-3xs",title:Zs(R.lastAttemptAt||R.createdAt),children:kr(R.lastAttemptAt||R.createdAt)}),skeletonClassName:"w-16"},{id:"httpCode",csvValue:R=>R.lastStatusCode??"",header:"HTTP",hideOnMobile:!0,align:"center",minWidth:72,renderCell:R=>e.jsx("span",{className:K("text-xs font-medium tabular-nums max-lg:text-3xs",_l(R.lastStatusCode)),children:Number.isFinite(R.lastStatusCode)?R.lastStatusCode:"â"}),skeletonClassName:"w-10"}],z=[{id:"endpoint",multiSelect:!1,defaultLabel:"All endpoints",filters:(t||[]).map(R=>({id:R.endpointId,label:R.name||R.endpointId})),activeFilters:i,onFilterChange:n},{id:"status",multiSelect:!1,defaultLabel:"All statuses",filters:pf.map(R=>({id:R,label:wr[R]})),activeFilters:r,onFilterChange:l}],q=Ul(c);return e.jsxs("div",{className:"space-y-3 max-lg:space-y-2","data-testid":"section-developers-deliveries",children:[e.jsx($s,{id:"developers-deliveries",title:"Delivery log",icon:bm,accentColor:a,countLabel:d?"":`${g.length} shown${p?" · more available":""}`,actions:e.jsxs(B,{variant:"outline",size:"sm",className:"h-8 gap-1.5 px-2.5 text-xs max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:gap-1 max-[1024px]:px-2 max-[1024px]:text-3xs dark:border-slate-600 dark:hover:bg-slate-700",onClick:()=>C(),disabled:d,"data-testid":"button-developers-refresh-deliveries",children:[e.jsx(ts,{className:K("size-3",d&&"animate-spin")}),"Refresh"]}),filters:z,hasActiveFilters:P,onClearFilters:()=>{n([]),l([])},error:f,columns:E,rows:g,onEndReached:p&&!d?N:null,loadingMore:x,loadingMoreLabel:"Loading more deliveriesâ¦",csvExport:{feature:"webhook-deliveries",view:{getRows:y}},rowKey:"deliveryId",rowClick:R=>u(R),rowTestId:R=>`row-developers-delivery-${R==null?void 0:R.deliveryId}`,loading:d,skeletonRowCount:5,emptyMessage:P?"No deliveries match the current filters.":"No deliveries yet. Deliveries appear here once events are sent to your endpoints.",tableLabel:"Webhook delivery log table",tableTestId:"table-developers-deliveries"}),e.jsx(at,{open:!!c,onOpenChange:R=>{!R&&!m&&u(null)},title:"Delivery details",description:(c==null?void 0:c.kind)==="ping"?"Ping delivery":(c==null?void 0:c.event)||"",contentClassName:"max-w-xl",contentTestId:"dialog-developers-delivery",mobileStickyFooter:!0,headerClassName:"max-[1024px]:px-3 max-[1024px]:pt-3 max-[1024px]:pb-2",footerClassName:"max-[1024px]:px-3 max-[1024px]:pt-2.5 max-[1024px]:gap-1.5",footer
318:e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",className:"min-h-10 rounded-lg max-[1024px]:min-h-8",onClick:()=>u(null),disabled:m,"data-testid":"button-developers-delivery-close",children:"Close"}),e.jsxs(B,{type:"button",className:"min-h-10 gap-1.5 rounded-lg text-white hover:opacity-95 max-[1024px]:min-h-8 max-[1024px]:gap-1",style:{backgroundColor:a},onClick:A,disabled:!q||m,title:q?void 0:"Only completed event deliveries can be replayed.","data-testid":"button-developers-delivery-replay",children:[m?e.jsx(Ve,{className:"size-4 animate-spin max-lg:size-3.5"}):e.jsx(No,{className:"size-4 max-lg:size-3.5"}),"Replay"]})]}),children:c?e.jsxs("div",{className:"space-y-3 max-lg:space-y-2",children:[e.jsx("div",{className:"rounded-xl border border-slate-200/90 bg-surface-raised shadow-sm dark:border-slate-700",children:e.jsxs("dl",{className:"divide-y divide-slate-200/90 dark:divide-slate-700/90",children:[e.jsx(Tt,{label:"Delivery ID",children:e.jsx("span",{className:"break-all font-mono",children:c.deliveryId||"â"})}),e.jsx(Tt,{label:"Event",children:e.jsx("span",{className:"break-all font-mono",children:c.kind==="ping"?"ping":c.event||"â"})}),e.jsx(Tt,{label:"Event ID",children:e.jsx("span",{className:"break-all font-mono",children:c.eventId||"â"})}),e.jsx(Tt,{label:"Endpoint",children:k[c.endpointId]||c.endpointId||"â"}),e.jsx(Tt,{label:"URL",children:e.jsx("span",{className:"break-all font-mono",children:c.url||"â"})}),e.jsx(Tt,{label:"Status",children:e.jsx(Cr,{status:c.status})}),e.jsx(Tt,{label:"Attempts",children:e.jsxs("span",{className:"tabular-nums",children:[c.attempts??0," of ",c.maxAttempts??"â"]})}),e.jsx(Tt,{label:"Last attempt",children:Zs(c.lastAttemptAt)}),e.jsx(Tt,{label:"Next attempt",children:Zs(c.nextAttemptAt)}),e.jsx(Tt,{label:"HTTP status",children:e.jsx("span",{className:K("font-medium tabular-nums",_l(c.lastStatusCode)),children:Number.isFinite(c.lastStatusCode)?c.lastStatusCode:"â"})}),e.jsx(Tt,{label:"Duration",children:Number.isFinite(c.durationMs)?`${c.durationMs}ms`:"â"}),c.replayOf?e.jsx(Tt,{label:"Replay of",children:e.jsx("span",{className:"break-all font-mono",children:c.replayOf})}):null]})}),c.lastError?e.jsxs("div",{className:"rounded-lg border border-red-200 bg-red-50 px-3 py-2.5 text-xs text-red-700 max-lg:px-2 max-lg:py-1.5 max-lg:text-2xs max-lg:leading-snug dark:border-red-800/60 dark:bg-red-950/30 dark:text-red-300",children:[e.jsx("span",{className:"font-semibold",children:"Error:"})," ",e.jsx("span",{className:"break-words",children:c.lastError})]}):null,q?null:e.jsx("p",{className:"text-xs text-content-tertiary max-lg:text-2xs max-lg:leading-snug",children:"Only completed event deliveries can be replayed."})]}):null})]})}Tc.propTypes={endpoints:Ne.arrayOf(Ne.object)};function ff(){const{userDoc:t,providerNetwork:s}=Se(),a=(t==null?void 0:t.providerNetworkId)||(s==null?void 0:s.id)||"",i=String((s==null?void 0:s.networkType)||"").toLowerCase()==="api",{endpoints:n,maxActiveEndpoints:r,loading:l,error:c,createEndpoint:u,updateEndpoint:m,deleteEndpoint:h,rotateSecret:g,sendTest:y}=rf();return e.jsxs("div",{className:"space-y-6 max-lg:space-y-3","data-testid":"section-developers",children:[e.jsx(Ec,{endpoints:n,maxActiveEndpoints:r,loading:l,error:c,createEndpoint:u,updateEndpoint:m,deleteEndpoint:h,rotateSecret:g,sendTest:y}),e.jsx(xf,{}),e.jsx(Tc,{endpoints:n}),i?e.jsx(mu,{providerNetworkId:a,enabled:!!a}):null]})}const bf=[{key:"soap",title:"SOAP notes",description:"Instructions for automatic and on-demand SOAP notes.",icon:Yl,effort:"soapEffort",fields:[["soapSystemPrompt","General instructions","Set the overall tone, structure, and documentation expectations."],["soapUserPrompt","Generation instructions","Add instructions to each SOAP generation request."],["soapSubjectivePrompt","Subjective","Guide the patient-reported history section."],["soapObjectivePrompt","Objective","Guide the findings and observations section."],["soapAssessmentPrompt","Assessment","Guide the clinical assessment section."],["soapPlanPrompt","Plan","Guide the care plan section."]]},{key:"assistant",title:"Visit assistance",description:"Ask AI â support while reviewing a patient visit.",icon:pa,effort:"chartAssistantEffort",fields:[["chartAssistantSystemPrompt","Assistant instructions","Guide how Ask AI responds using the patient chart."]]}],Pc=["low","medium","high"],Dl=t=>Pc.includes(t)?t:"medium",Xn=t=>t[0].toUpperCase()+t.slice(1);function yf({task:t,config:s,defaults:a,providerNetworkId:i,accentColor:n}){const[r,l]=o.useState(!1),[c,u]=o.useState({}
318),[m,h]=o.useState({}),[g,y]=o.useState(!1),[p,d]=o.useState(!1),[x,f]=o.useState(null),[C,N]=o.useState(""),v=JSON.stringify(c)!==JSON.stringify(m),k=Fu({isDirty:v,onDiscard:()=>l(!1)}),P=t.fields.filter(([O])=>typeof s[O]=="string"&&s[O].trim()).length,A="clinical-ai-"+t.key;function E(){const O={[t.effort]:Dl(s[t.effort]),...Object.fromEntries(t.fields.map(([j])=>[j,typeof s[j]=="string"?s[j]:""]))};h(O),u(O),N(""),f(null),l(!0)}async function z(O){O.preventDefault(),y(!0),N("");try{await Fe(he(ce,"ProviderNetworks",i),{...Object.fromEntries(Object.entries(c).map(([j,L])=>["ai."+j,L.trim()])),updatedAt:Pe()}),h(c),l(!1),Pt.success(t.title+" settings saved")}catch{N("Settings could not be saved. Your changes are still here. Please try again.")}finally{y(!1)}}async function q(){var O;d(!0),N("");try{const j=await rs("testSOAPPrompt",{providerNetworkId:i});f(j.soapNotes||((O=j.data)==null?void 0:O.soapNotes)||{})}catch{N("The sample could not be generated. Please try again.")}finally{d(!1)}}const R=([O,j,L])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(Or,{htmlFor:A+"-"+O,required:!1,children:j}),c[O]&&e.jsx(B,{type:"button",variant:"ghost",size:"sm",disabled:g||p,onClick:()=>u(b=>({...b,[O]:""})),children:"Use default"})]}),e.jsx(Is,{id:A+"-"+O,value:c[O]||"",disabled:g||p,maxLength:O==="chartAssistantSystemPrompt"?12e3:6e3,onChange:b=>u(w=>({...w,[O]:b.target.value})),placeholder:a[O+"Default"]||"Use platform default instructions","aria-describedby":A+"-"+O+"-help",className:"min-h-28"}),e.jsx("p",{id:A+"-"+O+"-help",className:"text-xs text-muted-foreground",children:L}),a[O+"Default"]&&e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer",children:"View platform default"}),e.jsx("p",{className:"mt-2 whitespace-pre-wrap",children:a[O+"Default"]})]})]},O);return e.jsxs(e.Fragment,{children:[e.jsx(Sr,{title:t.title,description:t.description,icon:t.icon,accentColor:n,className:"shadow-none",footer:e.jsxs(B,{variant:"outline",onClick:E,"data-testid":"configure-"+t.key,children:["Configure ",t.key==="soap"?"SOAP notes":"visit assistance"]}),children:e.jsxs("dl",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-muted-foreground",children:"AI effort"}),e.jsx("dd",{className:"font-medium",children:Xn(Dl(s[t.effort]))})]}),e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Instructions"}),e.jsx("dd",{children:P?P+" customized":"Platform defaults"})]})]})}),e.jsx(at,{open:r,onOpenChange:O=>{!g&&!p&&k.onOpenChange(l)(O)},...k.guardProps,size:"lg",title:t.title,description:t.description,contentTestId:A+"-dialog",mobileStickyFooter:!0,footer:e.jsxs(e.Fragment,{children:[t.key==="soap"&&e.jsxs(B,{variant:"outline",onClick:q,disabled:v||g||p,title:v?"Save changes before testing":"Uses saved settings and sample data",children:[p&&e.jsx($e,{label:"Generating sample"}),"Test saved settings"]}),e.jsx(B,{variant:"outline",disabled:g||p,onClick:()=>k.requestClose(()=>l(!1)),children:"Cancel"}),e.jsxs(B,{type:"submit",form:A,disabled:g||p||!v,children:[g&&e.jsx($e,{label:"Saving settings"}),"Save changes"]})]}),children:e.jsxs("form",{id:A,onSubmit:z,className:"space-y-4",children:[e.jsx($t,{children:e.jsxs("fieldset",{className:"space-y-3",disabled:g||p,children:[e.jsx("legend",{className:"text-sm font-medium",children:"AI effort"}),e.jsx("p",{id:A+"-effort-help",className:"text-sm text-muted-foreground",children:"Choose the level for this task. Medium is the default; the platform manages the underlying models."}),e.jsx(Ga,{value:c[t.effort],onValueChange:O=>u(j=>({...j,[t.effort]:O})),"aria-label":"AI effort","aria-describedby":A+"-effort-help",className:"grid grid-cols-3 gap-2",children:Pc.map(O=>e.jsxs("label",{htmlFor:A+"-"+O,className:"flex cursor-pointer items-center gap-2 rounded-lg border border-border p-3 text-sm",children:[e.jsx(Ka,{value:O,"aria-label":Xn(O),id:A+"-"+O,disabled:g||p}),Xn(O)]},O))})]})}),e.jsxs($t,{className:"space-y-5",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Leave an instruction blank to use the platform default. Chart-grounding and safety rules always apply."}),t.fields.slice(0,t.key==="soap"?2:1).map(R),t.key==="soap"&&e.jsxs("details",{className:"border-t border-border pt-4",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:"SOAP section instructions"}),e.jsx("div",{className:"mt-4 space-y-5",children:t.fields.slice(2).map(R)})]})]}),C&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:C}),x&&e.jsxs($t,{className:"space-y-4",children:[e.jsx("h3",{className:"font-medium",children:"Sample SOAP note"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Synthetic patient data · saved settings"}),Object.entries(x).map(([O,j])=>e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium capitalize",children:O}),e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:ym.sanitize(String(j||""))}})]},O))]})]})}),e.jsx(_s,{...k.confirmProps})]})}function vf({providerNetworkId:t,accentColor:s}){const{providerNetwork:a}=Se(),{branding:i}=Ce(),n=t||(a==null?void 0:a.id),[r,l]=o.useState(null),[c,u]=o.useState({}
318),[m,h]=o.useState(""),[g,y]=o.useState(0);return o.useEffect(()=>{if(l(null),h(""),!n)return;const p=()=>h("AI settings could not be loaded. Please try again."),d=qe(he(ce,"ProviderNetworks",n),f=>{var C;return l(((C=f.data())==null?void 0:C.ai)||{})},p),x=qe(he(ce,"System","AI_PROMPTS"),f=>u(f.data()||{}),p);return()=>{d(),x()}},[n,g]),n?m?e.jsxs("div",{role:"alert",className:"space-y-3",children:[e.jsx("p",{children:m}),e.jsx(B,{variant:"outline",onClick:()=>y(p=>p+1),children:"Retry"})]}):r?e.jsx("div",{className:"grid items-start gap-4 md:grid-cols-2",children:bf.map(p=>e.jsx(yf,{task:p,config:r,defaults:c,providerNetworkId:n,accentColor:s||(i==null?void 0:i.accentColor)},n+p.key))}):e.jsx($e,{label:"Loading AI settings"}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a provider network to configure AI."})}const Nf=[{id:"account",title:"Account settings",items:[{slug:"account-billing",aliases:["account","billing"],title:"Account and billing",description:"Plan details, primary billing contact, and account payment method.",icon:ga,renderContent:()=>e.jsx(Cg,{})},{slug:"overview",aliases:["hours"],title:"Network overview",description:"Network totals, business details, clinic address, and operating hours.",icon:xn,renderContent:()=>e.jsx(Mg,{userType:"Provider Network Admin"})},{slug:"operations",aliases:["visit-workflows","catalog-policy"],title:"Operations",description:"Scheduling rules, network policies, visit workflows, charting, and catalog policy.",icon:vo,renderContent:()=>e.jsx(zh,{})},{slug:"messaging",aliases:["message-templates","patient-message-templates","templates"],title:"Messaging",description:"Conversation defaults, linked-client overrides, and reusable patient message templates.",icon:pa,renderContent:()=>e.jsx(Gh,{})},{slug:"branding",title:"Branding",description:"Set the network identity, logos, colors, and branded presentation.",icon:Du,renderContent:()=>e.jsx(Zh,{})},{slug:"security",title:"Security",description:"Configure MFA requirements, inactivity timeouts, and account protection rules.",icon:Lr,renderContent:()=>e.jsx(sf,{tenantType:"providerNetwork",showInactivityLogout:!0})},{slug:"developers",title:"Developers",description:"Send network events to external systems with signed webhooks.",icon:Ms,renderContent:()=>e.jsx(ff,{})},{slug:"ai",title:"Artificial intelligence",description:"Set AI effort and instructions for SOAP notes and visit assistance.",icon:zu,renderContent:()=>e.jsx(vf,{})}]}];function jf({embedded:t=!1,embeddedPath:s=null,onEmbeddedNavigate:a=null}){return e.jsx(To,{groups:Nf,embedded:t,embeddedPath:s,onEmbeddedNavigate:a})}function wy({showHeader:t=!0,embedded:s=!1,embeddedPath:a=null,onEmbeddedNavigate:i=null}){const n=$l(),{userType:r,loading:l}=Se(),c=vm();o.useEffect(()=>{if(s||n.hash!=="#network-branding")return;const y=window.setTimeout(()=>{var p;(p=document.getElementById("network-branding"))==null||p.scrollIntoView({behavior:"smooth",block:"start"})},150);return()=>window.clearTimeout(y)},[s,n.pathname,n.hash]);
318const u=s?a||"/settings":n.pathname,m=Am(u);if(l)return e.jsx(Nm,{title:m?"Settings":"",description:m?"Manage networks, clients, and users.":"",message:"Loading settingsâ¦"});const h=t&&m,g=()=>{switch(r){case"Provider Network Admin":return e.jsx(jf,{embedded:s,embeddedPath:a,onEmbeddedNavigate:i});case"Client Admin":return e.jsx(kg,{embedded:s,embeddedPath:a,onEmbeddedNavigate:i});case"Client Staff":return e.jsx(wg,{embedded:s,embeddedPath:a,onEmbeddedNavigate:i});case"Business Staff":case"Business Location Admin":case"Provider":case"Business Provider":case"Provider Delegate":case"Business Provider Delegate":case"Patient":case"Standard User":default:return e.jsx("div",{className:"rounded-xl border border-subtle bg-surface-raised p-6 text-sm text-content-secondary",children:"Settings are not available for this account."})}};return e.jsxs("div",{className:"app-page-shell space-y-4 sm:space-y-6",children:[h?e.jsx(Go,{title:"Settings",description:r==="Client Admin"?"Manage your account, billing, patient experience, and integrations.":r==="Client Staff"?"Manage your personal notification preferences.":"Manage networks, clients, and users."}):null,g(),e.jsx(at,{accessibleTitle:"Settings",open:c.open,onOpenChange:c.onOpenChange,contentClassName:"max-w-4xl",...c.dialogProps,children:c.content})]})}export{wy 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.