PageSourceSearch

https://caremetric.ai/assets/VisitManager-Ei7UKJbA.js

js caremetric.ai collected 2026-10-05 15:01:52 UTC 101,315 bytes, 46 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/chunk-pdf-lib-D08dpjkn.js","assets/rolldown-runtime-DS2seoW7.js","assets/chunk-admin-DnJxlFde.js","assets/chunk-admin-subscription-CQfvBNB9.js","assets/chunk-admin-analytics-BXp2ft9X.js","assets/chunk-marketing-BxjL8zs6.js","assets/chunk-ambient-CTneTVtQ.js","assets/chunk-ai-notes-CK7snn-s.js","assets/chunk-landing-DxwtKZZg.js","assets/chunk-billing-PP2lfCeQ.js","assets/chunk-behavioral-D_MMZlmf.js","assets/chunk-ccm-C8LBGlVS.js","assets/chunk-calculators-CqjYQQPT.js","assets/chunk-clinical-intel-C-fcrlcB.js","assets/chunk-compliance-BsfCQbzq.js"])))=>i.map(i=>d[i]);
2import{a as es}from"./rolldown-runtime-DS2seoW7.js";import{B as We,Bn as ts,Ct as it,En as M,F as bt,G as xt,It as ct,L as ss,Mt as as,N as Tt,Nt as rt,O as dt,On as q,S as ns,St as _t,Tt as is,Vn as rs,Z as St,an as ls,bt as pe,dt as os,gt as cs,h as jt,m as mt,st as Dt,ut as ds,w as ht,wt as vt,x as et,xn as v,z as ms}from"./chunk-admin-DnJxlFde.js";import{k as us}from"./vendor-lucide-WrNCMbII.js";import{m as Ct}from"./chunk-super-admin-vaUPzFHQ.js";import{C as lt,S as tt,f as ot,l as ft}from"./chunk-admin-subscription-CQfvBNB9.js";import{N as xs,h as kt,j as gt,m as gs}from"./chunk-billing-PP2lfCeQ.js";import{D as hs,_ as fs}from"./chunk-ambient-CTneTVtQ.js";import{w as ps}from"./chunk-landing-DxwtKZZg.js";import{s as Et}from"./chunk-inbox-CdwcIotk.js";import{a as bs,c as js,h as Pt,i as vs,l as Ns,o as ws,u as Mt}from"./chunk-visit-workflow-CPJkzSpS.js";import{B as ys,C as _s,E as Ss,T as Cs,V as ks,b as Is,c as As,f as Ft,l as $s,p as zt,s as Rs,u as qt,w as Ts,y as Ds,z as Es}from"./chunk-telehealth-BRmT0eb8.js";import{n as Ps,r as Ms,w as Fs}from"./chunk-clinical-intel-C-fcrlcB.js";import{A as pt,E as Lt,F as zs,I as qs,M as Ls,O as It,x as Ue}from"./chunk-ai-notes-CK7snn-s.js";import{n as At}from"./chunk-cds-CeJkZ2Nn.js";import{t as Os}from"./chunk-ghost-notes-Dkhuk5F7.js";import{d as Ot}from"./chunk-subscription-7qq83iKn.js";import{n as $t}from"./index-DDsTNWwO.js";import{AddAddendum as Bt}from"./AddAddendum-CzVE9W5Y.js";import{EncounterAssessmentsPanel as Bs}from"./EncounterAssessmentsPanel-Bc2it5bY.js";import{t as Hs}from"./ChiefComplaintAutocomplete-nFryaTy8.js";import{NoteRevisionHistory as Ht}from"./NoteRevisionHistory-CrsNv87x.js";import Vt from"./SignaturePad-Bv2Arsw8.js";import{TemplatePreferences as Vs}from"./TemplatePreferences-D0-fvdWd.js";var a=es(rs(),1);function Us({onSave:s,delay:r=2500,enabled:y=!0}){const S=(0,a.useRef)(void 0),o=(0,a.useRef)(void 0),l=(0,a.useRef)(!1),i=(0,a.useRef)(!1),g=(0,a.useRef)(!0),h=(0,a.useRef)(r),T=(0,a.useRef)(s);(0,a.useEffect)(()=>{h.current=r,T.current=s});const[c,C]=(0,a.useState)(!1),[m,I]=(0,a.useState)(null),k=(0,a.useRef)(async()=>{}),E=(0,a.useCallback)(async()=>{if(!(!y||!g.current)){if(l.current){i.current=!0;return}try{l.current=!0,g.current&&C(!0),i.current=!1,await T.current(),g.current&&I(null),i.current&&g.current&&(i.current=!1,o.current=setTimeout(()=>k.current(),h.current))}catch(A){const d=q(A);M.error("Auto-save failed:",d),g.current&&I(d)}finally{l.current=!1,g.current&&C(!1)}}},[y]);(0,a.useEffect)(()=>{k.current=E});const j=(0,a.useCallback)(()=>{y&&(S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{E()},h.current))},[E,y]);return(0,a.useEffect)(()=>(g.current=!0,()=>{g.current=!1,o.current&&clearTimeout(o.current),S.current&&(clearTimeout(S.current),S.current=void 0),i.current&&!l.current&&(i.current=!1,T.current().catch(A=>{M.error("Auto-save flush on unmount failed:",q(A))}))}),[]),{scheduleSave:j,cancelSave:(0,a.useCallback)(()=>{S.current&&(clearTimeout(S.current),S.current=void 0),i.current=!1},[]),isSaving:c,lastError:m}}var e=ls(),Rt=[{id:"1",trigger:".wnl",content:"Within normal limits",category:"general"},{id:"2",trigger:".nad",content:"No acute distress",category:"general"},{id:"3",trigger:".aao",content:"Alert and oriented x3",category:"neuro"},{id:"4",trigger:".rrr",content:"Regular rate and rhythm, no murmurs, rubs, or gallops",category:"cardiac"},{id:"5",trigger:".ctab",content:"Clear to auscultation bilaterally, no wheezes, rales, or rhonchi",category:"pulm"},{id:"6",trigger:".soft",content:"Soft, non-tender, non-distended, normoactive bowel sounds",category:"abd"}
2,{id:"7",trigger:".neuro",content:"Cranial nerves II-XII intact, motor strength 5/5 all extremities, sensation intact",category:"neuro"},{id:"8",trigger:".skin",content:"Warm, dry, intact, no rashes or lesions",category:"skin"},{id:"9",trigger:".heent",content:"Normocephalic, atraumatic. PERRLA. TMs clear bilaterally. Oropharynx clear, no erythema or exudate",category:"heent"},{id:"10",trigger:".ext",content:"No clubbing, cyanosis, or edema. Pulses 2+ bilaterally",category:"ext"},{id:"11",trigger:".fu1w",content:"Follow up in 1 week",category:"plan"},{id:"12",trigger:".fu2w",content:"Follow up in 2 weeks",category:"plan"},{id:"13",trigger:".fu1m",content:"Follow up in 1 month",category:"plan"},{id:"14",trigger:".prn",content:"Return to clinic as needed for worsening symptoms",category:"plan"},{id:"15",trigger:".er",content:"Return to emergency room if symptoms worsen or new symptoms develop",category:"plan"}];function Ws({visit:s,patient:r,onClose:y,onComplete:S}){const{profile:o}=ct(),{showToast:l}=mt(),[i,g]=(0,a.useState)({subjective:"",objective:"",assessment:"",plan:""}),[h,T]=(0,a.useState)("subjective"),[c,C]=(0,a.useState)(new Set(["subjective","objective","assessment","plan"])),[m,I]=(0,a.useState)(null),[k,E]=(0,a.useState)([]),[j,A]=(0,a.useState)(!1),[d,N]=(0,a.useState)(!1),[L,B]=(0,a.useState)(null),[be,ne]=(0,a.useState)(!1),[p,D]=(0,a.useState)(!1),[F,z]=(0,a.useState)(!1),[_e,ie]=(0,a.useState)(!1),[Ke,ce]=(0,a.useState)(!1),[Ge,je]=(0,a.useState)(!1),[de,Se]=(0,a.useState)(""),[Pe,Me]=(0,a.useState)([]),[Je,te]=(0,a.useState)(""),[Ye,me]=(0,a.useState)(!1),[ue,Fe]=(0,a.useState)(""),[_,re]=(0,a.useState)(null),[U,Ce]=(0,a.useState)([]),[W,ke]=(0,a.useState)([]),[Ie,Ae]=(0,a.useState)(0),[se,xe]=(0,a.useState)(!1),[ze,$e]=(0,a.useState)(null),[st,qe]=(0,a.useState)(!1),[ae,K]=(0,a.useState)(!1),[ge,Xe]=(0,a.useState)(null),X=(0,a.useRef)(""),Q=(0,a.useRef)(!1),H=(0,a.useRef)(!1),G=(0,a.useRef)(null),J=(0,a.useRef)(null),ve=(0,a.useRef)(null),Ne=(0,a.useRef)({subjective:null,objective:null,assessment:null,plan:null}),Le=(0,a.useCallback)(async()=>{if(i.signed||d||Q.current||H.current)return;const t=JSON.stringify({subjective:i.subjective,objective:i.objective,assessment:i.assessment,plan:i.plan});if(t!==X.current&&!(!i.subjective&&!i.objective&&!i.assessment&&!i.plan)){H.current=!0;try{const{data:n}=await v.from("visit_notes").select("id").eq("visit_id",s.id).is("deleted_at",null).maybeSingle(),x={visit_id:s.id,subjective:i.subjective,objective:i.objective,assessment:i.assessment,plan:i.plan};if(n){const{error:u}=await v.from("visit_notes").update(x).eq("id",n.id);if(u)throw u}else{const{data:u,error:w}=await v.from("visit_notes").insert(x).select("id").maybeSingle();if(w)throw w;if(!u?.id)throw new Error("Failed to create visit note");g(P=>({...P,id:u.id}))}X.current=t,B(new Date)}finally{H.current=!1}}},[s.id,i,d]),{scheduleSave:Re,cancelSave:Te}=Us({onSave:Le,delay:2500,enabled:!i.signed}),De=(0,a.useCallback)(async()=>{N(!0);try{const{data:t}=await v.from("visit_notes").select("id").eq("visit_id",s.id).is("deleted_at",null).maybeSingle(),n={visit_id:s.id,subjective:i.subjective,objective:i.objective,assessment:i.assessment,plan:i.plan,ai_compliance_score:m?.score||0,ai_compliance_suggestions:m?.
2suggestions||[],ai_analysis:m?.analysis||{}};if(t){const{error:x}=await v.from("visit_notes").update(n).eq("id",t.id);if(x)throw x;g(u=>({...u,id:t.id}))}else{const{data:x,error:u}=await v.from("visit_notes").insert(n).select("id").maybeSingle();if(u)throw u;if(!x)throw new Error("Failed to create visit note");g(w=>({...w,id:x.id}))}k.length>0&&await kt(s.id,k),B(new Date),l("Note saved","success")}catch(t){const n=t instanceof Error?t.message:String(t);l("Error saving: "+n,"error")}finally{N(!1)}},[s.id,i.subjective,i.objective,i.assessment,i.plan,m,k,l]);(0,a.useEffect)(()=>($(),Y(),b(),Ze(),we(),()=>{ve.current&&clearInterval(ve.current),G.current&&G.current.stop(),J.current&&clearTimeout(J.current)}),[]),(0,a.useEffect)(()=>{Re()},[i.subjective,i.objective,i.assessment,i.plan,Re]),(0,a.useEffect)(()=>{function t(n){(n.metaKey||n.ctrlKey)&&(n.key==="s"||n.key==="S")&&(i.signed||d||H.current||(n.preventDefault(),De()))}return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[i.signed,d,De]);function we(){ve.current=setInterval(()=>{Ae(t=>t+1)},1e3)}async function Ze(){if(o?.id)try{const{data:t,error:n}=await v.from("profiles").select("requires_cosigner, cosigner_id").eq("id",o.id).maybeSingle();n?M.error("Error loading cosigner settings:",q(n)):t&&(K(t.requires_cosigner||!1),Xe(t.cosigner_id||null))}catch(t){M.error("Error loading cosigner settings:",q(t))}}async function b(){try{const[t,n,x]=await Promise.allSettled([v.from("vital_signs").select("*").eq("patient_id",r.id).order("recorded_at",{ascending:!1}).limit(1).maybeSingle(),v.from("medications").select("*").eq("patient_id",r.id).eq("status","active").order("medication_name"),v.from("problem_list").select("*").eq("patient_id",r.id).eq("status","active").order("diagnosis_name")]);t.status==="fulfilled"&&t.value?.data&&re(t.value.data),n.status==="fulfilled"&&n.value?.data&&Ce(n.value.data),x.status==="fulfilled"&&x.value?.data&&ke(x.value.data)}catch(t){M.error("Error loading patient context:",q(t))}}async function $(){try{const{data:t}=await v.from("visit_notes").select("*").eq("visit_id",s.id).is("deleted_at",null).maybeSingle();t?(g(t),I({score:t.ai_compliance_score??0,suggestions:t.ai_compliance_suggestions||[],gaps:[],analysis:t.ai_analysis||{}}),X.current=JSON.stringify({subjective:t.subjective||"",objective:t.objective||"",assessment:t.assessment||"",plan:t.plan||""})):s.chief_complaint&&g(n=>({...n,subjective:`Chief Complaint: ${s.chief_complaint}
3
4`}))}catch(t){M.error("Error loading visit note:",q(t))}}async function Y(){try{const{data:t}=await v.from("provider_template_preferences").select("template_id").eq("provider_id",o?.id),n=t?.map(O=>O.template_id)||[],{data:x}=await v.from("providers").select("specialty").eq("profile_id",o?.id).maybeSingle(),u=x?.specialty,w=s?.visit_type;let P=v.from("clinical_notes_templates").select("id, name, specialty, template_type, content").eq("is_public",!0);if(n.length>0)P=P.in("id",n);else if(u||w){const O=[];u&&O.push(u),w&&O.push(w),O.push("General Medicine"),O.push("General"),P=P.in("specialty",O)}const{data:V}=await P.order("specialty").order("name");if(Me(V||[]),V&&V.length===1&&!i.subjective&&!i.objective&&!i.assessment&&!i.plan){const O=V[0],Z=le(O.content);(Z.subjective||Z.objective||Z.assessment||Z.plan)&&(g(Ve=>({...Ve,subjective:Z.subjective||(s.chief_complaint?`Chief Complaint: ${s.chief_complaint}
5
6`:""),objective:Z.objective||Ve.objective,assessment:Z.assessment||Ve.assessment,plan:Z.plan||Ve.plan})),l(`Template "${O.name}" auto-applied`,"info"))}}catch(t){M.error("Error loading templates:",q(t))}}function Ee(t){const n=Ne.current[h];if(!n)return;const x=n.selectionStart,u=n.selectionEnd,w=i[h]||"",P=w.substring(0,x)+t.content+w.substring(u);g(V=>({...V,[h]:P})),me(!1),setTimeout(()=>{n.focus();const V=x+t.content.length;n.setSelectionRange(V,V)},0)}function Oe(t,n){if(t.key===" "||t.key==="Enter"){const x=t.currentTarget.selectionStart,u=(i[n]||"").substring(0,x).split(/\s/).pop()||"";if(u.startsWith(".")&&u.length>1){const w=Rt.find(P=>P.trigger===u);if(w){t.preventDefault();const P=(i[n]||"").substring(0,x-u.length),V=(i[n]||"").substring(x);g(O=>({...O,[n]:P+w.content+(t.key==="Enter"?`
7`:" ")+V}));return}}}if(t.key==="Tab"&&!t.shiftKey){t.preventDefault();const x=["subjective","objective","assessment","plan"],u=x[(x.indexOf(n)+1)%x.length];T(u),setTimeout(()=>
7Ne.current[u]?.focus(),0)}}function le(t){const n={subjective:"",objective:"",assessment:"",plan:""},x=t.match(/SUBJECTIVE:(.*?)(?=OBJECTIVE:|$)/is),u=t.match(/OBJECTIVE:(.*?)(?=ASSESSMENT:|$)/is),w=t.match(/ASSESSMENT:(.*?)(?=PLAN:|$)/is),P=t.match(/PLAN:(.*?)$/is);return x&&(n.subjective=x[1].trim()),u&&(n.objective=u[1].trim()),w&&(n.assessment=w[1].trim()),P&&(n.plan=P[1].trim()),n}function Be(t){if(!t||i.signed)return;const n=Pe.find(u=>u.id===t);if(!n)return;const x=le(n.content);g(u=>({...u,subjective:x.subjective||u.subjective,objective:x.objective||u.objective,assessment:x.assessment||u.assessment,plan:x.plan||u.plan})),te(""),l(`Template "${n.name}" applied`,"success")}function He(){if(!_)return;const t=`Vital Signs (${new Date(_.recorded_at).toLocaleDateString()}):
8- BP: ${_.blood_pressure_systolic||"--"}/${_.blood_pressure_diastolic||"--"} mmHg
9- HR: ${_.heart_rate||"--"} bpm
10- RR: ${_.respiratory_rate||"--"}/min
11- Temp: ${_.temperature||"--"}${_.temperature_unit}
12- SpO2: ${_.oxygen_saturation||"--"}%
13- Weight: ${_.weight||"--"} ${_.weight_unit}
14- Height: ${_.height||"--"} ${_.height_unit}
15${_.bmi?`- BMI: ${_.bmi.toFixed(1)}`:""}
16
17`;g(n=>({...n,objective:t+(n.objective||"")})),l("Vitals inserted into Objective","success")}function Qe(){if(W.length===0)return;const t=W.map((n,x)=>`${x+1}. ${n.diagnosis_name} (${n.diagnosis_code})`).join(`
18`);g(n=>({...n,assessment:(n.assessment||"")+`
19
20Active Problems:
21`+t})),l("Problems inserted into Assessment","success")}function f(){if(U.length===0)return;const t=[];t.push("Medications:"),U.forEach(n=>{t.push(`- ${n.medication_name} ${n.dosage} ${n.frequency}${n.pharmacy?` (${n.pharmacy})`:""}`)}),g(n=>({...n,plan:(n.plan||"")+`
22
23`+t.join(`
24`)})),l("Medications inserted into Plan","success")}function R(){let t="",n="",x="";if(_&&(t=`Vital Signs (${new Date(_.recorded_at).toLocaleDateString()}):
25- BP: ${_.blood_pressure_systolic||"--"}/${_.blood_pressure_diastolic||"--"} mmHg
26- HR: ${_.heart_rate||"--"} bpm
27- RR: ${_.respiratory_rate||"--"}/min
28- Temp: ${_.temperature||"--"}${_.temperature_unit}
29- SpO2: ${_.oxygen_saturation||"--"}%
30- Weight: ${_.weight||"--"} ${_.weight_unit}
31- Height: ${_.height||"--"} ${_.height_unit}
32${_.bmi?`- BMI: ${_.bmi.toFixed(1)}`:""}
33
34`),W.length>0&&(n=`
35
36Active Problems:
37`+W.map((u,w)=>`${w+1}. ${u.diagnosis_name} (${u.diagnosis_code})`).join(`
38`)),U.length>0&&(x=`
39
40Medications:
41`+U.map(u=>`- ${u.medication_name} ${u.dosage} ${u.frequency}${u.pharmacy?` (${u.pharmacy})`:""}`).join(`
42`)),!t&&!n&&!x){l("No patient context available to insert","info");return}g(u=>({...u,objective:t+(u.objective||""),assessment:(u.assessment||"")+n,plan:(u.plan||"")+x})),l("All patient context inserted","success")}async function ee(){if(o){A(!0);try{const t=await Is(i);I(t);const n=await Cs({subjective:i.subjective,objective:i.objective,assessment:i.assessment,plan:i.plan,chiefComplaint:s.chief_complaint});E(n),await _s(o.id,"compliance_check",i,{compliance:t,suggestedCodes:n},t.score),l(`Compliance score: ${t.score}%`,"success")}catch(t){M.error("Error analyzing note:",q(t)),l("Analysis failed","error")}finally{A(!1)}}}async function oe(t){const n=new TextEncoder().encode(t),x=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(x)).map(u=>u.toString(16).padStart(2,"0")).join("")}async function at(){if(!(!o||!de.trim()))try{const{data:t,error:n}=await v.from("visit_notes").select("id").eq("visit_id",s.id).is("deleted_at",null).maybeSingle();if(n)throw n;if(!t){l("No note found to void","error");return}const{error:x}=await v.from("visit_notes").update({voided:!0,voided_at:new Date().toISOString(),voided_by:o.id,void_reason:de}).eq("id",t.id);if(x)throw x;l("Note voided successfully","success"),ie(!1),Se(""),S?.(),y()}catch(t){const n=t instanceof Error?t.message:"Unknown error";l("Failed to void note: "+n,"error")}}async function Ut(){if(!(!o||!i.id||i.signed))try{const{error:t}=await v.from("visit_notes").update({deleted_at:new Date().toISOString(),deleted_by:o.id}).eq("id",i.id);if(t)throw t;Te(),X.current="",l("Note deleted","success"),ce(!1),S?.(),y()}catch(t){const n=t instanceof Error?t.message:"Unknown error";l("Failed to delete note: "+n,"error")}}async function Wt(t){if(o){if(H.current&&!await new Promise(n=>{const x=Date.now(),u=3e4,w=setInterval(()=>{H.current?Date.now()-x>u&&(clearInterval(w),n(!1)):(clearInterval(w),n(!0))},100)})){l("Note save timed out. Please wait for the save to complete before signing.","error");return}Q.current=!0;try{const n={visit_id:s.id,subjective:i.subjective,objective:i.objective,asse
42ssment:i.assessment,plan:i.plan,ai_compliance_score:m?.score||0,ai_compliance_suggestions:m?.suggestions||[],ai_analysis:m?.analysis||{}};let x=i.id;const{data:u}=await v.from("visit_notes").select("id").eq("visit_id",s.id).is("deleted_at",null).maybeSingle();if(u){const{error:he}=await v.from("visit_notes").update(n).eq("id",u.id);if(he)throw he;x=u.id}else{const{data:he}=await v.from("visit_notes").insert(n).select("id").maybeSingle();x=he?.id}if(!x)throw new Error("Failed to save visit note");k.length>0&&await kt(s.id,k);const w=await oe(t),P=`${o.first_name} ${o.last_name}`,V=o.specialty||o.provider_type||"",{data:O,error:Z}=await v.from("electronic_signatures").insert({organization_id:o.organization_id,user_id:o.id,signature_data:t,signature_hash:w,entity_type:"visit_note",entity_id:x,signer_name:P,signer_credentials:V,signer_npi:o.npi_number,user_agent:navigator.userAgent,timestamp:new Date().toISOString()}).select().maybeSingle();if(Z)throw Z;if(!O)throw new Error("Failed to create signature record");const Ve=ae&&ge,ut={signed:!0,signed_at:new Date().toISOString(),signed_by:o.id,signature_id:O.id};Ve&&(ut.pending_cosignature=!0,ut.cosigned_by=ge);const{error:wt}=await v.from("visit_notes").update(ut).eq("id",x);if(wt)throw wt;const{error:yt}=await v.from("visits").update({status:"completed"}).eq("id",s.id);if(yt)throw yt;if(k.length>0&&o.organization_id){const he=await gs({visitId:s.id,patientId:r.id,providerId:o.id,organizationId:o.organization_id,billingCodes:k,serviceDate:s.visit_date||new Date().toISOString().split("T")[0]});he.status==="ready"?l("Note signed -- claim created and ready for submission","success"):he.status==="scrubbed"?l(`Note signed -- claim created but needs review: ${he.scrubErrors.join(", ")}`,"warning"):he.status==="error"&&l("Note signed -- claim could not be auto-created","warning")}else l("Note signed and visit completed","success");ne(!1),S&&S()}catch(n){const x=n instanceof Error?n.message:String(n);l("Error signing: "+x,"error")}finally{Q.current=!1}}}function Kt(){if(!("webkitSpeechRecognition"in window)&&!("SpeechRecognition"in window)){l("Voice recognition not supported","error");return}const t=window.webkitSpeechRecognition||window.SpeechRecognition;if(!t)return;const n=new t;n.continuous=!0,n.interimResults=!0,n.lang="en-US",n.onstart=()=>{xe(!0),l("Listening...","info")},n.onresult=x=>{let u="";for(let w=x.resultIndex;w<x.results.length;w++)x.results[w].isFinal&&(u+=x.results[w][0].transcript+" ");u&&g(w=>({...w,[h]:(w[h]||"")+u}))},n.onerror=x=>{l("Voice error: "+x.error,"error"),xe(!1)},n.onend=()=>{xe(!1),J.current&&(clearTimeout(J.current),J.current=null)},n.start(),G.current=n,$e(n),J.current=setTimeout(()=>{G.current&&(G.current.stop(),l("Voice recording stopped after 2 minutes","info"))},12e4)}function Gt(){J.current&&(clearTimeout(J.current),J.current=null),G.current&&(G.current.stop(),G.current=null,xe(!1))}function Jt(t){return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,"0")}`}function Nt(t){return(i[t]||"").trim().split(/\s+/).filter(n=>n.length>0).length>=5}function Yt(){const t=["subjective","objective","assessment","plan"].filter(n=>Nt(n)).length;return Math.round(t/4*100)}async function Xt(){try{const{generateAndDownloadPdf:t,buildVisitNoteSections:n,buildPdfBranding:x}=await ts(async()=>{const{generateAndDownloadPdf:P,buildVisitNoteSections:V,buildPdfBranding:O}=await import("./chunk-pdf-lib-D08dpjkn.js").then(Z=>Z.t);return{generateAndDownloadPdf:P,buildVisitNoteSections:V,buildPdfBranding:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])),{data:u}=await v.from("organizations").select("*").eq("id",o?.organization_id).maybeSingle(),w=x(u);await t({title:"Visit Note",subtitle:`${r.first_name} ${r.last_name}`,branding:w,patientName:`${r.first_name} ${r.last_name}`,patientDob:r.date_of_birth||void 0,sections:n({visitDate:new Date(s.visit_date).toLocaleDateString(),visitType:s.visit_type,chiefComplaint:s.chief_complaint||void 0,subjective:i.subjective||void 0,objective:i.objective||void 0,assessment:i.assessment||void 0,plan:i.plan||void 0,allergies:r.allergies||void 0,complianceScore:m?.score,providerName:o?.full_name||`${o?.first_name||""} ${o?.last_name||""}`.trim(),providerCredentials:o?.credentials||void 0,signedAt:i.signed&&i.signed_at||void 0})},`Visit_Note_${r.last_name}_${new Date(s.visit_date).toISOString().split("T")[0]}.pdf`),l("Visit note exported","success")}
42catch(t){M.error("PDF export error:",q(t)),l("Failed to export PDF","error")}}const Zt=Rt.filter(t=>ue===""||t.trigger.toLowerCase().includes(ue.toLowerCase())||t.content.toLowerCase().includes(ue.toLowerCase())||t.category.toLowerCase().includes(ue.toLowerCase())),nt=Yt(),Qt=m&&m.score>=70&&!i.signed;return(0,e.jsxs)("div",{className:"fixed inset-0 bg-slate-100 z-50 flex flex-col",children:[(0,e.jsxs)("header",{className:"bg-white border-b border-slate-200 px-6 py-3 flex items-center justify-between shadow-xs",children:[(0,e.jsxs)("div",{className:"flex items-center gap-4",children:[(0,e.jsx)("button",{onClick:y,className:"p-2 hover:bg-slate-100 rounded-lg transition-colors",children:(0,e.jsx)(vt,{className:"w-5 h-5"})}),(0,e.jsxs)("div",{children:[(0,e.jsxs)("h1",{className:"text-lg font-bold text-slate-900",children:[r.first_name," ",r.last_name]}),(0,e.jsxs)("p",{className:"text-sm text-slate-600",children:[s.visit_type," Visit - ",new Date(s.visit_date).toLocaleDateString()]})]})]}),(0,e.jsxs)("div",{className:"flex items-center gap-6",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,e.jsx)(Et,{className:"w-4 h-4 text-slate-400"}),(0,e.jsx)("span",{className:"text-slate-600",children:Jt(Ie)})]}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("div",{className:"w-32 h-2 bg-slate-200 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:`h-full transition-all duration-300 ${nt>=75?"bg-green-500":nt>=50?"bg-yellow-500":"bg-blue-500"}`,style:{width:`${nt}%`}})}),(0,e.jsxs)("span",{className:"text-sm font-medium text-slate-600",children:[nt,"%"]})]}),(0,e.jsx)("div",{className:"flex items-center gap-2 text-sm",children:d?(0,e.jsxs)("span",{className:"text-blue-600 flex items-center gap-1",children:[(0,e.jsx)("div",{className:"w-3 h-3 border-2 border-blue-600 border-t-transparent rounded-full animate-spin"}),"Saving..."]}):L?(0,e.jsxs)("span",{className:"text-green-600 flex items-center gap-1",children:[(0,e.jsx)(tt,{className:"w-4 h-4"}),"Saved ",L.toLocaleTimeString()]}):null}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsxs)("button",{onClick:Xt,className:"flex items-center gap-2 px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 transition-colors font-medium",title:"Export PDF",children:[(0,e.jsx)(ds,{className:"w-4 h-4"}),"PDF"]}),!i.signed&&(0,e.jsxs)(e.Fragment,{children:[i.id&&(0,e.jsxs)("button",{onClick:()=>ce(!0),className:"flex items-center gap-2 px-4 py-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-colors font-medium border border-red-200",title:"Delete draft note",children:[(0,e.jsx)(ht,{className:"w-4 h-4"}),"Delete"]}),(0,e.jsxs)("button",{onClick:De,disabled:d,className:"flex items-center gap-2 px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 transition-colors font-medium",children:[(0,e.jsx)(bt,{className:"w-4 h-4"}),"Save"]}),(0,e.jsxs)("button",{onClick:ee,disabled:j,className:"flex items-center gap-2 px-4 py-2 bg-linear-to-r from-blue-600 to-cyan-600 text-white rounded-lg hover:from-blue-700 hover:to-cyan-700 transition-colors font-medium",children:[(0,e.jsx)(dt,{className:"w-4 h-4"}),j?"Analyzing...":"AI Check"]}),Qt&&(0,e.jsxs)("button",{onClick:()=>ne(!0),className:"flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium",children:[(0,e.jsx)(us,{className:"w-4 h-4"}),"Sign & Complete"]})]})]})]})]}),i.pending_cosignature&&(0,e.jsxs)("div",{className:"flex items-center gap-3 px-6 py-3 bg-amber-50 border-b border-amber-200",children:[(0,e.jsx)(et,{className:"w-5 h-5 text-amber-600 shrink-0"}),(0,e.jsx)("span",{className:"text-sm text-amber-800 font-medium",children:"Awaiting cosigner approval — this note is pending review by the supervising provider before it becomes final."})]}),(0,e.jsxs)("div",{className:"flex-1 flex overflow-hidden",children:[(0,e.jsxs)("aside",{className:"w-72 bg-white border-r border-slate-200 overflow-y-auto",children:[(0,e.jsxs)("div",{className:"p-4 border-b border-slate-200",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-3",children:[(0,e.jsx)("h3",{className:"text-sm font-semibold text-slate-500 uppercase tracking-wider",children:"Patient 
42Context"}),!i.signed&&(_||W.length>0||U.length>0)&&(0,e.jsxs)("button",{onClick:R,className:"flex items-center gap-1 px-2 py-1 text-[11px] font-semibold bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors",children:[(0,e.jsx)(ft,{className:"w-3 h-3"}),"Insert All"]})]}),r.allergies&&r.allergies.length>0&&(0,e.jsxs)("div",{className:"mb-4 p-3 bg-red-50 border border-red-200 rounded-lg",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 text-red-700 font-medium text-sm mb-1",children:[(0,e.jsx)(et,{className:"w-4 h-4"}),"Allergies"]}),(0,e.jsx)("div",{className:"text-sm text-red-600",children:r.allergies.join(", ")})]}),_&&(0,e.jsxs)("div",{className:"mb-4",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,e.jsx)("span",{className:"text-sm font-medium text-slate-700",children:"Recent Vitals"}),(0,e.jsx)("button",{onClick:He,className:"text-xs text-blue-600 hover:text-blue-700",children:"Insert"})]}),(0,e.jsxs)("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[(0,e.jsxs)("div",{className:"flex items-center gap-1 text-slate-600",children:[(0,e.jsx)(Ls,{className:"w-3 h-3 text-red-500"}),_.blood_pressure_systolic,"/",_.blood_pressure_diastolic]}),(0,e.jsxs)("div",{className:"flex items-center gap-1 text-slate-600",children:[(0,e.jsx)(rt,{className:"w-3 h-3 text-pink-500"}),_.heart_rate," bpm"]}),(0,e.jsxs)("div",{className:"flex items-center gap-1 text-slate-600",children:[(0,e.jsx)(Lt,{className:"w-3 h-3 text-orange-500"}),_.temperature,_.temperature_unit]}),(0,e.jsxs)("div",{className:"flex items-center gap-1 text-slate-600",children:[(0,e.jsx)(Pt,{className:"w-3 h-3 text-blue-500"}),_.oxygen_saturation,"%"]})]})]})]}),(0,e.jsxs)("div",{className:"p-4 border-b border-slate-200",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,e.jsx)("span",{className:"text-sm font-medium text-slate-700",children:"Active Problems"}),W.length>0&&(0,e.jsx)("button",{onClick:Qe,className:"text-xs text-blue-600 hover:text-blue-700",children:"Insert"})]}),W.length>0?(0,e.jsxs)("div",{className:"space-y-1",children:[W.slice(0,5).map(t=>(0,e.jsx)("div",{className:"text-sm text-slate-600 truncate",title:t.diagnosis_name,children:t.diagnosis_name},t.id)),W.length>5&&(0,e.jsxs)("div",{className:"text-xs text-slate-400",children:["+",W.length-5," more"]})]}):(0,e.jsx)("div",{className:"text-sm text-slate-400",children:"No active problems"})]}),(0,e.jsxs)("div",{className:"p-4 border-b border-slate-200",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,e.jsx)("span",{className:"text-sm font-medium text-slate-700",children:"Medications"}),U.length>0&&(0,e.jsx)("button",{onClick:f,className:"text-xs text-blue-600 hover:text-blue-700",children:"Insert"})]}),U.length>0?(0,e.jsxs)("div",{className:"space-y-1",children:[U.slice(0,5).map(t=>(0,e.jsxs)("div",{className:"text-sm text-slate-600 truncate",title:t.medication_name,children:[(0,e.jsx)(We,{className:"w-3 h-3 inline mr-1 text-green-500"}),t.medication_name]},t.id)),U.length>5&&(0,e.jsxs)("div",{className:"text-xs text-slate-400",children:["+",U.length-5," more"]})]}):(0,e.jsx)("div",{className:"text-sm text-slate-400",children:"No active medications"})]}),(0,e.jsxs)("div",{className:"p-4",children:[(0,e.jsx)("h3",{className:"text-sm font-semibold text-slate-500 uppercase tracking-wider mb-3",children:"Quick Tools"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsxs)("button",{onClick:()=>me(!0),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-left bg-slate-50 hover:bg-slate-100 rounded-lg transition-colors",children:[(0,e.jsx)(ft,{className:"w-4 h-4 text-yellow-500"}),"Smart Phrases"]}),(0,e.jsxs)("button",{onClick:se?Gt:Kt,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left rounded-lg transition-colors ${se?"bg-red-50 text-red-700":"bg-slate-50 hover:bg-slate-100"}`,children:[se?(0,e.jsx)(Es,{className:"w-4 h-4"}):(0,e.jsx)(hs,{className:"w-4 h-4 text-blue-500"}),se?"Stop Dictation":"Voice Dictation"]}),(0,e.jsxs)("div",{className:"pt-2",children:[(0,e.jsx)("label",{className:"text-xs text-slate-500 mb-1 block",children:"Apply Template"}),(0,e.jsxs)("select",{value:Je,onChange:t=>Be(t.target.value),className:"w-full text-sm px-3 py-2 border border-slate-200 rounded-lg",disabled:i.signed,children:[(0,e.jsx)("option",{value:"",children:"Select template..."}),Pe.map(t=>(0,e.jsx)("option",{value:t.id,children:t.name},t.id))]})]})]})]})]}),(0,e.jsx)("main",{className:"flex-1 overflow-y-auto p-6",children:(0,e.jsxs)("div",{className:"max-w-4xl mx-auto 
42space-y-4",children:[i.signed&&(0,e.jsxs)("div",{className:"p-4 bg-green-50 border border-green-200 rounded-xl flex items-center gap-3",children:[(0,e.jsx)(pe,{className:"w-6 h-6 text-green-600"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("div",{className:"font-medium text-green-800",children:"Note Signed"}),(0,e.jsx)("div",{className:"text-sm text-green-600",children:i.signed_at&&new Date(i.signed_at).toLocaleString()})]}),i.id&&(0,e.jsxs)("div",{className:"ml-auto flex gap-2",children:[(0,e.jsxs)("button",{onClick:()=>D(!0),className:"px-3 py-1.5 text-sm bg-white border border-green-300 text-green-700 rounded-lg hover:bg-green-50",children:[(0,e.jsx)(pt,{className:"w-4 h-4 inline mr-1"}),"History"]}),(0,e.jsxs)("button",{onClick:()=>z(!0),className:"px-3 py-1.5 text-sm bg-white border border-amber-300 text-amber-700 rounded-lg hover:bg-amber-50",children:[(0,e.jsx)(ks,{className:"w-4 h-4 inline mr-1"}),"Addendum"]})]})]}),m&&(0,e.jsxs)("div",{className:`rounded-xl border overflow-hidden ${m.score>=80?"border-green-200":m.score>=60?"border-yellow-200":"border-red-200"}`,children:[(0,e.jsxs)("div",{className:`p-4 ${m.score>=80?"bg-green-50":m.score>=60?"bg-yellow-50":"bg-red-50"}`,children:[(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsx)("span",{className:"font-medium text-slate-800",children:"Compliance Score"}),(0,e.jsxs)("span",{className:`text-2xl font-bold ${m.score>=80?"text-green-600":m.score>=60?"text-yellow-600":"text-red-600"}`,children:[m.score,"%"]})]}),m.score<100&&(0,e.jsx)("div",{className:"mt-1.5 w-full h-1.5 bg-white/60 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:`h-full rounded-full transition-all ${m.score>=80?"bg-green-500":m.score>=60?"bg-yellow-500":"bg-red-500"}`,style:{width:`${m.score}%`}})})]}),m.gaps&&m.gaps.length>0&&(0,e.jsx)("div",{className:"bg-white divide-y divide-slate-100",children:m.gaps.map((t,n)=>(0,e.jsxs)("div",{className:`px-4 py-2.5 flex items-start gap-2.5 ${t.severity==="error"?"bg-red-50/50":""}`,children:[(0,e.jsx)(_t,{className:`w-4 h-4 shrink-0 mt-0.5 ${t.severity==="error"?"text-red-500":"text-amber-500"}`}),(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:`text-xs font-semibold uppercase tracking-wide ${t.severity==="error"?"text-red-600":"text-amber-600"}`,children:t.field}),(0,e.jsx)("span",{className:`text-xs px-1.5 py-0.5 rounded-full font-medium ${t.severity==="error"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:t.severity})]}),(0,e.jsx)("p",{className:"text-sm text-slate-700 mt-0.5",children:t.message}),t.hint&&(0,e.jsx)("p",{className:"text-xs text-slate-500 mt-0.5 italic",children:t.hint})]})]},n))}),(!m.gaps||m.gaps.length===0)&&m.suggestions?.length>0&&(0,e.jsx)("div",{className:"bg-white px-4 py-3 space-y-1",children:m.suggestions.slice(0,3).map((t,n)=>(0,e.jsxs)("div",{className:"text-sm flex items-start gap-2",children:[(0,e.jsx)(_t,{className:"w-4 h-4 text-amber-500 shrink-0 mt-0.5"}),t]},n))})]}),["subjective","objective","assessment","plan"].map(t=>{const n=c.has(t),x=Nt(t),u={subjective:{title:"Subjective",subtitle:"Chief Complaint & History of Present Illness"},objective:{title:"Objective",subtitle:"Physical Exam & Findings"},assessment:{title:"Assessment",subtitle:"Diagnosis & Clinical Impression"},plan:{title:"Plan",subtitle:"Treatment & Follow-up"}};return(0,e.jsxs)("div",{className:`bg-white rounded-xl shadow-xs border transition-all ${h===t?"border-blue-300 ring-2 ring-blue-100":"border-slate-200"}`,children:[(0,e.jsxs)("button",{onClick:()=>{C(n?w=>{const P=new Set(w);return P.delete(t),P}:w=>new Set(w).add(t))},className:"w-full p-4 flex items-center justify-between text-left hover:bg-slate-50 transition-colors rounded-t-xl",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[x?(0,e.jsx)("div",{className:"w-6 h-6 rounded-full bg-green-100 flex items-center justify-center",children:(0,e.jsx)(tt,{className:"w-4 h-4 text-green-600"})}):(0,e.jsx)("div",{className:"w-6 h-6 rounded-full border-2 border-slate-300"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("div",{className:"font-semibold text-slate-900",children:u[t].title}),(0,e.jsx)("div",{className:"text-sm text-slate-500",children:u[t].subtitle})]})]}),n?(0,e.jsx)(qs,{className:"w-5 h-5 text-slate-400"}):(0,e.jsx)(is,{className:"w-5 h-5 text-slate-400"})]}),n&&(0,e.jsxs)("div",{className:"p-4 pt-0",children:[(0,e.jsx)("textarea",{ref:w=>{Ne.current[t]=w},value:i[t]||"",onChange:w=>g(P=>({...P,[t]:w.target.value})),onFocus:()=>T(t),onKeyDown:w=>Oe(w,t),placeholder:`Enter ${u[t].title.toLowerCase()} notes... (Type .phrase for smart phrases)`,className:"w-full min-h-[150px] p-3 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-y text-slate-800",disabled:i.signed}),(0,e.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-xs text-slate-400",children:[(0,e.jsx)("span",{children:"Tab to next section"}),(0,e.jsx)("span",{children:"|"}),(0,e.jsx)("span",{children:"Type .wnl, .nad, .ctab for quick phrases"})]})]})]},t)}),k.length>0&&(0,e.jsxs)("div",{className:"bg-white rounded-xl shadow-xs border border-slate-200 p-4",children:[(0,e.jsx)("h3",{className:"font-semibold text-slate-900 mb-3",children:"Suggested Billing Codes"}),(0,e.jsx)("div",{className:"grid grid-cols-2 gap-3",children:k.map((t,n)=>(0,e.jsxs)("div",{className:"p-3 bg-slate-50 rounded-lg border border-slate-200",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,e.jsx)("span",{className:`text-xs font-medium px-2 py-0.5 rounded ${t.codeType==="ICD10"?"bg-blue-100 text-blue-700":"bg-green-100 text-green-700"}`,children:t.codeType}),(0,e.jsxs)("span",{className:"text-xs text-slate-500",children:[t.confidence,"%"]})]}),(0,e.jsx)("div",{className:"font-medium text-slate-900",children:t.code}),(0,e.jsx)("div",{className:"text-sm text-slate-600 truncate",children:t.description})]},n))})]})]})}),o?.organization_id&&(0,e.jsx)(ws,{encounterId:s.id,patientId:r.id,organizationId:o.organization_id,visitData:{chiefComplaint:i.subjective||void 0,assessment:i.assessment||void 0,plan:i.plan||void 0}})]}),Ye&&(0,e.jsx)("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:(0,e.jsxs)("div",{className:"bg-white rounded-xl shadow-2xl max-w-lg w-full max-h-[80vh] flex flex-col",children:[(0,e.jsxs)("div",{className:"p-4 border-b border-slate-200 flex items-center justify-between",children:[(0,e.jsx)("h3",{className:"text-lg font-bold text-slate-900",children:"Smart Phrases"}),(0,e.jsx)("button",{onClick:()=>me(!1),className:"p-2 hover:bg-slate-100 rounded-lg",children:(0,e.jsx)(jt,{className:"w-5 h-5"})})]}),(0,e.jsx)("div",{className:"p-4 border-b border-slate-200",children:(0,e.jsx)("input",{type:"text",placeholder:"Search phrases...",value:ue,onChange:t=>Fe(t.target.value),className:"w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500",autoFocus:!0})}),(0,e.jsx)("div",{className:"flex-1 overflow-y-auto p-4",children:(0,e.jsx)("div",{className:"space-y-2",children:Zt.map(t=>(0,e.jsxs)("button",{onClick:()=>Ee(t),className:"w-full text-left p-3 hover:bg-blue-50 rounded-lg border border-slate-200 hover:border-blue-300 transition-colors",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,e.jsx)("code",{className:"text-sm font-mono text-blue-600 bg-blue-50 px-2 py-0.5 rounded",children:t.trigger}),(0,e.jsx)("span",{className:"text-xs text-slate-400 capitalize",children:t.category})]}),(0,e.jsx)("div",{className:"text-sm text-slate-700",children:t.content})]},t.id))})})]})}),be&&o&&(0,e.jsx)(Vt,{onSign:Wt,onCancel:()=>ne(!1),signerName:`${o.first_name} ${o.last_name}`,signerCredentials:o.specialty||o.provider_type,savedSignature:o.signature_data}),p&&i.id&&(0,e.jsx)(Ht,{visitNoteId:i.id,onClose:()=>D(!1)}),F&&i.id&&(0,e.jsx)(Bt,{visitNoteId:i.id,onClose:()=>z(!1),onSuccess:()=>{z(!1),$()}}),_e&&(0,e.jsx)("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:(0,e.jsxs)("div",{className:"bg-white rounded-xl shadow-2xl max-w-md w-full",children:[(0,e.jsx)("div",{className:"p-6 border-b border-slate-200",children:(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsx)("div",{className:"p-2 bg-orange-100 rounded-lg",children:(0,e.jsx)(xs,{className:"w-6 h-6 text-orange-600"})}),(0,e.jsxs)("div",{children:[(0,e.jsx)("h3",{className:"text-xl font-bold text-slate-900",children:"Void Note"}),(0,e.jsx)("p",{className:"text-sm text-slate-600",children:"This action cannot be undone"})]})]})}),(0,e.jsx)("div",{className:"p-6",children:(0,e.jsx)("textarea",{value:de,onChange:t=>Se(t.target.value),rows:4,placeholder:"Enter reason for voiding...",className:"w-full px-4 py-3 border border-slate-300 rounded-lg"})}),(0,e.jsxs)("div",{className:"p-6 border-t border-slate-200 bg-slate-50 flex gap-3",children:[(0,e.jsx)("button",{onClick:()=>{ie(!1),Se("")},className:"flex-1 px-6 py-3 bg-slate-200 text-slate-800 rounded-lg hover:bg-slate-300 font-medium",children:"Cancel"}),(0,e.jsx)("button",{onClick:at,disabled:!de.trim(),className:"flex-1 px-6 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700 font-medium disabled:opacity-50",children:"Void Note"})]})]})}),Ke&&(0,e.jsx)("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:(0,e.jsxs)("div",{className:"bg-white rounded-xl shadow-2xl max-w-md w-full",children:[(0,e.jsx)("div",{className:"p-6 border-b border-slate-200",children:(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsx)("div",{className:"p-2 bg-red-100 rounded-lg",children:(0,e.jsx)(ht,{className:"w-6 h-6 text-red-600"})}),(0,e.jsxs)("div",{children:[(0,e.jsx)("h3",{className:"text-xl font-bold text-slate-900",children:"Delete Draft Note"}),(0,e.jsx)("p",{className:"text-sm text-slate-600",children:"This will remove the unsaved draft"})]})]})}),(0,e.jsx)("div",{className:"p-6",children:(0,e.jsxs)("p",{className:"text-slate-700",children:["Are you sure you want to delete this draft note for"," ",(0,e.jsxs)("span",{className:"font-semibold",children:[r.first_name," ",r.last_name]}),"? This note has not been signed and can be deleted."]})}),(0,e.jsxs)("div",{className:"p-6 border-t border-slate-200 bg-slate-50 flex gap-3",children:[(0,e.jsx)("button",{onClick:()=>ce(!1),className:"flex-1 px-6 py-3 bg-slate-200 text-slate-800 rounded-lg hover:bg-slate-300 font-medium",children:"Cancel"}),(0,e.jsx)("button",{onClick:Ut,className:"flex-1 px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 font-medium",children:"Delete Note"})]})]})})]})}function Ks({patientId:s,visitId:r,currentNote:y,onInsertText:S,onApplyCode:o,collapsed:l=!1,onToggleCollapse:i}){const{showToast:g}=mt(),[h,T]=(0,a.useState)(!1),[c,C]=(0,a.useState)(null),[m,I]=(0,a.useState)([]),[k,E]=(0,a.useState)(""),[j,A]=(0,a.useState)([]),[d,N]=(0,a.useState)(!1),L=(0,a.useRef)(null);(0,a.useEffect)(()=>
42{if(!s)return;async function p(){if(await Ue.initialize(),await Ue.setContext({patientId:s,visitId:r,currentView:"encounter"}),s){const D=await Ue.loadPatientContext(s);C(D)}}p()},[s,r]),(0,a.useEffect)(()=>{L.current?.scrollIntoView({behavior:"smooth"})},[j]);async function B(){if(!y||!y.subjective&&!y.assessment){g("Add some documentation first","warning");return}T(!0);try{const p=await Ue.suggestBillingCodes(y),D=[];p&&Array.isArray(p)&&p.slice(0,5).forEach((F,z)=>{D.push({id:`code-${z}`,type:"code",title:F.code,content:F.description,confidence:F.confidence})}),I(D)}catch(p){M.error("Failed to generate suggestions:",q(p))}finally{T(!1)}}async function be(){if(!k.trim()||h)return;const p=k.trim();E(""),A(D=>[...D,{role:"user",content:p}]),T(!0);try{await Ue.setContext({patientId:s,visitId:r,currentView:"encounter",encounter:y?{visitId:r||"",subjective:y.subjective,objective:y.objective,assessment:y.assessment,plan:y.plan}:void 0});const D=await Ue.chat(p,{includeContext:!0});if(A(F=>[...F,{role:"assistant",content:D.text}]),D.suggestions){const F=D.suggestions.map((z,_e)=>({id:`sugg-${_e}`,type:z.type==="diagnosis"?"diagnosis":z.type==="procedure_code"?"code":"action",title:z.content?.code||z.content?.name||"Suggestion",content:z.reasoning||"",confidence:z.confidence}));I(z=>[...z,...F])}}catch{A(F=>[...F,{role:"assistant",content:"Sorry, I encountered an error. Please try again."}])}finally{T(!1)}}function ne(p){p.type==="code"&&o?o(p.title,p.title.startsWith("99")?"CPT":"ICD10"):p.type==="documentation"&&S&&S("assessment",p.content),I(D=>D.map(F=>F.id===p.id?{...F,applied:!0}:F)),g("Suggestion applied","success")}return l?(0,e.jsxs)("div",{className:"w-12 bg-white border-l border-slate-200 flex flex-col items-center py-4",children:[(0,e.jsx)("button",{onClick:i,className:"p-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",title:"Expand CareMetric Copilot",children:(0,e.jsx)(lt,{className:"w-5 h-5"})}),(0,e.jsxs)("div",{className:"mt-4 space-y-3",children:[(0,e.jsx)("button",{onClick:()=>{i?.(),N(!1)},className:"p-2 hover:bg-slate-100 rounded-lg transition-colors",title:"AI Suggestions",children:(0,e.jsx)(gt,{className:"w-5 h-5 text-slate-500"})}),(0,e.jsx)("button",{onClick:()=>{i?.(),N(!0)},className:"p-2 hover:bg-slate-100 rounded-lg transition-colors",title:"AI Chat",children:(0,e.jsx)(xt,{className:"w-5 h-5 text-slate-500"})})]})]}):(0,e.jsxs)("div",{className:"w-80 bg-white border-l border-slate-200 flex flex-col h-full",children:[(0,e.jsx)("div",{className:"p-3 border-b border-slate-200 bg-linear-to-r from-blue-600 to-blue-700",children:(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 text-white",children:[(0,e.jsx)(lt,{className:"w-5 h-5"}),(0,e.jsx)("span",{className:"font-semibold",children:"CareMetric Copilot"}),(0,e.jsx)(dt,{className:"w-4 h-4 text-yellow-300 animate-pulse"})]}),(0,e.jsx)("button",{onClick:i,className:"p-1 hover:bg-white/20 rounded transition-colors text-white",children:(0,e.jsx)(it,{className:"w-5 h-5"})})]})}),(0,e.jsxs)("div",{className:"flex border-b border-slate-200",children:[(0,e.jsxs)("button",{onClick:()=>N(!1),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${d?"text-slate-500 hover:bg-slate-50":"text-blue-600 border-b-2 border-blue-600 bg-blue-50"}`,children:[(0,e.jsx)(gt,{className:"w-4 h-4 inline mr-1"}),"Suggestions"]}),(0,e.jsxs)("button",{onClick:()=>N(!0),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${d?"text-blue-600 border-b-2 border-blue-600 bg-blue-50":"text-slate-500 hover:bg-slate-50"}`,children:[(0,e.jsx)(xt,{className:"w-4 h-4 inline mr-1"}),"Chat"]})]}),d?(0,e.jsxs)("div",{className:"flex-1 flex flex-col overflow-hidden",children:[(0,e.jsxs)("div",{className:"flex-1 overflow-auto p-3 space-y-3",children:[j.length===0?(0,e.jsxs)("div",{className:"text-center py-4 text-slate-500",children:[(0,e.jsx)(xt,{className:"w-10 h-10 mx-auto mb-2 text-slate-300"}),(0,e.jsx)("p",{className:"text-sm",children:"Ask me anything about this patient"})]}):j.map((p,D)=>(0,e.jsx)("div",{className:`p-2.5 rounded-lg text-sm ${p.role==="user"?"bg-blue-600 text-white ml-4":"bg-slate-100 text-slate-900 mr-4"}`,children:p.content},D)),h&&(0,e.jsxs)("div",{className:"flex items-center gap-2 text-slate-500 text-sm p-2",children:[(0,e.jsx)(St,{className:"w-4 h-4 animate-spin"}),"Thinking..."]}),(0,e.jsx)("div",{ref:L})]}),(0,e.jsx)("div",{className:"p-3 border-t border-slate-200",children:(0,e.jsxs)("div",{className:"flex gap-2",children:[(0,e.jsx)("input",{type:"text",value:k,onChange:p=>E(p.target.value),onKeyPress:p=>p.key==="Enter"&&be(),placeholder:"Ask about dx, codes, meds...",className:"flex-1 px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500",disabled:h}),(0,e.jsx)("button",{onClick:be,disabled:!k.trim()||h,className:"p-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-slate-300 transition-colors",children:(0,e.jsx)(Tt,{className:"w-4 h-4"})})]})})]}):(0,e.jsxs)("div",{className:"flex-1 flex flex-col overflow-hidden",children:[c&&(0,e.jsxs)("div",{className:"p-3 bg-slate-50 border-b border-slate-200",children:[(0,e.jsx)("p",{className:"text-xs font-medium text-slate-500 mb-1",children:"Patient 
42Context"}),(0,e.jsx)("p",{className:"text-sm font-medium text-slate-900",children:c.name}),(0,e.jsxs)("p",{className:"text-xs text-slate-500",children:[c.age,"yo ",c.gender," | ",c.activeProblems.length," problems"]})]}),(0,e.jsx)("div",{className:"p-3 border-b border-slate-200",children:(0,e.jsx)("button",{onClick:B,disabled:h,className:"w-full flex items-center justify-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-slate-300 transition-colors text-sm font-medium",children:h?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(St,{className:"w-4 h-4 animate-spin"}),"Analyzing..."]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(ft,{className:"w-4 h-4"}),"Get AI Suggestions"]})})}),(0,e.jsx)("div",{className:"flex-1 overflow-auto p-3 space-y-2",children:m.length===0?(0,e.jsxs)("div",{className:"text-center py-8 text-slate-500",children:[(0,e.jsx)(gt,{className:"w-10 h-10 mx-auto mb-2 text-slate-300"}),(0,e.jsx)("p",{className:"text-sm",children:"Click above to get AI suggestions"}),(0,e.jsx)("p",{className:"text-xs text-slate-400 mt-1",children:"Based on your documentation"})]}):m.map(p=>(0,e.jsx)("div",{className:`p-3 rounded-lg border transition-all ${p.applied?"bg-green-50 border-green-200":"bg-white border-slate-200 hover:border-blue-300 cursor-pointer"}`,role:"button",tabIndex:p.applied?-1:0,"aria-label":`Apply suggestion: ${p.title}${p.applied?" (applied)":""}`,"aria-disabled":p.applied,onClick:()=>!p.applied&&ne(p),onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&!p.applied&&(D.preventDefault(),ne(p))},children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,e.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[p.type==="code"&&(0,e.jsx)(os,{className:"w-4 h-4 text-green-600"}),p.type==="diagnosis"&&(0,e.jsx)(ot,{className:"w-4 h-4 text-blue-600"}),p.type==="documentation"&&(0,e.jsx)(Dt,{className:"w-4 h-4 text-purple-600"}),(0,e.jsx)("span",{className:"font-medium text-slate-900 text-sm",children:p.title})]}),(0,e.jsx)("p",{className:"text-xs text-slate-600 line-clamp-2",children:p.content})]}),p.applied?(0,e.jsx)(pe,{className:"w-5 h-5 text-green-600 shrink-0"}):(0,e.jsxs)("span",{className:`text-xs px-2 py-0.5 rounded-full shrink-0 ${p.confidence>.8?"bg-green-100 text-green-700":p.confidence>.5?"bg-yellow-100 text-yellow-700":"bg-slate-100 text-slate-600"}`,children:[Math.round(p.confidence*100),"%"]})]})},p.id))})]})]})}function Gs({patient:s,diagnosis:r}){const[y,S]=(0,a.useState)(!1),[o,l]=(0,a.useState)("medications"),[i,g]=(0,a.useState)([]),[h,T]=(0,a.useState)(null),[c,C]=(0,a.useState)(null);async function m(){if(r){S(!0);try{const d=s.allergies||[],N=await Ss(r,d);g(N)}catch(d){M.error("Error loading medication suggestions:",q(d))}finally{S(!1)}}}async function I(){S(!0);try{const d=await Ds(s.id,s.organization_id??"");T(d)}catch(d){M.error("Error loading trends:",q(d))}finally{S(!1)}}async function k(){S(!0);try{const d=await Ts(s.id,s.organization_id??"");C(d)}catch(d){M.error("Error loading risk assessment:",q(d))}finally{S(!1)}}const E=d=>{l(d),d==="medications"&&i.length===0?m():d==="trends"&&!h?I():d==="risk"&&!c&&k()},j=d=>{switch(d){case"high":return"text-red-600 bg-red-100";case"medium":return"text-yellow-600 bg-yellow-100";case"low":return"text-green-600 bg-green-100";default:return"text-slate-600 bg-slate-100"}},A=d=>{switch(d){case"improving":return"text-green-600";case"worsening":return"text-red-600";case"stable":return"text-blue-600";default:return"text-slate-600"}};return(0,e.jsxs)("div",{className:"bg-linear-to-br from-blue-50 to-blue-50 rounded-xl p-6 border border-blue-200",children:[(0,e.jsxs)("div",{className:"flex items-center space-x-3 mb-6",children:[(0,e.jsx)("div",{className:"p-3 bg-blue-600 rounded-lg",children:(0,e.jsx)(lt,{className:"w-6 h-6 text-white"})}),(0,e.jsxs)("div",{children:[(0,e.jsx)("h3",{className:"text-lg font-bold text-slate-900",children:"AI Clinical Decision Support"}),(0,e.jsx)("p",{className:"text-sm text-slate-600",children:"Powered by advanced medical AI"})]}),(0,e.jsx)(dt,{className:"w-5 h-5 text-yellow-500 animate-pulse ml-auto"})]}),(0,e.jsxs)("div",{className:"flex space-x-2 mb-4",children:[(0,e.jsxs)("button",{onClick:()=>E("medications"),className:`flex-1 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${o==="medications"?"bg-blue-600 text-white":"bg-white text-slate-700 hover:bg-slate-50"}`,children:[(0,e.jsx)(We,{className:"w-4 h-4 inline mr-2"}),"Medication Suggestions"]}),(0,e.jsxs)("button",{onClick:()=>E("trends"),className:`flex-1 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${o==="trends"?"bg-blue-600 text-white":"bg-white text-slate-700 hover:bg-slate-50"}`,children:[(0,e.jsx)(ns,{className:"w-4 h-4 inline mr-2"}),"Clinical Trends"]}),(0,e.jsxs)("button",{onClick:()=>E("risk"),className:`flex-1 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${o==="risk"?"bg-blue-600 text-white":"bg-white text-slate-700 hover:bg-slate-50"}`,children:[(0,e.jsx)(et,{className:"w-4 h-4 inline mr-2"}),"Risk Prediction"]})]}),y?(0,e.jsx)("div",{className:"flex items-center justify-center h-48",children:(0,e.jsx)("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"})}):(0,e.jsxs)("div",{className:"bg-white rounded-lg p-4 min-h-[300px]",children:[o==="medications"&&(0,e.jsx)("div",{children:r?i.length===0?(0,e.jsx)("p",{className:"text-slate-500 text-center py-8",children:"No medication suggestions available for this diagnosis"}):(0,e.jsx)("div",{className:"space-y-3",children:i.map((d,N)=>(0,e.jsxs)("div",{className:`p-4 rounded-lg border-2 ${d.confidence===0?"border-red-300 bg-red-50":"border-green-300 bg-green-50"}`,children:[(0,e.jsxs)("div",{className:"flex items-start justify-between mb-2",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h4",{className:"font-semibold text-slate-900",children:d.medication}),(0,e.jsxs)("p",{className:"text-sm text-slate-600",children:[d.dosage," - ",d.frequency]})]}),(0,e.jsxs)("span",{className:`px-3 py-1 rounded-full text-xs font-medium ${d.confidence===0?"bg-red-100 text-red-800":"bg-green-100 text-green-800"}`,children:[d.confidence,"% confidence"]})]}),(0,e.jsx)("p",{className:"text-sm text-slate-700 mb-2",children:d.rationale}),d.warnings.length>0&&(0,e.jsx)("div",{className:"mt-2 p-2 bg-red-100 border border-red-300 rounded",children:d.warnings.map((L,B)=>(0,e.jsx)("p",{className:"text-sm text-red-800 font-medium",children:L},B))})]},N))}):(0,e.jsx)("p",{className:"text-slate-500 text-center py-8",children:"Enter a diagnosis to get AI-powered medication suggestions"})}),o==="trends"&&h&&(0,e.jsxs)("div",{children:[h.alerts.length>0&&(0,e.jsxs)("div",{className:"mb-4 p-4 bg-red-50 border-l-4 border-red-500 rounded",children:[(0,e.jsxs)("h4",{className:"font-semibold text-red-900 mb-2 flex items-center",children:[(0,e.jsx)(et,{className:"w-5 h-5 mr-2"}),"Critical Alerts"]}),h.alerts.map((d,N)=>(0,e.jsx)("p",{className:"text-sm text-red-800",children:d},N))]}),(0,e.jsx)("div",{className:"space-y-4",children:h.trends.length===0?(0,e.jsx)("p",{className:"text-slate-500 text-center py-8",children:"Insufficient data to analyze trends. Need at least 2 vital sign records."}):h.trends.map((d,N)=>(0,e.jsxs)("div",{className:"p-4 bg-slate-50 rounded-lg",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,e.jsx)("h4",{className:"font-semibold text-slate-900",children:d.metric}),(0,e.jsx)("span",{className:`px-3 py-1 rounded-full text-xs font-medium ${A(d.trend)}`,children:d.trend})]}),(0,e.jsxs)("p",{className:"text-sm text-slate-600 mb-1",children:["Change: ",d.change>0?"+":"",d.change]}),(0,e.jsxs)("p",{className:"text-sm text-slate-700",children:[(0,e.jsx)("span",{className:"font-medium",children:"Recommendation:"})," ",d.recommendation]})]},N))})]}),o==="risk"&&c&&(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,e.jsxs)("div",{className:"p-4 bg-slate-50 rounded-lg",children:[(0,e.jsx)("h4",{className:"text-sm font-medium text-slate-600 mb-2",children:"Readmission Risk"}),(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsxs)("span",{className:"text-2xl font-bold text-slate-900",children:[c.readmissionRisk.score,"%"]}),(0,e.jsx)("span",{className:`px-3 py-1 rounded-full text-xs font-medium ${j(c.readmissionRisk.level)}`,children:c.readmissionRisk.level})]})]}),(0,e.jsxs)("div",{className:"p-4 bg-slate-50 rounded-lg",children:[(0,e.jsx)("h4",{className:"text-sm font-medium text-slate-600 mb-2",children:"Complication Risk"}),(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsxs)("span",{className:"text-2xl font-bold text-slate-900",children:[c.complicationRisk.score,"%"]}),(0,e.jsx)("span",{className:`px-3 py-1 rounded-full text-xs font-medium ${j(c.complicationRisk.level)}`,children:c.complicationRisk.level})]})]}),(0,e.jsxs)("div",{className:"p-4 bg-slate-50 rounded-lg",children:[(0,e.jsx)("h4",{className:"text-sm font-medium text-slate-600 mb-2",children:"Adherence Risk"}),(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsxs)("span",{className:"text-2xl font-bold text-slate-900",children:[c.medicationAdherenceRisk.score,"%"]}),(0,e.jsx)("span",{className:`px-3 py-1 rounded-full text-xs font-medium ${j(c.medicationAdherenceRisk.level)}`,children:c.medicationAdherenceRisk.level})]})]})]}),(0,e.jsxs)("div",{className:"p-4 bg-yellow-50 border border-yellow-200 rounded-lg",children:[(0,e.jsx)("h4",{className:"font-semibold text-yellow-900 mb-2",children:"Risk Factors"}),(0,e.jsxs)("div",{className:"space-y-2 text-sm text-yellow-800",children:[c.readmissionRisk.factors.map((d,N)=>(0,e.jsxs)("p",{children:["• ",d]},N)),c.complicationRisk.factors.map((d,N)=>(0,e.jsxs)("p",{children:["• ",d]},N)),c.medicationAdherenceRisk.factors.map((d,N)=>(0,e.jsxs)("p",{children:["• ",d]},N))]})]}),c.recommendations.length>0&&(0,e.jsxs)("div",{className:"p-4 bg-blue-50 border border-blue-200 rounded-lg",children:[(0,e.jsx)("h4",{className:"font-semibold text-blue-900 mb-2",children:"AI Recommendations"}),(0,e.jsx)("div",{className:"space-y-1 text-sm text-blue-800",children:c.recommendations.map((d,N)=>(0,e.jsxs)("p",{children:["✓ ",d]},N))})]})]})]})]})}var fe=[{id:"vitals",label:"Vitals & Reconciliation",shortLabel:"Vitals",icon:(0,e.jsx)(rt,{className:"w-4 h-4"})},{id:"documentation",label:"Clinical Documentation",shortLabel:"Docs",icon:(0,e.jsx)(Dt,{className:"w-4 h-4"})},{id:"orders",label:"Orders & Prescriptions",shortLabel:"Orders",icon:(0,e.jsx)(We,{className:"w-4 h-4"})}];function Js({visit:s,patient:r,onClose:y,onComplete:S}){const{profile:o}=ct(),{showToast:l}=mt(),{confirm:i}=Ot(),[g,h]=(0,a.useState)("vitals"),[T,c]=(0,a.useState)(new Set),{note:C,existingNoteId:m,noteSigned:I,setNoteSigned:k,saving:E,lastSaved:j,loading:A,templates:d,patientContext:N,previousNote:L,autoCarriedForward:B,dism
42issAutoCarryForward:be,updateSection:ne,insertIntoSection:p,applyTemplate:D,carryForward:F,deleteNote:z,saveNow:_e}=zt({visit:s,patientId:r.id}),{complianceResult:ie,suggestedCodes:Ke,selectedCodes:ce,analyzing:Ge,runAnalysis:je,toggleCode:de,acceptAllHighConfidence:Se,getSelectedBillingCodes:Pe}=Ft({note:C,visitId:s.id,chiefComplaint:s.chief_complaint||void 0,autoAnalyze:!0}),{signing:Me,signNote:Je}=qt({visit:s,patient:r,noteId:m,complianceScore:ie?.score??null,billingCodes:Pe(),onSigned:()=>k(!0),onCompleted:()=>{S?.(),y()}}),[te,Ye]=(0,a.useState)({}),[me,ue]=(0,a.useState)(!1),[Fe,_]=(0,a.useState)(!1),[re,U]=(0,a.useState)([]),[Ce,W]=(0,a.useState)(0),[ke,Ie]=(0,a.useState)(!1),[Ae,se]=(0,a.useState)(!1),[xe,ze]=(0,a.useState)(!0),[$e,st]=(0,a.useState)(!0),[qe,ae]=(0,a.useState)(!0),K=(0,a.useRef)(null),ge=(0,a.useMemo)(()=>{if(!r.date_of_birth)return null;const f=new Date,R=new Date(r.date_of_birth);let ee=f.getFullYear()-R.getFullYear();const oe=f.getMonth()-R.getMonth();return(oe<0||oe===0&&f.getDate()<R.getDate())&&ee--,ee},[r.date_of_birth]),Xe=(0,a.useMemo)(()=>({encounterId:s.id,patientId:r.id,organizationId:o?.organization_id||"",providerId:o?.id||"",patientAge:ge,patientSex:r.sex||null,chiefComplaint:s.chief_complaint||"",diagnoses:[],problems:N.problems.map(f=>f.problem_name||""),allergies:N.allergies.map(f=>f.allergen||""),medications:N.activeMedications.map(f=>f.medication_name||""),noteText:[C.subjective,C.objective,C.assessment,C.plan].filter(Boolean).join(`
43`),pendingOrders:re,visitType:s.visit_type||""}),[s.id,r.id,o?.organization_id,o?.id,ge,r.sex,s.chief_complaint,N.problems,N.allergies,N.activeMedications,C.subjective,C.objective,C.assessment,C.plan,re,s.visit_type]),X=[C.subjective,C.objective,C.assessment,C.plan].filter(Boolean).join(`
44`),{docNudges:Q,orderNudges:H,hardStop:G,clearHardStop:J,acceptNudge:ve,dismissNudge:Ne,snoozeNudge:Le,nudges:Re,enabled:Te}=As({encounterId:s.id,patientId:r.id,organizationId:o?.organization_id||"",context:Xe,noteText:X,pendingOrders:re});(0,a.useEffect)(()=>{async function f(){try{const{data:R}=await v.from("visits").select("med_reconciliation_completed_at").eq("id",s.id).maybeSingle();R?.med_reconciliation_completed_at&&_(!0)}catch{}}f()},[s.id]),(0,a.useEffect)(()=>(g==="documentation"&&!K.current?K.current=setInterval(()=>{W(f=>f+1)},1e3):g!=="documentation"&&K.current&&(clearInterval(K.current),K.current=null),()=>{K.current&&(clearInterval(K.current),K.current=null)}),[g]),(0,a.useEffect)(()=>()=>{K.current&&clearInterval(K.current)},[]);async function De(){if(!te.blood_pressure_systolic&&!te.heart_rate&&!te.temperature){l("Please enter at least one vital sign","error");return}try{const{error:f}=await v.from("vital_signs").insert({patient_id:r.id,visit_id:s.id,organization_id:o?.organization_id,recorded_by:o?.id,...te});if(f)throw f;ue(!0),l("Vitals saved","success")}catch{l("Failed to save vitals","error")}}async function we(){try{const{error:f}=await v.from("visits").update({med_reconciliation_completed_at:new Date().toISOString(),med_reconciliation_completed_by:o?.id}).eq("id",s.id);if(f)throw f;_(!0),p("objective",`
45Medication Reconciliation: Completed on ${new Date().toLocaleDateString()} by ${o?.first_name||""} ${o?.last_name||""}. Current medication list reviewed and verified with patient.`),l("Medication reconciliation completed","success")}catch(f){M.error("Med reconciliation error:",q(f)),l("Failed to complete reconciliation","error")}}async function Ze(){await i({title:"Delete Note",message:"Are you sure you want to delete this note? This cannot be undone.",confirmText:"Delete",cancelText:"Cancel",variant:"danger"})&&(await z(),l("Note deleted","success"))}function b(f){c(R=>new Set([...R,g])),h(f)}function $(){const f=fe.findIndex(R=>R.id===g);f<fe.length-1&&(c(R=>new Set([...R,g])),h(fe[f+1].id))}function Y(){const f=fe.findIndex(R=>R.id===g);f>0&&h(fe[f-1].id)}function Ee(f){return`${Math.floor(f/60)}:${(f%60).toString().padStart(2,"0")}`}function Oe(f){const R=new Date,ee=new Date(f);let oe=R.getFullYear()-ee.getFullYear();const at=R.getMonth()-ee.getMonth();return(at<0||at===0&&R.getDate()<ee.getDate())&&oe--,oe}const le=fe.findIndex(f=>f.id===g),Be=(le+1)/fe.length*100,He=`${o?.first_name||""} ${o?.last_name||""}`.trim(),Qe=o?.specialty||o?.provider_type||"";return A?(0,e.jsx)("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:(0,e.jsxs)("div",{className:"bg-white rounded-2xl p-8 flex flex-col items-center gap-4",children:[(0,e.jsx)("div",{className:"w-12 h-12 border-4 border-blue-500 border-t-transparent roun
45ded-full animate-spin"}),(0,e.jsx)("p",{className:"text-slate-600",children:"Loading patient data..."})]})}):(0,e.jsxs)("div",{className:"fixed inset-0 bg-slate-100 z-50 flex flex-col",children:[(0,e.jsxs)("header",{className:"bg-white border-b border-slate-200 px-6 py-3 flex items-center justify-between shrink-0",children:[(0,e.jsxs)("div",{className:"flex items-center gap-4",children:[(0,e.jsx)("button",{onClick:y,className:"p-2 hover:bg-slate-100 rounded-lg transition-colors",children:(0,e.jsx)(jt,{className:"w-5 h-5 text-slate-500"})}),(0,e.jsxs)("div",{children:[(0,e.jsxs)("h1",{className:"text-lg font-bold text-slate-900",children:[r.first_name," ",r.last_name,(0,e.jsxs)("span",{className:"text-slate-400 font-normal ml-2",children:[r.date_of_birth&&`${Oe(r.date_of_birth)} y/o`,r.sex&&` ${r.sex}`]})]}),(0,e.jsxs)("p",{className:"text-sm text-slate-500",children:[s.visit_type?.replace(/_/g," ")," - ",new Date(s.visit_date).toLocaleDateString(),s.chief_complaint&&` - ${s.chief_complaint}`]})]})]}),(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[g==="documentation"&&(0,e.jsxs)("div",{className:"flex items-center gap-2 text-sm text-slate-500",children:[(0,e.jsx)(Et,{className:"w-4 h-4"}),(0,e.jsx)("span",{children:Ee(Ce)})]}),j&&(0,e.jsxs)("div",{className:"flex items-center gap-1 text-sm text-slate-400",children:[(0,e.jsx)(tt,{className:"w-4 h-4"}),"Saved ",j.toLocaleTimeString()]}),(0,e.jsx)($s,{score:ie?.score??null,analyzing:Ge,onRunAnalysis:je,compact:!0}),I?(0,e.jsxs)("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-green-100 text-green-700 rounded-lg text-sm font-medium",children:[(0,e.jsx)(pe,{className:"w-4 h-4"}),"Signed"]}):(0,e.jsxs)("button",{onClick:()=>{if(!m){l("Save the note first","error");return}ie===null&&je(),Ie(!0)},className:"flex items-center gap-1.5 px-4 py-2 bg-green-600 text-white rounded-lg text-sm font-medium hover:bg-green-700 transition-colors",children:[(0,e.jsx)(pe,{className:"w-4 h-4"}),"Sign & Close"]}),N.allergies.some(f=>f.severity==="severe")&&(0,e.jsxs)("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-red-100 text-red-700 rounded-lg text-sm font-medium",children:[(0,e.jsx)(et,{className:"w-4 h-4"}),"Severe Allergies"]})]})]}),(0,e.jsxs)("div",{className:"bg-white border-b border-slate-200 px-6 py-2 shrink-0",children:[(0,e.jsx)("div",{className:"flex items-center justify-between mb-2",children:fe.map((f,R)=>{const ee=T.has(f.id),oe=g===f.id;return(0,e.jsxs)("button",{onClick:()=>b(f.id),className:`flex items-center gap-2 px-4 py-2 rounded-lg transition-all relative ${oe?"bg-blue-50 text-blue-700 font-medium":ee||R<le?"text-blue-600 hover:bg-blue-50":"text-slate-400 hover:bg-slate-50"}`,children:[(0,e.jsx)("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${ee?"bg-blue-500 text-white":oe?"bg-blue-100 text-blue-700":"bg-slate-100 text-slate-400"}`,children:ee?(0,e.jsx)(tt,{className:"w-4 h-4"}):f.icon}),(0,e.jsx)("span",{className:"hidden lg:inline",children:f.label}),(0,e.jsx)("span",{className:"lg:hidden",children:f.shortLabel}),f.id==="orders"&&H.length>0&&(0,e.jsx)("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-amber-500 text-white text-[9px] font-bold rounded-full flex items-center justify-center",children:H.length}),f.id==="documentation"&&Q.length>0&&(0,e.jsx)("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-blue-600 text-white text-[9px] font-bold rounded-full flex items-center justify-center",children:Q.length})]},f.id)})}),(0,e.jsx)("div",{className:"h-1 bg-slate-100 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:"h-full bg-linear-to-r from-blue-500 to-blue-600 transition-all duration-300",style:{width:`${Be}%`}})})]}),(0,e.jsxs)("main",{className:"flex-1 overflow-hidden flex",children:[(0,e.jsx)(vs,{patient:r,recentVitals:N.recentVitals,activeMedications:N.activeMedications,problems:N.problems,allergies:N.allergies,collapsed:Ae,onToggle:()=>se(!Ae)}),(0,e.jsxs)("div",{className:"flex-1 flex flex-col overflow-hidden",children:[g==="vitals"&&o?.organization_id&&(0,e.jsxs)("div",{className:"shrink-0 border-b border-slate-200 bg-linear-to-r from-slate-50 to-white",children:[(0,e.jsxs)("button",{onClick:()=>st(!$e),className:"w-full flex items-center justify-between px-6 py-3 hover:bg-slate-50 transition-colors",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(ot,{className:"w-4 h-4 text-blue-600"}),(0,e.jsx)("span",{className:"text-sm font-semibold text-slate-800",children:"Encounter Intelligence"})]}),(0,e.jsx)(it,{className:`w-4 h-4 text-slate-400 transition-transform ${$e?"rotate-90":""}`})]}),$e&&(0,e.jsxs)("div",{className:"px-6 pb-4 space-y-4",children:[(0,e.jsx)($t,{fallback:(0,e.jsx)(e.Fragment,{}),children:(0,e.jsxs)("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[(0,e.jsx)(Ms,{patientId:r.id,organizationId:o.organization_id}),(0,e.jsx)(Ps,{patientId:r.id,organizationId:o.organization_id,encounterId:s.id})]})}),(0,e.jsx)($t,{fallback:(0,e.jsx)(e.Fragment,{}),children:(0,e.jsx)(Gs,{patient:r,diagnosis:s.chief_complaint||void 0})})]})]}),g==="vitals"&&(0,e.jsx)(Ys,{patient:r,recentVitals:N.recentVitals,newVitals:te,setNewVitals:Ye,vitalsRecorded:me,activeMedications:N.activeMedications,medReconciliationComplete:Fe,onSaveVitals:De,onMedReconciliation:we,saving:E,onNext:$}),g==="documentation"&&(0,e.jsxs)("div",{className:"flex-1 flex overflow-hidden",children:[(0,e.jsx)("div",{className:"flex-1 overflow-y-auto p-6",style:{minWidth:0},children:(0,e.jsxs)("div",{className:"max-w-4xl mx-auto",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsx)("h2",{className:"text-lg font-semibold text-slate-900",children:"Clinical Note"}),L&&!I&&(0,e.jsxs)("button",{onClick:F,className:"flex items-center gap-1.5 text-sm px-3 py-1.5 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors",children:[(0,e.jsx)(pt,{className:"w-3.5 h-3.5"}),"Carry Forward"]}),m&&!I&&(0,e.jsxs)("button",{onClick:Ze,className:"flex items-center gap-1.5 text-sm px-3 py-1.5 text-red-500 hover:bg-red-50 rounded-lg transition-colors",children:[(0,e.jsx)(ht,{className:"w-3.5 h-3.5"}),"Delete"]})]}),(0,e.jsx)("div",{className:"flex items-center gap-2",children:(0,e.jsxs)("button",{onClick:_e,disabled:E||I,className:"flex items-center gap-1.5 text-sm px-3 py-1.5 bg-slate-100 text-slate-600 rounded-lg hover:bg-slate-200 transition-colors disabled:opacity-50",children:[(0,e.jsx)(bt,{className:"w-3.5 h-3.5"}),E?"Saving...":"Save"]})})]}),B&&(0,e.jsxs)("div",{className:"mx-4 mt-3 flex items-center gap-3 px-4 py-2.5 bg-blue-50 border border-blue-200 rounded-lg",children:[(0,e.jsx)(pt,{className:"w-4 h-4 text-blue-600 shrink-0"}),(0,e.jsx)("span",{className:"text-sm text-blue-800 font-medium flex-1",children:"Assessment & plan carried forward from previous visit — review and update as needed."}),(0,e.jsx)("button",{onClick:be,className:"text-xs text-blue-600 hover:text-blue-800 font-medium underline shrink-0",children:"Dismiss"})]}),(0,e.jsx)(bs,{note:C,noteSigned:I,onUpdateSection:ne,onInsertIntoSection:p,recentVitals:N.recentVitals,activeMedications:N.activeMedications,problems:N.problems,templates:d,onApplyTemplate:D}),(0,e.jsx)(Os,{patientId:r.id,visitId:s.id,note:C,onAcceptSuggestion:(f,R)=>p(f,R),disabled:I})]})}),!xe&&(0,e.jsx)("div",{className:"w-80 border-l border-slate-200 overflow-y-auto bg-white",children:(0,e.jsx)(Ks,{patientId:r.id,visitId:s.id,currentNote:C,onInsertText:(f,R)=>p(f,R),onApplyCode:(f,R)=>de(f),collapsed:!1,onToggleCollapse:()=>ze(!0)})}),xe&&(0,e.jsxs)("button",{onClick:()=>ze(!1),className:"w-10 bg-white border-l border-slate-200 flex flex-col items-center py-4 gap-2 shrink-0 hover:bg-slate-50 transition-colors",title:"Open AI Copilot",children:[(0,e.jsx)(dt,{className:"w-4 h-4 text-blue-600"}),(0,e.jsx)("span",{className:"text-[10px] text-slate-400 [writing-mode:vertical-lr]",children:"AI Copilot"})]}),Te&&qe&&(Q.length>0||H.length>0)&&(0,e.jsx)(At,{docNudges:Q,orderNudges:H,hardStop:G,onAccept:ve,onDismiss:Ne,onSnooze:Le,onClearHardStop:J,onClose:()=>ae(!1)}),Te&&!qe&&Re.length>0&&(0,e.jsxs)("button",{onClick:()=>ae(!0),className:"w-10 bg-white border-l border-slate-200 flex flex-col items-center py-4 gap-2 shrink-0 hover:bg-slate-50 transition-colors relative",title:"Open CDS Nudges",children:[(0,e.jsx)(lt,{className:"w-4 h-4 text-blue-600"}),(0,e.jsx)("span",{className:"text-[10px] text-slate-400 [writing-mode:vertical-lr]",children:"CDS"}),(0,e.jsx)("span",{className:"absolute top-3 right-1 w-4 h-4 bg-blue-600 text-white text-[9px] font-bold rounded-full flex items-center justify-center",children:Re.length})]})]}),g==="orders"&&(0,e.jsxs)("div",{className:"flex-1 flex overflow-hidden",children:[(0,e.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,e.jsx)(Xs,{patient:r,visit:s,pendingOrders:re,setPendingOrders:U,activeMedications:N.activeMedications,onPrevious:Y})}),Te&&H.length>0&&(0,e.jsx)(At,{docNudges:[],orderNudges:H,hardStop:G,onAccept:ve,onDismiss:Ne,onSnooze:Le,onClearHardStop:J})]})]})]}),(0,e.jsxs)("footer",{className:"bg-white border-t border-slate-200 px-6 py-3 flex items-center justify-between shrink-0",children:[(0,e.jsxs)("button",{onClick:Y,disabled:le===0,className:"flex items-center gap-2 px-4 py-2 text-slate-600 hover:text-slate-900 transition-colors disabled:opacity-30 disabled:cursor-not-allowed",children:[(0,e.jsx)(vt,{className:"w-5 h-5"}),"Back"]}),(0,e.jsx)("div",{className:"flex items-center gap-3",children:le<fe.length-1&&(0,e.jsxs)("button",{onClick:$,className:"flex items-center gap-2 px-6 py-2.5 bg-blue-600 text-white rounded-xl font-medium hover:bg-blue-700 transition-colors",children:["Continue",(0,e.jsx)(it,{className:"w-5 h-5"})]})})]}),ke&&(0,e.jsx)(Mt,{signerName:He,signerCredentials:Qe,savedSignature:o?.signature_data||null,complianceScore:ie?.score??null,complianceSuggestions:ie?.suggestions||[],suggestedCodes:Ke,selectedCodes:ce,onToggleCode:de,onAcceptAllHighConfidence:Se,noteText:X,visitType:s.visit_type||"office",onSign:async(f,R)=>await Je(f,R),onClose:()=>
45Ie(!1),onRunAnalysis:je,analyzing:Ge,signing:Me})]})}function Ys({recentVitals:s,newVitals:r,setNewVitals:y,vitalsRecorded:S,activeMedications:o,medReconciliationComplete:l,onSaveVitals:i,onMedReconciliation:g,saving:h,onNext:T}){return(0,e.jsx)("div",{className:"flex-1 overflow-auto p-6",children:(0,e.jsxs)("div",{className:"max-w-3xl mx-auto space-y-6",children:[(0,e.jsxs)("div",{className:"bg-white rounded-xl shadow-xs p-6",children:[(0,e.jsxs)("h2",{className:"text-lg font-semibold text-slate-900 mb-4 flex items-center gap-2",children:[(0,e.jsx)(rt,{className:"w-5 h-5 text-blue-600"}),"Record Vital Signs"]}),S?(0,e.jsxs)("div",{className:"flex items-center gap-2 text-green-600 bg-green-50 p-4 rounded-lg",children:[(0,e.jsx)(pe,{className:"w-5 h-5"}),(0,e.jsx)("span",{className:"font-medium",children:"Vitals recorded for this visit"})]}):(0,e.jsxs)(e.Fragment,{children:[s&&(0,e.jsxs)("div",{className:"mb-4 p-3 bg-blue-50 rounded-lg",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,e.jsxs)("p",{className:"text-sm text-blue-700 font-medium",children:["Previous Vitals (",s.recorded_at?new Date(s.recorded_at).toLocaleDateString():"N/A",")"]}),(0,e.jsx)("button",{type:"button",onClick:()=>y({blood_pressure_systolic:s.blood_pressure_systolic??void 0,blood_pressure_diastolic:s.blood_pressure_diastolic??void 0,heart_rate:s.heart_rate??void 0,temperature:s.temperature??void 0,respiratory_rate:s.respiratory_rate??void 0,oxygen_saturation:s.oxygen_saturation??void 0,weight:s.weight??void 0,height:s.height??void 0}),className:"text-xs text-blue-600 hover:text-blue-800 font-semibold underline underline-offset-2",children:"Use last recorded"})]}),(0,e.jsxs)("div",{className:"flex flex-wrap gap-3 text-sm text-blue-600",children:[s.blood_pressure_systolic&&(0,e.jsxs)("span",{children:["BP: ",s.blood_pressure_systolic,"/",s.blood_pressure_diastolic]}),s.heart_rate&&(0,e.jsxs)("span",{children:["HR: ",s.heart_rate]}),s.temperature&&(0,e.jsxs)("span",{children:["Temp: ",s.temperature]}),s.oxygen_saturation&&(0,e.jsxs)("span",{children:["SpO2: ",s.oxygen_saturation,"%"]})]})]}),(0,e.jsxs)("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[(0,e.jsx)(ye,{label:"Systolic BP",icon:(0,e.jsx)(ot,{className:"w-4 h-4 text-red-400"}),value:r.blood_pressure_systolic||"",onChange:c=>y({...r,blood_pressure_systolic:c?Number(c):void 0}),unit:"mmHg"}),(0,e.jsx)(ye,{label:"Diastolic BP",icon:(0,e.jsx)(ot,{className:"w-4 h-4 text-red-400"}),value:r.blood_pressure_diastolic||"",onChange:c=>y({...r,blood_pressure_diastolic:c?Number(c):void 0}),unit:"mmHg"}),(0,e.jsx)(ye,{label:"Heart Rate",icon:(0,e.jsx)(rt,{className:"w-4 h-4 text-blue-400"}),value:r.heart_rate||"",onChange:c=>y({...r,heart_rate:c?Number(c):void 0}),unit:"bpm"}),(0,e.jsx)(ye,{label:"Temperature",icon:(0,e.jsx)(Lt,{className:"w-4 h-4 text-orange-400"}),value:r.temperature||"",onChange:c=>y({...r,temperature:c?Number(c):void 0}),unit:"F"}),(0,e.jsx)(ye,{label:"Resp. Rate",icon:(0,e.jsx)(fs,{className:"w-4 h-4 text-green-400"}),value:r.respiratory_rate||"",onChange:c=>y({...r,respiratory_rate:c?Number(c):void 0}),unit:"/min"}),(0,e.jsx)(ye,{label:"SpO2",icon:(0,e.jsx)(Pt,{className:"w-4 h-4 text-cyan-400"}),value:r.oxygen_saturation||"",onChange:c=>y({...r,oxygen_saturation:c?Number(c):void 0}),unit:"%"}),(0,e.jsx)(ye,{label:"Weight",icon:(0,e.jsx)(It,{className:"w-4 h-4 text-purple-400"}),value:r.weight||"",onChange:c=>y({...r,weight:c?Number(c):void 0}),unit:"lbs"}),(0,e.jsx)(ye,{label:"Height",icon:(0,e.jsx)(It,{className:"w-4 h-4 text-purple-400"}),value:r.height||"",onChange:c=>y({...r,height:c?Number(c):void 0}),unit:"in"})]}),(0,e.jsx)("div",{className:"mt-4 flex justify-end",children:(0,e.jsxs)("button",{onClick:i,disabled:h,className:"flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-xl hover:bg-blue-700 transition-colors disabled:opacity-50",children:[(0,e.jsx)(bt,{className:"w-4 h-4"}),"Save Vitals"]})})]})]}),(0,e.jsxs)("div",{className:"bg-white rounded-xl shadow-xs p-6",children:[(0,e.jsxs)("h2",{className:"text-lg font-semibold text-slate-900 mb-4 flex items-center gap-2",children:[(0,e.jsx)(We,{className:"w-5 h-5 text-blue-600"}),"Medication Reconciliation"]}),l?(0,e.jsxs)("div",{className:"flex items-center gap-2 text-green-600 bg-green-50 p-4 rounded-lg",children:[(0,e.jsx)(pe,{className:"w-5 h-5"}),(0,e.jsx)("span",{className:"font-medium",children:"Medication reconciliation completed"})]}):(0,e.jsxs)(e.Fragment,{children:[o.length>0?(0,e.jsx)("div",{className:"space-y-2 mb-4",children:o.map(c=>(0,e.jsxs)("div",{className:"flex items-center justify-between p-3 bg-slate-50 rounded-lg",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("span",{className:"font-medium text-slate-900",children:c.medication_name}),(0,e.jsxs)("span",{className:"text-slate-500 ml-2",children:[c.dosage," ",c.frequency]})]}),(0,e.jsxs)("div",{className:"flex items-center gap-1 text-green-600 text-sm",children:[(0,e.jsx)(tt,{className:"w-4 h-4"}),"Active"]})]},c.id))}):(0,e.jsx)("p",{className:"text-slate-400 mb-4",children:"No active medications on file"}),(0,e.jsxs)("button",{onClick:g,disabled:h,className:"flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-xl hover:bg-blue-700 transition-colors disabled:opacity-50",children:[(0,e.jsx)(ss,{className:"w-4 h-4"}),"Complete Reconciliation"]})]})]}),(0,e.jsx)("div",{className:"flex justify-end pt-4",children:(0,e.jsxs)("button",{onClick:T,className:"flex items-center gap-2 px-6 py-3 bg-linear-to-r from-blue-600 to-blue-600 text-white rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all",children:["Continue to Documentation",(0,e.jsx)(it,{className:"w-5 h-5"})]})})]})})}function ye({label:s,icon:r,value:y,onChange:S,unit:o}){return(0,e.jsxs)("div",{children:[(0,e.jsxs)("label",{className:"block text-sm font-medium text-slate-700 mb-1 flex items-center gap-1.5",children:[r,s]}),(0,e.jsxs)("div",{className:"relative",children:[(0,e.jsx)("input",{type:"number",value:y,onChange:l=>S(l.target.value),className:"w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm",placeholder:"--"}),(0,e.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-slate-400",children:o})]})]})}function Xs({pendingOrders:s,setPendingOrders:r,onPrevious:y}){const[S,o]=(0,a.useState)(!1),[l,i]=(0,a.useState)("lab"),[g,h]=(0,a.useState)(""),[T,c]=(0,a.useState)([]),[C,m]=(0,a.useState)(!1),I=(0,a.useRef)(null);async function k(j,A){if(j.length<1){m(!1);return}const{data:d}=await v.from("common_orders_catalog").select("*").eq("order_type",A).ilike("name",`%${j}%`).limit(10);c(d||[]),m(!0)}function E(){g.trim()&&(r([...s,{id:Date.now().toString(),order_type:l,order_name:g.trim(),description:g.trim()}]),h(""),o(!1))}return(0,e.jsx)("div",{className:"flex-1 overflow-auto p-6",children:(0,e.jsxs)("div",{className:"max-w-3xl mx-auto 
45space-y-6",children:[(0,e.jsxs)("div",{className:"bg-white rounded-xl shadow-xs p-6",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,e.jsxs)("h2",{className:"text-lg font-semibold text-slate-900 flex items-center gap-2",children:[(0,e.jsx)(We,{className:"w-5 h-5 text-blue-600"}),"Orders & Prescriptions"]}),(0,e.jsxs)("button",{onClick:()=>o(!0),className:"flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm",children:[(0,e.jsx)(ms,{className:"w-4 h-4"}),"Add Order"]})]}),S&&(0,e.jsxs)("div",{className:"mb-4 p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3",children:[(0,e.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Order Type"}),(0,e.jsxs)("select",{value:l,onChange:j=>i(j.target.value),className:"w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent",children:[(0,e.jsx)("option",{value:"lab",children:"Lab"}),(0,e.jsx)("option",{value:"imaging",children:"Imaging"}),(0,e.jsx)("option",{value:"referral",children:"Referral"})]})]}),(0,e.jsxs)("div",{className:"md:col-span-2 relative",children:[(0,e.jsx)("label",{className:"block text-sm font-medium text-slate-700 mb-1",children:"Description"}),(0,e.jsx)("input",{ref:I,type:"text",value:g,onChange:j=>{h(j.target.value),k(j.target.value,l)},onFocus:()=>{g.length>=1&&k(g,l)},onBlur:()=>setTimeout(()=>m(!1),200),placeholder:"Start typing to search...",className:"w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent",autoComplete:"off"}),C&&T.length>0&&(0,e.jsx)("div",{className:"absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg max-h-60 overflow-auto",children:T.map(j=>(0,e.jsxs)("button",{type:"button",onMouseDown:A=>A.preventDefault(),onClick:()=>{h(j.name),m(!1),I.current?.focus()},className:"w-full text-left px-3 py-2 hover:bg-blue-50 transition-colors border-b border-slate-100 last:border-b-0",children:[(0,e.jsx)("div",{className:"font-medium text-slate-900 text-sm",children:j.name}),(0,e.jsxs)("div",{className:"text-xs text-slate-500 flex items-center gap-2",children:[j.description,j.cpt_code&&(0,e.jsxs)("span",{className:"text-xs bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded",children:["CPT: ",j.cpt_code]})]})]},j.id))})]})]}),(0,e.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,e.jsx)("button",{onClick:()=>o(!1),className:"px-4 py-2 text-slate-600 hover:text-slate-900",children:"Cancel"}),(0,e.jsx)("button",{onClick:E,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700",children:"Add Order"})]})]}),s.length>0?(0,e.jsx)("div",{className:"space-y-2",children:s.map(j=>(0,e.jsxs)("div",{className:"flex items-center justify-between p-3 bg-slate-50 rounded-lg",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsx)("span",{className:`text-xs px-2 py-1 rounded-full font-medium ${j.order_type==="lab"?"bg-blue-100 text-blue-700":j.order_type==="imaging"?"bg-amber-100 text-amber-700":"bg-blue-100 text-blue-700"}`,children:j.order_type}),(0,e.jsx)("span",{className:"font-medium text-slate-900",children:j.description})]}),(0,e.jsx)("button",{onClick:()=>r(s.filter(A=>A.id!==j.id)),className:"text-slate-400 hover:text-red-500",children:(0,e.jsx)(jt,{className:"w-4 h-4"})})]},j.id))}):(0,e.jsx)("p",{className:"text-slate-400 text-sm",children:"No orders added for this visit"})]}),(0,e.jsx)("div",{className:"flex justify-between pt-4",children:(0,e.jsxs)("button",{onClick:y,className:"flex items-center gap-2 px-4 py-2 text-slate-600 hover:text-slate-900 transition-colors",children:[(0,e.jsx)(vt,{className:"w-5 h-5"}),"Back"]})})]})})}function wa({preselectedVisit:s,onVisitChange:r}){const{profile:y}=ct(),[S,o]=(0,a.useState)([]),[l,i]=(0,a.useState)(s||null),[g,h]=(0,a.useState)(null);async function T(){if(y?.organization_id)try{const{data:m,error:I}=await v.from("visits").select("id, patient_id, appointment_id, visit_date, visit_type, chief_complaint, status, created_at, updated_at, patient:patients!inner(id, first_name, last_name, organization_id)").eq("patient.organization_id",y.organization_id).in("status",["scheduled","in_progress"]).order("visit_date",{ascending:!1}).limit(20);if(I)throw I;const k=m||[],E=k.map(A=>A.appointment_id).filter(A=>!!A),j={};if(E.length>0){const{data:A}=await v.from("appointments").select("id, intake_status, is_new_patient").in("id",E);A&&A.forEach(d=>{j[d.id]={intake_status:d.intake_status,is_new_patient:d.is_new_patient}})}o(k.map(A=>({...A,_intakeStatus:A.appointment_id?j[A.appointment_id]?.intake_status??"not_sent":null,_isNewPatient:A.appointment_id?j[A.appointment_id]?.is_new_patient??!1:!1}
45)))}catch(m){M.error("Error loading visits:",q(m)),o([])}}async function c(m){try{const{data:I,error:k}=await v.from("patients").select("id, first_name, last_name, date_of_birth, gender, sex, mrn, phone, email, allergies, insurance_provider, insurance_id, insurance_group, active, created_at, updated_at").eq("id",m).maybeSingle();if(k)throw k;h(I)}catch(I){M.error("Error loading patient for visit:",q(I))}}(0,a.useEffect)(()=>{queueMicrotask(()=>T())},[y?.organization_id]),(0,a.useEffect)(()=>{s&&queueMicrotask(()=>{i(s),c(s.patient_id)})},[s]);function C(){i(null),h(null),r?.()}return l?(0,e.jsx)(Zs,{visit:l,patient:g,preselectedVisit:!!s,onClearSelection:C,onVisitChange:()=>{T(),r?.()}}):(0,e.jsxs)("div",{children:[(0,e.jsx)("div",{className:"flex items-center gap-4 mb-6",children:(0,e.jsx)("h2",{className:"text-3xl font-bold text-slate-900",children:"Visit Notes"})}),(0,e.jsxs)("div",{className:"bg-white rounded-xl shadow-xs p-6",children:[(0,e.jsx)("h3",{className:"text-xl font-semibold mb-4",children:"Select a Visit"}),(0,e.jsx)("div",{className:"space-y-3",children:S.length===0?(0,e.jsx)("div",{className:"text-center py-8 text-slate-500",children:"No pending visits"}):S.map(m=>{const I=m,k=I._intakeStatus??null,E=I._isNewPatient??!1,j=k==="complete"||k==="reviewed"?{label:"Intake Complete",cls:"bg-blue-100 text-blue-800 border-blue-200",icon:pe}:k==="partial"?{label:"Intake Partial",cls:"bg-amber-100 text-amber-700 border-amber-200",icon:Fs}:k==="sent"?{label:"Intake Sent",cls:"bg-blue-100 text-blue-700 border-blue-200",icon:Tt}:null;return(0,e.jsx)("button",{onClick:()=>{i(m),h(m.patient),c(m.patient_id)},className:"w-full text-left p-4 border border-slate-200 rounded-lg hover:border-blue-300 hover:bg-blue-50/50 transition-colors",children:(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsxs)("span",{className:"font-semibold text-slate-900",children:[m.patient?.first_name??"Unknown"," ",m.patient?.last_name??""]}),E&&(0,e.jsxs)("span",{className:"flex items-center gap-1 text-xs bg-blue-600 text-white px-2 py-0.5 rounded-full font-medium",children:[(0,e.jsx)(ps,{className:"w-2.5 h-2.5"}),"New"]})]}),(0,e.jsxs)("div",{className:"text-sm text-slate-600 mt-0.5",children:[new Date(m.visit_date).toLocaleString()," — ",m.visit_type]}),m.chief_complaint&&(0,e.jsx)("div",{className:"text-sm text-slate-500 mt-0.5 truncate",children:m.chief_complaint})]}),(0,e.jsxs)("div",{className:"flex flex-col items-end gap-1.5 shrink-0",children:[(0,e.jsx)("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${m.status==="in_progress"?"bg-blue-100 text-blue-800":"bg-yellow-100 text-yellow-800"}`,children:m.status==="in_progress"?"In Progress":"Scheduled"}),j&&(0,e.jsxs)("span",{className:`flex items-center gap-1 px-2.5 py-1 text-xs font-medium rounded-full border ${j.cls}`,children:[(0,e.jsx)(j.icon,{className:"w-3 h-3"}),j.label]})]})]})},m.id)})})]})]})}function Zs({visit:s,patient:r,preselectedVisit:y,onClearSelection:S,onVisitChange:o}){const{profile:l}=ct(),{showToast:i}=mt(),{confirm:g}=Ot(),{note:h,setNote:T,existingNoteId:c,noteSigned:C,setNoteSigned:m,saving:I,lastSaved:k,patientContext:E,previousNote:j,carryForward:A,deleteNote:d,saveNow:N,reload:L}=zt({visit:s,patientId:s.patient_id}),{complianceResult:B,suggestedCodes:be,selectedCodes:ne,analyzing:p,runAnalysis:D,toggleCode:F,getSelectedBillingCodes:z}=Ft({note:h,visitId:s.id,chiefComplaint:s.chief_complaint||void 0,autoAnalyze:!0}),{signing:_e,signNote:ie}=qt({visit:s,patient:r||{id:s.patient_id,first_name:"",last_name:""},noteId:c,complianceScore:B?.score??null,billingCodes:z(),onSigned:()=>m(!0),onCompleted:()=>o()}),[Ke,ce]=(0,a.useState)(!1),[Ge,je]=(0,a.useState)(!1),[de,Se]=(0,a.useState)(""),[Pe,Me]=(0,a.useState)(!1),[Je,te]=(0,a.useState)(!1),[Ye,me]=(0,a.useState)(!1),[ue,Fe]=(0,a.useState)(!1),[_,re]=(0,a.useState)(!1),[U,Ce]=(0,a.useState)(!1),[W,ke]=(0,a.useState)(!1),[Ie,Ae]=(0,a.useState)(s.chief_complaint||""),[se,xe]=(0,a.useState)(s.visit_type||"office"),[ze,$e]=(0,a.useState)(!1),[st,qe]=(0,a.useState)(null),[ae,K]=(0,a.useState)(null),[ge,Xe]=(0,a.useState)({isNewPatient:!1,clinicalFlagCount:0,intakeSubmission:null}),X=(0,a.useRef)(null),Q=(0,a.useRef)(!1),H=(0,a.useCallback)(b=>{X.current&&clearTimeout(X.current),Q.current=!0,X.current=setTimeout(async()=>{const{error:$}=await v.from("visits").update({chief_complaint:b}).eq("id",s.id);$&&M.error("Failed to save chief complaint:",new Error(String($.message))),Q.current=!1},500)},[s.id]),G=(0,a.useCallback)(async()=>{(I||Q.current)&&!await g({title:"Unsaved Changes",message:"Your note is still saving. If you leave now some changes may be lost. Leave anyway?",confirmText:"Leave",cancelText:"Stay",variant:"warning"})||S()},[I,S,g]);(0,a.useEffect)(()=>()=>{X.current&&clearTimeout(X.current)},[]);async function J(){const{data:b}=await v.from("visits").select("med_reconciliation_completed_at, med_reconciliation_completed_by").eq("id",s.id).maybeSingle();if(b?.med_reconciliation_completed_at&&b?.med_reconciliation_completed_by){const{data:$}=await v.from("profiles").select("first_name, last_name").eq("id",b.med_reconciliation_completed_by).maybeSingle();qe({completedAt:b.med_reconciliation_completed_at,completedByName:$?`${$.first_name} ${$.last_name}`:"Unknown"})}}async function ve(b){const{data:$}=await v.from("profiles").select("first_name, last_name").eq("id",b).maybeSingle();$&&K($)}async function Ne(){try{const b=s.appointment_id;if(!b)return;const{data:$}=await v.from("appointments").select("is_new_patient, intake_status").eq("id",b).maybeSingle(),{data:Y}=await v.from("patient_intake_sessions").select("status, completion_percent, pain_level, new_symptoms, assessment_scores, review_of_systems, form_data, pushed_to_chart").eq("appointment_id",b).order("created_at",{ascending:!1}).limit(1).maybeSingle(),{count:Ee}=await v.from("intake_clinical_flags").select("id",{count:"exact",head:!0}).eq("patient_id",s.patient_id).eq("resolved",!1);Xe({isNewPatient:$?.is_new_patient??!1,clinicalFlagCount:Ee??0,intakeSubmission:Y??null})}catch(b){M.error("Failed to load intake data:",q(b))}}(0,a.useEffect)(()=>{queueMicrotask(()=>{J(),Ne()})},[s.id]),(0,a.useEffect)(()=>{!ze&&!s.chief_complaint&&s.appointment_id&&(queueMicrotask(()=>$e(!0)),v.from("appointments").select("chief_complaint").eq("id",s.appointment_id).maybeSingle().then(({data:b})=>b?.chief_complaint?(Ae(b.chief_complaint),v.from("visits").update({chief_complaint:b.chief_complaint}).eq("id",s.id)):null).then(b=>{b&&"error"in b&&b.error&&M.error("Failed to copy appointment chief complaint to visit",b.error)}))},[s.id,s.appointment_id,s.chief_complaint,ze]),(0,a.useEffect)(()=>{const b=h.cosigned_by;h.pending_cosignature&&b&&queueMicrotask(()=>ve(b))},[h.cosigned_by,h.pending_cosignature]);async function Le(){if(!l)return;const{error:b}=await v.from("visits").update({med_reconciliation_completed_at:new Date().toISOString(),med_reconciliation_completed_by:l.id}).eq("id",s.id);if(b){i("Error completing medication reconciliation","error");return}qe({completedAt:new Date().toISOString(),completedByName:`${l.first_name} ${l.last_name}`});const $=`
46Medication Reconciliation: Completed on ${new Date().toLocaleDateString()} by ${l.first_name} ${l.last_name}
46. Current medication list reviewed and verified with patient.`;T(Y=>({...Y,objective:(Y.objective||"")+$}))}async function Re(b){if(C)return;xe(b);const{error:$}=await v.from("visits").update({visit_type:b}).eq("id",s.id);if($){i("Failed to update visit type","error");return}o()}async function Te(){if(l){if(C){i('This note has been signed. Please use "Void Note" instead.',"warning");return}if(!c){if(!await g({title:"Clear Note",message:"Are you sure you want to clear this note?",confirmText:"Clear",cancelText:"Cancel",variant:"warning"}))return;T({subjective:"",objective:"",assessment:"",plan:""});return}if(await g({title:"Delete Note",message:"Are you sure you want to delete this note? This will soft-delete the note and it can only be recovered by administrators.",confirmText:"Delete",cancelText:"Cancel",variant:"danger"})){M.info("Attempting to delete note",{noteId:c});try{await d(),o(),i("Note deleted successfully","success")}catch(b){M.error("Error deleting note",q(b)),i("Error deleting note: "+(b instanceof Error?b.message:"Unknown error"),"error")}}}}async function De(b){if(!(!l||!c))try{const $=new TextEncoder().encode(b),Y=await crypto.subtle.digest("SHA-256",$),Ee=Array.from(new Uint8Array(Y)).map(Qe=>Qe.toString(16).padStart(2,"0")).join(""),{data:Oe,error:le}=await v.from("electronic_signatures").insert({organization_id:l.organization_id,user_id:l.id,signature_data:b,signature_hash:Ee,entity_type:"visit_note_cosign",entity_id:c,signer_name:`${l.first_name} ${l.last_name}`,signer_credentials:l.specialty||l.provider_type||"",signer_npi:l.npi_number,user_agent:navigator.userAgent,timestamp:new Date().toISOString()}).select("id").maybeSingle();if(le)throw le;if(!Oe)throw new Error("Failed to create cosignature");const{error:Be}=await v.from("visit_notes").update({pending_cosignature:!1,cosigned:!0,cosigned_at:new Date().toISOString(),cosignature_id:Oe.id}).eq("id",c);if(Be)throw Be;const{error:He}=await v.from("tasks").update({status:"completed",completed_at:new Date().toISOString()}).eq("visit_note_id",c).eq("task_type","cosign_note").eq("assigned_to",l.id);if(He)throw He;re(!1),L(),i("Note co-signed successfully","success")}catch($){i("Error co-signing note: "+($ instanceof Error?$.message:"Unknown error"),"error")}}const we=r?`${r.first_name} ${r.last_name}`:"Patient",Ze=l?`${l.first_name} ${l.last_name}`:"";return(0,e.jsxs)("div",{children:[(0,e.jsxs)("div",{className:"flex items-center gap-4 mb-6",children:[y&&(0,e.jsx)("button",{onClick:G,className:"p-2 hover:bg-slate-100 rounded-lg transition-colors",title:"Back to Encounters",children:(0,e.jsx)(as,{className:"w-6 h-6 text-slate-600"})}),(0,e.jsx)("h2",{className:"text-3xl font-bold text-slate-900",children:"Visit Notes"}),(0,e.jsxs)("div",{className:"ml-auto flex items-center gap-3",children:[r&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("button",{onClick:()=>ke(!0),className:"flex items-center gap-2 px-4 py-2 bg-linear-to-r from-emerald-600 to-cyan-600 text-white rounded-lg hover:from-emerald-700 hover:to-cyan-700 transition-colors font-medium shadow-xs",children:[(0,e.jsx)(zs,{className:"w-4 h-4"}),"Vitals & Orders"]}),(0,e.jsxs)("button",{onClick:()=>Ce(!0),className:"flex items-center gap-2 px-4 py-2 bg-linear-to-r from-blue-600 to-cyan-600 text-white rounded-lg hover:from-blue-700 hover:to-cyan-700 transition-colors font-medium shadow-xs",children:[(0,e.jsx)(ys,{className:"w-4 h-4"}),"Sign & Close Note"]})]}),(0,e.jsx)("button",{onClick:G,className:"text-slate-600 hover:text-slate-900 text-sm font-medium",children:"Change Visit"})]})]}),(0,e.jsxs)("div",{className:"bg-white rounded-xl shadow-xs p-5 mb-5",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h3",{className:"text-lg font-semibold text-slate-900",children:we}),(0,e.jsx)("p",{className:"text-sm text-slate-500",children:new Date(s.visit_date).toLocaleString()})]}),(0,e.jsxs)("div",{className:"flex items-center gap-4",children:[!C&&(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("label",{className:"block text-xs font-medium text-slate-500 mb-1",children:"Visit Type"}),(0,e.jsxs)("select",{value:se,onChange:b=>Re(b.target.value),className:"px-3 py-1.5 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent",children:[(0,e.jsx)("option",{value:"office",children:"Office Visit"}),(0,e.jsx)("option",{value:"telehealth",children:"Telehealth"}),(0,e.jsx)("option",{value:"hospital",children:"Hospital"}),(0,e.jsx)("option",{value:"emergency",children:"Emergency"}),(0,e.jsx)("option",{value:"follow_up",children:"Follow-up"}),(0,e.jsx)("option",{value:"consultation",children:"Consultation"}),(0,e.jsx)("option",{value:"h_and_p",children:"H&P"}),(0,e.jsx)("option",{value:"annual_wellness",children:"Annual Wellness"}),(0,e.jsx)("option",{value:"home",children:"Home Visit"}),(0,e.jsx)("option",{value:"nursing_facility",children:"Nursing Facility"})]})]}),(0,e.jsx)("div",{className:"flex-1 min-w-[200px]",children:(0,e.jsx)(Hs,{value:
46Ie,onChange:b=>{Ae(b),H(b)},organizationId:l?.organization_id,label:"Chief Complaint",placeholder:"Reason for visit..."})})]}),(0,e.jsxs)("div",{className:"flex items-center gap-2 text-sm text-slate-600",children:[(0,e.jsx)(We,{className:"w-4 h-4"}),st?(0,e.jsxs)("span",{className:"flex items-center gap-1.5 text-xs text-green-700 bg-green-50 px-2 py-1 rounded-lg",children:[(0,e.jsx)(pe,{className:"w-3.5 h-3.5"}),"Med Rec Done"]}):(0,e.jsx)("button",{onClick:Le,className:"text-xs px-2 py-1 bg-amber-50 text-amber-700 rounded-lg hover:bg-amber-100 transition-colors border border-amber-200",children:"Med Reconciliation"})]})]})]}),C&&(0,e.jsxs)("div",{className:"mt-4 pt-4 border-t border-slate-200 space-y-2",children:[(0,e.jsxs)("div",{className:"p-3 bg-green-50 border border-green-200 rounded-lg flex items-center gap-2 text-green-800 text-sm",children:[(0,e.jsx)(pe,{className:"w-4 h-4"}),(0,e.jsxs)("span",{className:"font-medium",children:["Note signed on ",h.signed_at?new Date(h.signed_at).toLocaleString():"Unknown"]})]}),h.pending_cosignature&&(0,e.jsxs)("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg flex items-center justify-between",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 text-amber-800 text-sm",children:[(0,e.jsx)(cs,{className:"w-4 h-4"}),(0,e.jsxs)("span",{className:"font-medium",children:["Pending Co-signature",ae&&` from ${ae.first_name} ${ae.last_name}`]})]}),l&&h.cosigned_by===l.id&&(0,e.jsxs)("button",{onClick:()=>re(!0),className:"flex items-center gap-2 px-3 py-1.5 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors text-xs font-medium",children:[(0,e.jsx)(Ct,{className:"w-3.5 h-3.5"}),"Co-sign"]})]}),h.cosigned&&(0,e.jsxs)("div",{className:"p-3 bg-sky-50 border border-sky-200 rounded-lg flex items-center gap-2 text-sky-800 text-sm",children:[(0,e.jsx)(Ct,{className:"w-4 h-4"}),(0,e.jsxs)("span",{className:"font-medium",children:["Co-signed on ",h.cosigned_at?new Date(h.cosigned_at).toLocaleString():"Unknown",ae&&` by ${ae.first_name} ${ae.last_name}`]})]})]})]}),(0,e.jsx)("div",{className:"bg-white rounded-xl shadow-xs overflow-hidden mb-6",style:{minHeight:"calc(100vh - 320px)"},children:(0,e.jsx)(Rs,{visitId:s.id,patientId:s.patient_id,patientName:we,visitDate:s.visit_date,visitType:se,chiefComplaint:Ie,patientContext:E,note:h,noteSigned:C,saving:I,lastSaved:k,existingNoteId:c,complianceScore:B?.score??null,complianceSuggestions:B?.suggestions,analyzing:p,previousNote:j,signedAt:h.signed_at,organizationId:l?.organization_id||void 0,isNewPatient:ge.isNewPatient,clinicalFlagCount:ge.clinicalFlagCount,intakeSubmission:ge.intakeSubmission,onUpdateNote:b=>T($=>({...$,...b})),onRunAnalysis:D,onSave:N,onSignAndClose:async()=>{await N(),ce(!0)},onDeleteNote:Te,onViewHistory:()=>Me(!0),onAddAddendum:C?()=>te(!0):void 0,onVoidNote:C?()=>me(!0):void 0,onCarryForward:()=>{A(),i("Previous visit note carried forward","success")},onManageFavorites:()=>Fe(!0),onSaved:()=>L()})}),r&&l?.organization_id&&(0,e.jsx)(Bs,{patientId:r.id,patientName:we,organizationId:l.organization_id,visitId:s.id}),Ke&&l&&(0,e.jsx)(Mt,{signerName:Ze,signerCredentials:l.specialty||l.provider_type||void 0,savedSignature:l.signature_data,complianceScore:B?.score??null,complianceSuggestions:B?.suggestions,suggestedCodes:be,selectedCodes:ne,noteText:[h.subjective,h.objective,h.assessment,h.plan].filter(Boolean).join(" "),visitType:se,onToggleCode:F,onSign:async(b,$)=>{const Y=await ie(b,$);return Y&&(ce(!1),Se(new Date().toISOString()),je(!0)),Y},onClose:()=>ce(!1),onRunAnalysis:D,analyzing:p,signing:_e}),Ge&&r&&(0,e.jsx)(Ns,{patientName:`${r.first_name} ${r.last_name}`,visitDate:s.visit_date,visitType:se,complianceScore:B?.score??null,selectedCodesCount:z().length,signedAt:de,onGoToBilling:()=>{je(!1),o()},onClose:()=>{je(!1),o()}}),Ye&&c&&(0,e.jsx)(js,{visitNoteId:c,patientName:we,visitDate:s.visit_date,onClose:()=>me(!1),onSuccess:()=>{me(!1),L()}}),Pe&&c&&(0,e.jsx)(Ht,{visitNoteId:c,onClose:()=>Me(!1)}),Je&&c&&(0,e.jsx)(Bt,{visitNoteId:c,onClose:()=>te(!1),onSuccess:()=>{te(!1),L()}}),ue&&(0,e.jsx)(Vs,{onClose:()=>Fe(!1),onSave:()=>L()}),_&&l&&(0,e.jsx)(Vt,{onSign:De,onCancel:()=>re(!1),signerName:`${l.first_name} ${l.last_name}`,signerCredentials:l.specialty||l.provider_type,savedSignature:l.signature_data,title:"Co-sign Visit Note",attestationText:"I have reviewed this clinical documentation and attest to its accuracy and completeness."}),U&&r&&(0,e.jsx)(Ws,{visit:s,patient:r,onClose:()=>{Ce(!1),L()},onComplete:()=>{Ce(!1),o()}}),W&&r&&(0,e.jsx)(Js,{visit:s,patient:r,onClose:()=>{ke(!1),L()},onComplete:()=>{ke(!1),o()}})]})}export{wa as VisitManager};

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.