PageSourceSearch

https://care.soberpedia.ai/assets/ProductsClientView-BEf4Ev-A.js

js soberpedia.ai collected 2026-10-05 15:10:51 UTC 154,991 bytes, 2 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ProductDetailsDialog-qRBsFrxt.js","assets/react-vendor-CU6Sz31W.js","assets/index-DEXJEDAi.js","assets/firebase-w6DYUbFN.js","assets/payment-icons-Daq1K3F1.js","assets/index-ClGd-I0y.css","assets/ClientFormularyMedicationsTable-DGS5GEg6.js","assets/searchMatchPosition-D039Jv6R.js","assets/catalogCategoryVisibility-PKrVnYt-.js","assets/ProductInlineEditPopovers-B7oRL8nE.js","assets/CatalogSelectionList-D9FsL1Nv.js","assets/formularyVariants-BV7CaEYS.js","assets/formularyRules-DurNzATt.js","assets/formularyMappings-C8mJfsp2.js","assets/providerOperations-ELdKx_YD.js","assets/networkLicensurePolicy-Ct3PZM4V.js","assets/DataTableCard-BluwWKn_.js","assets/index-BSuGcRaZ.js","assets/table-CxPdvV_9.js","assets/arrow-up-D6DFVL4j.js","assets/arrow-down-BjUlbB4f.js","assets/pill-filter-CtZSNPVl.js","assets/date-picker-filter-Qp1kqu9t.js","assets/calendar-RV2oTCrW.js","assets/addWeeks-1hrFjz19.js","assets/clear-filters-button-DmPemFGr.js","assets/ExportCsvAction-BJr9eiP6.js","assets/modal-option-cards-Dksohkou.js","assets/ellipsis-tooltip-CfKm8VFV.js","assets/text-highlight-BFqqfcjs.js","assets/useTableSort-KpNOL2n3.js","assets/useFormularyTypesenseSearch-b2YherGX.js","assets/collectExportPages-B1mgoF_8.js","assets/editor-D8UbQKN1.js","assets/use-unsaved-changes-B6nL5Xdd.js","assets/useFormularySendTiming-PW-jkqj4.js","assets/formularySendSchedules-hEX-RQcj.js","assets/formularySearchSeed-DFztyQr8.js","assets/pencil-CpqYHolO.js","assets/useProviderNetworkFormularyCustomNames-DLzu7zBJ.js","assets/labRecencyWindow-BLArGdSC.js","assets/productSupplyUnit-CNM1yKaW.js","assets/FormularyMappingManager-Cp-K-vjw.js","assets/patient-name-link-BAfQKbEs.js","assets/productRefillReminder-B85vMVb4.js","assets/CatalogItemFormsTab-DGZAm4cd.js","assets/CatalogItemAdminFormPreviewModal-BQ14I7dT.js","assets/IntakeVersionEditorDialog-AuX4y5Es.js","assets/FormBuilder-yfdeRhed.js","assets/date-of-birth-picker-BQ2yrZNI.js","assets/quill-editor-D-DS6c39.js","assets/audio-lines-GJL3_Ka2.js","assets/square-D7DkS8S2.js","assets/link-2-a8lhpkQ6.js","assets/code-BEcI87AG.js","assets/strikethrough-CiKozLGy.js","assets/underline-B_XtWKJP.js","assets/list-ordered-GNrnoOhB.js","assets/quill-editor-DPlll35e.css","assets/useEditorTranscription-CN2PcNng.js","assets/AssistantMarkdownContent-OjQ8GujO.js","assets/useOfflineFormDraftSync-D_7gScL0.js","assets/offlineFormDrafts-CAcyqTIL.js","assets/FormPreviewDialog-DrDrSHEH.js","assets/square-check-big-BIK4lrHD.js","assets/PatientFieldDefinitionDialog-BZBSN9SQ.js","assets/usePatientFieldDefinitions-DS6fhdRU.js","assets/patientFieldDefinitionCaches-PDqtgCkY.js","assets/modal-form-CqN5DZuv.js","assets/redo-2-DoWP9VFC.js","assets/sliders-horizontal-Bt65nPrH.js","assets/arrow-right-left-B4vnGqzD.js","assets/core.esm-DPjjHB-Z.js","assets/sortable.esm-Cj9Co3ow.js","assets/type-CJ1z0FOW.js","assets/circle-dot-B6AVn653.js","assets/user-round-c4EWOTq5.js","assets/keyboard-DLwPN9xF.js","assets/git-branch-BaXsltg0.js","assets/ban-DZ1NMSKK.js","assets/ellipsis-C0FvDuxB.js","assets/hash-C7GcXMrW.js","assets/intakeVersionsApi-DctKdHHP.js","assets/ellipsis-vertical-C-dQ6Kzj.js","assets/power-D6NB1cYy.js","assets/labDisplayUtils-D6xhR45u.js","assets/lab-markers-popover-Dp7gAQYc.js","assets/CatalogStateExclusionsPanel-eJPBk-Pg.js","assets/collapsible-JRJGT2Lx.js","assets/catalogStateExclusions-C6BtORvT.js","assets/clinicalRulesWindows-XIF-DYAK.js","assets/ClinicalRuleCards-DDP8Y6Vb.js","assets/labBiomarkerApi-Ck21Kuon.js","assets/LabAdjudicationUnavailableNotice-Caxh_Djm.js","assets/CheckoutShell-DPiImp5d.js","assets/checkoutDisplay-6C7UrTTD.js","assets/checkoutShellChrome-B_HUtum-.js","assets/EditorialCheckoutAccordion-BKtWmc-J.js","assets/PublicCheckoutContactStep-CBDZu5yA.js","assets/CheckoutPreviewViewport-D2aw1liL.js","assets/productCheckoutSummary-CjlX7xkp.js","assets/package-check-BNvVCLtI.js","assets/monitor-CzX6E2vl.js","assets/ProductSubscriptionRuleSection-SchGISa4.js","assets/productSubscriptionRule-Btb3VTHz.js","assets/SubscriptionsManager-BDbX__WY.js","assets/cells-Db2ZEFlu.js","assets/clientViewHelpers-DdlucuaE.js","assets/useLocalStorageState-BlY8ICA4.js","assets/rawTableExport-DjSsUxyR.js","assets/ClientProductCouponsManager-B7-aMQgR.js","assets/usePatientTerminology-D5bkkKg2.js","assets/useOpenPatientProfile-CASNKG5E.js","assets/LabEnablementBlockedDialog-DsmO0bev.js","assets/useFormularyVisibility-DLbkVZJM.js","assets/pharmacyCoverage-Di9Ay0IK.js","assets/labsData-CkdRlz2Q.js","assets/manageLabApi-BUlVz8vT.js","assets/ProductStorefrontCard-Bfcwwd2M.js","assets/labIntegrationDefinitions-DsxE_lJg.js","assets/providerAssignments-C7MWOvAk.js","assets/integrationScopeAccess-DxVEy3Qu.js","assets/file-spreadsheet-B-mAJD3-.js","assets/LabForm-sUCZJmQL.js","assets/AssociatedProductsField-9aZuux92.js","assets/clock-3-31WD3-4z.js","assets/arrow-right-BC3JVmLt.js","assets/SendProductToPatientModal-B_zcqAFo.js","assets/patientInviteApi-BQHHKSjN.js","assets/catalogVisitMode-De-HDuz9.js","assets/useProductSubscriptionOffer-DL7oz6fV.js","assets/subscriptionOffer--xmeipjh.js","assets/beaker-DG-PilI_.js","assets/ClientCategoriesManagerDialog-D_NihaRA.js","assets/scopedCategoryFirestore-C15ZJbmw.js","assets/CategoryFormDialog-bVZylz8q.js","assets/RequirementControls-Wb_UaVb6.js","assets/labBiomarkerRequirementModel-Bqa1eFIF.js","assets/archive-restore-1_z2aByp.js","assets/ClientProductSmartUploadDialog-BhYps6im.js","assets/UnsavedGuard-CHqsTdlf.js","assets/ProductsPageProductMedicationsSheet-Dl84wnBq.js","assets/useClientFormularyPairingPrices-BjCy1Qoq.js","assets/ProductsPageBulkMedicationsSheet-DfvJ-GdB.js"])))=>i.map(i=>d[i]);
2import{au as we,g as Mr,i as L,a3 as Oc,S as V,ax as Na,dd as xs,qQ as Bc,j as fe,c6 as Rl,cr as Ml,I as Ee,a0 as Sa,E as zn,aQ as Ol,e as at,fG as Pa,g9 as Or,aw as Dc,u as qc,al as Uc,eo as _c,aD as $c,b as zc,hj as br,be as xr,as as O,rz as Vc,rA as Kc,pc as Wc,t as p,jb as Vn,rB as Qc,aT as Hc,f_ as Gc,g0 as Yc,cQ as vr,az as De,fF as Jc,nK as kr,de as Kn,bN as ba,bO as xa,bP as va,aL as Wn,bQ as ka,ce as wr,fJ as Qn,fL as Hn,d as Zc,cf as Gn,fT as Xc,fU as ed,bX as us,gN as td,ae as Me,af as Oe,ag as Be,bR as Yn,aA as ad,c7 as sd,c8 as rd,c9 as id,ca as nd,cb as Pr,gB as ld,lT as od,cd,eq as dd,cN as dt,c_ as Jn,c$ as Zn,d0 as ud,d2 as md,nm as Xn,nn as el,no as tl,np as al,nq as sl,nr as rl,ns as il,nt as nl,nL as ll,nN as ol,nM as cl,ad as pd,rC as ms,c5 as It,ma as dl,rD as ul,fV as gd,aY as fd,nO as ps,a_ as ml,aZ as pl,rE as hd}from"./index-DEXJEDAi.js";import{r as l,j as a}from"./react-vendor-CU6Sz31W.js";import{c as yd}from"./searchMatchPosition-D039Jv6R.js";import{L as bd,S as xd}from"./SubscriptionsManager-BDbX__WY.js";import{S as gs,f as gl,T as Br,a as vd,n as Pt,I as pa,d as ga,b as kd,e as fl,g as Dr,h as wd,j as hl}from"./clientViewHelpers-DdlucuaE.js";import{T as Sr}from"./text-highlight-BFqqfcjs.js";import{P as Pd,a as Sd,c as Nd,b as Cd}from"./ProductInlineEditPopovers-B7oRL8nE.js";import{u as Id}from"./useTableSort-KpNOL2n3.js";import{u as je}from"./useLocalStorageState-BlY8ICA4.js";import{s as jd}from"./rawTableExport-DjSsUxyR.js";import{p as Ld,t as Ed,a as yl}from"./productRefillReminder-B85vMVb4.js";import{B as Td}from"./formularyRules-DurNzATt.js";import{n as Fd,D as Ad}from"./productCheckoutSummary-CjlX7xkp.js";import{r as Rd}from"./productSupplyUnit-CNM1yKaW.js";import{d as me,m as fs,s as Re,g as St,e as fa,t as Md,c as Od,j as Bd,i as bl}from"./firebase-w6DYUbFN.js";import{b as Dd,C as qd}from"./ClientProductCouponsManager-B7-aMQgR.js";import{b as Ud,n as _d}from"./productSubscriptionRule-Btb3VTHz.js";import{H as Vt}from"./ExportCsvAction-BJr9eiP6.js";import{L as $d}from"./LabEnablementBlockedDialog-DsmO0bev.js";import{b as zd,a as Vd}from"./DataTableCard-BluwWKn_.js";import"./patient-name-link-BAfQKbEs.js";import{I as Kd,D as Wd}from"./cells-Db2ZEFlu.js";import{i as tt,u as Qd,a as Nr,B as Hd,D as Gd,l as Yd,E as Jd,F as Ct,G as Zd,H as Xd,I as eu,J as xl,K as Cr,L as tu,M as au,N as su,r as Ir,O as vl}from"./formularyMappings-C8mJfsp2.js";import{J as ru,K as iu,g as kl,b as wl}from"./formularyVariants-BV7CaEYS.js";import{u as nu}from"./useFormularyVisibility-DLbkVZJM.js";import{b as lu,g as ou,a as cu,h as du,c as uu}from"./pharmacyCoverage-Di9Ay0IK.js";import{b as Pl}from"./labsData-CkdRlz2Q.js";import{P as Sl,a as mu}from"./ProductStorefrontCard-Bfcwwd2M.js";import{a as Nl,n as pu}from"./catalogStateExclusions-C6BtORvT.js";import{M as gu}from"./modal-option-cards-Dksohkou.js";import{M as fu,o as hu}from"./modal-form-CqN5DZuv.js";import{s as yu,i as bu}from"./labIntegrationDefinitions-DsxE_lJg.js";import{listLabQualificationReviews as xu}from"./labBiomarkerApi-Ck21Kuon.js";import{L as vu,a as hs,b as Cl,q as jr}from"./LabAdjudicationUnavailableNotice-Caxh_Djm.js";import{S as ku}from"./sliders-horizontal-Bt65nPrH.js";import{F as wu}from"./file-spreadsheet-B-mAJD3-.js";function Bl(c,g){return!c||!g||c.clientId!==g||c.itemType==="package"||c.itemType==="subscription"||c.storageModel==="available_integration"?!1:!!String(c.catalogEntryId||c.id||"").trim()}const Pu=new Set(["id","catalogEntryId","clientProductId","couponEligibleClientProductId","legacyClientProductId","duplicateIndex","isDuplicate","sourceClientProductId","duplicatedFrom","duplicatedFromProductId","createdAt","createdBy","updatedAt","updatedBy","preservedFormProductIds","protocolReplacementId","subscriptionId","subscription"]);function Lr(c={}){return Object.fromEntries(Object.entries(c).filter(([g])=>!Pu.has(g)))}async function Dl(c,g={}){const S=we.currentUser;if(!S)throw new Error("Not authenticated");const w=await S.getIdToken(),x=await fetch(Mr("manageProduct"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`},body:JSON.stringify({action:c,...g})}),v=await x.json().catch(()=>null);if(!x.ok||!(v!=null&&v.success))throw new Error((v==null?void 0:v.error)||"Unable to update the product source.");return v}function ql(c){return Dl("listClientProductSourceOptions",{clientId:c})}function Su(c){return Dl("reassignClientProductSource",c)}function ut(c){return(c==null?void 0:c.displayTitle)||(c==null?void 0:c.displayName)||(c==null?void 0:c.name)||"Untitled product"}function Er(c){return(c==null?void 0:c.displayDescription)||(c==null?void 0:c.description)||""}function ys(c={}){return String(c.id||c.catalogEntryId||c.clientProductId||c.productId||"").trim()}function Il(c={}){const g=String(c.type||c.itemType||"product").trim().toLowerCase();return{lab:"Lab",visit:"Visit",product:"Product",protocol:"Product"}[g]||`${g.charAt(0).toUpperCase()}${g.slice(1)}`}function Nu(c){return!(c!=null&&c.providerNetworkId)||(c==null?void 0:c.itemType)==="package"||(c==null?void 0:c.itemType)==="subscription"?!1:!["lab","visit"].includes(String((c==null?void 0:c.type)||"").toLowerCase())}function Cu({open:c,onOpenChange:g,packageProducts:S,clientId:w,accentColor:x,onCreatePackage:v,onCreateProduct:R,initialStep:b="type"}){const[y,F]=l.useState(b),[W,te]=l.useState(""),[Z,pe]=l.useState([]),[B,k]=l.useState(!1),[$,G]=l.useState([]),[He,q]=l.useState(!1),[qe,Ge]=l.useState(""),[Ue,E]=l.useState(0);l.useEffect(()=>{if(!c||y!=="protocol"||!w)return;let P=!1;return q(!0),Ge(""),G([]),ql(w).then(U=>{P||G((U.options||[]).map(_=>({..._,id:_.sourceProductId,productId:_.sourceProductId})))}).catch(U=>{P||Ge(U.message||"Unable to load protocols. Try again.")}).finally(()=>{P||q(!1)}),()=>{P=!0}},[w,Ue,c,y]),l.useEffect(()=>{c&&(F(b),te(""),pe([]),k(!1))},[b,c]);const he=l.useMemo(()=>$.filter(Nu).sort((P,U)=>ut(P).localeCompare(ut(U))),[$]),I=l.useMemo(()=>(Array.isArray(S)?S:[]).filter(P=>Bl(P,w)).sort((P,U)=>ut(P).localeCompare(ut(U))),[S,w]),N=l.useMemo(()=>{const P=y==="package-products"?I:he,U=W.trim().toLowerCase();return U?P.filter(_=>`${_.id||""} ${_.productId||""} ${_.catalogEntryId||""} ${_.sourceProductId||""} ${_.clientId||""} ${_.businessId||""} ${_.providerNetworkId||""} ${ut(_)} ${Er(_)} ${Il(_)}`.toLowerCase().includes(U)):P},[he,W,I,y]),D=I.filter(P=>Z.includes(ys(P))),le=[...new Set(D.map(P=>
2String(P.providerNetworkId||"").trim()).filter(Boolean))];async function st(P){if(!B){k(!0);try{await(R==null?void 0:R({sourceProduct:P,creationMode:"clinical",configuration:{}})),g(!1)}catch(U){Or.error(U)}finally{k(!1)}}}function jt(P){const U=ys(P),_=String(P.providerNetworkId||"").trim(),Pe=Z.includes(U);!Pe&&_&&le.some(ye=>ye!==_)||pe(ye=>Pe?ye.filter(Lt=>Lt!==U):[...ye,U])}async function Ca(){if(!(B||D.length<2||le.length>1)){k(!0);try{await(v==null?void 0:v({selectedProducts:D})),g(!1)}catch(P){Or.error(P)}finally{k(!1)}}}const pt=y==="type"?"What would you like to create?":y==="protocol"?"Choose a clinical protocol":"Choose products for the package",ks=y==="type"?"Create a clinical product or bundle products into a package.":y==="protocol"?"Selecting a protocol creates an inactive product and opens its editor.":"Select at least two products. Labs and visits can be included alongside products.",gt=y==="type"?null:a.jsxs("div",{className:"flex w-full items-center gap-2 max-lg:gap-1.5",children:[a.jsxs(L,{type:"button",variant:"outline",className:"h-9 rounded-full px-4 max-lg:h-8 max-lg:px-3",disabled:B,onClick:()=>{if(b!=="type"){g(!1);return}F("type"),te("")},children:[a.jsx(Oc,{className:"mr-2 size-4"}),"Back"]}),y==="package-products"?a.jsxs(L,{type:"button",className:"ml-auto h-9 rounded-full px-4 text-white max-lg:h-8 max-lg:px-3",style:{backgroundColor:x},disabled:B||D.length<2||le.length>1,onClick:Ca,children:[B?a.jsx(V,{size:"md",className:"mr-2"}):null,"Create package"]}):null]});return a.jsxs(Na,{open:c,onOpenChange:P=>{B||g(P)},title:pt,description:ks,size:"2xl",contentTestId:fe("dialog","products","create-wizard"),mobileFullHeight:!0,mobileStickyHeader:!0,mobileStickyFooter:!0,footer:gt,children:[y==="type"?a.jsx(gu,{columns:2,accentColor:x,options:[{id:"product",icon:xs,title:"Product",description:"Create a product from an approved provider-network clinical protocol.",testId:fe("button","products","create-product"),onSelect:()=>F("protocol")},{id:"package",icon:Bc,title:"Package",description:"Choose products, labs, and visits to bundle under one price.",testId:fe("button","products","create-package"),onSelect:()=>F("package-products")}]}):null,y!=="type"?a.jsxs(Rl,{className:"overflow-hidden bg-surface-raised p-0",children:[a.jsx("div",{className:"border-b border-subtle px-4 py-3 max-lg:px-2.5 max-lg:py-2",children:a.jsxs("div",{className:"relative",children:[a.jsx(Ml,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-slate-400"}),a.jsx(Ee,{value:W,onChange:P=>te(P.target.value),placeholder:y==="protocol"?"Search clinical protocols":"Search products, labs, and visits",className:"pl-9","aria-label":y==="protocol"?"Search clinical protocols":"Search package products"})]})}),y==="protocol"?a.jsx("div",{className:"divide-y divide-border",children:He?a.jsxs("div",{className:"space-y-3 p-5","aria-label":"Loading protocols",children:[a.jsx(Sa,{className:"h-12 w-full"}),a.jsx(Sa,{className:"h-12 w-full"})]}):qe?a.jsx(zn,{reason:"error",title:"Unable to load protocols",description:qe,action:{label:"Try again",onClick:()=>E(P=>P+1)}}):N.length===0?a.jsx(zn,{reason:W?"filtered":"empty",title:W?"No matching protocols":"No available protocols",description:W?"Try another search.":"Your linked provider networks have no active clinical protocols.",action:W?{label:"Clear search",onClick:()=>te("")}:null}):N.map(P=>a.jsxs("button",{type:"button",disabled:B,className:"flex w-full items-start justify-between gap-4 px-5 py-4 text-left hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-60 max-lg:gap-2 max-lg:px-3 max-lg:py-2.5 sm:px-6",onClick:()=>st(P),children:[a.jsxs("span",{className:"min-w-0",children:[a.jsx("span",{className:"block break-words text-sm font-medium text-content-primary max-lg:text-xs",children:ut(P)}),a.jsx("span",{className:"block text-xs text-muted-foreground",children:P.providerNetworkName}),Er(P)?a.jsx("span",{className:"mt-1 block text-xs text-content-tertiary max-lg:mt-0.5 max-lg:text-2xs max-lg:leading-snug",children:Er(P)}):null]}),a.jsx("span",{className:"shrink-0 text-xs text-content-tertiary max-lg:text-3xs",children:P.reviewNetworkLabel&&P.reviewNetworkLabel!==P.providerNetworkId?P.reviewNetworkLabel:"Provider network"})]},`${P.providerNetworkId}::${ys(P)}`))}):a.jsxs("div",{className:"max-h-[55dvh] overflow-auto",children:[a.jsxs("table",{className:"w-full min-w-[34rem] text-left text-sm","data-testid":fe("table","products","package-selection"),children:[a.jsx("thead",{className:"sticky top-0 bg-surface-sunken text-xs font-medium text-content-tertiary",children:a.jsxs("tr",{children:[a.jsx("th",{className:"w-14 px-4 py-2",children:a.jsx("span",{className:"sr-only",children:"Selected"})}),a.jsx("th",{className:"px-3 py-2",children:"Product"}),a.jsx("th",{className:"w-28 px-3 py-2",children:"Type"}),a.jsx("th",{className:"w-28 px-4 py-2 text-right",children:"Price"})]})}),a.jsx("tbody",{className:"divide-y divide-slate-200 dark:divide-slate-700",children:N.map(P=>{const U=ys(P),_=Z.includes(U),Pe=String(P.providerNetworkId||"").trim(),ye=!_&&Pe&&le.some(Lt=>Lt!==Pe);return a.jsxs("tr",{className:at(_&&"bg-blue-50/70 dark:bg-blue-950/30",ye&&"opacity-50"),children:[a.jsx("td",{className:"px-4 py-3",children:a.jsx("button",{type:"button",disabled:ye,"aria-pressed":_,"aria-label":`${_?"Remove":"Include"} ${ut(P)}`,onClick:()=>jt(P),className:at("flex size-7 items-center justify-center rounded-md border max-lg:size-6",_?"border-blue-600 bg-blue-600 text-white":"border-default bg-surface-raised text-transparent"),children:a.jsx(Ol,{className:"size-3.5"})})}),a.jsxs("td",{className:"px-3 py-3",children:[a.jsx("div",{className:"font-medium text-content-primary max-lg:text-2xs",children:ut(P)}),ye?a.jsx("div",{className:"mt-0.5 text-xs text-amber-700 max-lg:text-3xs dark:text-amber-300",children:"Choose products from one provider network."}):null]}),a.jsx("td",{className:"px-3 py-3 text-content-secondary",children:Il(P)}),a.jsx("td",{className:"px-4 py-3 text-right font-medium text-content-primary",children:Pa(P.customerPrice)||"—"})]},U)})})]}),N.length===0?a.jsx("p",{className:"px-5 py-8 text-center text-sm text-content-tertiary max-lg:px-3 max-lg:py-5 max-lg:text-xs",children:"No products match this search."}):null]})]}):null]})}function Iu({open:c,onOpenChange:g,clientId:S,product:w,accentColor:x,onChanged:v}){const[R,b]=l.useState([]),[y,F]=l.useState(""),[W,te]=l.useState(""),[Z,pe]=l.useState(!1),[B,k]=l.useState(!1),[$,G]=l.useState(""),[He,q]=l.useState(0),qe=(w==null?void 0:w.sourceProductId)||
2(w==null?void 0:w.productId)||"",Ue=`${(w==null?void 0:w.providerNetworkId)||""}::${qe}`;l.useEffect(()=>{if(!c||!S)return;let N=!1;return pe(!0),G(""),F(""),te(""),ql(S).then(D=>{N||b(Array.isArray(D.options)?D.options:[])}).catch(D=>{N||G(D.message||"Unable to load provider network products.")}).finally(()=>{N||pe(!1)}),()=>{N=!0}},[S,He,c]);const E=l.useMemo(()=>{const N=y.trim().toLowerCase();return N?R.filter(D=>[D.id,D.sourceProductId,D.productId,D.clientProductId,D.catalogEntryId,D.providerNetworkId,D.clientId,D.businessId,D.name,D.description,D.providerNetworkName].some(le=>String(le||"").toLowerCase().includes(N))):R},[R,y]),he=R.find(N=>`${N.providerNetworkId}::${N.sourceProductId}`===W);async function I(){if(!(!he||!(w!=null&&w.catalogEntryId))){k(!0),G("");try{const N=await Su({clientId:S,clientProductId:w.catalogEntryId,targetProviderNetworkId:he.providerNetworkId,targetSourceProductId:he.sourceProductId});await(v==null?void 0:v(N,he)),g(!1)}catch(N){G(N.message||"Unable to change the product source.")}finally{k(!1)}}}return a.jsx(Na,{open:c,onOpenChange:N=>{B||g(N)},title:"Change provider network product",description:"Select the product this client catalog entry should use.",contentClassName:"max-w-xl",contentTestId:"dialog-products-source",preventOutsideDismiss:!0,mobileStickyHeader:!0,mobileStickyFooter:!0,footer:a.jsxs("div",{className:"flex w-full justify-end gap-2 max-lg:gap-1.5",children:[a.jsx(L,{type:"button",variant:"outline",className:"h-9 rounded-full px-4 max-lg:h-8 max-lg:px-3 max-lg:text-xs",onClick:()=>g(!1),disabled:B,children:"Cancel"}),a.jsxs(L,{type:"submit",form:"client-product-source-dialog-form",className:"h-9 rounded-full px-4 text-white max-lg:h-8 max-lg:px-3 max-lg:text-xs",style:{backgroundColor:x},disabled:!he||B,"data-testid":"button-products-change-source",children:[B?a.jsx(V,{size:"sm",className:"mr-1.5"}):null,"Change product"]})]}),children:a.jsx("form",{id:"client-product-source-dialog-form",className:fu,onSubmit:hu(I,{disabled:!he||B}),children:a.jsxs(Rl,{className:"overflow-hidden bg-surface-raised p-0",bodyClassName:"divide-y divide-slate-200 dark:divide-slate-700",children:[a.jsx("section",{className:"px-5 py-4 max-lg:px-3 max-lg:py-2.5 sm:px-6",children:a.jsxs("div",{className:"relative",children:[a.jsx(Ml,{className:"pointer-events-none absolute left-2.5 top-2.5 size-3.5 text-slate-400"}),a.jsx(Ee,{value:y,onChange:N=>F(N.target.value),placeholder:"Search products or networks","aria-label":"Search provider network products",className:"h-9 pl-8 text-sm max-lg:h-8","data-testid":"input-products-source-search"})]})}),a.jsx("section",{className:"max-h-[min(52vh,26rem)] overflow-y-auto",children:Z?a.jsx("div",{className:"space-y-1 p-2",children:[0,1,2,3].map(N=>a.jsx(Sa,{className:"h-14 w-full rounded-lg max-lg:h-11"},N))}):$?a.jsxs("div",{className:"space-y-2 p-5 text-center text-sm text-red-600 max-lg:space-y-1.5 max-lg:p-3 max-lg:text-xs dark:text-red-400",children:[a.jsx("p",{children:$}),a.jsx(L,{type:"button",variant:"outline",className:"h-8 rounded-full px-3 text-xs max-lg:h-7 max-lg:px-2.5 max-lg:text-2xs",onClick:()=>q(N=>N+1),children:"Retry"})]}):E.length===0?a.jsx("div",{className:"p-5 text-center text-sm text-content-tertiary max-lg:p-3 max-lg:text-xs",children:"No matching provider network products."}):a.jsx("div",{className:"divide-y divide-slate-200 dark:divide-slate-700",role:"radiogroup","aria-label":"Provider network products",children:E.map(N=>{const D=`${N.providerNetworkId}::${N.sourceProductId}`,le=D===Ue,st=D===W;return a.jsxs("button",{type:"button",role:"radio","aria-checked":st,disabled:le,onClick:()=>te(D),className:at("flex w-full items-center gap-3 px-3 py-2.5 text-left transition-colors","max-lg:gap-2 max-lg:px-2 max-lg:py-2",st?"bg-slate-100 dark:bg-slate-800":"hover:bg-slate-50 dark:hover:bg-slate-800/60",le&&"cursor-default opacity-55"),children:[a.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center rounded-full border border-default",style:st?{borderColor:x,backgroundColor:x}:void 0,children:st?a.jsx(Ol,{className:"size-3 text-white"}):null}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"block truncate text-sm font-medium text-content-primary max-lg:text-xs",children:N.name}),a.jsxs("span",{className:"block truncate text-xs text-content-tertiary max-lg:text-3xs",children:[N.providerNetworkName,le?" · Current":""]})]})]},D)})})})]})})})}function ju({open:c,productId:g,clientId:S,callManageProduct:w,onClose:x,onDeleted:v,onReviewPackage:R}){const b=l.useRef(w);b.current=w;const[y,F]=l.useState(null),[W,te]=l.useState(!0),[Z,pe]=l.useState(!1),[B,k]=l.useState(!1),[$,G]=l.useState(""),[He,q]=l.useState(0),[qe,Ge]=l.useState(!1);l.useEffect(()=>{if(!c||qe)return;let I=!1;return te(!0),F(null),G(""),b.current("previewClientProductDeleti
2on",{clientId:S,productId:g}).then(N=>{I||F(N)}).catch(N=>{I||G(N.message||"Unable to load affected packages. Try again.")}).finally(()=>{I||te(!1)}),()=>{I=!0}},[S,g,c,He,qe]);async function Ue(){if(!(!y||W||Z||B)){pe(!0),G("");try{const I=await b.current("deleteClientProduct",{clientId:S,productId:g,impactToken:y.impactToken});Ge(!0),y.packages.length===0&&x(),v(I)}catch(I){G(I.message||"Unable to delete this product. Try again."),I.code==="DELETE_IMPACT_CHANGED"&&F(null)}finally{pe(!1)}}}async function E(I){k(!0),G("");try{await R(I.id)}catch(N){G(N.message||"Unable to open this package. Try again.")}finally{k(!1)}}const he=(y==null?void 0:y.product.itemType)==="package";return qe&&(y==null?void 0:y.packages.length)>0?a.jsx(Na,{open:c,onOpenChange:I=>{!I&&!B&&x()},size:"lg",title:"Product deleted. Review your packages",description:`“${y.product.name}” was removed from the packages below. Review their contents and pricing before offering them to patients.`,mobileStickyFooter:!0,contentTestId:"dialog-products-delete-next-steps",footer:a.jsx(L,{type:"button",variant:"outline",className:"rounded-full",disabled:B,onClick:x,children:"Close"}),children:a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-muted-foreground",children:"Package prices and availability have not changed. Edit each affected package to add a replacement, adjust its price, or deactivate it. Closing an editor returns you to this list."}),a.jsx("ul",{className:"divide-y divide-border","aria-label":"Packages changed by deletion",children:y.packages.map(I=>a.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[a.jsxs("div",{className:"min-w-0 flex-1 basis-48",children:[a.jsx("p",{className:"break-words text-sm font-medium text-foreground",children:I.name}),a.jsx("p",{className:"text-xs text-muted-foreground",children:I.remainingCount===0?"Deletion left this package empty. Add an item or deactivate it.":"Review the remaining items and price."})]}),a.jsx(L,{type:"button",variant:"outline",className:"rounded-full",disabled:B,"aria-label":`Edit package ${I.name}`,onClick:()=>E(I),children:"Edit package"})]},I.id))}),$?a.jsxs("p",{role:"alert",className:"text-sm text-destructive",children:[$," Try opening the package again."]}):null]})}):a.jsx(Dc,{open:c,onOpenChange:I=>{!I&&!Z&&!B&&x()},title:y?`Delete “${y.product.name}”?`:"Delete product?",description:"This permanently deletes the client product and its formulary mappings. Existing orders are kept.",tone:"destructive",busy:Z,confirmDisabled:W||B||!y,confirmLabel:he?"Delete package":"Delete product",confirmationText:y==null?void 0:y.product.name,onConfirm:Ue,contentTestId:"dialog-products-delete",confirmationTestId:"input-products-delete-confirmation",confirmTestId:"button-products-delete-confirm",children:a.jsxs("div",{className:"space-y-3 text-sm",children:[W?a.jsx(Sa,{className:"h-12 w-full","aria-label":"Loading affected packages"}):null,(y==null?void 0:y.packages.length)>0?a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"font-medium",children:"The following packages will lose this product."}),a.jsx("p",{className:"text-muted-foreground",children:"Open a package to review or edit it. Closing its editor returns here with an updated list. Package prices stay the same."}),a.jsx("ul",{className:"space-y-1",children:y.packages.map(I=>a.jsxs("li",{children:[a.jsx(L,{type:"button",variant:"link",className:"h-auto max-w-full whitespace-normal rounded-full text-left",disabled:Z||B,onClick:()=>E(I),children:I.name}),I.remainingCount<2?a.jsx("p",{className:"text-xs text-muted-foreground",children:I.remainingCount===0?"This package will have no items.":"This package will have one item remaining."}):null]},I.id))})]}):y?a.jsx("p",{className:"text-muted-foreground",children:"No packages contain this product."}):null,$?a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{role:"alert",className:"text-destructive",children:$}),a.jsx(L,{type:"button",variant:"outline",className:"rounded-full",disabled:Z||B||W,onClick:()=>q(I=>I+1),children:"Refresh affected packages"})]}):null]})})}function jl(c=[]){if(!Array.isArray(c)||c.length===0)return null;const g=c.map(x=>[...new Set((Array.isArray(x)?x:[]).map(v=>
2String(v||"").trim()).filter(Boolean))]),[S,...w]=g;return S.filter(x=>w.every(v=>v.includes(x))).sort()}const Ll=l.lazy(()=>It(()=>import("./ProductDetailsDialog-qRBsFrxt.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122])));async function El(c=[]){const g=[...new Set(c.filter(Boolean))],S=await Promise.all(g.map(async w=>{try{const x=await xu({providerNetworkId:w});return[w,(x==null?void 0:x.approvedLabProductIdsByNetworkProduct)||{}]}catch(x){return console.error("Error loading network lab approvals:",x),[w,{}]}}));return new Map(S)}const Lu=l.lazy(()=>It(()=>import("./LabForm-sUCZJmQL.js").then(c=>c.a),__vite__mapDeps([123,1,2,3,4,5,117,124,28,125,119,120,121,92,126]))),Tl=l.lazy(()=>It(()=>import("./SendProductToPatientModal-B_zcqAFo.js"),__vite__mapDeps([127,1,2,3,4,5,27,111,128,117,129,130,131,68,132]))),Eu=l.lazy(()=>It(()=>import("./ClientCategoriesManagerDialog-D_NihaRA.js"),__vite__mapDeps([133,1,2,3,4,5,21,16,17,18,19,20,22,23,24,25,26,27,29,43,30,134,89,135,87,88,136,85,92,93,40,137,107,106,83,53,68,38,138]))),Tu=l.lazy(()=>It(()=>import("./ClientProductSmartUploadDialog-BhYps6im.js"),__vite__mapDeps([139,1,3,2,4,5,68,140,34,122]))),Fu=l.lazy(()=>It(()=>import("./ProductsPageProductMedicationsSheet-Dl84wnBq.js"),__vite__mapDeps([141,1,17,2,3,4,5,21,29,39,11,12,13,14,15,31,32,142,37,7])).then(c=>({default:c.ProductsPageProductMedicationsSheet}))),Au=l.lazy(()=>It(()=>import("./ProductsPageBulkMedicationsSheet-DfvJ-GdB.js"),__vite__mapDeps([143,1,17,2,3,4,5,29,31,13,11,12,14,15,32,142,37])).then(c=>({default:c.ProductsPageBulkMedicationsSheet}))),Le="gen-health.products.filters.client.v1",Ru=["displayTitle","displaySummary","categorySort","ownerSort","typeSort","priceSort","formularyMappingCount"],Mu=["asc","desc"],Ul=new Set(["requiresLab","requiresLabs","labRecencyDays","labRecencyUnit","requiredLabTests","requiredLabTestIds","suggestedLabProductIds","approvedLabProductIds","supportedLabProductIds","sourceRequiresLabs","requiredLabPriceOverrides","requiredLabAudiences","labFirstWorkflow","labTests","labTestIds","panels","biomarkers","markerNames","labBiomarkerExtraction","labRequirementVersion","labRequirementHash","labRequirementReviewStatus","labRequirementVerifiedBy","labRequirementVerifiedAt","labBiomarkerVersion","labBiomarkerHash","labBiomarkerReviewStatus","labBiomarkerVerifiedBy","labBiomarkerVerifiedAt"]),Ou=new Set(["requiresLab","requiresLabs","approvedLabProductIds","requiredLabPriceOverrides","requiredLabAudiences","labFirstWorkflow"]),Fl=(c={})=>Object.keys(c).some(g=>Ul.has(g));function Bu(c={}){return Object.entries(c).reduce((g,[S,w])=>(Ul.has(S)?Ou.has(S)&&(g.labPatch[S]=w):g.safePayload[S]=w,g),{safePayload:{},labPatch:{}})}const Du=c=>typeof c=="string",Nt=c=>Array.isArray(c)&&c.every(g=>typeof g=="string"),qu=c=>typeof c=="boolean",ha="rounded-sm underline decoration-dotted decoration-border underline-offset-4 hover:text-link focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",Uu=c=>c===null||Ru.includes(c),_u=c=>Mu.includes(c);function qr(c={}){return(c==null?void 0:c.status)!=="inactive"}function Tr(c={},g={}){if(!qr(c)||(c==null?void 0:c.showPatient)===!1)return!1;const S=String((c==null?void 0:c.id)||"").trim();return!((c==null?void 0:c.showPatient)===void 0&&S&&g[`product_${S}`]===!1)}function Fr(c){return c?{status:"active"}:{status:"inactive",showPatient:!1}}function Ar(c){const g=wa(c);return Br[g]||g.charAt(0).toUpperCase()+g.slice(1)}function wa(c){return(c==null?void 0:c.itemType)==="package"?"package":(c==null?void 0:c.itemType)==="subscription"?(c==null?void 0:c.planType)==="program"?"program":"subscription":(c==null?void 0:c.type)||"product"}function Al(c){const g=Pa(c==null?void 0:c.customerPrice);if(!g)return"—";const S=Math.max(1,Number(c==null?void 0:c.periodCount)||1),w=String((c==null?void 0:c.periodUnit)||"months").replace(/s$/,"");return`${g} / ${S} ${S===1?w:`${w}s`}`}function Kt({label:c="Loading…"}){return a.jsx(Na,{open:!0,onOpenChange:()=>{},accessibleTitle:c,size:"sm",bodyClassName:"flex items-center justify-center !p-6",children:a.jsx(V,{size:"md",label:c})})}function bs(c={}){return String(c.id||c.catalogEntryId||c.clientProductId||c.productId||"").trim()}function ya(c={}){return String(c.catalogEntryId||c.id||c.clientProductId||c.productId||"").trim()}const vs={productFirst:"Patient pays for the product first, then enters the app to finish onboarding, intake forms, and visit scheduling when applicable.",assessmentFirst:"Patient completes the product intake form and required forms first, then pays for the visit only. Product payment is not collected in this flow.",intakeFirst:"Patient completes the product intake form and required forms first, then checks out to pay for the product."},$u={productFirst:"Patient pays for their lab and any assessment fee, then enters the app for intake. Product is charged only if the provider approves.",assessmentFirst:"Patient completes intake forms, then pays for their lab and any assessment fee. Product is charged only if the provider approves.",intakeFirst:"Patient completes intake forms, then pays for their lab and any assessment fee. Product is charged only if the provider approves."};function zu(c={}){var g;return((g=c==null?void 0:c.labFirstWorkflow)==null?void 0:g.enabled)===!0?$u:vs}const Vu={no_items:"This package has no included products.",multiple_items:"Packages with more than one item can't be paired. Pair each included protocol on its own row.",lab_or_visit:"Packages that include a lab or visit can't be paired.",not_network_protocol:"Only a package whose single item is a provider-network protocol can be paired.",item_unpaired:"The included protocol has no paired medications yet. Pair that protocol first."};function _l(c){return Vu[c]||"This package can't be paired with formulary medications."}function Rr({product:c,mappingCount:g=0,hasFormularyPharmacies:S,isClientOwnedProduct:w,prescribeByProductEnabled:x=!1,resolvePackagePairing:v=()=>({eligible:!1,reason:null})}
2){if(!c)return{status:"ineligible",filterId:"ineligible",label:"Not eligible",description:"This product cannot be paired with formulary medications."};if(Ct(c)){const R=typeof v=="function"?v(c):{eligible:!1,reason:null};if(!(R!=null&&R.eligible))return{status:"ineligible_package",filterId:"ineligible",label:"Can't pair packages",reason:(R==null?void 0:R.reason)||null,description:_l(R==null?void 0:R.reason)}}else if(w(c)){if(!x)return{status:"ineligible_client_owned",filterId:"ineligible",label:"Client-owned",description:"Direct-sale client products do not use provider-network formulary mapping."}}else if(!c.providerNetworkId)return{status:"ineligible_no_provider_network",filterId:"ineligible",label:"No provider network",description:"Products without a provider network cannot be paired to formulary medications."};return S?g>0?{status:"eligible_paired",filterId:"paired",label:`${g} medication${g===1?"":"s"}`,description:"This product has paired formulary medications."}:{status:"eligible_unpaired",filterId:"unpaired",label:"Needs pairing",description:"This product is eligible for formulary mapping and has no paired medications."}:{status:"no_formulary_pharmacy",filterId:"ineligible",label:"No pharmacy",description:"Connect an active formulary pharmacy before pairing medications."}}function Ku(c,g){var S,w,x,v,R,b,y,F;return c.active===g.active&&c.showOnStorefront===g.showOnStorefront&&c.displayTitle===g.displayTitle&&c.displaySummary===g.displaySummary&&c.categorySort===g.categorySort&&c.ownerLabel===g.ownerLabel&&c.typeSort===g.typeSort&&c.priceSort===g.priceSort&&c.formularyMappingCount===g.formularyMappingCount&&((S=c.formularyReadiness)==null?void 0:S.status)===((w=g.formularyReadiness)==null?void 0:w.status)&&((x=c.formularyReadiness)==null?void 0:x.filterId)===((v=g.formularyReadiness)==null?void 0:v.filterId)&&((R=c.formularyReadiness)==null?void 0:R.label)===((b=g.formularyReadiness)==null?void 0:b.label)&&((y=c.formularyReadiness)==null?void 0:y.reason)===((F=g.formularyReadiness)==null?void 0:F.reason)}const Wu=l.memo(function({productKey:g,product:S,onVisible:w}){const x=l.useRef(S);return x.current=S,l.useEffect(()=>{typeof w=="function"&&w(x.current)},[g,w]),null});function mt({label:c,tooltip:g}){const S=a.jsxs("span",{className:"inline-flex max-w-full items-center justify-center gap-1 text-center",children:[a.jsx("span",{className:"truncate",children:c}),g?a.jsx(ba,{delayDuration:150,children:a.jsxs(xa,{children:[a.jsx(va,{asChild:!0,children:a.jsx("button",{type:"button",className:"inline-flex size-4 shrink-0 items-center justify-center rounded-full text-slate-400 hover:text-slate-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring dark:text-slate-500 dark:hover:text-slate-300","aria-label":`${c} info`,onClick:w=>w.stopPropagation(),children:a.jsx(fd,{className:"size-3.5"})})}),a.jsx(ka,{side:"top",className:"max-w-xs text-xs",children:g})]})}):null]});return a.jsx("div",{className:"flex w-full justify-center",children:S})}function Qu({product:c,disabled:g,saving:S,accentColor:w,onSave:x}){const v=Dr(c.addOns),R=!!v,b=Number.isFinite(Number(v==null?void 0:v.count))&&Number(v.count)>0?String(v.count):"1",y=Number.isFinite(Number(v==null?void 0:v.expiresInDays))&&Number(v.expiresInDays)>0?String(v.expiresInDays):"",F=g||S,[W,te]=l.useState(!1),[Z,pe]=l.useState(R),[B,k]=l.useState(b),[$,G]=l.useState(y);if(l.useEffect(()=>{W&&(pe(R),k(b),G(y))},[b,y,R,W]),c.itemType==="subscription")return a.jsx("span",{className:"flex min-h-[76px] items-center justify-center px-1 text-xs text-content-tertiary max-lg:text-3xs",children:"—"});const He=async()=>{await x(c,{enabled:Z,count:B,expiresInDays:$})&&te(!1)};return a.jsxs(Me,{open:W,onOpenChange:q=>!F&&te(q),children:[a.jsx(Oe,{asChild:!0,children:a.jsx("div",{role:"button",tabIndex:F?-1:0,className:at("flex min-h-[76px] w-full items-center justify-center px-1 transition-colors 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-700/50 dark:focus-visible:ring-slate-500",F&&"cursor-not-allowed opacity-60 hover:bg-transparent dark:hover:bg-transparent"),onClick:q=>{q.stopPropagation(),F||te(!0)},onKeyDown:q=>{q.key!=="Enter"&&q.key!==" "||(q.preventDefault(),q.stopPropagation(),F||te(!0))},"data-row-click-ignore":!0,"data-table-cell-focus-target":!0,"aria-disabled":F,"aria-label":`Offer included visits for ${c.displayTitle}`,children:a.jsx(De,{checked:R,disabled:F,tabIndex:-1,"aria-hidden":"true",className:"size-5 pointer-events-none max-lg:size-4"})})}),a.jsx(Be,{className:"w-72 rounded-lg border-subtle p-3 shadow-lg",align:"center","data-row-click-ignore":!0,children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("label",{className:"flex items-center justify-between gap-3 rounded-lg border border-subtle bg-surface-raised px-3 py-2",children:[a.jsx("span",{className:"text-sm font-semibold text-content-primary",children:"Included visits"}),a.jsx(De,{checked:Z,onCheckedChange:q=>pe(q===!0),"aria-label":`Enable included visits for ${c.displayTitle}`})]}),Z?a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{children:[a.jsx("label",{className:"mb-1 block text-xs font-medium text-content-secondary",children:"Visits"}),a.jsx(Ee,{value:B,onChange:q=>k(q.target.value.replace(/[^0-9]/g,"")),inputMode:"numeric",className:"h-9",placeholder:"1"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"mb-1 block text-xs font-medium text-content-secondary",children:"Expires"}),a.jsx(Ee,{value:$,onChange:q=>G(q.target.value.replace(/[^0-9]/g,"")),inputMode:"numeric",className:"h-9",placeholder:"Days"})]})]}):null,a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:w},disabled:S,onClick:He,children:[S?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Apply"]})]})})]})}function Hu({embedded:c=!1,hideHeader:g=!1}){var Tn,Fn,An,Rn,Mn,On,Bn,Dn,qn;const[S,w]=l.useState(null),{userDoc:x,userType:v,loading:R,clientData:b,providerNetworkBrandingMap:y}=qc(),{branding:F,experience:W}=Uc(),te=_c(),[Z,pe]=$c(),B=Z.get("product")||"",[k,$]=l.useState([]),[G,He]=l.useState([]),[q,qe]=l.useState([]),[Ge,Ue]=l.useState([]),[E,he]=l.useState(null),[I,N]=l.useState({}),[D,le]=l.useState(()=>new Map),[st,jt]=l.useState(!0),[Ca,pt]=l.useState({}),[ks,gt]=l.useState({}),[P,U]=l.useState({}),[_,Pe]=l.useState({}),[ye,Lt]=l.useState(null),[ws,Ia]=je(`${Le}.searchTerm`,"",{validate:Du}
2),$l=l.useDeferredValue(ws),[rt,ja]=je(`${Le}.statusFilter`,"all",{validate:e=>gs.includes(e)}),[Et,Ps]=je(`${Le}.storefrontOnly`,!1,{validate:qu}),[Wt,La]=je(`${Le}.categoryFilters`,[],{validate:Nt}),[Qt,Ss]=je(`${Le}.ownerFilters`,[],{validate:Nt}),[Ht,Ns]=je(`${Le}.typeFilters`,[],{validate:Nt}),[Gt,Cs]=je(`${Le}.priceFilters`,[],{validate:Nt}),[Yt,Is]=je(`${Le}.imageFilters`,[],{validate:Nt}),[Tt,js]=je(`${Le}.formularyFilters`,[],{validate:Nt}),[Jt,Ls]=je(`${Le}.paymentFilters`,[],{validate:Nt}),[zl,Ur]=je(`${Le}.sortKey`,"displayTitle",{validate:Uu}),[Vl,_r]=je(`${Le}.sortDirection`,"asc",{validate:_u}),[Kl,$r]=l.useState(!1),[zr,Wl]=l.useState(null),[Es,Vr]=l.useState(!1),[Kr,Wr]=l.useState(!1),[Qr,Hr]=l.useState(!1),[oe,Gr]=l.useState([]),[Ye,Yr]=l.useState(!1),[A,Jr]=l.useState(!1),ft=l.useRef(null),[Zr,Ea]=l.useState([]),[Ts,Xr]=l.useState(!0),[ei,ti]=l.useState(""),[ai,si]=l.useState(""),[Fs,ri]=l.useState(!0),[ii,ni]=l.useState(""),[li,oi]=l.useState(""),[ci,di]=l.useState(""),[ui,mi]=l.useState(""),[pi,gi]=l.useState(""),[fi,hi]=l.useState([]),[As,yi]=l.useState(!0),[Ta,bi]=l.useState("all"),[it,xi]=l.useState(!0),[vi,Rs]=l.useState([]),[Zt,Xt]=l.useState([]),[Ms,Os]=l.useState(!1),[Ql,Bs]=l.useState(!1),[M,nt]=l.useState(""),[Hl,Fa]=l.useState(!1),[ea,Se]=l.useState(""),[ie,ae]=l.useState(""),[ht,Ds]=l.useState(null),[K,Aa]=l.useState(null),[Ra,Ft]=l.useState(!1),[be,ta]=l.useState(null),[Gl,Ma]=l.useState(""),[Yl,Oa]=l.useState(""),[aa,ki]=l.useState(null),[Jl,qs]=l.useState({}),[Zl,wi]=l.useState([]),[Xl,Ba]=l.useState(!1),[eo,Us]=l.useState(""),[to,Pi]=l.useState(null),Da=l.useRef(null),[Si,Ni]=l.useState(!1),[qa,_s]=l.useState(null),[ao,sa]=l.useState(null),[Je,At]=l.useState({open:!1,reason:null,product:null,count:1}),[_e,yt]=l.useState({}),Ne=l.useRef({}),[$s,so]=l.useState({}),ro=l.useRef({}),[Ua,Ci]=l.useState({}),_a=l.useRef({}),[se,$a]=l.useState([]),[Ii,zs]=l.useState([]),[Te,za]=l.useState(!1),[Va,Ka]=l.useState({configured:!1,excludedStatesById:new Map,loading:!1,error:null}),[Ze,Vs]=l.useState(""),[io,no]=l.useState(!1),[bt,Ks]=l.useState(!1),Rt=l.useRef(null);Rt.current=b;const ji=l.useRef({});ji.current=y||{};const Li=l.useRef(R);Li.current=R;const Ws=Object.values(y||{}).map(e=>String((e==null?void 0:e.name)||"").trim()).filter(Boolean).join("|"),lo=l.useMemo(()=>{const e=Ws?Ws.split("|"):[];return e.length===1?e[0]:"your provider network"},[Ws]),[Wa,oo]=l.useState(null),[co,Qs]=l.useState(!1),[Ei,Ti]=l.useState(null),[Qa,Mt]=l.useState(!1),[Fe,Ot]=l.useState(null),[Fi,Ai]=l.useState(null),[Ha,Ri]=l.useState(null),[Mi,Oi]=l.useState(!1),[Bi,Di]=l.useState(null),[qi,Ui]=l.useState(!1),[_i,$i]=l.useState(null),m=x==null?void 0:x.clientId,$e=x==null?void 0:x.businessId,Hs=Array.isArray((Tn=x==null?void 0:x.catalogCategoryAccess)==null?void 0:Tn.products)?x.catalogCategoryAccess.products.join("|"):null,zi=l.useMemo(()=>Dd(x==null?void 0:x.userType,Hs?Hs.split("|"):null),[x==null?void 0:x.userType,Hs]),h=v==="Business Admin"||v==="Business Staff",Y=h?$e:m,Gs=h?"business":"client",Vi=h||!!(b!=null&&b.id),C=(F==null?void 0:F.accentColor)||(E==null?void 0:E.accentColor)||(E==null?void 0:E.primaryColor)||zc,Ys=l.useMemo(()=>new Set(oe.map(e=>e.id)),[oe]),X=v!=="Client Staff",xe=br(x)==="Client"&&xr(v,"Client Admin"),Ga=br(x)==="Client"&&xr(v,"Client Admin");l.useEffect(()=>{if(!aa||!m||h||v!=="Client Admin"){wi([]),Ba(!1),Us("");return}return Ba(!0),Us(""),yu({ownerType:"client",scopeId:m,readOnly:!1,onData:e=>{var t;wi((((t=e.overview)==null?void 0:t.ownIntegrations)||[]).filter(s=>bu(s)&&s.status==="active")),Ba(!1)},onError:e=>{console.error("Unable to load lab integrations for product setup:",e),Us("Unable to load lab integrations."),Ba(!1)}})},[m,h,aa,v]);const Ce=k,Js=l.useMemo(()=>{const e=new Map;return k.forEach(t=>{const s=(t==null?void 0:t.catalogEntryId)||(t==null?void 0:t.productId)||(t==null?void 0:t.id)||(t==null?void 0:t.clientProductId);s&&([t==null?void 0:t.id,t==null?void 0:t.catalogEntryId,t==null?void 0:t.clientProductId].forEach(r=>{r&&e.set(String(r),s)}),!(t!=null&&t.sourceProductId)&&(t!=null&&t.productId)&&e.set(String(t.productId),s))}),e},[k]),j=l.useCallback(e=>!h&&(e==null?void 0:e.catalogScope)==="client",[h]),Ya=l.useCallback(e=>j(e)?"client":"network",[j]),xt=l.useCallback((e,t)=>{if(h)return me(O,"Businesses",$e,"Products",e);const s=Js.get(String(t||""))||Js.get(String(e||""))||e||t;return s?me(O,"Clients",m,"Products",s):null},[m,h,$e,Js]),Zs=br(x)==="Client"&&xr(v,"Client Admin"),ve=!h&&(v==="Client Admin"||v==="Client Staff"),[Xs,er]=l.useState(!1),uo=l.useCallback((e,t)=>{if(!e)return;const s=tt(e),r=t||{};yt(i=>{const n={...i,[s]:r};return Ne.current=n,n})},[]),mo=e=>{if(e==null||e==="")return!0;const t=Number.parseFloat(e);return Number.isNaN(t)||t===0},po=e=>{const t=Dr(e==null?void 0:e.addOns),s=Number.parseInt(t==null?void 0:t.count,10);return Number.isFinite(s)&&s>0?s:0},ze=l.useCallback(e=>{const t=new Set,s=[],r=[e==null?void 0:e.displayCategoryIds];return j(e)&&r.push(e==null?void 0:e.categories),r.forEach(i=>
2{(Array.isArray(i)?i:[]).forEach(n=>{n&&Ys.has(n)&&!t.has(n)&&(t.add(n),s.push(n))})}),s.length===0&&typeof(e==null?void 0:e.category)=="string"&&Ys.has(e.category.trim())&&s.push(e.category),s},[Ys,j]),go=l.useCallback(e=>{const t=new Set,s=[];return[e==null?void 0:e.categories,e==null?void 0:e.displayCategoryIds].forEach(r=>{(Array.isArray(r)?r:[]).forEach(i=>{const n=String(i||"").trim();n&&!t.has(n)&&(t.add(n),s.push(n))})}),s},[]),[ra,fo]=l.useState({}),Ki=l.useRef(new Set),Wi=l.useMemo(()=>{if(h)return"";const e=new Set;return k.forEach(t=>{var i;const s=String((t==null?void 0:t.providerNetworkId)||"").trim();if(!s||j(t))return;const r=String(((i=y==null?void 0:y[s])==null?void 0:i.name)||"").trim();r&&r!==s||e.add(s)}),Array.from(e).sort().join("|")},[h,j,k,y]);l.useEffect(()=>{const e=Wi.split("|").filter(t=>t&&!Ki.current.has(t));e.length!==0&&(e.forEach(t=>Ki.current.add(t)),Vc(O,e).then(t=>{const s={};Object.entries(t||{}).forEach(([r,i])=>{const n=String((i==null?void 0:i.name)||"").trim();n&&n!==r&&(s[r]=n)}),Object.keys(s).length>0&&fo(r=>({...r,...s}))}).catch(()=>{}))},[Wi]);const Ja=l.useCallback(e=>{var r;const t=String((e==null?void 0:e.providerNetworkId)||"").trim();return[e==null?void 0:e.reviewNetworkLabel,e==null?void 0:e.providerNetworkName,t?(r=y==null?void 0:y[t])==null?void 0:r.name:"",t?ra[t]:""].map(i=>String(i||"").trim()).find(i=>i&&i!==t)||(t?"Provider network":"")},[ra,y]),Za=l.useCallback(e=>(e==null?void 0:e.providerNetworkAccentColor)||C,[C]);l.useEffect(()=>{h||!y||Object.keys(y).length===0||$(e=>{let t=!1;const s=e.map(r=>{const i=r==null?void 0:r.providerNetworkId,n=i?y[i]:null;if(!n)return r;const o=n.name||r.providerNetworkName||"",d=n.accentColor||r.providerNetworkAccentColor||"",u=!j(r)&&n.legitScriptEnabled===!0,f=r.reviewNetworkLabel&&r.reviewNetworkLabel!==i?r.reviewNetworkLabel:o;return r.legitScriptEnabled===u&&r.providerNetworkName===o&&r.providerNetworkAccentColor===d&&r.reviewNetworkLabel===f?r:(t=!0,{...r,legitScriptEnabled:u,providerNetworkName:o,providerNetworkAccentColor:d,reviewNetworkLabel:f})});return t?s:e})},[h,y]),l.useEffect(()=>{h||Object.keys(ra).length===0||$(e=>{let t=!1;const s=e.map(r=>{const i=String((r==null?void 0:r.providerNetworkId)||"").trim(),n=i?ra[i]:"";if(!n)return r;const o=d=>!String(d||"").trim()||d===i;return!o(r.providerNetworkName)&&!o(r.reviewNetworkLabel)?r:(t=!0,{...r,providerNetworkName:o(r.providerNetworkName)?n:r.providerNetworkName,reviewNetworkLabel:o(r.reviewNetworkLabel)?n:r.reviewNetworkLabel})});return t?s:e})},[ra,h]),l.useEffect(()=>{Ne.current=_e},[_e]),l.useEffect(()=>{_a.current=Ua},[Ua]),l.useEffect(()=>{if(!ve||!m){er(!1);return}let e=!1;return(async()=>{try{const t=await Td(m);e||er(t)}catch{e||er(!1)}})(),()=>{e=!0}},[m,ve]),l.useEffect(()=>{if(!ve||!m){$a([]),za(!1);return}let e=!1;return za(!0),(async()=>{try{const t=Qd(m);t&&!e&&($a(gl(t)),za(!1));const s=await Kc({clientId:m});if(e)return;const r=gl((Array.isArray(s==null?void 0:s.pharmacies)?s.pharmacies:[]).map(i=>Nr(i,m)));$a(i=>{if(i.length>0&&i.some(n=>Array.isArray(n.drugs)&&n.drugs.length>0)){const n=new Map(i.map(o=>[String(o.id||o.pharmacyId||""),o]));return r.map(o=>{const d=String(o.id||o.pharmacyId||""),u=n.get(d);return u&&Array.isArray(u.drugs)&&u.drugs.length>0?{...o,drugs:u.drugs}:o})}return r})}catch(t){e||(console.error("Error loading client formulary pharmacies for products grid:",t),$a(s=>s.length>0?s:[]))}finally{e||za(!1)}})(),()=>{e=!0}},[m,ve]),l.useEffect(()=>{if(!ve||!m){zs([]);return}let e=!1;return(async()=>{try{const t=await ru(O,m,{includeInactive:!0});if(e)return;zs(Object.values(iu(t)))}catch(t){e||(console.error("Error loading formulary medication variants:",t),zs([]))}})(),()=>{e=!0}},[m,ve]),l.useEffect(()=>{if(!m||!ve){Ks(!1);return}let e=!1;return(async()=>{try{const{enabled:t}=await Hd(O,{clientId:m});if(e)return;Ks(t)}catch(t){e||(console.error("Error resolving prescribe-by-product flag:",t),Ks(!1))}})(),()=>{e=!0}},[m,ve]);const ia=l.useRef(k);ia.current=k;const tr=l.useMemo(()=>k.map(e=>String((e==null?void 0:e.id)||"")).join("|"),[k]);l.useEffect(()=>{if(h||!m||!ve||!tr){yt({}),Ne.current={};return}const e=ia.current.filter(s=>(s==null?void 0:s.itemType)!=="package");if(e.length===0){yt({}),Ne.current={};return}let t=!1;return(async()=>{try{const s=await Gd(O,{clientId:m,products:e});if(t)return;
2Ne.current=s,yt(s)}catch(s){t||(console.error("Error loading product formulary mappings:",s),yt({}),Ne.current={})}})(),()=>{t=!0}},[m,h,ve,tr]);const Qi=l.useRef(new Map),ar=l.useCallback(e=>{const t=tt(e);if(!t)return Promise.resolve();const s=Qi.current;if(s.has(t))return s.get(t);const r=Yd(O,{providerNetworkId:e.providerNetworkId,products:[e]}).then(i=>{so(n=>{const o={...n,...i};return ro.current=o,o})}).catch(i=>{s.delete(t),console.error("Error loading product formulary mappings:",i)});return s.set(t,r),r},[]),Hi=l.useCallback(e=>{const t=tt(e);if(!t||!m)return Promise.resolve();const s=`package-extras:${t}`,r=Qi.current;if(r.has(s))return r.get(s);const i=Jd(O,{clientId:m,product:e}).then(n=>{Ci(o=>{const d={...o,[t]:n};return _a.current=d,d})}).catch(n=>{r.delete(s),console.error("Error loading package formulary extras:",n)});return r.set(s,i),i},[m]),Ve=l.useCallback(e=>{if(!e||h||!m||!ve)return Promise.resolve();const t=ia.current,s=[];if(Ct(e)){if(Zd(e,t).reason)return Promise.resolve();s.push(Hi(e)),(Array.isArray(e.includedProducts)?e.includedProducts:[]).forEach(r=>{const i=String((r==null?void 0:r.clientProductId)||(r==null?void 0:r.productId)||"").trim();if(!i)return;const n=t.find(o=>(o==null?void 0:o.itemType)==="package"?!1:[o==null?void 0:o.id,o==null?void 0:o.clientProductId,o==null?void 0:o.productId,o==null?void 0:o.catalogEntryId].filter(Boolean).map(String).includes(i));n&&!j(n)&&n.providerNetworkId&&s.push(ar(n))})}else!j(e)&&e.providerNetworkId&&s.push(ar(e));return s.length?Promise.all(s):Promise.resolve()},[m,ve,j,h,ar,Hi]),Bt=l.useMemo(()=>Xd({protocolMappingsByKey:_e,packageExtraMappingsByProductKey:Ua,catalogProducts:k}),[_e,Ua,k]),na=l.useCallback(e=>{const t=tt(e),s=Bt[t]||{};let r=$s[t]||{};return j(e)?r={}:Ct(e)&&eu(e,k)&&(r=xl(e,$s,k)),{clientMappings:s,networkMappings:r}},[Bt,j,$s,k]),lt=l.useCallback(e=>Cr(e,{catalogProducts:k,protocolMappingsByKey:_e}),[_e,k]),ot=l.useCallback(e=>{if(Ct(e)&&!lt(e).eligible)return 0;const{clientMappings:t}=na(e);return tu({clientMappings:t,networkMappings:{},pharmacies:se,scopeId:m})},[se,m,lt,na]),Gi=l.useCallback(e=>{const{clientMappings:t,networkMappings:s}=na(e),r=au({clientMappings:t,networkMappings:s,pharmacies:se,scopeId:m}),i=new Set;return r.forEach(n=>{const o=String(n).split(":").pop();o&&i.add(o)}),[...i]},[se,m,na]),ho=Object.values(Bt).some(e=>Object.values(e||{}).some(t=>{var s;return((s=t==null?void 0:t.medicationIds)==null?void 0:s.length)>0})),vt=ve&&(Xs||ho),{hiddenIds:Yi,ready:Ji}=nu(O,{clientId:m});l.useEffect(()=>{if(!m||!Xs){Ka({configured:!1,excludedStatesById:new Map,loading:!1,error:null});return}let e=!1;return Ka(t=>({...t,loading:!0,error:null})),(async()=>{try{const t=await Wc({integrationScopeType:"client",integrationScopeId:m});if(e)return;const s=Array.isArray(t==null?void 0:t.pharmacies)?t.pharmacies:[];Ka({configured:(t==null?void 0:t.configured)===!0,excludedStatesById:lu(s),loading:!1,error:null})}catch(t){if(e)return;Ka({configured:!1,excludedStatesById:new Map,loading:!1,error:(t==null?void 0:t.message)||"Unable to load pharmacy coverage."})}})(),()=>{e=!0}},[m,Xs]);const Xa=l.useCallback(e=>{if(ot(e)<=0||!Va.configured)return{hasPartialCoverage:!1,uncoveredStates:[]};const s=tt(e),r=Bt[s]||{},i=ou(r);if(i.length===0)return{hasPartialCoverage:!1,uncoveredStates:[]};const n=i.map(d=>cu(Va.excludedStatesById,d)),o=!du(n);return{hasPartialCoverage:o,uncoveredStates:o?uu(n):[]}},[Bt,ot,Va.configured,Va.excludedStatesById]),yo=l.useMemo(()=>k.some(e=>ot(e)>0),[ot,k]),bo=se.length>0||yo||Te,xo=l.useCallback(async({product:e,drug:t,pharmacy:s,nextChecked:r})=>{const i=kl(t),n=tt(e);if(!m||!i||!n||!e)return;await Ve(e);const o=Nr(s,m);if(Ct(e)){const u=Cr(e,{catalogProducts:k,protocolMappingsByKey:Ne.current});if(!u.eligible){p.error(`Can't pair packages. ${_l(u.reason)}`);return}const f=xl(e,Ne.current,k),T=wl(f,o,m),Q=_a.current[n]||{},ee=wl(Q,o,m);if(r){if(T.includes(i))return}else if(T.includes(i)&&!ee.includes(i)){p.message("This medication is inherited from an included protocol.");return}const J=r?Array.from(new Set([...ee,i])):ee.filter(z=>z!==i);try{const{payload:z}=await su(O,{clientId:m,product:e,pharmacy:o,medicationIds:J,user:we.currentUser});Ci(re=>{const de={...re,[n]:Ir(re[n]||{},o,{...z,source:"client",hasOverride:!0})};return _a.current=de,de})}catch(z){console.error("Error saving package formulary extra from products grid:",z),p.error((z==null?void 0:z.message)||"Unable to save package formulary mapping.")}return}const d=Ne.current[n]||{};try{const{payload:u}=await vl(O,{clientId:m,product:e,pharmacy:o,drug:t,nextChecked:r,mapping:d,user:we.currentUser});yt(f=>{const T={...f,[n]:Ir(f[n]||{},o,{...u,source:"client",hasOverride:!0})};return Ne.current=T,T})}catch(u){console.error("Error saving formulary mapping from products grid:",u),p.error((u==null?void 0:u.message)||"Unable to save formulary mapping.")}},[m,Ve,k]),vo=l.useCallback(async({products:e,drug:t,pharmacy:s,nextChecked:r})=>{const i=kl(t),n=Nr(s,m||"");if(!m||!i||!(n!=null&&n.id)||!Array.isArray(e)||e.length===0)return;const o={},d=()=>{Object.keys(o).length!==0&&yt(u=>{const f=Object.keys(o).reduce((T,Q)=>({...T,[Q]:o[Q]}),{...u});return Ne.current=f,f})};try{await Promise.all(e.map(T=>Ve(T)));const u=e.flatMap(T=>{const Q=tt(T);return Q?[{product:T,productKey:Q}]:[]}),f=8;for(let T=0;T<u.length;T+=f)(await Promise.all(u.slice(T,T+f).map(async({product:ee,productKey:J})=>{const z=Ne.current[J]||{},{payload:re}=await vl(O,{clientId:m,product:ee,pharmacy:n,drug:t,nextChecked:r,mapping:z,user:we.currentUser});return{productKey:J,mappings:Ir(z,n,{...re,source:"client",hasOverride:!0})}}
2))).forEach(({productKey:ee,mappings:J})=>{o[ee]=J});d(),p.success(`${r?"Paired":"Unpaired"} formulary for ${Object.keys(o).length} product${Object.keys(o).length===1?"":"s"}`)}catch(u){console.error("Error saving bulk formulary mapping:",u),d(),p.error((u==null?void 0:u.message)||"Unable to save bulk formulary mapping.")}},[m,Ve]),Zi=l.useMemo(()=>{const e=new Map;return oe.forEach(t=>{t!=null&&t.id&&(t.status||"active")==="active"&&e.set(t.id,(t.name||"Category").toString().trim())}),e},[oe]),ko=l.useMemo(()=>{const e=new Map;return oe.forEach(t=>{t!=null&&t.id&&e.set(t.id,t)}),e},[oe]),wo=l.useMemo(()=>{const e=new Map;return k.forEach(t=>{const s=Number.parseFloat(t==null?void 0:t.customerPrice);Number.isFinite(s)&&[t.clientProductId,t.id,t.productId].forEach(r=>{const i=String(r||"").trim();i&&e.set(i,s)})}),e},[k]),Xi=l.useCallback(e=>{const t=ze(e);if(t.length===0)return[];const s=new Set,r=[];return t.forEach(i=>{if(s.has(i))return;const n=(Zi.get(i)||"").toString().trim();n&&(r.push(n),s.add(i))}),r},[Zi,ze]),en=l.useMemo(()=>{const e=new Map;return k.forEach(t=>{ze(t).forEach(s=>{e.set(s,(e.get(s)||0)+1)})}),e},[ze,k]);l.useEffect(()=>{if(!h){le(Pl(G));return}if(!k.some(r=>(r==null?void 0:r.requiresLabs)===!0&&Array.isArray(r==null?void 0:r.approvedLabProductIds)&&r.approvedLabProductIds.length>0)||!Y){le(new Map);return}let t=!1;async function s(){try{const r=await Vn(O,Y,{type:"lab"});t||le(Pl(r.products||[]))}catch(r){console.warn("Unable to load lab prices for product storefront preview",r),t||le(new Map)}}return s(),()=>{t=!0}},[h,G,k,Y]);const Po=l.useMemo(()=>oe.filter(e=>(e.status||"active")==="active").map(e=>({id:e.id,label:e.name,count:en.get(e.id)||0})).filter(e=>e.count>0),[oe,en]),So=l.useMemo(()=>{if(h)return[];const e=k.reduce((t,s)=>{const r=Ya(s);return t[r]=(t[r]||0)+1,t},{});return[{id:"network",label:"Network",count:e.network||0},{id:"client",label:"Client",count:e.client||0}]},[Ya,h,k]),tn=l.useMemo(()=>{const e={};return Ce.forEach(t=>{const s=wa(t);e[s]=(e[s]||0)+1}),Object.entries(e).sort(([t],[s])=>t.localeCompare(s)).map(([t,s])=>({id:t,label:Br[t]||t.charAt(0).toUpperCase()+t.slice(1),count:s}))},[Ce]),es=l.useCallback(e=>mo(e==null?void 0:e.customerPrice)?"no-price":"priced",[]),ts=l.useCallback(e=>e!=null&&e.displayImageUrl||e!=null&&e.displayThumbnailUrl?"with-image":"missing-image",[]),as=l.useCallback(e=>{const t=ot(e),s=Rr({product:e,mappingCount:t,hasFormularyPharmacies:se.length>0||t>0||Te,isClientOwnedProduct:j,prescribeByProductEnabled:bt,resolvePackagePairing:lt});return s.filterId==="paired"&&Xa(e).hasPartialCoverage?"partial-coverage":s.filterId},[se.length,Te,ot,Xa,lt,j,bt]),ss=l.useCallback(()=>!h&&Wa===!1?"needs-payment":"payment-ready",[Wa,h]),Xe=l.useMemo(()=>{const e={price:{priced:0,"no-price":0},image:{"with-image":0,"missing-image":0},formulary:{paired:0,unpaired:0,ineligible:0,"partial-coverage":0},payment:{"payment-ready":0,"needs-payment":0}};return Ce.forEach(t=>{e.price[es(t)]+=1,e.image[ts(t)]+=1,e.formulary[as(t)]+=1,e.payment[ss(t)]+=1}),e},[as,ts,ss,es,Ce]),No=()=>{ja(e=>{const t=gs.indexOf(e);return gs[(t+1)%gs.length]}),La([])},Co=e=>{La(e),ja("all")},Io=e=>{Ss(e||[])},jo=e=>{Ns(e||[])},Lo=e=>{const t=e.replace(/[^0-9]/g,"");ti(t)};function rs(e,t){const s=new Set(Array.isArray(e)?e:[e]),r=Object.prototype.hasOwnProperty.call(t,"requiresLabs"),i=Object.prototype.hasOwnProperty.call(t,"excludedStates");$(n=>n.map(o=>{if(!s.has(o.id))return o;if(!r&&!i)return{...o,...t};let d={...t};if(i){const{excludedStates:f,...T}=d;d={...T,...Nl(o,f)}}let u={...o,...d};if(r){const f=t.requiresLabs===!0;u={...u,tenantRequiresLabs:f,requiresLabs:f||o.sourceRequiresLabs===!0}}return u}))}async function ct(e,t){const s=we.currentUser;if(!s)throw new Error("Not authenticated");const r=xt(e.id,e.clientProductId);if(!r)throw new Error("Client product not found");if(Fl(t)){const o=(await Ae("saveTenantCatalogProduct",{...h?{businessId:$e}:{clientId:m},productId:r.id,...t})).patch||{};return rs(e.id,o),o}const i={...t,updatedAt:Re(),updatedBy:s.uid};return await fs(r,i,{merge:!0}),rs(e.id,t),i}async function Ke(e,t,s,r){try{return ae(`${t}-${e.id}`),await ct(e,s),Object.prototype.hasOwnProperty.call(s,"showPatient")&&N(i=>({...i,[`product_${e.id}`]:s.showPatient})),p.success(r),!0}catch(i){return p.error(i.message||"Unable to update product"),!1}finally{ae("")}}function Dt(e,{allowBlank:t=!0,min:s=null}={}){const r=String(e??"").trim();if(!r)return t?{value:null}:{error:"Enter a value"};if(!/^\d+(?:\.\d+)?$/.test(r))return{error:"Enter a valid amount"};const i=Number.parseFloat(r);return!Number.isFinite(i)||s!==null&&i<s?{error:"Enter a valid amount"}:{value:i}}function is(e,{allowBlank:t=!0,min:s=1}={}){const r=String(e??"").trim();if(!r)return t?{value:null}:{error:"Enter a value"};if(!/^\d+$/.test(r))return{error:"Enter a valid number"};const i=Number.parseInt(r,10);return!Number.isFinite(i)||i<s?{error:"Enter a valid number"}:{value:i}}function Eo(e){e.key==="Enter"&&(e.preventDefault(),e.currentTarget.blur())}async function To(e,t){if(!X)return;const s=e.customerPrice==null?"":String(e.customerPrice),r=String(t??"").trim();if(r===s)return;const i=Dt(r,{allowBlank:!0,min:0});if(i.error){p.error(i.error);return}await Ke(e,"price",{customerPrice:i.value},"Price updated")}async function Fo(e,t){if(!X)return;const s=e.syncVisitPrice==null?"":String(e.syncVisitPrice),r=String(t??"").trim();if(r===s)return;const i=Dt(r,{allowBlank:!0,min:0});if(i.error){p.error("Enter a valid assessment price");return}await Ke(e,"assessment",{syncVisitPrice:i.value},"Assessment price updated")}async function Ao(e,t){const s=e.shippingPrice==null?"":String(e.shippingPrice),r=String(t??"").trim();if(r===s)return;const i=Dt(r,{allowBlank:!0,min:0});if(i.error){p.error("Enter a valid shipping price");return}await Ke(e,"shipping",{shippingPrice:i.value===null?null:i.value.toFixed(2)},"Shipping updated")}async function Ro(e,t){const s=e.quantityMonths==null?"1":String(e.quantityMonths),r=String(t??"").trim();if(r===s)return;const i=is(r,{allowBlank:!1,min:1});if(i.error){p.error("Enter a valid month supply");return}await Ke(e,"month-supply",{quantityMonths:i.value},"Month supply updated")}async function Mo(e,t){const s=e.prescriptionFillQuantity==null?"":String(e.prescriptionFillQuantity),r=String(t??"").trim();if(r===s)return;const i=is(r,{allowBlank:!0,min:1});if(i.error){p.error("Enter a valid quantity");return}await Ke(e,"quantity",{prescriptionFillQuantity:i.value},"Quantity updated")}async function Oo(e,t){if(!e.active)return;await Ke(e,"storefront",{showPatient:t===!0},"Storefront visibility updated")}async function Bo(e,{enabled:t,count:s,expiresInDays:r}){const i=Number.parseInt(s,10),n=Number.parseInt(r,10);if(t&&(!Number.isFinite(i)||i<1))return p.error("Enter a valid included visit count"),!1;if(t&&String(r??"").trim()&&(!Number.isFinite(n)||n<1))return p.error("Enter a valid expiration window"),!1;const o=t===!0?{addOns:[{type:"free_visit",count:i,expiresInDays:Number.isFinite(n)&&n>0?n:null}]}:{addOns:[]};return rs(e.id,o),await Ke(e,"included-visits",o,"Included visits updated"),!0}async function Do(e,t){const r={[e.itemType==="package"?"requiresSyncVisitOverride":"requiresSyncVisit"]:t===!0};rs(e.id,r),await Ke(e,"sync-visit",r,"Sync visit requirement updated")}function qo({product:e,approvedLabProductIds:t=[]}={}){var r,i;if(!e)return!0;const s=ms({product:{...e,requiresLabs:!0,approvedLabProductIds:t.length>0?t:["pending"]},platformBilling:(r=Rt.current)==null?void 0:r.platformBilling,clientModel:(E==null?void 0:E.model)||((i=Rt.current)==null?void 0:i.model)});return s.blocked&&s.reason===dt.PLATFORM_PAYMENT?(At({open:!0,reason:s.reason,product:e,count:1}),!1):!0}async function Uo(e,t){if(t===!0){const i=ms({product:{...e,requiresLabs:!0,approvedLabProductIds:["pending"]},platformBilling:b==null?void 0:b.platformBilling,clientModel:(E==null?void 0:E.model)||(b==null?void 0:b.model)});if(i.blocked&&i.reason===dt.PLATFORM_PAYMENT){At({open:!0,reason:i.reason,product:e,count:1});return}const n=Pt(e.approvedLabProductIds||[]);if(n.length===0){Ut(e,{focusSection:"labs"}),p.info("Choose at least one qualifying lab in the product editor.");return}let o=[];try{ae(`requires-labs-${e.id}`);const f=String(e.providerNetworkId||"").trim(),T=!h&&f&&Array.isArray(e.supportedLabProductIds)?await El([f]):new Map,Q=await dl(O,{clientId:m,businessId:h?$e:null,networkQualifiedLabProductIds:(T.get(f)||{})[hs(e)]||[],additionalLabConstraints:e.additionalLabConstraints||[],supportedLabProductIds:Array.isArray(e.supportedLabProductIds)?e.supp
2ortedLabProductIds:null}),ee=vr(e),J=Q.eligibleLabs||[];if(ee.length===0)o=J;else{const z=await Cl({labs:J,requiredLabTests:ee,providerNetworkId:String(e.providerNetworkId||"").trim()||void 0,networkProductId:hs(e)||void 0});o=jr(z.rows)}}catch(f){console.error("Error loading lab eligibility:",f),p.error("Unable to verify lab options."),ae("");return}const d=new Set(o.map(f=>f.id).filter(Boolean));if(o.length===0||n.some(f=>!d.has(f))){ae(""),Ut(e,{focusSection:"labs"}),p.info("Review the qualifying labs and choose which options to approve.");return}await Ke(e,"requires-labs",{requiresLabs:!0,approvedLabProductIds:n},"Lab requirement updated");return}await Ke(e,"requires-labs",{requiresLabs:!1,approvedLabProductIds:[],requiredLabPriceOverrides:[],requiredLabAudiences:[],labFirstWorkflow:{enabled:!1}},"Lab requirement updated")}async function _o(e,t){if(!X){p.error("You do not have permission to update product pricing");return}const s=t??e.customerPrice??"",r=s===""?null:Number.parseFloat(String(s).replace(/[^0-9.]/g,""));if(s!==""&&!Number.isFinite(r)){p.error("Enter a valid price");return}try{ae(`price-${e.id}`),await ct(e,{customerPrice:r}),pt(i=>({...i,[e.id]:r==null?"":String(r)})),Se(""),p.success("Price updated")}catch(i){p.error(i.message||"Unable to update price")}finally{ae("")}}async function $o(e,t){const s=(t??e.displayTitle??"").toString().trim();if(!s){p.error("Enter a product name");return}const r={displayName:s,...j(e)?{name:s}:{}};try{ae(`name-${e.id}`),await ct(e,r),gt(i=>({...i,[e.id]:s})),Se(""),p.success("Name updated")}catch(i){p.error(i.message||"Unable to update name")}finally{ae("")}}async function zo(e,t){const s=(t??e.displaySummary??"").toString().trim(),r={displayDescription:s,...j(e)?{description:s}:{}};try{ae(`description-${e.id}`),await ct(e,r),U(i=>({...i,[e.id]:s})),Se(""),p.success("Description updated")}catch(i){p.error(i.message||"Unable to update description")}finally{ae("")}}async function Vo(e,t){const s=Pt(t??ze(e));try{ae(`category-${e.id}`),await ct(e,{displayCategoryIds:s}),Se(""),p.success("Categories updated")}catch(r){p.error(r.message||"Unable to update categories")}finally{ae("")}}async function an(e,t=[]){const s=t[0];if(s)try{if(ae(`image-${e.id}`),!Object.keys(ga).includes(s.type))throw new Error("Invalid file type");if(s.size>pa)throw new Error("File size exceeds 10MB");const r=await ll(s,{scope:h?"business-products":"client-products",targetId:h?e.id:e.catalogEntryId||e.productId||e.id||e.clientProductId,tenantId:Y});await ct(e,{displayImageUrl:r.highResUrl,displayThumbnailUrl:r.thumbnailUrl}),Pe(i=>({...i,[e.id]:r.highResUrl})),p.success("Image updated")}catch(r){p.error(r.message||"Unable to update image")}finally{ae("")}}async function Ko(){if(!(K!=null&&K.source)||!(K!=null&&K.target))return;const{source:e,target:t}=K,s=(e.displayImageUrl||"").trim(),r=(e.displayThumbnailUrl||e.displayImageUrl||"").trim();if(!s){Aa(null),p.error("Source product does not have an image.");return}try{ae(`image-${t.id}`),await ct(t,{displayImageUrl:s,displayThumbnailUrl:r}),Pe(i=>({...i,[t.id]:s})),p.success("Image applied"),Aa(null)}catch(i){p.error(i.message||"Unable to apply image")}finally{ae("")}}function Wo(e,t){!(e!=null&&e.id)||!(t!=null&&t.id)||e.id===t.id||e.displayImageUrl&&Aa({source:e,target:t})}function sn(e){Ea(t=>{const s=new Set(t);return s.has(e)?s.delete(e):s.add(e),Array.from(s)})}function Qo(){Yr(!1),Ea([]),Xr(!0),ni(""),oi(""),di(""),mi(""),gi(""),hi([]),yi(!0),bi("all"),ti(""),si(""),ri(!0),xi(!0),Rs([]),Fa(!1)}const qt=l.useCallback((e=[])=>[...e].sort((t,s)=>{const r=Number(t==null?void 0:t.displaySortOrder),i=Number(s==null?void 0:s.displaySortOrder);return Number.isFinite(r)&&Number.isFinite(i)&&r!==i?r-i:Number.isFinite(r)&&!Number.isFinite(i)?-1:!Number.isFinite(r)&&Number.isFinite(i)?1:((t==null?void 0:t.displayName)||(t==null?void 0:t.name)||"").localeCompare((s==null?void 0:s.displayName)||(s==null?void 0:s.name)||"")}),[]),ns=l.useCallback((...e)=>{const t=new Map;return e.flat().forEach(s=>{const r=bs(s);r&&s.itemType!=="package"&&t.set(r,{...s,id:s.id||r})}
2),qt(Array.from(t.values()))},[qt]),sr=l.useCallback(e=>{const t=e.client||e.business||{},s=qt((e.products||[]).filter(i=>(i==null?void 0:i.type)!=="visit")),r={};he(t),h||oo(vd(t)),$(s),Array.isArray(e.catalogCategories)&&Gr(e.catalogCategories),Ue(ns(e.products||[])),s.forEach(i=>{r[`product_${i.id}`]=i.showPatient!==void 0?i.showPatient:!0}),N(r),pt(s.reduce((i,n)=>(i[n.id]=n.customerPrice!==null&&n.customerPrice!==void 0?String(n.customerPrice):"",i),{})),gt(s.reduce((i,n)=>(i[n.id]=n.displayName||"",i),{})),U(s.reduce((i,n)=>(i[n.id]=n.displayDescription||"",i),{})),Pe(s.reduce((i,n)=>(i[n.id]=n.displayImageUrl||"",i),{}))},[h,ns,qt]),et=l.useCallback(async()=>{if(!Y){jt(!1);return}try{if(jt(!0),h){const n=await Vn(O,Y,{includeInactive:!0});sr(n);return}if(!Vi||!Rt.current){jt(Li.current);return}const e={includeInactiveClientEntries:!0,includeClientOwnedProducts:!0,skipFormCoverage:!0,clientData:Rt.current,providerNetworkBrandingMap:{...Qc(Rt.current||{}),...ji.current},allowLegacyFallback:!1,includeLabProducts:!0},t=await Hc(O,Y,e),s=t.products||[],r=s.filter(n=>n.type==="lab"),i=s.filter(n=>n.type!=="lab");sr({...t,products:i}),He(r),Ue(ns(i,r))}catch(e){console.error("Error fetching data:",e),p.error("Unable to load products. Please try again.")}finally{jt(!1)}},[sr,Vi,h,ns,Y]);l.useEffect(()=>{et()},[et]);const rn=l.useRef(null);l.useEffect(()=>{!Y||k.length===0||rn.current!==Y&&(rn.current=Y,Gc({products:k,scope:h?"business-products":"client-products",tenantId:Y}).catch(e=>{console.warn("Catalog thumbnail backfill request failed",e)}))},[h,k,Y]);async function Ae(e,t={}){const s=we.currentUser;if(!s)throw new Error("Not authenticated");const r=await s.getIdToken(),i=await fetch(Mr("manageProduct"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({action:e,...t})}),n=await i.json().catch(()=>null);if(!i.ok||!(n!=null&&n.success))throw Object.assign(new Error((n==null?void 0:n.error)||"Request failed"),{code:n==null?void 0:n.code});return n}async function rr(e,t){const{safePayload:s,labPatch:r}=Bu(t);if(await fs(e,s),Object.keys(r).length===0)return{patch:{}};try{return await Ae(t.itemType==="package"?"updatePackage":"saveTenantCatalogProduct",{clientId:m,productId:e.id,...r})}catch(i){throw await bl(e).catch(()=>{}),i}}async function nn(e,t={}){const s=we.currentUser;if(!s)throw new Error("Not authenticated");const r=await s.getIdToken(),i=await fetch(Mr("manageSubscription"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({action:e,...t})}),n=await i.json().catch(()=>null);if(!i.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||"Unable to update subscription settings");return n}function Ho(){Mt(!1),Ot(null),Qs(!0)}async function Go(e,t="inactive"){var s;if(e!=null&&e.id)try{Ti(e.id);const r=(s=we.currentUser)==null?void 0:s.uid;if(!m||!r)throw new Error("Not authenticated");await fs(me(O,"Clients",m,"Products",e.id),{...Fr(t==="active"),updatedAt:Re(),updatedBy:r},{merge:!0}),p.success(t==="inactive"?"Product archived":"Product restored"),await et()}catch(r){console.error("Error archiving client product:",r),p.error(r.message||"Unable to update product.")}finally{Ti(null)}}async function ir(e,t={}){var $n;if(!xe)throw new Error("Client Admin access is required.");if(!(e!=null&&e.catalogEntryId||e!=null&&e.id)||!m)throw new Error("Unable to resolve source product for duplicate.");
2if((e==null?void 0:e.type)==="lab")throw new Error("Duplicate labs from the Labs page so biomarker validation is applied.");const s=($n=we.currentUser)==null?void 0:$n.uid;if(!s)throw new Error("Not authenticated");if(j(e)){const ue=await St(me(O,"Clients",m,"Products",e.catalogEntryId||e.id));if(!ue.exists())throw new Error("This product no longer exists. Refresh the catalog and try again.");const ne=ue.data()||{},Qe=me(fa(O,"Clients",m,"Products")),hr=`${e.displayName||e.name||ne.displayName||ne.name||"Product"} (Copy)`,yr={...Lr(ne),catalogScope:"client",clientId:m,providerNetworkId:null,businessId:null,productId:Qe.id,sourceProductId:null,legacyClientProductId:Qe.id,name:hr,displayName:hr,description:e.displayDescription||e.description||ne.displayDescription||ne.description||"",displayDescription:e.displayDescription||ne.displayDescription||e.description||ne.description||"",displayImageUrl:e.displayImageUrl||ne.displayImageUrl||"",displayThumbnailUrl:e.displayThumbnailUrl||ne.displayThumbnailUrl||e.displayImageUrl||ne.displayImageUrl||"",displayImageBackgroundColor:e.displayImageBackgroundColor||ne.displayImageBackgroundColor||"",status:"inactive",showPatient:!1,createdAt:Re(),createdBy:s,updatedAt:Re(),updatedBy:s},Mc=await rr(Qe,yr);return Object.assign(yr,Mc.patch||{}),{duplicateProduct:{...e,...yr,id:Qe.id,catalogEntryId:Qe.id,clientProductId:Qe.id,couponEligibleClientProductId:Qe.id,active:!1},label:hr}}const r=ya(e);if(!r)throw new Error("Unable to resolve source product for duplicate.");const i=me(O,"Clients",m,"Products",r),n=t.guidedCreation?null:await St(i);if(!t.guidedCreation&&!n.exists())throw new Error("This product no longer exists. Refresh the catalog and try again.");const o=(n==null?void 0:n.data())||{},d=hd(e,{clientId:m})||hl(o.sourceProductId)||hl(o.productId)||r;if(!d)throw new Error("Unable to resolve source product for duplicate.");const u=e.providerNetworkId||o.providerNetworkId||null,f=me(fa(O,"Clients",m,"Products")),T=f.id,Q=e.displayName||e.name||"Product",ee=Number.parseInt(e.quantityMonths,10),J=Number.isFinite(ee)&&ee>0?ee:Number.isFinite(Number(o.quantityMonths))&&Number(o.quantityMonths)>0?Number.parseInt(o.quantityMonths,10):1,z=Number.parseInt(e.prescriptionFillQuantity,10),re=Number.isFinite(z)&&z>0?z:Number.isFinite(Number(o.prescriptionFillQuantity))&&Number(o.prescriptionFillQuantity)>0?Number.parseInt(o.prescriptionFillQuantity,10):null,de=Array.isArray(e.displayCategoryIds)&&e.displayCategoryIds.length>0?[...e.displayCategoryIds]:Array.isArray(o.displayCategoryIds)?[...o.displayCategoryIds]:[],Ec=Array.isArray(e.approvedLabProductIds)&&e.approvedLabProductIds.length>0?[...e.approvedLabProductIds]:Array.isArray(o.approvedLabProductIds)?[...o.approvedLabProductIds]:[],Un=Array.isArray(e.addOns)&&e.addOns.length>0?e.addOns.map(ue=>({...ue})):Array.isArray(o.addOns)?o.addOns.map(ue=>({...ue})):[],_n=Math.max(0,Number.parseInt(t.includedVisitCount,10)||0),Tc=t.guidedCreation===!0?[...Un.filter(ue=>(ue==null?void 0:ue.type)!=="free_visit"),..._n>0?[{type:"free_visit",count:_n,expiresInDays:null}]:[]]:Un,zt={...Lr(o),catalogScope:"provider_network",productId:d,sourceProductId:d,providerNetworkId:u,clientId:m,type:e.type||o.type||"product",status:"inactive",showPatient:!1,customerPrice:e.customerPrice??o.customerPrice??null,quantityMonths:t.quantityMonths||J,prescriptionFillQuantity:re,displayName:t.guidedCreation?Q:`${Q} (Copy)`,displayDescription:e.displayDescription||o.displayDescription||"",displayImageUrl:e.displayImageUrl||o.displayImageUrl||"",displayThumbnailUrl:e.displayThumbnailUrl||o.displayThumbnailUrl||e.displayImageUrl||o.displayImageUrl||"",displayImageBackgroundColor:e.displayImageBackgroundColor||o.displayImageBackgroundColor||"",displayCategoryIds:de,displaySortOrder:e.displaySortOrder??o.displaySortOrder??null,requiresLabs:e.tenantRequiresLabs===!0||o.requiresLabs===!0||t.requiresLabs===!0,requiresSyncVisitOverride:e.requiresSyncVisitOverride===!0||o.requiresSyncVisitOverride===!0||t.requiresSyncVisit===!0,approvedLabProductIds:Ec,addOns:Tc,...t.creationMode?{creationMode:t.creationMode}:{},reviewNetworkLabel:e.reviewNetworkLabel||o.reviewNetworkLabel||"",storageModel:"scoped"}
2,Fc={...zt,createdAt:Re(),createdBy:s,updatedAt:Re(),updatedBy:s},Ac=await rr(f,Fc);Object.assign(zt,Ac.patch||{});const Rc=t.guidedCreation?me(O,"ProviderNetworks",u,"Products",d):i;try{const ue=await Od(fa(Rc,"Formulary"));for(let ne=0;ne<ue.docs.length;ne+=400){const Qe=Bd(O);ue.docs.slice(ne,ne+400).forEach(fr=>{Qe.set(me(fa(f,"Formulary"),fr.id),{...fr.data(),updatedAt:Re(),updatedBy:s})}),await Qe.commit()}}catch(ue){throw await bl(f),ue}return{duplicateProduct:{...e,...zt,id:T,catalogEntryId:T,clientProductId:T,couponEligibleClientProductId:T,productId:d,sourceProductId:d,active:!1,tenantRequiresLabs:zt.requiresLabs===!0,requiresLabs:zt.requiresLabs===!0||e.sourceRequiresLabs===!0},label:zt.displayName}}function nr(e=[]){e.length!==0&&($(t=>qt([...t,...e])),N(t=>e.reduce((s,r)=>({...s,[`product_${r.id}`]:!1}),t)),pt(t=>e.reduce((s,r)=>({...s,[r.id]:r.customerPrice!==null&&r.customerPrice!==void 0?String(r.customerPrice):""}),t)),gt(t=>e.reduce((s,r)=>({...s,[r.id]:r.displayName||""}),t)),U(t=>e.reduce((s,r)=>({...s,[r.id]:r.displayDescription||""}),t)),Pe(t=>e.reduce((s,r)=>({...s,[r.id]:r.displayImageUrl||""}),t)))}async function Yo(e){try{const{duplicateProduct:t,label:s}=await ir(e);nr([t]),Ma(""),Oa(t.catalogEntryId||t.id),sa(null),ta(t),Ft(!0),p.success(`Created "${s}"`)}catch(t){console.error("Error duplicating product:",t),p.error(t.message||"Unable to duplicate product.")}}async function Jo({sourceProduct:e,creationMode:t,configuration:s}){try{const r=me(O,"ProviderNetworks",e.providerNetworkId,"Products",e.sourceProductId);let i=await St(r);if(i.exists()||(i=await St(me(O,"Products",e.sourceProductId))),!i.exists()||i.data().status!=="active")throw new Error("This protocol is no longer available. Choose another protocol.");const n=i.data(),{duplicateProduct:o,label:d}=await ir({...n,...e,catalogScope:"provider_network",sourceRequiresLabs:n.requiresLabs===!0||n.requiresLab===!0,sourceRequiresSyncVisit:n.requiresSyncVisit===!0,tenantRequiresLabs:!1,requiresSyncVisitOverride:!1},{...s,creationMode:t,guidedCreation:!0});nr([o]),Ma(""),Oa(o.catalogEntryId||o.id),sa(null),ta(o),Ft(!0),p.success(`Created "${d}"`)}catch(r){throw console.error("Error creating guided product:",r),p.error(r.message||"Unable to create product."),r}}function ln(e){const t=ya(e);!t||!m||!xe||e.type==="lab"||w({id:t})}async function Zo(e){const t=await St(me(O,"Clients",m,"Products",e));if(!t.exists()||t.data().itemType!=="package")throw new Error("This package no longer exists. Refresh affected packages.");Ot({...t.data(),id:t.id,catalogEntryId:t.id}),Mt(!0)}async function Xo(e){var s;if(!(e!=null&&e.catalogEntryId||e!=null&&e.id)||!m){p.error("Unable to resolve source package for duplicate.");return}const t=(s=we.currentUser)==null?void 0:s.uid;if(!t){p.error("Not authenticated");return}try{const r=await St(me(O,"Clients",m,"Products",e.catalogEntryId||e.id)),i=r.exists()?r.data()||{}:{};if(i.itemType!=="package"){p.error("This item is not a package.");return}const n=me(fa(O,"Clients",m,"Products")),d=`${i.displayName||i.name||e.displayName||e.name||"Package"} (Copy)`,u={...Lr(i),itemType:"package",catalogScope:"client",clientId:m,providerNetworkId:null,businessId:null,productId:n.id,sourceProductId:null,legacyClientProductId:n.id,name:d,displayName:d,status:"inactive",showPatient:!1,createdAt:Re(),createdBy:t,updatedAt:Re(),updatedBy:t};await rr(n,u),p.success(`Created "${d}"`),await et()}catch(r){console.error("Error duplicating package:",r),p.error(r.message||"Unable to duplicate package.")}}async function ec(e,t="inactive"){if(e!=null&&e.id)try{Ai(e.id),await Ae("archivePackage",{clientId:m,productId:e.id,status:t}),p.success(t==="inactive"?"Package archived":"Package restored"),await et()}catch(s){console.error("Error archiving package:",s),p.error(s.message||"Unable to update package.")}finally{Ai(null)}}async function on(e){const s=!(e.status!=="inactive");if(s&&!h){const r=ms({product:e,platformBilling:b==null?void 0:b.platformBilling,clientModel:(E==null?void 0:E.model)||(b==null?void 0:b.model)});if(r.blocked){At({open:!0,reason:r.reason,product:e,count:1});return}}if(e.itemType==="package"){await ec(e,s?"active":"inactive");return}if(j(e)){await Go(e,s?"active":"inactive");return}try{await ct(e,Fr(s)),s||N(r=>({...r,[`product_${e.id}`]:!1})),p.success(s?"Product activated":"Product deactivated")}catch(r){p.error(r.message||"Unable to update product.")}}function cn(e){return!h&&ps(e)?ml({client:E,path:pl(m,ps(e))}):""}function lr(e){navigator.clipboard.writeText(e),Ri(e),p.success("Package checkout URL copied"),setTimeout(()=>Ri(null),2e3)}function tc(e){Wl(e),$r(!0)}function dn(e){const t=Dr(e.addOns),s=q.find(n=>(n==null?void 0:n.planType)!=="program"&&((n==null?void 0:n.productRefs)||[]).some(o=>String((o==null?void 0:o.clientProductId)||"")===String(e.catalogEntryId||e.clientProductId||e.id||""))),r=ul(e.prescriptionFillQuantity),i=ul(e.prescriptionRefills,{allowZero:!0});return{displayName:e.displayName||e.name||"",displayDescription:e.displayDescription||e.description||"",dis
2playImageUrl:e.displayImageUrl||"",displayThumbnailUrl:e.displayThumbnailUrl||"",displayImageBackgroundColor:e.displayImageBackgroundColor||"",customerPrice:e.customerPrice!=null?String(e.customerPrice):"",syncVisitPrice:wd(e.syncVisitPrice),shippingPrice:e.shippingPrice!=null?String(e.shippingPrice):"",supplyUnit:Rd(e).unit,quantityMonths:e.quantityMonths!=null?String(e.quantityMonths):"1",quantityWeeks:e.quantityWeeks!=null?String(e.quantityWeeks):"",prescriptionFillQuantity:r==null?"":String(r),prescriptionRefills:i==null?"":String(i),displayCategoryIds:ze(e),excludedStates:pu(e.tenantExcludedStates??e.excludedStates),catalogActive:e.status!=="inactive",showPatient:e.showPatient!==!1,showSupplyDetailsOnStorefront:e.showSupplyDetailsOnStorefront===!0,requiresLabs:e.itemType==="package"?e.requiresLabs===!0:e.tenantRequiresLabs===!0,approvedLabProductIds:Array.isArray(e.approvedLabProductIds)?e.approvedLabProductIds.map(n=>String(n).trim()).filter(Boolean):[],requiredLabPriceOverrides:Array.isArray(e.requiredLabPriceOverrides)?e.requiredLabPriceOverrides:[],freeVisitEnabled:!!t,freeVisitCount:t!=null&&t.count?String(t.count):"",freeVisitExpiration:t!=null&&t.expiresInDays?String(t.expiresInDays):"",subscriptionEnabled:!!(s&&s.status!=="inactive"),subscriptionPeriodCount:String(Math.max(1,Number(s==null?void 0:s.periodCount)||1)),subscriptionPeriodUnit:_d(s==null?void 0:s.periodUnit,{isStaging:gd().isStaging}),subscriptionBillingMode:Ud(s),subscriptionOfferOneTime:(s==null?void 0:s.checkoutOfferOneTime)!==!1,subscriptionOfferSubscription:(s==null?void 0:s.checkoutOfferSubscription)!==!1,formId:j(e)&&e.formId||"",prescriptionDirections:e.prescriptionDirections||"",clientPrescribingNote:e.clientPrescribingNote||"",clinicalDifferenceStatement:e.clinicalDifferenceStatement||"",dirxMedicalNecessityStatement:e.dirxMedicalNecessityStatement||"",includedProductIds:Array.isArray(e.includedProducts)?Pt(e.includedProducts.map(n=>(n==null?void 0:n.clientProductId)||(n==null?void 0:n.productId))):[],syncVisitAudience:e.syncVisitAudience||"all",requiresSyncVisitOverride:e.itemType==="package"?e.requiresSyncVisitOverride===!0:e.tenantRequiresSyncVisit===!0||e.requiresSyncVisitOverride===!0||e.requiresSyncVisit===!0&&e.sourceRequiresSyncVisit!==!0,labFirstWorkflow:Ed(e.labFirstWorkflow),refillReminder:Ld(e.refillReminder),clinicalRulesWindowPrices:e.clinicalRulesWindowPrices&&typeof e.clinicalRulesWindowPrices=="object"&&!Array.isArray(e.clinicalRulesWindowPrices)?Object.fromEntries(Object.entries(e.clinicalRulesWindowPrices).map(([n,o])=>[n,o==null||o===""?"":String(o)])):{},productCheckoutSummary:Fd({...Ad,...e.productCheckoutSummary&&typeof e.productCheckoutSummary=="object"?e.productCheckoutSummary:{}})}}async function un({product:e,enabled:t,periodCount:s,periodUnit:r,billingMode:i,checkoutOfferOneTime:n,checkoutOfferSubscription:o,payload:d}){var Q,ee,J,z;if(!Ga||!m)return;const u=String(e.catalogEntryId||e.clientProductId||e.id||"").trim();if(!u)throw new Error("Unable to resolve the subscription product");const f=q.find(re=>(re==null?void 0:re.planType)!=="program"&&((re==null?void 0:re.productRefs)||[]).some(de=>String((de==null?void 0:de.clientProductId)||"")===u));if(!t){f!=null&&f.id&&f.status!=="inactive"&&await nn("archiveSubscription",{scope:"client",ownerId:m,subscriptionId:f.id,status:"inactive"}),await((ee=(Q=ft.current)==null?void 0:Q.refresh)==null?void 0:ee.call(Q));return}const T={scope:"client",ownerId:m,planType:"subscription",title:d.displayName,description:d.displayDescription,price:d.customerPrice,periodCount:s,periodUnit:r,billingMode:i,checkoutOfferOneTime:n!==!1,checkoutOfferSubscription:o!==!1,productRefs:[{clientProductId:u}],status:d.status,showPatient:d.showPatient};await nn(f!=null&&f.id?"updateSubscription":"createSubscription",f!=null&&f.id?{...T,subscriptionId:f.id}:T),await((z=(J=ft.current)==null?void 0:J.refresh)==null?void 0:z.call(J))}async function ac({selectedProducts:e}){const t=e.map(d=>({clientProductId:bs(d)})),s=e.reduce((d,u)=>{const f=Number.parseFloat(u.customerPrice);return d+(Number.isFinite(f)?f:0)},0),r=await Ae("createPackage",{clientId:m,name:"New package",description:"",customerPrice:s.toFixed(2),status:"inactive",showPatient:!1,includedProducts:t}),i=r==null?void 0:r.productId;if(!i)throw new Error("The package was created without an identifier");const n=await St(me(O,"Clients",m,"Products",i)),o={id:i,catalogEntryId:i,clientProductId:i,productId:i,itemType:"package",catalogScope:"client",active:!1,...n.exists()?n.data():{}};$(d=>qt([...d,o])),Ot(o),Mt(!0),p.success("Package created. Finish its details before publishing.")}function Ut(e,t={}){if((e==null?void 0:e.itemType)==="package"){Ot(e),Mt(!0);return}Ma(t.focusSection||""),Oa(e.catalogEntryId||e.id||e.productId||""),sa(null),ta(e),Ft(!0)}function sc({requiredLabTests:e=[]}={}){Da.current=null,qs({}),ki({requiredLabTests:e}),Ft(!1)}function mn(){const e=Da.current;Da.current=null,Pi(e),Ft(!0),ki(null),qs({})}function rc({product:e,payload:t,parsedPrice:s}){const r=Object.prototype.hasOwnProperty.call(t,"requiresLabs")?t.requiresLabs===!0:e.tenantRequiresLabs===!0,i=r||e.sourceRequiresLabs===!0,n={...t,tenantRequiresLabs:r,requiresLabs:i,...Object.prototype.hasOwnProperty.call(t,"excludedStates")?Nl(e,t.excludedStates):{}};$(o=>o.map(d=>d.id===e.id?{...d,...n}:d)),Ue(o=>o.map(d=>bs(d)===bs(e)?{...d,...n}:d)),N(o=>({...o,[`product_${e.id}`]:t.showPatient})),gt(o=>({...o,[e.id]:t.displayName})),U(o=>({...o,[e.id]:t.displayDescription})),Pe(o=>({...o,[e.id]:t.displayImageUrl})),pt(o=>({...o,[e.id]:s==null?"":String(s)}))}function ls(e,t,s){e(r=>{if(!Object.prototype.hasOwnProperty.call(r,t)||t===s)return r;const i={...r,[s]:r[t]};return delete i[t],i})}async function ic(e,t){const s=qa==null?void 0:qa.id,r=e.clientProductId;if(!s||!r)return;const i=o=>o.id===s?{...o,id:r,catalogEntryId:r,clientProductId:r,couponEligibleClientProductId:r,productId:e.productId||t.sourceProductId,sourceProductId:e.sourceProductId||null,duplicateIndex:e.duplicateIndex??null,isDuplicate:!!e.sourceProductId,providerNetworkId:e.providerNetworkId,providerNetworkName:e.providerNetworkName,reviewNetworkLabel:e.providerNetworkName,name:e.sourceProductName||t.name,description:t.description||"",type:e.type||t.type||o.type,status:e.status||o.status,showPatient:e.showPatient,sourceRequiresLabs:e.sourceRequiresLabs===!0,sourceRequiresSyncVisit:e.sourceRequiresSyncVisit===!0,requiresLabs:e.sourceRequiresLabs===!0||o.requiresLabs===!0,requiresSyncVisit:e.sourceRequiresSyncVisit===!0||o.tenantRequiresSyncVisit===!0,tenantRequiresLabs:e.requiresLabs===!0,supportedLabProductIds:e.supportedLabProductIds||null,approvedLabProductIds:e.approvedLabProductIds||[],requiredLabPriceOverrides:yl(o.requiredLabPriceOverrides,e.approvedLabProductIds||[]),requiredLabAudiences:yl(o.requiredLabAudiences,e.approvedLabProductIds||[]),labFirstWorkflow:e.labFirstWorkflow||{enabled:!1}}:o;$(o=>o.map(i)),Ue(o=>o.map(i)),ta(o=>
2o&&i(o)),_s(o=>o&&i(o)),sa(e),ls(pt,s,r),ls(gt,s,r),ls(U,s,r),ls(Pe,s,r),N(o=>{const d=`product_${s}`;if(!Object.prototype.hasOwnProperty.call(o,d)||s===r)return o;const u={...o,[`product_${r}`]:o[d]};return delete u[d],u});const n=Array.isArray(e.warnings)?e.warnings.filter(Boolean):[];n.length>0?p.warning(n.join(" ")):p.success("Provider network product changed")}function nc(e){const t=(e==null?void 0:e.itemType)==="package",s=t?cn(e):(e==null?void 0:e.itemType)==="subscription"||(e==null?void 0:e.itemType)==="form"?"":xn(e);if(!s){p.info("Patients start this from the storefront. There is no checkout link to preview.");return}if(t?e.status==="inactive":e.active===!1){p.info(`Activate this ${t?"package":"product"} to preview its intake.`);return}os(s)}function pn(e,t={}){const{ctaLabel:s="Start Intake",onAction:r}=t,i={...e,displayName:(ks[e.id]||e.displayName||e.name||"").trim(),displayDescription:(P[e.id]||e.displayDescription||e.description||"").trim(),displayImageUrl:_[e.id]||e.displayImageUrl,customerPrice:Ca[e.id]!==void 0?Ca[e.id]:e.customerPrice};return a.jsx(mu,{product:i,categoryById:ko,getProductCategoryIds:go,getIncludedFreeVisitCount:po,priceByClientProductId:wo,labPriceByProductId:D,categoriesLoading:!1,searchTerm:ke,accentColor:C,ctaLabel:s,onAction:r||(()=>nc(e))},i.id)}function or(e,t){navigator.clipboard.writeText(e),Lt(e),p.success(`${t} URL copied to clipboard`),setTimeout(()=>Lt(null),2e3)}function os(e){window.open(e,"_blank")}const ke=$l.trim(),la=l.useMemo(()=>Ce.filter(e=>{const t=qr(e);if(rt==="active"&&!t||rt==="inactive"&&t||Et&&!Tr(e,I))return!1;const s=ze(e);if(!zi(s)||Wt.length>0&&!Wt.some(T=>s.includes(T))||Qt.length>0&&!Qt.includes(Ya(e)))return!1;const r=wa(e);if(Ht.length>0&&!Ht.includes(r)||Gt.length>0&&!Gt.includes(es(e))||Yt.length>0&&!Yt.includes(ts(e))||Tt.length>0&&!Tt.includes(as(e))||Jt.length>0&&!Jt.includes(ss(e)))return!1;if(!ke)return!0;const i=ke.toLowerCase(),n=(e.name||"").toLowerCase(),o=(e.description||"").toLowerCase(),d=(e.displayName||"").toLowerCase(),u=(e.displayDescription||"").toLowerCase();return n.includes(i)||o.includes(i)||d.includes(i)||u.includes(i)||[e.id,e.catalogEntryId,e.clientProductId,e.productId,e.sourceProductId,e.clientId,e.businessId,e.providerNetworkId].some(f=>String(f||"").toLowerCase().includes(i))}),[ke,Wt,ze,as,ts,Ya,ss,es,Tt,I,Yt,Qt,Jt,Gt,zi,Ce,rt,Et,Ht]),cr=l.useCallback(e=>{const t=Xi(e),s=j(e)?(E==null?void 0:E.name)||"Client":Ja(e)||"Network",r=qr(e),i=Tr(e,I),n=ot(e),o=Rr({product:e,mappingCount:n,hasFormularyPharmacies:se.length>0||n>0||Te,isClientOwnedProduct:j,prescribeByProductEnabled:bt,resolvePackagePairing:lt});return{...e,active:r,showOnStorefront:i,displayTitle:e.displayName||e.name||"Untitled product",displaySummary:e.displayDescription||e.description||"",categoryNames:t,categorySort:t.join(", "),ownerLabel:s,ownerSort:s,typeSort:Br[wa(e)]||Ar(e),priceSort:Number(e.customerPrice??0),formularyMappingCount:n,formularyReadiness:o}},[E==null?void 0:E.name,se.length,Te,I,Xi,ot,Ja,lt,j,bt]),gn=l.useRef(new WeakMap),kt=l.useMemo(()=>la.map(e=>{const t=cr(e),s=gn.current.get(e);return s&&Ku(s,t)?s:(gn.current.set(e,t),t)}),[cr,la]),{sortedData:dr,sortKey:_t,sortDirection:oa,handleSort:lc}=Id(kt,zl,Vl),fn=l.useMemo(()=>ke.trim()&&_t==="displayTitle"&&oa==="asc"?[...dr].sort((e,t)=>yd(e.displayTitle,t.displayTitle,ke)):dr,[ke,dr,oa,_t]);l.useEffect(()=>{Ur(_t)},[Ur,_t]),l.useEffect(()=>{_r(oa)},[_r,oa]),l.useEffect(()=>{if(!Ze)return;const e=ia.current.find(t=>t.id===Ze);e&&Ve(e)},[Ve,Ze]);const hn=Tt.length>0||_t==="formularyMappingCount";l.useEffect(()=>{hn&&ia.current.forEach(e=>{Ve(e)})},[tr,Ve,hn]);const ur=l.useMemo(()=>{const e=kt.filter(t=>t.showOnStorefront&&Yc(t)).sort((t,s)=>(t.displayTitle||"").localeCompare(s.displayTitle||""));return[...e.filter(t=>t.itemType==="package"),...e.filter(t=>t.itemType!=="package")]},[kt]),yn=l.useMemo(()=>new Map,[]),oc=l.useMemo(()=>Ge.filter(e=>Bl(e,m)).map(e=>{const t=Gi(e),s=t.length,r=Rr({product:e,mappingCount:s,hasFormularyPharmacies:se.length>0||s>0||Te,isClientOwnedProduct:j,prescribeByProductEnabled:bt,resolvePackagePairing:lt});return{...e,formularyMappingCount:s,formularyReadiness:r,formularyMedicationLabels:t.map(i=>yn.get(i)||i)}}),[se.length,Te,yn,Gi,lt,j,Ge,m,bt]),bn=l.useMemo(()=>!Qa&&!Fe?null:Fe||{id:"new-package",itemType:"package",catalogScope:"client",status:"active",showPatient:!0,displayName:"",displayDescription:"",displayImageUrl:"",displayThumbnailUrl:"",displayImageBackgroun
2dColor:"",customerPrice:"",syncVisitPrice:"",shippingPrice:"",displayCategoryIds:[],requiresLabs:!1,approvedLabProductIds:[],requiresSyncVisitOverride:!1,includedProducts:[]},[Fe,Qa]),xn=e=>!h&&ps(e)?ml({client:E,path:pl(m,ps(e))}):"",wt=l.useMemo(()=>new Set(Zr),[Zr]),cs=l.useMemo(()=>la.filter(e=>e.itemType!=="subscription"&&(h?!0:!!xt(e.id,e.clientProductId))),[la,xt,h]),ca=l.useMemo(()=>cs.map(e=>e.id),[cs]),vn=l.useMemo(()=>ca.length>0&&ca.every(e=>wt.has(e)),[ca,wt]),H=l.useMemo(()=>cs.filter(e=>wt.has(e.id)),[cs,wt]),da=l.useMemo(()=>vr({requiredLabTests:H.flatMap(e=>vr(e))}),[H]),cc=da.map(e=>e.id).sort().join("|"),mr=l.useMemo(()=>jl(H.filter(e=>!j(e)&&e.sourceRequiresLabs===!0&&Array.isArray(e.supportedLabProductIds)).map(e=>Pt(e.supportedLabProductIds||[]))),[H,j]),dc=mr===null?"none":mr.join("|");l.useEffect(()=>{Xt([]),Rs([]),Bs(!1)},[dc,cc]),l.useEffect(()=>{var s;if(!B)return;const e=kt.find(r=>[r.id,r.productId,r.clientProductId].some(i=>i&&String(i)===B));if(!e)return;((s=e.formularyReadiness)==null?void 0:s.status)!=="ineligible_package"&&Vs(e.id);const t=new URLSearchParams(Z);t.delete("product"),pe(t)},[Z,kt,B,pe]);const ua=l.useMemo(()=>{var t;if(!Ze)return null;const e=kt.find(s=>
2s.id===Ze)||Ce.find(s=>s.id===Ze)||null;return!e||((t=e.formularyReadiness)==null?void 0:t.status)==="ineligible_package"||!e.formularyReadiness&&Ct(e)&&!Cr(e,{catalogProducts:k,protocolMappingsByKey:_e}).eligible?null:e},[_e,Ze,kt,k,Ce]),uc=l.useMemo(()=>new Set,[]),kn=H.length>0,$t=l.useMemo(()=>H.filter(e=>e.itemType!=="package"&&xe),[H,xe]),wn=l.useMemo(()=>H.filter(e=>!j(e)&&(e==null?void 0:e.providerNetworkId)&&(e==null?void 0:e.itemType)!=="package"),[H,j]);async function Pn(e){var i;if(H.length===0){p.error("Select at least one product.");return}const t=we.currentUser;if(!t){p.error("Not authenticated");return}let s=H,r=null;if(e&&!h){const n=[];if(s=H.filter(o=>{const d=ms({product:o,platformBilling:b==null?void 0:b.platformBilling,clientModel:(E==null?void 0:E.model)||(b==null?void 0:b.model)});return d.blocked?(n.push({product:o,reason:d.reason}),!1):!0}),n.length){const o=n.filter(f=>f.reason===dt.PLATFORM_PAYMENT),d=o.length>0,u=d?o:n.filter(f=>f.reason===dt.APPROVED_LABS);if(r={open:!0,reason:d?dt.PLATFORM_PAYMENT:dt.APPROVED_LABS,product:((i=u[0])==null?void 0:i.product)||null,count:u.length},s.length===0){At(r);return}}}nt(e?"activate":"deactivate");try{const n=[];for(const d of s){if(d.itemType==="package"){await Ae("archivePackage",{clientId:m,productId:d.id,status:e?"active":"inactive"}),n.push(d.id);continue}const u=xt(d.id,d.clientProductId);if(!u)throw new Error(`Client product not found for ${d.name||d.id}`);await fs(u,{...Fr(e),updatedAt:Re(),updatedBy:t.uid},{merge:!0}),n.push(d.id)}const o=new Set(n);$(d=>d.map(u=>o.has(u.id)?{...u,active:e,showOnStorefront:e?Tr({...u,status:"active",showPatient:u.showPatient},I):!1,status:e?"active":"inactive",showPatient:e?u.showPatient:!1}:u)),e||N(d=>n.reduce((u,f)=>({...u,[`product_${f}`]:!1}),d)),p.success(`${e?"Activated":"Deactivated"} ${n.length} product${n.length===1?"":"s"}`)}catch(n){console.error("Error applying bulk status:",n),p.error(n.message||"Unable to update products.")}finally{nt("")}r&&At(r)}async function Ie(e,t,s,r=H){if(r.length===0){p.error("Select at least one product.");return}const i=we.currentUser;if(!i){p.error("Not authenticated");return}nt(e);try{const n=await Promise.all(r.map(async d=>{const u=xt(d.id,d.clientProductId);if(!u)throw new Error(`Client product not found for ${d.name||d.id}`);const f=typeof t=="function"?t(d):t;if(e==="sync-visit"&&d.itemType==="package")return await Ae("updatePackage",{clientId:m,productId:u.id,...f}),{productId:d.id,fields:f};if(e==="sync-visit"||Fl(f)){const T=await Ae("saveTenantCatalogProduct",{...h?{businessId:$e}:{clientId:m},productId:u.id,...f});return{productId:d.id,fields:T.patch||{}}}return await Md(u,{...f,updatedAt:Re(),updatedBy:i.uid}),{productId:d.id,fields:f}})),o=n.reduce((d,u)=>(d[u.productId]=u.fields,d),{});return $(d=>d.map(u=>{if(!Object.prototype.hasOwnProperty.call(o,u.id))return u;const f=o[u.id];if(!Object.prototype.hasOwnProperty.call(f,"requiresLabs"))return{...u,...f};const T=f.requiresLabs===!0,Q=T||u.sourceRequiresLabs===!0;return{...u,...f,tenantRequiresLabs:T,requiresLabs:Q}})),p.success(`${s} for ${n.length} product${n.length===1?"":"s"}`),!0}catch(n){return console.error("Error applying bulk update:",n),p.error(n.message||"Unable to update products. Please try again."),!1}finally{nt("")}}async function mc(){if(!X){p.error("You do not have permission to update product pricing");return}const e=Dt(ii,{allowBlank:!1,min:0});if(e.error){p.error("Enter a valid price.");return}await Ie("price",{customerPrice:e.value},"Price updated")}async function pc(){await Ie("storefront",{showPatient:Ts===!0},"Storefront visibility updated")&&N(t=>H.reduce((s,r)=>({...s,[`product_${r.id}`]:Ts===!0}),t))}async function gc(){if(!X){p.error("You do not have permission to update product pricing");return}const e=Dt(li,{allowBlank:!0,min:0});if(e.error){p.error("Enter a valid assessment price.");return}await Ie("assessment",{syncVisitPrice:e.value},"Assessment price updated")}async function fc(){const e=Dt(ci,{allowBlank:!0,min:0});if(e.error){p.error("Enter a valid shipping price.");return}await Ie("shipping",{shippingPrice:e.value===null?null:e.value.toFixed(2)},"Shipping updated")}async function hc(){const e=is(ui,{allowBlank:!1,min:1});if(e.error){p.error("Enter a valid month supply.");return}await Ie("month-supply",{quantityMonths:e.value},"Month supply updated")}async function yc(){const e=is(pi,{allowBlank:!0,min:1});if(e.error){p.error("Enter a valid quantity.");return}await Ie("quantity",{prescriptionFillQuantity:e.value},"Quantity updated")}async function bc(){const e=H.filter(s=>{var r;return s.itemType==="package"||s.sourceRequiresSyncVisit!==!0&&((r=s.labFirstWorkflow)==null?void 0:r.enabled)!==!0});if(e.length===0){p.error("The selected products require sync visits through their provider network or lab-first workflow.");return}const t=await Ie("sync-visit",s=>({[s.itemType==="package"?"requiresSyncVisitOverride":"requiresSyncVisit"]:As===!0,syncVisitAudience:Ta}),"Sync visit requirement updated",e);t&&e.length<H.length&&p.info("Products with provider-network or lab-first sync requirements were left unchanged."),t&&await et()}async function xc(){const e=Pt(fi);if(e.length===0){p.error("Choose at least one category.");return}await Ie("category",{displayCategoryIds:e},"Categories updated")}async function vc(e=[]){const t=e[0];if(t){if(!kn){p.error("Select at least one product.");return}try{if(nt("image"),!Object.keys(ga).includes(t.type))throw new Error("Invalid file type");if(t.size>pa)throw new Error("File size exceeds 10MB");const s=await ll(t,{scope:h?"business-products":"client-products",targetId:`${Y||"scope"}-bulk-${Date.now()}`,tenantId:Y});await Ie("image",{displayImageUrl:s.highResUrl,displayThumbnailUrl:s.thumbnailUrl},"Image updated")}catch(s){console.error("Error applying bulk image:",s),p.error(s.message||"Unable to upload image."),nt("")}}}async function kc(){if(A&&!Fs){await Ie("included-visits",{addOns:[]},"Included visits updated");return}const e=Number.parseInt((ei||"").toString().trim(),10);if(!Number.isFinite(e)||e<=0){p.error("Enter an included visit count greater than 0.");return}const t=(ai||"").toString().trim(),s=t?Number.parseInt(t,10):null;if(t&&(!Number.isFinite(s)||s<=0)){p.error("Enter a valid expiration in days, or leave it blank.");return}await Ie("included-visits",{addOns:[{type:"free_visit",count:e,expires
2InDays:s}]},"Included visits updated")}async function wc(){if(!(!m||Zt.length>0||Ms)){Os(!0),Bs(!1);try{const e=H.filter(u=>!j(u)&&u.sourceRequiresLabs===!0&&Array.isArray(u.supportedLabProductIds)),t=!h&&e.length>0?await El(e.map(u=>String(u.providerNetworkId||"").trim())):new Map,s=t.size>0?jl(e.map(u=>Pt([...u.supportedLabProductIds||[],...(t.get(String(u.providerNetworkId||"").trim())||{})[hs(u)]||[]])))||[]:[],i=(await dl(O,{clientId:m,businessId:h?$e:null,supportedLabProductIds:mr,networkQualifiedLabProductIds:s,additionalLabConstraints:H.flatMap(u=>u.additionalLabConstraints||[])})).eligibleLabs||[];if(da.length===0){Xt(i);return}const n=new Set(H.map(u=>String(u.providerNetworkId||"").trim()).filter(Boolean)),o=new Set(H.map(u=>hs(u)).filter(Boolean)),d=await Cl({labs:i,requiredLabTests:da,providerNetworkId:n.size===1?[...n][0]:void 0,networkProductId:o.size===1?[...o][0]:void 0,onDeterministic:u=>{Xt(jr(u)),Os(!1)}});Xt(jr(d.rows)),Bs(d.adjudicationUnavailable)}catch(e){console.error("Error loading bulk lab eligibility:",e),Xt([])}finally{Os(!1)}}}async function Pc(){const e=it?Pt(vi):[];if(it&&Zt.length===0){p.error("No eligible lab catalog offers are configured.");return}if(it&&e.length===0){p.error("Choose at least one approved lab.");return}const t=new Set(Zt.map(s=>s.id));if(it&&e.some(s=>!t.has(s))){p.error("Choose labs supported by the selected products.");return}await Ie("required-labs",{requiresLabs:it===!0,approvedLabProductIds:e,...it?{}:{requiredLabPriceOverrides:[],requiredLabAudiences:[],labFirstWorkflow:{enabled:!1}}},"Lab requirements updated")}async function Sc(){if($t.length===0){p.error("Select at least one product to duplicate.");return}nt("duplicate");try{const e=[];for(const t of $t){const s=await ir(t);e.push(s),nr([s.duplicateProduct]),Ea(r=>r.filter(i=>i!==t.id))}Fa(!1),p.success(`Duplicated ${e.length} product${e.length===1?"":"s"}`)}catch(e){console.error("Error bulk duplicating products:",e),p.error(e.message||"Unable to duplicate selected products.")}finally{nt("")}}const ds=R||st,pr=!!(ke||rt!=="all"||Et||Wt.length>0||Qt.length>0||Ht.length>0||Gt.length>0||Yt.length>0||Tt.length>0||Jt.length>0),Sn=ke?"No products match your search.":pr?"No products match the current filters.":"No products available.",Nc="Set up a payment processor before patients can purchase this product.",Cc=()=>!h&&Wa===!1,Ic=e=>{const t=e.itemType==="package",s=t?cn(e):xn(e);if(!s)return[];if(t){const ee=e.status==="inactive",J="Activate this package before sharing checkout links.",z=ol(s),re=cl(s),de=ee;return[{id:"product-first",label:"Product-first",description:vs.productFirst,copied:Ha===s,disabled:de,disabledTooltip:de?J:void 0,onCopy:()=>lr(s),onOpen:()=>window.open(s,"_blank")},{id:"assessment-first",label:"Assessment-first",description:vs.assessmentFirst,copied:Ha===z,disabled:de,disabledTooltip:de?J:void 0,onCopy:()=>lr(z),onOpen:()=>window.open(z,"_blank")},{id:"intake-first",label:"Intake-first",description:vs.intakeFirst,copied:Ha===re,disabled:de,disabledTooltip:de?J:void 0,onCopy:()=>lr(re),onOpen:()=>window.open(re,"_blank")}]}const r=ol(s),i=cl(s),n=zu(e),o=!e.active,d="Activate this product before sharing checkout links.",u=o,f=o?d:void 0,T=o?d:void 0,Q=u?d:void 0;return[{id:"product-first",label:"Product-first",description:n.productFirst,copied:ye===s,disabled:o,disabledTooltip:f,onCopy:()=>or(s,"Product-first"),onOpen:()=>os(s)},{id:"assessment-first",label:"Assessment-first",description:n.assessmentFirst,copied:ye===r,disabled:o,disabledTooltip:T,onCopy:()=>or(r,"Assessment-first"),onOpen:()=>os(r)},{id:"intake-first",label:"Intake-first",description:n.intakeFirst,copied:ye===i,disabled:u,disabledTooltip:Q,onCopy:()=>or(i,"Intake-first"),onOpen:()=>os(i)}]},Nn=e=>{const t=e.itemType==="package",s=e.itemType==="subscription",r=j(e),i=Ei===e.id,n=Fi===e.id;if(s){const o=e.status!=="inactive";return[{id:"edit-subscription",label:e.planType==="program"?"Edit program":"Edit subscription",onSelect:()=>{var d,u;return(u=(d=ft.current)==null?void 0:d.openEdit)==null?void 0:u.call(d,e.subscription)}},{id:"toggle-subscription",label:o?"Deactivate":"Activate",onSelect:()=>{var d,u;return(u=(d=ft.current)==null?void 0:d.archiveSubscription)==null?void 0:u.call(d,{...e.subscription,id:e.subscriptionId,status:o?"active":"inactive"})}}]}if(t){const o=e.status!=="inactive";return[{id:"edit",label:"Edit package",onSelect:()=>{Ot(e),Mt(!0)}},{id:"send-to-patient",label:"Send to Patient",disabled:e.status==="inactive",onSelect:()=>{Di(e),Oi(!0)}},xe&&{id:"duplicate",label:"Duplicate",onSelect:()=>Xo(e)},{id:"toggle-active",label:o?"Deactivate":"Activate",disabled:n,onSelect:()=>on(e)},xe&&r&&{id:"delete-package",label:"Delete package",danger:!0,disabled:n,onSelect:()=>ln(e)}
2].filter(Boolean)}return[{id:"edit",label:"Edit details",onSelect:()=>Ut(e)},!h&&ya(e)&&{id:"copy-id",label:"Copy ID",icon:pd,onSelect:()=>{(async()=>{try{await navigator.clipboard.writeText(ya(e)),p.success("ID copied")}catch{p.error("Could not copy ID")}})()}},{id:"preview",label:"Preview",onSelect:()=>tc(e)},!h&&(e==null?void 0:e.clientProductId)&&{id:"send-to-patient",label:"Send to Patient",disabled:!e.active,onSelect:()=>{$i(e),Ui(!0)}},xe&&{id:"duplicate",label:"Duplicate",onSelect:()=>Yo(e)},xe&&{id:"delete-product",label:"Delete product",danger:!0,onSelect:()=>ln(e)},(!r||xe)&&{id:"toggle-active",label:e.active?"Deactivate":"Activate",disabled:r?i:!1,onSelect:()=>on(e)}].filter(Boolean)},jc=Nn;function ma({product:e,fieldKey:t,value:s,placeholder:r="",inputMode:i="decimal",onBlur:n,disabled:o=!1}){return e.itemType==="subscription"?a.jsx("span",{className:"flex min-h-[76px] items-center justify-center px-1 text-xs text-content-tertiary max-lg:text-3xs",children:"—"}):a.jsx("div",{className:"flex min-h-[76px] items-center justify-center px-1","data-row-click-ignore":!0,children:a.jsx(Ee,{"data-table-cell-focus-target":!0,defaultValue:s??"",placeholder:r,inputMode:i,disabled:o||ie===`${t}-${e.id}`,onClick:d=>d.stopPropagation(),onKeyDown:Eo,onBlur:d=>n(e,d.currentTarget.value),className:"h-8 w-[5.25rem] rounded-md px-2 text-center text-xs max-lg:h-7 max-lg:w-[4.25rem] max-lg:px-1.5","aria-label":`${t} for ${e.displayTitle}`},`${t}-${e.id}-${s??""}`)})}function gr({product:e,fieldKey:t,checked:s,onChange:r,disabled:i=!1,label:n}){if(e.itemType==="subscription")return a.jsx("span",{className:"flex min-h-[76px] items-center justify-center px-1 text-xs text-content-tertiary max-lg:text-3xs",children:"—"});const o=i||ie===`${t}-${e.id}`;return a.jsx("div",{role:"button",tabIndex:o?-1:0,className:at("flex min-h-[76px] w-full items-center justify-center px-1 transition-colors 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-700/50 dark:focus-visible:ring-slate-500",o&&"cursor-not-allowed opacity-60 hover:bg-transparent dark:hover:bg-transparent"),onClick:d=>{d.stopPropagation(),o||r(e,!s)},onKeyDown:d=>{d.key!=="Enter"&&d.key!==" "||(d.preventDefault(),d.stopPropagation(),o||r(e,!s))},"data-row-click-ignore":!0,"data-table-cell-focus-target":!0,"aria-disabled":o,"aria-label":`${n} for ${e.displayTitle}`,children:a.jsx(De,{checked:s,disabled:o,tabIndex:-1,"aria-hidden":"true",className:"size-5 pointer-events-none max-lg:size-4"})})}function Cn(e){const t=String((e==null?void 0:e.clientProductId)||(e==null?void 0:e.productId)||"").trim();if(!t)return((e==null?void 0:e.name)||"").trim()||"—";const s=k.find(n=>(n==null?void 0:n.itemType)==="package"?!1:[n==null?void 0:n.id,n==null?void 0:n.clientProductId,n==null?void 0:n.productId,n==null?void 0:n.catalogEntryId].filter(Boolean).map(d=>String(d)).includes(t)),r=((s==null?void 0:s.displayName)||(s==null?void 0:s.name)||"").trim(),i=((e==null?void 0:e.name)||"").trim();return r||(i&&i!==t?i:i||t||"—")}const In=!h&&Object.values(y||{}).some(e=>e.legitScriptEnabled===!0),Lc=l.useMemo(()=>[In&&{id:"legitScript",header:"LS",renderHeader:()=>a.jsx("span",{title:"LegitScript approval","aria-label":"LegitScript approval",children:"LS"}),minWidth:56,fixedWidth:!0,align:"center",cellClassName:"p-2",renderCell:e=>e.legitScriptEnabled&&!j(e)&&["product","protocol"].includes(e.type)&&e.itemType!=="package"?a.jsx(bd,{approved:e.legitScriptApproved===!0}):a.jsx("span",{"aria-label":"Not applicable",children:"—"}),csvValue:e=>e.legitScriptEnabled&&["product","protocol"].includes(e.type)&&e.itemType!=="package"?e.legitScriptApproved?"Approved":"Not approved":"",skeletonClassName:"size-7"},Ye&&{id:"bulkSelect",header:"",minWidth:44,cellClassName:"p-0",renderHeader:()=>a.jsx(De,{checked:vn,onCheckedChange:e=>{Ea(e===!0?ca:[])},"aria-label":"Select all visible products"}),renderCell:e=>a.jsx("div",{role:"button",tabIndex:0,className:"flex h-[76px] w-full items-center justify-center max-lg:h-auto max-lg:min-h-8",onClick:t=>{t.stopPropagation(),sn(e.id)},onKeyDown:t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),t.stopPropagation(),sn(e.id))},"data-row-click-ignore":!0,"aria-label":`${wt.has(e.id)?"Deselect":"Select"} ${e.displayTitle}`,children:a.jsx(De,{checked:wt.has(e.id),"aria-hidden":"true",tabIndex:-1})}),skeletonClassName:"size-4 rounded"},{id:"image",header:"Image",minWidth:72,renderCell:e=>{if(e.itemType==="subscription")return a.jsx("div",{className:"flex min-h-[76px] items-center justify-center px-3 text-xs text-content-tertiary max-lg:px-2 max-lg:text-3xs",children:"—"});const t=!!e.displayImageUrl,{thumbnailUrl:s}=Jc(e);return a.jsx(kr,{accept:ga,multiple:!1,maxSize:pa,noClick:t,onDrop:r=>an(e,r),children:({getRootProps:r,getInputProps:i})=>a.jsxs("button",{type:"button",...r({onClick:n=>{n.stopPropagation(),t&&(n.preventDefault(),Ds(e))},onDragStart:n=>{t&&(n.stopPropagation(),n.dataTransfer.setData("application/x-genhealth-product-image",e.id),n.dataTransfer.effectAllowed="copy")},onDragOver:n=>{Array.from(n.dataTransfer.types||[]).includes("application/x-genhealth-product-image")&&(n.preventDefault(),n.stopPropagation(),n.dataTransfer.dropEffect="copy")},onDrop:n=>{const o=n.dataTransfer.getData("application/x-genhealth-product-image");if(!o)return;n.preventDefault(),n.stopPropagation();const d=k.find(u=>u.id===o);Wo(d,e)}}),className:"relative rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500","aria-label":t?`View image for ${e.displayTitle}`:`Upload image for ${e.displayTitle}`,"data-row-click-ignore":!0,draggable:t,children:[a.jsx("input",{...i()}),a.jsx(Kd,{src:s,alt:e.displayTitle,fallback:ie===`image-${e.id}`?a.jsx(V,{size:"md"}):e.itemType==="package"?a.jsx(Kn,{className:"size-4"}):a.jsx(xs,{className:"size-4"}),className:"size-10 rounded-lg max-lg:size-8"})]})})},skeletonClassName:"size-10 rounded-lg"},{id:"displayTitle",header:"Name",sortKey:"displayTitle",minWidth:200,cellClassName:"p-0 align-middle",csvValue:e=>e.displayTitle,renderCell:e=>{const t=e.itemType==="package"?e.includedProducts||[]:[];if(e.itemType==="subscription")return a.jsx("div",{className:"flex min-h-[76px] min-w-0 items-center px-3 py-2 max-lg:px-2 max-lg:py-1",children:a.jsx("button",{type:"button",className:`${ha} min-w-0 truncate text-left text-sm font-medium text-content-primary max-lg:text-2xs`,onClick:r=>{var i,n;r.stopPropagation(),(n=(i=ft.current)==null?void 0:i.openEdit)==null||n.call(i,e.subscription)},children:a.jsx(Sr,{text:e.displayTitle,highlight:ke})})});const s=`name-${e.id}`;return a.jsxs("div",{className:"flex min-h-[76px] min-w-0 items-center px-3 py-2 max-lg:px-2 max-lg:py-1",children:[a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col justify-center",children:[a.jsxs("span",{className:"flex max-w-full min-w-0 flex-wrap items-center gap-1.5 max-lg:gap-1",children:[Cc()?a.jsx(ba,{delayDuration:150,children:a.jsxs(xa,{children:[a.jsx(va,{asChild:!0,children:a.jsx("span",{className:"inline-flex shrink-0 items-center justify-center text-red-600 transition hover:text-red-700 dark:text-red-400 dark:hover:text-red-300","aria-label":"Payment processor missing",children:a.jsx(Wn,{className:"size-5 fill-red-600 stroke-white max-lg:size-4 dark:fill-red-500",strokeWidth:3})})}),a.jsx(ka,{side:"top",className:"max-w-xs text-xs",children:Nc})]})}):null,a.jsx(Pd,{open:ea===s,onOpenChange:r=>{Se(r?s:i=>i===s?"":i)},initialValue:e.displayTitle||"",accentColor:C,saving:ie===`name-${e.id}`,onSave:r=>$o(e,r),trigger:a.jsx("button",{type:"button",className:`${ha} min-w-0 truncate text-left text-sm font-medium text-content-primary max-lg:text-2xs`,onClick:r=>r.stopPropagation(),"data-row-click-ignore":!0,children:a.jsx(Sr,{text:e.displayTitle,highlight:ke})})})]}),t.length>0?a.jsxs("span",{className:"mt-1.5 flex min-w-0 items-center gap-1 max-lg:mt-1",children:[a.jsx("span",{className:"truncate rounded-md border border-subtle bg-surface-sunken px-2 py-0.5 text-xs font-normal text-slate-700 max-lg:px-1.5 max-lg:text-3xs dark:text-slate-300",title:Cn(t[0]),children:Cn(t[0])}),t.length>1?a.jsxs(wr,{variant:"outline",className:"shrink-0 rounded-md border-subtle bg-surface-sunken px-2 py-0.5 text-3xs font-normal text-content-tertiary max-lg:px-1.5",children:["+",t.length-1]}):null]}):e.itemType==="package"?a.jsx("span",{className:"mt-1 text-xs text-slate-400 max-lg:mt-0.5 max-lg:text-3xs dark:text-slate-500",children:"No protocols linked"}):null,e.active?e.showOnStorefront?null:a.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-3xs",children:"Hidden from storefront"}):a.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-3xs",children:"Inactive"})]}),a.jsx("span",{className:"flex shrink-0 items-center gap-1 pr-2",children:[{required:e.requiresSyncVisit===!0,Icon:Qn,label:"Telehealth visit required"},{required:e.requiresLabs===!0,Icon:Hn,label:"Labs required"}].filter(({required:r})=>r).map(({Icon:r,label:i})=>a.jsx(ba,{delayDuration:150,children:a.jsxs(xa,{children:[a.jsx(va,{asChild:!0,children:a.jsx(L,{type:"button",variant:"ghost",size:"icon","aria-label":i,className:"size-6 shrink-0 text-muted-foreground",onClick:n=>n.stopPropagation(),children:a.jsx(r,{className:"size-4","aria-hidden":!0})})}),a.jsx(ka,{side:"top",className:"text-xs",children:i})]})},i))})]})},skeletonClassName:"w-36"},A&&{id:"configStorefront",header:"Storefront",minWidth:104,align:"center",cellClassName:"p-0",headerClassName:"px-1",renderHeader:()=>
2a.jsx(mt,{label:"Storefront",tooltip:"Controls only whether an active product appears in the patient storefront. Direct checkout links stay available."}),renderCell:e=>gr({product:e,fieldKey:"storefront",checked:e.showOnStorefront===!0,disabled:!e.active,label:"Show on storefront",onChange:Oo}),skeletonClassName:"size-4 rounded"},A&&{id:"configPrice",header:"Price",sortKey:"priceSort",minWidth:88,align:"center",cellClassName:"p-0",headerClassName:"px-1",renderCell:e=>ma({product:e,fieldKey:"price",value:e.customerPrice==null?"":String(e.customerPrice),placeholder:"0.00",disabled:!X,onBlur:To}),skeletonClassName:"w-16"},A&&{id:"configAssessment",header:"Assessment",minWidth:116,align:"center",cellClassName:"p-0",headerClassName:"px-1",renderHeader:()=>a.jsx(mt,{label:"Assessment",tooltip:"Price for the visit or assessment. This charge is not refunded if the patient is denied."}),renderCell:e=>ma({product:e,fieldKey:"assessment",value:e.syncVisitPrice==null?"":String(e.syncVisitPrice),placeholder:"0",disabled:!X,onBlur:Fo}),skeletonClassName:"w-16"},A&&{id:"configShipping",header:"Shipping",minWidth:108,align:"center",cellClassName:"p-0",headerClassName:"px-1",renderHeader:()=>a.jsx(mt,{label:"Shipping"}),renderCell:e=>ma({product:e,fieldKey:"shipping",value:e.shippingPrice==null?"":String(e.shippingPrice),placeholder:"0.00",onBlur:Ao}),skeletonClassName:"w-16"},A&&{id:"configMonthSupply",header:"Months",minWidth:96,align:"center",cellClassName:"p-0",headerClassName:"px-1",renderHeader:()=>a.jsx(mt,{label:"Months",tooltip:"Month supply metadata that helps providers understand the intended duration of therapy when prescribing."}),renderCell:e=>{const t=h||e.itemType==="package"||j(e);return ma({product:e,fieldKey:"month-supply",value:t?"":e.quantityMonths==null?"1":String(e.quantityMonths),placeholder:"1",inputMode:"numeric",disabled:t,onBlur:Ro})},skeletonClassName:"w-14"},A&&{id:"configQuantity",header:"Quantity",minWidth:96,align:"center",cellClassName:"p-0",headerClassName:"px-1",renderHeader:()=>a.jsx(mt,{label:"Quantity",tooltip:"Pharmacy fill quantity, such as capsules or tablets. It helps prefill prescriptions, but providers can edit it."}),renderCell:e=>{const t=h||e.itemType==="package"||j(e);return ma({product:e,fieldKey:"quantity",value:t||e.prescriptionFillQuantity==null?"":String(e.prescriptionFillQuantity),placeholder:"Qty",inputMode:"numeric",disabled:t,onBlur:Mo})},skeletonClassName:"w-14"},A&&{id:"configIncludedVisits",header:"Included visits",minWidth:120,align:"center",cellClassName:"p-0",headerClassName:"px-1",renderHeader:()=>a.jsx(mt,{label:"Included visits",tooltip:"Adds included visit redemptions to the product purchase."}),renderCell:e=>a.jsx(Qu,{product:e,disabled:!X||e.itemType==="package",saving:ie===`included-visits-${e.id}`,accentColor:C,onSave:Bo}),skeletonClassName:"size-4 rounded"},A&&{id:"configSyncVisit",header:"Requires sync",minWidth:116,align:"center",cellClassName:"p-0",headerClassName:"px-1",renderHeader:()=>a.jsx(mt,{label:"Requires sync",tooltip:"Requires a live sync visit or assessment before this product can be completed."}),renderCell:e=>{const t=e.itemType!=="package"&&!j(e)&&e.sourceRequiresSyncVisit===!0;return gr({product:e,fieldKey:"sync-visit",checked:t||e.requiresSyncVisit===!0||e.requiresSyncVisitOverride===!0,disabled:t||!X||h,label:"Requires sync visit",onChange:Do})},skeletonClassName:"size-4 rounded"},A&&{id:"configRequiresLabs",header:"Requires labs",minWidth:112,align:"center",cellClassName:"p-0",headerClassName:"px-1",renderHeader:()=>a.jsx(mt,{label:"Requires labs",tooltip:"Requires labs before completion. Enabling this checks that eligible lab options exist and applies approved labs."}),renderCell:e=>{const t=e.itemType!=="package"&&!j(e)&&e.sourceRequiresLabs===!0;return gr({product:e,fieldKey:"requires-labs",checked:t||e.requiresLabs===!0,disabled:t||!X,label:"Requires labs",onChange:Uo})},skeletonClassName:"size-4 rounded"},!A&&{id:"displaySummary",header:"Description",sortKey:"displaySummary",minWidth:200,hideOnTablet:!0,cellClassName:"p-0 align-middle",csvValue:e=>e.displaySummary||"—",renderCell:e=>{if(e.itemType==="subscription")return a.jsx("div",{className:"flex min-h-[76px] items-center px-3 py-2 text-xs text-content-secondary max-lg:px-2 max-lg:py-1 max-lg:text-3xs",children:a.jsx("span",{className:"line-clamp-2",children:e.displaySummary||"—"})});const t=`description-${e.id}`;return a.jsx("div",{className:"flex min-h-[76px] items-center px-3 py-2 max-lg:px-2 max-lg:py-1",children:a.jsx(Sd,{open:ea===t,onOpenChange:s=>{Se(s?t:r=>r===t?"":r)},initialValue:e.displaySummary||"",accentColor:C,saving:ie===`description-${e.id}`,onSave:s=>zo(e,s),trigger:a.jsx("button",{type:"button",className:`${ha} max-w-full text-left`,onClick:s=>s.stopPropagation(),"data-row-click-ignore":!0,children:a.jsx("span",{className:"line-clamp-2 text-xs text-content-secondary max-lg:text-3xs",children:a.jsx(Sr,{text:e.displaySummary||"—",highlight:ke})})})})})},skeletonClassName:"w-52"},!A&&{id:"categorySort",header:"Category",sortKey:"categorySort",minWidth:160,hideOnMobile:!0,cellClassName:"p-0 align-middle",csvValue:e=>e.categorySort,renderCell:e=>{if(e.itemType==="subscription")return a.jsx("span",{className:"px-3 text-xs text-content-tertiary max-lg:px-2 max-lg:text-3xs",children:"—"});const t=`category-${e.id}`;return a.jsx("div",{className:"flex min-h-[76px] min-w-0 items-center px-3 py-2 max-lg:px-2 max-lg:py-1",children:a.jsx(Nd,{open:ea===t,onOpenChange:s=>{Se(s?t:r=>r===t?"":r)},initialCategoryIds:ze(e),categories:oe,accentColor:C,saving:ie===`category-${e.id}`,onSave:s=>Vo(e,s),trigger:a.jsxs("button",{type:"button",className:`${ha} inline-flex max-w-full min-w-0 flex-wrap items-center gap-1.5 text-left max-lg:gap-1 ${ie===`category-${e.id}`?" pointer-events-none opacity-60":""}`,onClick:s=>s.stopPropagation(),"data-row-click-ignore":!0,"aria-label":`Edit categories for ${e.displayTitle}`,children:[ie===`category-${e.id}`?a.jsx(Zc,{className:"size-3.5 shrink-0 animate-spin opacity-70","aria-hidden":!0}):null,e.categoryNames.length>0?e.categoryNames.map(s=>a.jsx(wr,{variant:"outline",className:`${Gn("slate")} max-w-[140px] truncate underline decoration-dotted underline-offset-2`,children:s},`${e.id}-${s}`)):a.jsx("span",{className:"font-normal text-content-tertiary opacity-70 max-lg:text-3xs",children:"No categories — click to add"})]})})})},skeletonClassName:"w-24 rounded-full"}
2,!A&&{id:"ownerSort",header:"Owner",sortKey:"ownerSort",minWidth:140,hideOnLg:!0,csvValue:e=>e.ownerLabel,renderCell:e=>j(e)?a.jsx(Xc,{accentColor:C,className:"max-w-[180px] truncate",children:e.ownerLabel}):a.jsx(ed,{primaryColor:Za(e),className:"max-w-[180px] truncate",children:e.ownerLabel}),skeletonClassName:"w-28 rounded-full"},!A&&{id:"typeSort",header:"Type",sortKey:"typeSort",minWidth:100,hideOnLg:!0,csvValue:e=>Ar(e),renderCell:e=>{const t=wa(e),s=Ar(e),r={product:"bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-300",protocol:"bg-violet-50 text-violet-700 dark:bg-violet-900/25 dark:text-violet-300",visit:"bg-emerald-50 text-emerald-700 dark:bg-emerald-900/25 dark:text-emerald-300",lab:"bg-amber-50 text-amber-700 dark:bg-amber-900/25 dark:text-amber-300",package:"bg-indigo-50 text-indigo-700 dark:bg-indigo-900/25 dark:text-indigo-300",subscription:"bg-emerald-50 text-emerald-700 dark:bg-emerald-900/25 dark:text-emerald-300",program:"bg-teal-50 text-teal-700 dark:bg-teal-900/25 dark:text-teal-300"};return a.jsx("span",{className:`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium max-lg:px-1.5 max-lg:text-3xs ${r[t]||r.product}`,children:s})},skeletonClassName:"w-16 rounded-full"},!A&&{id:"priceSort",header:"Price",sortKey:"priceSort",minWidth:100,cellClassName:"p-0 align-middle text-metric",csvValue:e=>e.itemType==="subscription"?Al(e):Pa(e.customerPrice)||"—",renderCell:e=>{if(e.itemType==="subscription")return a.jsx("div",{className:"flex min-h-[76px] w-full min-w-0 items-center px-3 py-2 text-sm font-medium text-content-primary max-lg:px-2 max-lg:py-1 max-lg:text-2xs",children:Al(e)});const t=`price-${e.id}`,s=e.customerPrice==null?"":String(e.customerPrice);return X?a.jsx("div",{className:"flex min-h-[76px] min-w-0 items-center px-3 py-2 max-lg:px-2 max-lg:py-1",children:a.jsx(Cd,{open:ea===t,onOpenChange:r=>{Se(r?t:i=>i===t?"":i)},initialValue:s,accentColor:C,saving:ie===`price-${e.id}`,onSave:r=>_o(e,r),trigger:a.jsx("button",{type:"button",className:`${ha} text-left text-sm font-medium text-content-primary max-lg:text-2xs`,onClick:r=>r.stopPropagation(),"data-row-click-ignore":!0,children:Pa(e.customerPrice)||"—"})})}):a.jsx("div",{className:"flex min-h-[76px] w-full min-w-0 items-center px-3 py-2 text-sm font-medium text-content-primary max-lg:px-2 max-lg:py-1 max-lg:text-2xs",children:Pa(e.customerPrice)||"—"})},skeletonClassName:"w-16"},!A&&vt&&{id:"formularyPairings",header:"Paired formulary",sortKey:"formularyMappingCount",align:"center",minWidth:152,hideOnLg:!0,csvValue:e=>{const t=e.formularyReadiness||{},s=e.formularyMappingCount||0;return t.label||(s===0?"No pairings":`${s} medication${s===1?"":"s"}`)},renderCell:e=>{const t=a.jsx(Wu,{productKey:tt(e),product:e,onVisible:Ve}),s=e.formularyReadiness||{};if(s.status==="ineligible_package")return a.jsx("div",{className:"flex justify-center","data-row-click-ignore":!0,children:a.jsx(ba,{delayDuration:150,children:a.jsxs(xa,{children:[a.jsx(va,{asChild:!0,children:a.jsx(wr,{variant:"outline",tabIndex:0,"data-table-cell-focus-target":!0,"aria-label":`${s.label}. ${s.description}`,className:Gn("slate","cursor-default whitespace-nowrap"),children:s.label})}),a.jsx(ka,{className:"max-w-sm",children:a.jsx("p",{className:"text-xs",children:s.description})})]})})});if(s.status==="ineligible_client_owned"||s.status==="ineligible_no_provider_network"||s.status==="no_formulary_pharmacy")return a.jsx("span",{className:"text-xs text-content-tertiary max-lg:text-3xs",children:s.label||"Not eligible"});const r=e.formularyMappingCount||0,i=s.status==="eligible_unpaired",n=Xa(e),o=n.hasPartialCoverage?`Paired pharmacies do not cover all 50 states. Missing: ${n.uncoveredStates.join(", ")}. Patients in these states will be routed to another available pharmacy; the provider chooses at prescribing time.`:"";return a.jsxs("div",{className:"flex justify-center","data-row-click-ignore":!0,children:[t,a.jsx(ba,{delayDuration:150,children:a.jsxs(xa,{children:[a.jsx(va,{asChild:!0,children:a.jsxs(L,{type:"button",variant:"outline",size:"sm",className:at("h-auto min-h-8 max-w-full justify-center whitespace-nowrap rounded-full px-3 py-1.5 max-lg:!min-h-6 max-lg:px-2 max-lg:py-0.5",i&&"border-amber-300 bg-amber-50 text-amber-800 hover:bg-amber-100 dar
2k:border-amber-800 dark:bg-amber-900/20 dark:text-amber-200 dark:hover:bg-amber-900/30",n.hasPartialCoverage&&!i&&"border-amber-300 bg-amber-50 text-amber-800 hover:bg-amber-100 dark:border-amber-800 dark:bg-amber-900/20 dark:text-amber-200 dark:hover:bg-amber-900/30"),onClick:d=>{d.stopPropagation(),Vs(e.id)},children:[i||n.hasPartialCoverage?a.jsx(Wn,{className:"mr-1.5 size-3.5"}):null,a.jsx("span",{className:at("text-xs",i||n.hasPartialCoverage?"font-medium":r===0?"text-content-tertiary":"font-medium text-slate-800 dark:text-slate-100"),children:s.label||(r===0?"No pairings":`${r} medication${r===1?"":"s"}`)})]})}),n.hasPartialCoverage?a.jsx(ka,{className:"max-w-sm",children:a.jsx("p",{className:"text-xs",children:o})}):null]})})]})},skeletonClassName:"w-28"},{id:"actions",header:"Actions",align:"center",fixedWidth:!0,minWidth:104,cellClassName:"px-2",renderCell:e=>{const t=Ic(e);return a.jsxs("div",{className:"flex items-center justify-center gap-1",children:[t.length>0?a.jsx(kd,{actions:t,label:`Checkout links for ${e.displayTitle}`,testId:fe("menu","products",`links-${e.id}`)}):null,a.jsx(Wd,{actions:Nn(e),label:`Open actions for ${e.displayTitle}`,testId:fe("menu","products",`row-${e.id}`)})]})},skeletonClassName:"w-7 rounded-md"}].filter(Boolean),[C,ea,ke,vn,Ye,ca,X,xe,oe,ie,Te,se,Wa,A,Ha,ye,Ve,ze,Xa,Za,j,h,Ei,Fi,k,wt,vt,In]),jn=[{id:"status",type:"custom",render:()=>a.jsx(L,{type:"button",variant:"outline",onClick:No,className:at("h-8 rounded-full border px-3 text-xs",rt==="all"?"border-subtle bg-surface-raised text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-slate-700":"hover:brightness-95"),style:rt!=="all"?{backgroundColor:us(C,.1),borderColor:us(C,.3),color:C}:void 0,"aria-label":`Status filter: ${fl[rt]}. Click to cycle.`,children:fl[rt]})},{id:"storefront",type:"custom",render:()=>a.jsx(L,{type:"button",variant:"outline",onClick:()=>Ps(e=>!e),className:at("h-8 rounded-full border px-3 text-xs",Et?"hover:brightness-95":"border-border bg-card text-foreground hover:bg-muted"),style:Et?{backgroundColor:us(C,.1),borderColor:us(C,.3),color:C}:void 0,"aria-pressed":Et,children:"Storefront only"})},{id:"categories",filters:Po,activeFilters:Wt,onFilterChange:Co,multiSelect:!0,defaultLabel:"Categories"},!h&&{id:"owner",filters:So,activeFilters:Qt,onFilterChange:Io,multiSelect:!0,defaultLabel:"Owner"},tn.length>1&&{id:"type",filters:tn,activeFilters:Ht,onFilterChange:jo,multiSelect:!0,defaultLabel:"Type"},{id:"price",filters:[{id:"priced",label:"Priced",count:Xe.price.priced},{id:"no-price",label:"No price",count:Xe.price["no-price"]}],activeFilters:Gt,onFilterChange:Cs,multiSelect:!0,defaultLabel:"Price"},{id:"image",filters:[{id:"with-image",label:"Has image",count:Xe.image["with-image"]},{id:"missing-image",label:"Missing image",count:Xe.image["missing-image"]}],activeFilters:Yt,onFilterChange:Is,multiSelect:!0,defaultLabel:"Images"},vt&&{id:"formulary",filters:[{id:"paired",label:"Paired",count:Xe.formulary.paired},{id:"unpaired",label:"Unpaired",count:Xe.formulary.unpaired},{id:"partial-coverage",label:"Partial state coverage",count:Xe.formulary["partial-coverage"]}],activeFilters:Tt,onFilterChange:js,multiSelect:!0,defaultLabel:"Formulary"},!h&&{id:"payment",filters:[{id:"payment-ready",label:"Payment ready",count:Xe.payment["payment-ready"]},{id:"needs-payment",label:"Needs payment setup",count:Xe.payment["needs-payment"]}],activeFilters:Jt,onFilterChange:Ls,multiSelect:!0,defaultLabel:"Payment"},{id:"bulk-toggle",type:"custom",className:"product-table-mode-actions ml-auto",render:()=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Vt,{variant:Ye?"default":"outline",icon:a.jsx(td,{className:"size-3.5"}),label:Ye?"Cancel bulk":"Bulk",className:Ye?"text-white":"",style:Ye?{backgroundColor:C}:void 0,onClick:()=>{if(Ye){Qo();return}Yr(!0)},"aria-pressed":Ye}),a.jsx(Vt,{variant:A?"default":"outline",icon:a.jsx(ku,{className:"size-3.5"}),label:A?"Normal view":"Config view",className:A?"text-white":"",style:A?{backgroundColor:C}:void 0,onClick:()=>{Jr(e=>!e),Vr(!1)},"aria-pressed":A})]})}
2].filter(Boolean),ge=!kn||!!M,ce="h-8 rounded-full px-3 text-xs max-lg:h-7 max-lg:!min-h-7 max-lg:px-2 max-lg:text-3xs",We="w-[min(20rem,calc(100vw-2rem))] rounded-xl border border-subtle p-3 shadow-lg max-lg:p-2 dark:bg-slate-900",Ln=Ye?a.jsx("div",{className:"rounded-xl border border-subtle bg-surface-raised p-3 max-lg:p-2",children:a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 max-lg:gap-1.5",children:[a.jsxs("p",{className:"text-xs font-medium text-content-secondary max-lg:text-2xs",children:[H.length," selected"]}),a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 max-lg:w-full max-lg:flex-nowrap max-lg:justify-start max-lg:gap-1 max-lg:overflow-x-auto max-lg:pb-0.5 max-lg:[&>*]:shrink-0",children:[A?null:a.jsxs(a.Fragment,{children:[a.jsxs(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge||M==="activate",onClick:()=>Pn(!0),children:[M==="activate"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Activate"]}),a.jsxs(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge||M==="deactivate",onClick:()=>Pn(!1),children:[M==="deactivate"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Deactivate"]})]}),!A&&vt?a.jsx(l.Suspense,{fallback:null,children:a.jsx(Au,{products:wn,clientId:m,medicationRows:[],mappingsByProductKey:_e,canEdit:Zs,onToggleMedication:vo,onOpenChange:no,pharmacies:se,hiddenMedicationIds:Yi,formularyVariants:Ii,loading:io&&(Te&&se.length===0||!Ji),children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:wn.length===0||!bo||Te&&se.length===0,children:"Pair Formulary"})})}):null,X&&(!h||A)?a.jsxs(Me,{children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Show on storefront"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("label",{className:"flex items-center justify-between gap-3 rounded-lg border border-subtle bg-surface-raised px-3 py-2 max-lg:gap-2 max-lg:px-2 max-lg:py-1.5",children:[a.jsx("span",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Show on storefront"}),a.jsx(De,{checked:Ts,onCheckedChange:e=>Xr(e===!0),"aria-label":"Set products to show on storefront"})]}),a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="storefront",onClick:pc,children:[M==="storefront"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Apply"]})]})})]}):null,X?a.jsxs(Me,{children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Update price"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Update price"}),a.jsx(Ee,{value:ii,onChange:e=>ni(e.target.value),placeholder:"0.00",inputMode:"decimal",className:"h-9"}),a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="price",onClick:mc,children:[M==="price"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Apply"]})]})})]}):null,X&&(!h||A)?a.jsxs(Me,{children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Assessment price"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Assessment price"}),a.jsx(Ee,{value:li,onChange:e=>oi(e.target.value),placeholder:"0",inputMode:"decimal",className:"h-9"}),a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="assessment",onClick:gc,children:[M==="assessment"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Apply"]})]})})]}):null,a.jsxs(Me,{children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Update shipping"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Update shipping"}),a.jsx(Ee,{value:ci,onChange:e=>di(e.target.value),placeholder:"0.00",inputMode:"decimal",className:"h-9"}),a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="shipping",onClick:fc,children:[M==="shipping"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Apply"]})]})})]}
2),X&&(!h||A)?a.jsxs(a.Fragment,{children:[a.jsxs(Me,{children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Month supply"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Month supply"}),a.jsx(Ee,{value:ui,onChange:e=>mi(e.target.value.replace(/[^0-9]/g,"")),placeholder:"1",inputMode:"numeric",className:"h-9"}),a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="month-supply",onClick:hc,children:[M==="month-supply"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Apply"]})]})})]}),a.jsxs(Me,{children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Quantity"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Quantity"}),a.jsx(Ee,{value:pi,onChange:e=>gi(e.target.value.replace(/[^0-9]/g,"")),placeholder:"Optional",inputMode:"numeric",className:"h-9"}),a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="quantity",onClick:yc,children:[M==="quantity"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Apply"]})]})})]})]}):null,A?null:a.jsxs(Me,{children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Set category"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Set category"}),a.jsx("div",{className:"max-h-48 space-y-1 overflow-auto",children:oe.filter(e=>(e.status||"active")==="active").map(e=>{const t=fi.includes(e.id);return a.jsxs("label",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-slate-50 dark:hover:bg-slate-800",children:[a.jsx(De,{checked:t,onCheckedChange:()=>{hi(s=>s.includes(e.id)?s.filter(r=>r!==e.id):[...s,e.id])}}),a.jsx("span",{className:"truncate",children:e.name||"Category"})]},e.id)})}),a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="category",onClick:xc,children:[M==="category"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Apply"]})]})})]}),A?null:a.jsx(kr,{accept:ga,multiple:!1,maxSize:pa,disabled:ge,onDrop:vc,children:({getRootProps:e,getInputProps:t})=>a.jsxs(L,{type:"button",variant:"outline",size:"sm",...e(),className:ce,disabled:ge||M==="image",children:[a.jsx("input",{...t()}),M==="image"?a.jsx(V,{size:"xs",className:"mr-2"}):a.jsx(Yn,{className:"mr-1.5 size-3.5"}),"Upload image"]})}),a.jsxs(Me,{children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Offer included visits"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Offer included visits"}),A?a.jsxs("label",{className:"flex items-center justify-between gap-3 rounded-lg border border-subtle bg-surface-raised px-3 py-2",children:[a.jsx("span",{className:"text-sm font-medium text-content-primary",children:"Enabled"}),a.jsx(De,{checked:Fs,onCheckedChange:e=>ri(e===!0),"aria-label":"Set products to offer included visits"})]}):null,!A||Fs?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"mb-1 block text-xs font-medium text-content-secondary",children:"Included visits"}),a.jsx(Ee,{type:"text",inputMode:"numeric",value:ei,onChange:e=>Lo(e.target.value),placeholder:"Enter count",className:"h-9"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"mb-1 block text-xs font-medium text-content-secondary",children:"Expiration days"}),a.jsx(Ee,{type:"text",inputMode:"numeric",value:ai,onChange:e=>si(e.target.value.replace(/[^0-9]/g,"")),placeholder:"Optional",className:"h-9"})]})]}):null,a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="included-visits",onClick:kc,children:[M==="included-visits"?a.jsx(V,{size:"xs",className:"mr-2"}):null,"Apply"]})]})})]}
2),X&&(!h||A)?a.jsxs(Me,{children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Requires sync visit"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("label",{className:"flex items-center justify-between gap-3 rounded-lg border border-subtle bg-surface-raised px-3 py-2 max-lg:gap-2 max-lg:px-2 max-lg:py-1.5",children:[a.jsx("span",{className:"text-sm font-semibold text-content-primary max-lg:text-xs",children:"Requires sync visit"}),a.jsx(De,{checked:As,onCheckedChange:e=>yi(e===!0),"aria-label":"Set products to require sync visit"})]}),As?a.jsxs("div",{className:"space-y-2",children:[a.jsx(ad,{htmlFor:"bulk-sync-audience",children:"Require sync visit for"}),a.jsxs(sd,{value:Ta,onValueChange:bi,children:[a.jsx(rd,{id:"bulk-sync-audience","aria-describedby":"bulk-sync-audience-help",children:a.jsx(id,{})}),a.jsxs(nd,{children:[a.jsx(Pr,{value:"all",children:"All purchases"}),a.jsx(Pr,{value:"first_time_patient",children:"First-time patients"}),a.jsx(Pr,{value:"first_purchase",children:"First purchase of each product"})]})]}),a.jsx("p",{id:"bulk-sync-audience-help",className:"text-xs text-muted-foreground",children:Ta==="first_time_patient"?"Patients with no completed purchase with this client.":Ta==="first_purchase"?"Patients with no completed purchase of the selected product or package.":"Every purchase requires a live assessment."})]}):null,a.jsx("p",{className:"text-xs text-muted-foreground",children:"Provider-network, included-product, and lab-first requirements remain enforced."}),a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="sync-visit",onClick:bc,children:[M==="sync-visit"?a.jsx(V,{size:"xs",className:"mr-2"}):a.jsx(Qn,{className:"mr-2 size-3"}),"Apply"]})]})})]}):null,a.jsxs(Me,{onOpenChange:e=>{e&&wc()},children:[a.jsx(Oe,{asChild:!0,children:a.jsx(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:ge,children:"Set required labs"})}),a.jsx(Be,{className:We,align:"end",children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("label",{className:"flex items-center justify-between gap-3 rounded-lg border border-subtle bg-surface-raised px-3 py-2",children:[a.jsx("span",{className:"text-sm font-semibold text-content-primary",children:"Requires labs"}),a.jsx(De,{checked:it,onCheckedChange:e=>xi(e===!0),"aria-label":"Set products to require labs"})]}),it?a.jsxs("div",{children:[a.jsx("p",{className:"mb-2 text-xs font-medium text-content-secondary",children:"Approved lab options"}),da.length>0?a.jsxs("p",{className:"mb-2 text-xs text-content-tertiary",children:["Each option includes ",da.map(e=>e.name).join(", "),"."]}):null,Ms?a.jsxs("p",{className:"flex items-center gap-2 text-xs text-content-tertiary",children:[a.jsx(V,{size:"xs"}),"Loading labs"]}):Zt.length>0?a.jsx("div",{className:"max-h-44 space-y-1 overflow-auto",children:Zt.map(e=>{const t=vi.includes(e.id);return a.jsxs("label",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-surface-sunken",children:[a.jsx(De,{checked:t,onCheckedChange:()=>{Rs(s=>s.includes(e.id)?s.filter(r=>r!==e.id):[...s,e.id])}}),a.jsx("span",{className:"truncate",children:e.name||e.id})]},e.id)})}):a.jsx("p",{className:"text-xs text-content-tertiary",children:"No eligible lab catalog offers."}),Ql?a.jsx(vu,{}):null]}):null,a.jsxs(L,{type:"button",size:"sm",className:"w-full text-white",style:{backgroundColor:C},disabled:M==="required-labs"||Ms,onClick:Pc,children:[M==="required-labs"?a.jsx(V,{size:"xs",className:"mr-2"}):a.jsx(Hn,{className:"mr-2 size-3"}),"Apply"]})]})})]}),A?null:a.jsxs(L,{type:"button",variant:"outline",size:"sm",className:ce,disabled:$t.length===0||!!M,onClick:()=>Fa(!0),children:[M==="duplicate"?a.jsx(V,{size:"xs",className:"mr-2"}):a.jsx(Kn,{className:"mr-1.5 size-3.5"}),"Duplicate"]})]})]})}):null,En=a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 max-lg:flex-nowrap max-lg:gap-1 max-lg:[&>*]:shrink-0",children:[a.jsx(qd,{products:k,categories:oe,branding:F,accentColor:C,userType:v,clientId:m,clientExperienceConfig:b==null?void 0:b.experienceConfig,hoverRevealTrigger:!0}),a.jsx(Vt,{icon:a.jsx(ld,{className:"size-3.5"}),label:Es?"Table":"Storefront",onClick:()=>{Vr(e=>{const t=!e;return t&&Jr(!1),t})},"aria-pressed":Es}),h?null:a.jsx(Vt,{icon:a.jsx(od,{className:"size-3.5"}),label:"Categories",onClick:()=>Wr(!0)}),Ga?a.jsx(xd,{ref:ft,scope:{type:"client",id:Y},products:k,accentColor:C,showTriggerButton:!1,showManagerDialog:!1,loadOnMount:!0,onSubscriptionsChange:qe}):null,xe?a.jsx(Vt,{icon:a.jsx(wu,{className:"size-3.5"}),label:"Smart upload",onClick:()=>Hr(!0)}):null,xe?a.jsx(Vt,{variant:"default",icon:a.jsx(cd,{className:"size-3.5"}),label:"Create",className:"border-transparent text-white",style:{backgroundColor:C},onClick:()=>Qs(!0)}):null]});return a.jsxs("div",{className:c?"space-y-4 max-lg:space-y-2.5":"app-page-shell space-y-4 max-lg:space-y-3 sm:space-y-6",children:[!g&&a.jsx(dd,{headerId:"products-client",titleClassName:"max-lg:truncate"}),!Y&&!ds?a.jsxs("div",{className:"rounded-lg border border-red-200 bg-red-50 p-6 max-lg:p-3 dark:border-red-800 dark:bg-red-900/20",children:[a.jsxs("h3",{className:"font-semibold text-red-900 max-lg:text-sm dark:text-red-200",children:["No ",Gs[0].toUpperCase()+Gs.slice(1)," Assigned"]}),a.jsxs("p",{className:"mt-1 text-sm text-red-700 max-lg:text-xs dar
2k:text-red-300",children:["You must be assigned to a ",Gs," to manage products."]})]}):a.jsxs(a.Fragment,{children:[Es?a.jsx(zd,{id:"products-client-products",title:"Products",icon:xs,accentColor:C,actions:En,filteredCount:ur.length,totalCount:Ce.length,search:{placeholder:"Search products…",value:ws,onChange:Ia,testId:fe("input","products","client-search")},filters:jn,hasActiveFilters:pr,headerExtra:Ln,onClearFilters:()=>{Ia(""),ja("all"),Ps(!1),La([]),Ss([]),Ns([]),Cs([]),Is([]),js([]),Ls([])},loading:ds,bodyClassName:"bg-surface-raised p-4",children:ds?a.jsx("div",{className:`${Sl} max-lg:gap-3`,children:Array.from({length:6}).map((e,t)=>a.jsx(Sa,{className:"h-80 rounded-2xl max-lg:h-64"},`storefront-skeleton-${t}`))}):ur.length>0?a.jsx("div",{className:`${Sl} max-lg:gap-3`,children:ur.map(e=>a.jsx("div",{"data-testid":fe("row","products",`storefront-${e.id}`),children:pn(e)},e.id))}):a.jsxs("div",{className:"rounded-xl border border-dashed border-subtle p-10 text-center max-lg:p-5",children:[a.jsx("p",{className:"text-sm font-medium text-content-primary max-lg:text-xs",children:"No patient-visible products"}),a.jsx("p",{className:"mt-1 text-sm text-content-tertiary max-lg:text-2xs",children:Sn})]})}):a.jsx(Vd,{id:"products-client-products",title:"Products",icon:xs,accentColor:C,actions:En,filteredCount:la.length,totalCount:Ce.length,search:{placeholder:"Search products…",value:ws,onChange:Ia,testId:fe("input","products","client-search")},filters:jn,hasActiveFilters:pr,headerExtra:Ln,onClearFilters:()=>{Ia(""),ja("all"),Ps(!1),La([]),Ss([]),Ns([]),Cs([]),Is([]),js([]),Ls([])},mobileList:{title:"displayTitle",subtitle:"displaySummary",actions:"actions",fields:["priceSort","categorySort"]},columns:Lc,rows:fn,csvExport:{feature:"products",tenantSlug:(b==null?void 0:b.name)||(E==null?void 0:E.name),hoverRevealTrigger:!0,rawExport:{getRows:()=>jd(fn,Ce)},allData:{mode:"client",getRows:()=>Ce.map(cr)}},rowClick:e=>{var t,s;if(e.itemType==="subscription"){(s=(t=ft.current)==null?void 0:t.openEdit)==null||s.call(t,e.subscription);return}Ut(e)},rowClassName:e=>e.active?"":"opacity-60",rowTestId:e=>fe("row","products",e.id),contextMenuActions:jc,loading:ds,skeletonRowCount:6,emptyMessage:Sn,tableLabel:"Client products table",tableTestId:fe("table","products","client-products"),sortKey:_t,sortDirection:oa,onSort:lc,maxHeight:c?"420px":"min(calc(100dvh - 12rem), 960px)",virtualized:!0,virtualRowHeight:76}),Ra||be?a.jsx(l.Suspense,{fallback:a.jsx(Kt,{label:"Loading product editor…"}),children:a.jsx(Ll,{open:Ra,onOpenChange:e=>{Ft(e),e||(ta(null),Ma(""),Oa(""),sa(null))},product:be,getInitialDetailForm:dn,categories:oe,catalogProducts:k,accentColor:C,isClientOwnedProduct:j,getProductReviewNetworkLabel:Ja,getProductReviewNetworkColor:Za,getProductSettingsRef:xt,isBusinessTenant:h,catalogTenantId:Y,clientId:m,clientName:(b==null?void 0:b.name)||(b==null?void 0:b.displayName)||"Client",branding:F,clientExperience:W,businessId:h?$e:null,canEditPricing:X,canEditStateExclusions:v==="Client Admin",canEditFormularyMappings:Zs,assertLabEnablementAllowed:qo,prescribeByProductEnabled:bt,showFormularyTab:vt,formularyReadiness:vt&&(be==null?void 0:be.formularyReadiness)||null,initialFocusSection:Gl,onFormularyMappingsSnapshot:uo,onSaveSuccess:rc,onProductSubscriptionSave:Ga?un:void 0,canChangeProductSource:!!(v==="Client Admin"&&(be!=null&&be.catalogEntryId)&&(be!=null&&be.providerNetworkId)&&!j(be)),onRequestProductSourceChange:e=>{_s(e),Ni(!0)},editorSessionKey:Yl,sourcePickerOpen:Si,sourceChangeResult:ao,copyableProductId:h?"":ya(be),onCreateLabPanel:!h&&v==="Client Admin"?sc:void 0,suspendForLabCreation:!!aa,returningLabSelection:to,onReturningLabHandled:()=>Pi(null)})}):null,aa?a.jsx(Na,{open:!0,onOpenChange:e=>{e||mn()},title:"Create qualifying lab panel",description:"Add a client lab and review the biomarkers it includes.",size:"xl",mobileFullHeight:!0,mobileStickyHeader:!0,contentTestId:fe("dialog","products","create-qualifying-lab"),...Jl,children:a.jsx(l.Suspense,{fallback:a.jsx("div",{className:"flex min-h-48 items-center justify-center",children:a.jsx(V,{label:"Loading lab editor"})}),children:a.jsx(Lu,{product:null,targetRequiredLabTests:aa.requiredLabTests,onSaved:({productId:e,product:t})=>{Da.current={productId:e,name:(t==null?void 0:t.name)||""}},onClose:mn,categories:oe,integrations:Zl,integrationsLoading:Xl,integrationsError:eo,setDialogProps:qs,accentColor:C,backgroundColor:F==null?void 0:F.backgroundColor,canEditPrice:!0,showPlatformBillingFields:!1,allowStateExclusions:!1,billingTenant:E||b})})}):null,a.jsx(Iu,{open:Si,onOpenChange:e=>{Ni(e),e||_s(null)},clientId:m,product:qa,accentColor:C,onChanged:ic}),a.jsx($d,{open:Je.open,onOpenChange:e=>At(t=>({...t,open:e})),reason:Je.reason,productName:((Fn=Je.product)==null?void 0:Fn.displayName)||((An=Je.product)==null?void 0:An.name)||"",count:Je.count,accentColor:C,onAction:()=>
2{if(Je.reason===dt.PLATFORM_PAYMENT){te("/settings/account");return}Je.reason===dt.APPROVED_LABS&&Je.product&&Ut(Je.product)}}),ua?a.jsx(l.Suspense,{fallback:null,children:a.jsx(Fu,{open:!!Ze,onOpenChange:e=>{e||Vs("")},product:ua,clientId:m,pharmacies:se,medicationRows:[],hiddenMedicationIds:Yi,formularyVariants:Ii,loading:!!Ze&&(Te&&se.length===0||!Ji),mappingsForProduct:(Ct(ua)?Bt:_e)[tt(ua)]||{},fallbackMappingsForProduct:na(ua).networkMappings,inheritedMedicationRowKeys:uc,canEdit:Zs,onToggleProduct:xo})}):null,a.jsx(Jn,{open:!!ht,onOpenChange:e=>{e||Ds(null)},children:a.jsx(Zn,{className:"max-h-[calc(100dvh-2rem)] w-full max-w-[min(100vw-2rem,56rem)] gap-0 overflow-hidden p-0","aria-label":"Product image","data-testid":fe("dialog","products","image-preview"),children:ht?a.jsxs("div",{className:"relative bg-slate-950",children:[a.jsx("div",{className:"flex max-h-[calc(100dvh-6rem)] min-h-[18rem] items-center justify-center",children:a.jsx("img",{src:ht.displayImageUrl,alt:ht.displayTitle||"Product image",className:"max-h-[calc(100dvh-6rem)] w-full object-contain"})}),a.jsx("div",{className:"absolute bottom-3 right-3",children:a.jsx(kr,{accept:ga,multiple:!1,maxSize:pa,onDrop:async e=>{await an(ht,e),Ds(null)},children:({getRootProps:e,getInputProps:t})=>a.jsxs(L,{type:"button",variant:"outline",size:"sm",...e(),className:"rounded-full border-white/20 bg-surface-raised text-content-primary hover:bg-slate-100",disabled:ie===`image-${ht.id}`,children:[a.jsx("input",{...t()}),ie===`image-${ht.id}`?a.jsx(V,{size:"sm",className:"mr-2"}):a.jsx(Yn,{className:"mr-2 size-3.5"}),"Replace"]})})})]}):null})}),a.jsx(Jn,{open:Kl,onOpenChange:$r,children:a.jsxs(Zn,{className:"max-h-[calc(100dvh-2rem)] w-full max-w-[min(100vw-2rem,42rem)] overflow-y-auto max-lg:p-3","aria-label":"Product preview","data-testid":fe("dialog","products","preview"),children:[a.jsx(ud,{children:a.jsx(md,{children:"Product Preview"})}),zr&&a.jsx("div",{className:"mt-4 max-lg:mt-2.5",children:pn(zr)})]})}),Kr?a.jsx(l.Suspense,{fallback:a.jsx(Kt,{label:"Loading categories…"}),children:a.jsx(Eu,{open:Kr,onOpenChange:Wr,scopeId:Y,isBusinessTenant:h,clientId:m,businessId:$e,accentColor:C,onCategoriesChanged:Gr,canManage:v==="Client Admin",providerNetworkName:lo,exportTenantSlug:F==null?void 0:F.businessName})}):null,Qr&&xe?a.jsx(l.Suspense,{fallback:a.jsx(Kt,{label:"Loading smart upload…"}),children:a.jsx(Tu,{open:Qr,onOpenChange:Hr,currentUserId:(x==null?void 0:x.id)||((Rn=we.currentUser)==null?void 0:Rn.uid)||null,accentColor:C,callManageProduct:Ae,onApplied:et})}):null,a.jsx(Cu,{open:co,onOpenChange:Qs,packageProducts:Ge,clientId:m,accentColor:C,onCreatePackage:ac,onCreateProduct:Jo}),bn?a.jsx(l.Suspense,{fallback:a.jsx(Kt,{label:"Loading package editor…"}),children:a.jsx(Ll,{open:Qa,suspended:Ra,onOpenChange:e=>{Mt(e),e||Ot(null)},product:bn,editorType:"package",isCreating:!(Fe!=null&&Fe.id),getInitialDetailForm:dn,categories:oe,accentColor:C,isClientOwnedProduct:j,getProductReviewNetworkLabel:Ja,getProductReviewNetworkColor:Za,getProductSettingsRef:xt,isBusinessTenant:h,catalogTenantId:Y,clientId:m,clientName:(b==null?void 0:b.name)||(b==null?void 0:b.displayName)||"Client",branding:F,clientExperience:W,businessId:h?$e:null,canEditPricing:X,canEditStateExclusions:v==="Client Admin",canEditFormularyMappings:!1,show
2FormularyTab:!1,formularyReadiness:vt&&(Fe==null?void 0:Fe.formularyReadiness)||null,packageSelectableProducts:oc,onPackageProductEdit:(e,t)=>Ut(e,t),onBack:Fe?void 0:Ho,onPackageSave:async(e,{isUpdate:t,product:s})=>{let r=null;if(t){const i=await Ae("updatePackage",{clientId:m,productId:s.id,...e});r={...i&&typeof i=="object"?i:{},productId:(i==null?void 0:i.productId)||s.id}}else r=await Ae("createPackage",{clientId:m,...e});return await et(),r},onProductSubscriptionSave:Ga?un:void 0})}):null,Mi||Bi?a.jsx(l.Suspense,{fallback:a.jsx(Kt,{label:"Loading package offer…"}),children:a.jsx(Tl,{open:Mi,onClose:()=>{Oi(!1),Di(null)},product:Bi,clientId:m,variant:"package"})}):null,qi||_i?a.jsx(l.Suspense,{fallback:a.jsx(Kt,{label:"Loading product offer…"}),children:a.jsx(Tl,{open:qi,onClose:()=>{Ui(!1),$i(null)},product:_i,clientId:m})}):null,a.jsx(Xn,{open:Hl,onOpenChange:Fa,children:a.jsxs(el,{children:[a.jsxs(tl,{children:[a.jsx(al,{children:"Duplicate selected products?"}),a.jsxs(sl,{children:["This will create inactive copies of"," ",$t.length," selected product",$t.length===1?"":"s","."]})]}),a.jsxs(rl,{children:[a.jsx(il,{disabled:M==="duplicate",children:"Cancel"}),a.jsxs(nl,{onClick:e=>{e.preventDefault(),Sc()},disabled:M==="duplicate"||$t.length===0,className:"text-white",style:{backgroundColor:C},children:[M==="duplicate"?a.jsx(V,{size:"md",className:"mr-2"}):null,"Duplicate"]})]})]})}),a.jsx(Xn,{open:!!K,onOpenChange:e=>{e||Aa(null)},children:a.jsxs(el,{children:[a.jsxs(tl,{children:[a.jsx(al,{children:"Apply product image?"}),a.jsxs(sl,{children:["Do you want the same image to be applied to"," ",((Mn=K==null?void 0:K.target)==null?void 0:Mn.displayTitle)||"this product"," ","from"," ",((On=K==null?void 0:K.source)==null?void 0:On.displayTitle)||"that product","?"]})]}),a.jsxs(rl,{children:[a.jsx(il,{disabled:ie===`image-${(Bn=K==null?void 0:K.target)==null?void 0:Bn.id}`,children:"Cancel"}),a.jsxs(nl,{onClick:e=>{e.preventDefault(),Ko()},disabled:ie===`image-${(Dn=K==null?void 0:K.target)==null?void 0:Dn.id}`,className:"text-white",style:{backgroundColor:C},children:[ie===`image-${(qn=K==null?void 0:K.target)==null?void 0:qn.id}`?a.jsx(V,{size:"md",className:"mr-2"}):null,"Apply image"]})]})]})})]}),S?a.jsx(ju,{open:!Qa&&!Ra,productId:S.id,clientId:m,callManageProduct:Ae,onClose:()=>w(null),onReviewPackage:Zo,onDeleted:()=>{Or.success("Product deleted"),et()}},S.id):null]})}const Fm=Object.freeze(Object.defineProperty({__proto__:null,default:Hu},Symbol.toStringTag,{value:"Module"}));export{Fm as P,jl as a,Bl as i};

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.