PageSourceSearch

https://bitacora.ai/assets/PacienteDetalle-OMR9iQmx.js

js bitacora.ai collected 2026-10-05 15:28:20 UTC 273,927 bytes, 64 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jspdf.es.min-BurAA85T.js","assets/index-BiVk33Bn.js","assets/index-C_EkV28a.css"])))=>i.map(i=>d[i]);
2import{c as Ae,u as W,j as t,I as le,r as p,ac as we,m as _e,z as F,e as K,aM as Fe,aN as de,a9 as pe,s as ut,a1 as Ya,az as Y,aC as ar,aO as ta,aD as Re,aP as Ra,x as fe,aA as Xa,H as Pn,G as An,aQ as Ln,aF as Ot,aR as ua,aS as ft,aJ as Dn,aT as Pt,aU as On,aV as $n,ad as Mn,aq as Rn,aW as Fn,ao as Vn,a as sr,p as rr,av as Za,aX as In,N as Bn,aY as Ja,X as zn,i as Un,A as Wn,aH as Hn,aI as Kn,Z as nr,aZ as Qa,a_ as $t,a$ as mt,L as Pe,b0 as ht,aB as ir,b1 as lr,b2 as or,at as qn,ae as Gn,g as Yn}from"./index-BiVk33Bn.js";import{V as tt}from"./ViewToggle-B6Oc7Rno.js";import{u as at}from"./useListView-Cd7ahFXU.js";import{B as Xn,I as Zn,L as Jn,u as cr,S as dr,P as ur,E as mr}from"./index-CiDC4-iS.js";import{g as Qn,u as ei,c as ti,l as pr}from"./notes-MWT6Egzy.js";import{u as xr,d as ai}from"./e2e-1pzREh-U.js";import{l as aa,E as fr,a as hr,b as br}from"./E2ERecoveryModal-DbMeRsEl.js";import{B as si}from"./Breathing-BHGKpnYj.js";import{u as ri,T as yr}from"./TextareaWithMic-i7TLaVCb.js";import{V as Nt}from"./WhisperDisclaimerModal-BLkoEFSa.js";import{L as ni}from"./list-BHEiAzn9.js";import{S as ii,M as li}from"./square-SfJCRdgT.js";import{L as sa}from"./lock-BqCMcMEJ.js";import{S as gr}from"./save-CgIUpHlW.js";import{D as es,t as kr}from"./DatePicker-Be3K5t8V.js";import{A as vr}from"./arrow-right-xs5yaljM.js";import{u as jr,f as oi,g as ci,s as di}from"./patients-BbfSHjXB.js";import{u as ui,D as mi,C as pi,G as xi,I as fi,A as hi,i as bi,d as ys,S as yi,a as wr,b as gi,l as ki,g as vi,e as ji,f as Wt,c as wi,h as gs,s as _i,j as Ni}from"./GenderSelect-ChSpxa1_.js";import{S as ra}from"./star-YTvrMvtj.js";import{P as ts}from"./pencil-V5I7XxeK.js";import{E as ma}from"./ellipsis-r9x8pUBT.js";import{R as Si}from"./RecordButton-DXupM-Nh.js";import{S as Ci}from"./SessionCreateDialog-B6xaiK0Q.js";import{R as Ei}from"./RegisterPaymentDialog-Dxjvl0lh.js";import{r as Ti,l as _r}from"./payments-pEfOdCkI.js";import{D as as}from"./download-BHAxTLf1.js";import{P as Lt}from"./plus-DR5aqSon.js";import{g as bt,d as Mt}from"./library-DcgI-Yl4.js";import{l as Nr,T as Sr,a as Pi,b as Ai,c as Li,d as Di,r as Oi,e as $i}from"./task-mlwlyDok.js";import{l as Cr,a as Er,g as Mi,b as Ri}from"./evaluations-DBFNL7gL.js";import{l as Fi,u as Vi,A as Ii}from"./useAlerts-C5pDeyqU.js";import{M as Tr}from"./mail-CFHv1ZSR.js";import{C as dt}from"./copy-B3UcKl_7.js";import{C as Qt}from"./check-BeXug3s7.js";import{P as Bi}from"./agenda-series-DtU7KVyA.js";import{U as ss}from"./upload-Ds9LlTej.js";import{u as zi}from"./ContentAreaPanel-B-gB7PWQ.js";import{u as Ui,T as Wi,a as Hi}
2from"./TreatmentPlanGeneratorDrawer-DbsQiFYt.js";import{c as Ki,T as qi}from"./treatment-plans-DO1-4yqt.js";import{L as Rt,a as rs,b as Gi}from"./LibraryUploadDialog-BTg4C1h7.js";import{A as ka}from"./archive-4YfGudjU.js";import{c as Yi,P as ks}from"./plan-COMPwFK-.js";import{N as Xi}from"./NewEvaluationModal-BPy9CYgt.js";import{w as Zi,c as Ht,s as Ji,i as va,a as Pr,u as Ar,r as Lr,b as Qi,S as el,d as Dr,e as tl,f as al,g as sl,h as rl,j as nl,p as il,k as ll,l as ol,m as Or,n as cl,o as dl,q as ul,t as ml,v as pl,x as $r,y as xl,z as vs,A as fl,R as hl,L as bl,C as yl,X as gl,Y as kl,T as vl,B as jl}from"./LineChart-Bpq3Xar9.js";import{r as wl}from"./index-CdO84lzA.js";import{C as _l}from"./clipboard-list-Cm_MC67t.js";import{N as Nl}from"./NewTaskModal-CzYzESA0.js";import{R as Sl}from"./rotate-cw-CtwvSGZP.js";import{l as Cl,g as El}from"./analyses-CXgcb1-1.js";import"./transcription-Dp5GYTw8.js";import"./practice-locations-U-aabBYR.js";import"./quotaError-BaYSVV0J.js";import"./link-2-BzeOl-d8.js";import"./folders-C01WPKVG.js";import"./library-Bh3Rz1tB.js";import"./Combobox-LFTjfCFD.js";import"./ContextDisclosure-BpRhF1JV.js";import"./QuotaUpgradeToast-Bv1rMDNC.js";import"./PatientCombobox-Ev8Ltelw.js";import"./arrow-left-CmSIiUGN.js";import"./circle-alert-Cmi3VKC8.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};e.SENTRY_RELEASE={id:"daca8474617e38beb40596519f5b410a89e15552"};var s=new e.Error().stack;s&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[s]="ca5c87f0-cdcd-4d77-b04f-260049a64ada",e._sentryDebugIdIdentifier="sentry-dbid-ca5c87f0-cdcd-4d77-b04f-260049a64ada")}catch{}})();/**
3 * @license lucide-react v0.508.0 - ISC
4 *
5 * This source code is licensed under the ISC license.
6 * See the LICENSE file in the root directory of this source tree.
7 */const Tl=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],Pl=Ae("activity",Tl);/**
8 * @license lucide-react v0.508.0 - ISC
9 *
10 * This source code is licensed under the ISC license.
11 * See the LICENSE file in the root directory of this source tree.
12 */const Al=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]],Ll=Ae("ban",Al);/**
13 * @license lucide-react v0.508.0 - ISC
14 *
15 * This source code is licensed under the ISC license.
16 * See the LICENSE file in the root directory of this source tree.
17 */const Dl=[["path",{d:"M20 21v-8a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8",key:"1w3rig"}],["path",{d:"M4 16s.5-1 2-1 2.5 2 4 2 2.5-2 4-2 2.5 2 4 2 2-1 2-1",key:"n2jgmb"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M7 8v3",key:"1qtyvj"}],["path",{d:"M12 8v3",key:"hwp4zt"}],["path",{d:"M17 8v3",key:"1i6e5u"}],["path",{d:"M7 4h.01",key:"1bh4kh"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M17 4h.01",key:"1upcoc"}]],Ol=Ae("cake",Dl);/**
18 * @license lucide-react v0.508.0 - ISC
19 *
20 * This source code is licensed under the ISC license.
21 * See the LICENSE file in the root directory of this source tree.
22 */const $l=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]],Ml=Ae("chart-column",$l);/**
23 * @license lucide-react v0.508.0 - ISC
24 *
25 * This source code is licensed under the ISC license.
26 * See the LICENSE file in the root directory of this source tree.
27 */const Rl=[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]],Fl=Ae("file-audio",Rl);/**
28 * @license lucide-react v0.508.0 - ISC
29 *
30 * This source code is licensed under the ISC license.
31 * See the LICENSE file in the root directory of this source tree.
32 */const Vl=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]],Il=Ae("file-image",Vl);/**
33 * @license lucide-react v0.508.0 - ISC
34 *
35 * This source code is licensed under the ISC license.
36 * See the LICENSE file in the root directory of this source tree.
37 */const Bl=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]],zl=Ae("file-video",Bl);/**
38 * @license lucide-react v0.508.0 - ISC
39 *
40 * This source code is licensed under the ISC license.
41 * See the LICENSE file in the root directory of this source tree.
42 */const Ul=[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]],Wl=Ae("key-round",Ul);/**
43 * @license lucide-react v0.508.0 - ISC
44 *
45 * This source code is licensed under the ISC license.
46 * See the LICENSE file in the root directory of this source tree.
47 */const Hl=[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]],ns=Ae("message-circle",Hl);/**
48 * @license lucide-react v0.508.0 - ISC
49 *
50 * This source code is licensed under the ISC license.
51 * See the LICENSE file in the root directory of this source tree.
52 */const Kl=[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]],ql=Ae("pause",Kl);/**
53 * @license lucide-react v0.508.0 - ISC
54 *
55 * This source code is licensed under the ISC license.
56 * See the LICENSE file in the root directory of this source tree.
57 */const Gl=[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]],Yl=Ae("phone",Gl),na={private_normal:"Privada",private_e2e:"Privada con autenticador",shareable:"Compartible"},Xl=["standalone","phone_call","supervision","observation"],pt={session:"Sesión",standalone:"Nota libre",phone_call:"Llamada",supervision:"Supervisión",observation:"Observación"},Zl=["bold","italic","bulletList","orderedList"];function Mr({editor:e,context:s,patientId:a,showMic:r=!0,disabled:n=!1,commands:i=Zl}){const{t:l}=W("sesiones"),o=ri({patientId:a,context:s,onText:g=>{e&&e.chain().focus("end").insertContent(`<p>${to(g)}</p>`).run()}});if(!e)return null;const c="inline-flex items-center justify-center w-8 h-8 rounded text-bark hover:bg-bark/5 transition-colors disabled:opacity-40",d="bg-bark/10";return t.jsxs("div",{className:"flex items-center gap-1 mb-4 pb-4 border-b border-bark/10","data-testid":"editor-toolbar-with-mic",children:[i.includes("bold")?t.jsx("button",{type:"button",disabled:n,onClick:()=>e.chain().focus().toggleBold().run(),className:`${c} ${e.isActive("bold")?d:""}`,"aria-label":l("toolbar.bold"),title:l("toolbar.bold"),children:t.jsx(le,{as:Xn,size:14})}):null,i.includes("italic")?t.jsx("button",{type:"button",disabled:n,onClick:()=>e.chain().focus().toggleItalic().run(),className:`${c} ${e.isActive("italic")?d:""}`,"aria-label":l("toolbar.italic"),title:l("toolbar.italic"),children:t.jsx(le,{as:Zn,size:14})}):null,i.includes("bulletList")?t.jsx("button",{type:"button",disabled:n,onClick:()=>e.chain().focus().toggleBulletList().run(),className:`${c} ${e.isActive("bulletList")?d:""}`,"aria-label":l("toolbar.bulletList"),title:l("toolbar.bulletList"),children:t.jsx(le,{as:ni,size:14})}):null,i.includes("orderedList")?t.jsx("button",{type:"button",disabled:n,onClick:()=>e.chain().focus().toggleOrderedList().run(),className:`${c} ${e.isActive("orderedList")?d:""}`,"aria-label":l("toolbar.orderedList"),title:l("toolbar.orderedList"),children:t.jsx(le,{as:Jn,size:14})}):null,r?t.jsxs(t.Fragment,{children:[i.length>0?t.jsx("span",{className:"w-px h-4 bg-bark/20 mx-2"}):null,t.jsx(Jl,{mic:o,disabled:n})]}):null,o.disclaimer]})}function Jl({mic:e,disabled:s}){const a=s||!e.isSupported||e.state==="processing",r=Ql(e.state,!e.isSupported),n=e.isSupported?e.state==="recording"?Nt.recordButton.tooltipRecording:e.state==="processing"?Nt.recordButton.tooltipProcessing:Nt.recordButton.tooltipIdle:e.disabledTooltip;return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",disabled:a,onClick:e.onClick,className:r,"aria-label":Nt.recordButton.tooltipIdle,"aria-pressed":e.state==="recording",title:n,"data-mic-state":e.state,children:[e.state==="processing"&&t.jsx(si,{size:9}),e.state==="recording"&&t.jsx(le,{as:ii,size:14}),e.state==="idle"&&t.jsx(le,{as:li,size:14})]}),e.state==="recording"&&t.jsx("span",{className:"ml-2 text-tiny uppercase tracking-widest text-terracotta tabular-nums",children:eo(e.durationSeconds)}),e.state==="processing"&&t.jsx("span",{className:"ml-2 text-tiny uppercase tracking-widest text-bark-muted",children:Nt.recordButton.tooltipProcessing})]})}function Ql(e,s){const a="inline-flex items-center justify-center w-8 h-8 rounded text-bark transition-colors disabled:opacity-40";return s?`${a} hover:bg-bark/5`:e==="recording"?`${a} text-terracotta animate-pulse`:e==="processing"?`${a} text-bark-muted`:`${a} hover:bg-bark/5`}function eo(e){const s=Math.floor(e/60),a=e%60;return`${s}:${String(a).padStart(2,"0")}`}function to(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ao({session:e,onClose:s}){const{t:a,i18n:r}=W("sesiones"),n=p.useRef(null);
57we(!0),_e(n,!0);const[i,l]=p.useState(null),[o,c]=p.useState("private_normal"),[d,g]=p.useState(!0),[u,m]=p.useState(!1),[f,y]=p.useState(null),[_,h]=p.useState(!1),[T,x]=p.useState(!1),[P,S]=p.useState(!1),[L,I]=p.useState(null),v=xr(C=>C.master),O=cr({extensions:[dr,ur.configure({placeholder:a("noteEditor.placeholder")})],content:"",editorProps:{attributes:{class:"prose-bitacora min-h-[300px] focus:outline-none text-bark"}}});p.useEffect(()=>{let C=!1;return aa().then(N=>{C||y(N)}).catch(()=>{}),()=>{C=!0}},[]),p.useEffect(()=>{let C=!1;return Qn(e.id).then(N=>{C||(l(N),N&&(c(N.privacy_level),N.privacy_level==="private_e2e"?N.encrypted_content&&N.encryption_iv&&I({ct:N.encrypted_content,iv:N.encryption_iv}):N.plain_content&&O&&O.commands.setContent(N.plain_content)))}).catch(N=>{C||F.error(K(N,a("noteEditor.loadError")))}).finally(()=>{C||g(!1)}),()=>{C=!0}},[e.id,O]),p.useEffect(()=>{if(!O||!L||!v)return;let C=!1;return ai(L,v).then(N=>{C||(O.commands.setContent(N),I(null))}).catch(()=>{C||F.error(a("noteEditor.decryptError"))}),()=>{C=!0}},[O,L,v]);const k=o==="private_e2e"&&!v,E=o==="private_e2e"&&!f,A=o==="private_e2e"&&!!L&&!v;async function D(){if(O){if(o==="private_e2e"){if(!f){h(!0);return}if(!v){x(!0);return}}m(!0);try{const C=O.getHTML(),N=await ei({sessionId:e.id,privacyLevel:o,plainContent:C,expectedVersion:i==null?void 0:i.version});l(N),F.success(a("noteEditor.saved"))}catch(C){F.error(K(C,a("noteEditor.saveError")))}finally{m(!1)}}}return t.jsxs("div",{ref:n,className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 p-0 lg:px-4",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"bg-bone w-full h-full max-w-none max-h-none overflow-y-auto rounded-none p-6 lg:h-auto lg:max-w-3xl lg:max-h-[90vh] lg:rounded-lg lg:p-8",children:[t.jsxs("header",{className:"mb-8",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb-2",children:a("noteEditor.subtitle",{date:de(e.scheduled_start),time:Fe(e.scheduled_start)})}),t.jsx("h2",{className:"text-h2 font-sans text-bark",children:a("noteEditor.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-2",children:i?a("noteEditor.version",{version:i.version,date:new Date(i.updated_at).toLocaleString(r.language)}):a("noteEditor.newNote")})]}),t.jsxs("div",{className:"mb-6",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-2",children:a("noteEditor.privacyLabel")}),t.jsx("div",{className:"flex flex-wrap gap-2",children:Object.keys(na).map(C=>{const N=o===C,R=C==="private_e2e";return t.jsxs("button",{type:"button",onClick:()=>c(C),className:`inline-flex items-center gap-2 h-8 px-4 text-tiny uppercase tracking-widest rounded-full border transition-colors ${N?"border-bark bg-bark text-linen":"border-bark/30 text-bark hover:border-bark"}`,children:[R?t.jsx(sa,{size:12,strokeWidth:1.5}):null,na[C]]},C)})}),E?t.jsxs("p",{className:"text-tiny text-bark-muted mt-2 italic",children:[a("noteEditor.e2eHint")," ",t.jsx("button",{type:"button",onClick:()=>h(!0),className:"text-terracotta hover:underline",children:a("noteEditor.activateNow")})]}):k?t.jsxs("p",{className:"text-tiny text-bark-muted mt-2 italic",children:[a("noteEditor.encryptedLocked")," ",t.jsx("button",{type:"button",onClick:()=>x(!0),className:"text-terracotta hover:underline",children:a("noteEditor.unlockNow")})]}):null]}),d?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted py-12",children:a("noteEditor.loading")}):A?t.jsxs("div",{className:"border border-bark/10 rounded-lg p-6 bg-linen min-h-[300px] flex flex-col items-center justify-center gap-3",children:[t.jsx(sa,{size:20,strokeWidth:1.5,className:"text-bark-muted"}),t.jsx("p",{className:"text-small text-bark-muted",children:a("noteEditor.encryptedContent")}),t.jsx("button",{type:"button",onClick:()=>x(!0),className:"text-tiny uppercase tracking-widest text-terracotta hover:underline",children:a("noteEditor.unlockToView")})]}):t.jsxs("div",{className:"border border-bark/10 rounded-lg p-6 bg-linen min-h-[300px]",children:[t.jsx(Mr,{editor:O,context:"session_note",patientId:e.patient_id,disabled:u||k||E}),t.jsx(mr,{editor:O})]}),t.jsxs("footer",{className:"mt-6 flex gap-3 justify-end",children:[t.jsx("button",{type:"button",onClick:s,disabled:u,className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-6 py-2.5 hover:bg-bark/5 transition-colors disabled:opacity-50",children:a("noteEditor.close")}),t.jsxs("button",{type:"button",onClick:D,disabled:u||d,className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-6 py-2.5 hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-50",children:[t.jsx(gr,{size:14,strokeWidth:1.5}),a(u?"noteEditor.saving":"noteEditor.save")]})]})]}),_?t.jsx(fr,{onClose:()=>h(!1),onCompleted:()=>{h(!1),aa().then(y)}}):null,T&&f?t.jsx(hr,{material:f,onClose:()=>x(!1),onUnlocked:()=>x(!1),onRequestRecovery:()=>{x(!1),S(!0)}}):null,P&&f?t.jsx(br,{material:f,onClose:()=>S(!1),onRecovered:C=>{y(C),S(!1)}}):null]})}function so(){const e=new Date,s=e.getFullYear(),a=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${s}-${a}
57-${r}`}function ro({sessions:e,onCancel:s,onSubmit:a}){var T;const{t:r}=W("sesiones"),n=p.useRef(null);we(!0),_e(n,!0);const i=p.useMemo(()=>[...e].sort((x,P)=>P.scheduled_start.localeCompare(x.scheduled_start)).slice(0,10),[e]),[l,o]=p.useState(i.length>0?"session":"standalone"),[c,d]=p.useState(((T=i[0])==null?void 0:T.id)??""),[g,u]=p.useState("standalone"),[m,f]=p.useState(so());function y(){if(l==="session"){const P=i.find(S=>S.id===c);if(!P)return;a({mode:"session",session:P});return}const x=new Date(`${m}T12:00:00`).toISOString();a({mode:"standalone",kind:g,occurredAt:x})}const _=i.length>0,h=l==="standalone"||!!c;return t.jsx("div",{ref:n,className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 px-4",role:"dialog","aria-modal":"true","aria-label":r("notePicker.title"),children:t.jsxs("div",{className:"bg-bone w-full max-w-xl rounded-lg p-8",children:[t.jsxs("header",{className:"mb-6",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb-2",children:r("notePicker.title")}),t.jsx("h2",{className:"text-h2 font-sans text-bark",children:r("notePicker.question")})]}),t.jsxs("div",{className:"space-y-5",children:[_?t.jsx("label",{className:`block border rounded-md p-4 cursor-pointer transition-colors ${l==="session"?"border-bark bg-linen":"border-bark/15 hover:border-bark/40"}`,children:t.jsxs("span",{className:"flex items-start gap-3",children:[t.jsx("input",{type:"radio",name:"note-mode",value:"session",checked:l==="session",onChange:()=>o("session"),className:"mt-1 accent-bark"}),t.jsxs("span",{className:"flex-1",children:[t.jsx("span",{className:"block text-body text-bark",children:r("notePicker.fromSessionLabel")}),t.jsx("span",{className:"block text-small text-bark-muted mt-1",children:r("notePicker.fromSessionDescription")}),l==="session"?t.jsxs("span",{className:"mt-3 block",children:[t.jsx("span",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1 block",children:r("notePicker.chooseSession")}),t.jsx("select",{value:c,onChange:x=>d(x.target.value),className:"w-full border border-bark/20 bg-bone rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark",children:i.map(x=>t.jsxs("option",{value:x.id,children:[de(x.scheduled_start)," ·"," ",Fe(x.scheduled_start)]},x.id))})]}):null]})]})}):null,t.jsx("label",{className:`block border rounded-md p-4 cursor-pointer transition-colors ${l==="standalone"?"border-bark bg-linen":"border-bark/15 hover:border-bark/40"}`,children:t.jsxs("span",{className:"flex items-start gap-3",children:[t.jsx("input",{type:"radio",name:"note-mode",value:"standalone",checked:l==="standalone",onChange:()=>o("standalone"),className:"mt-1 accent-bark"}),t.jsxs("span",{className:"flex-1",children:[t.jsx("span",{className:"block text-body text-bark",children:r("notePicker.freeLabel")}),t.jsx("span",{className:"block text-small text-bark-muted mt-1",children:r("notePicker.freeDescription")}),l==="standalone"?t.jsxs("span",{className:"mt-3 block space-y-3",children:[t.jsxs("span",{className:"block",children:[t.jsx("span",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1 block",children:r("notePicker.type")}),t.jsx("select",{value:g,onChange:x=>u(x.target.value),className:"w-full border border-bark/20 bg-bone rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark",children:Xl.map(x=>t.jsx("option",{value:x,children:pt[x]},x))})]}),t.jsxs("span",{className:"block",children:[t.jsx("span",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1 block",children:r("notePicker.when")}),t.jsx(es,{value:m,onChange:f,ariaLabel:r("notePicker.when"),max:kr(new Date)})]})]}):null]})]})})]}),t.jsxs("footer",{className:"mt-8 flex gap-3 justify-end",children:[t.jsx("button",{type:"button",onClick:s,className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-6 py-2.5 hover:bg-bark/5 transition-colors",children:r("notePicker.cancel")}),t.jsxs("button",{type:"button",onClick:y,disabled:!h,className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-6 py-2.5 hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-50",children:[r("notePicker.continue"),t.jsx(vr,{size:14,strokeWidth:1.5})]})]})]})})}const no={standalone:"standalone.placeholderStandalone",phone_call:"standalone.placeholderPhoneCall",supervision:"standalone.placeholderSupervision",observation:"standalone.placeholderObservation"};
57function io(e,s){return new Date(e).toLocaleDateString(s,{day:"2-digit",month:"short",year:"numeric"})}function lo({patient:e,kind:s,occurredAt:a,onSaved:r,onClose:n}){const{t:i,i18n:l}=W("sesiones"),o=p.useRef(null);we(!0),_e(o,!0);const[c,d]=p.useState("private_normal"),[g,u]=p.useState(!1),[m,f]=p.useState(null),[y,_]=p.useState(!1),[h,T]=p.useState(!1),[x,P]=p.useState(!1),S=xr(k=>k.master);p.useEffect(()=>{let k=!1;return aa().then(E=>{k||f(E)}).catch(()=>{}),()=>{k=!0}},[]);const L=c==="private_e2e"&&!S,I=c==="private_e2e"&&!m,v=cr({extensions:[dr,ur.configure({placeholder:i(no[s])})],content:"",editorProps:{attributes:{class:"prose-bitacora min-h-[300px] focus:outline-none text-bark"}}});async function O(){if(v){if(c==="private_e2e"){if(!m){_(!0);return}if(!S){T(!0);return}}u(!0);try{const k=v.getHTML(),E=await ti({patientId:e.id,kind:s,occurredAt:a,privacyLevel:c,plainContent:k});F.success(i("noteEditor.saved")),r(E)}catch(k){F.error(K(k,i("noteEditor.saveError")))}finally{u(!1)}}}return t.jsxs("div",{ref:o,className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 p-0 lg:px-4",role:"dialog","aria-modal":"true","aria-label":`Nota ${pt[s].toLowerCase()}`,children:[t.jsxs("div",{className:"bg-bone w-full h-full max-w-none max-h-none overflow-y-auto rounded-none p-6 lg:h-auto lg:max-w-3xl lg:max-h-[90vh] lg:rounded-lg lg:p-8",children:[t.jsxs("header",{className:"mb-8",children:[t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb-2",children:[pt[s]," · ",io(a,l.language)]}),t.jsx("h2",{className:"text-h2 font-sans text-bark",children:i("standalone.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-2",children:i("standalone.noSession")})]}),t.jsxs("div",{className:"mb-6",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-2",children:i("noteEditor.privacyLabel")}),t.jsx("div",{className:"flex flex-wrap gap-2",children:Object.keys(na).map(k=>{const E=c===k,A=k==="private_e2e";return t.jsxs("button",{type:"button",onClick:()=>d(k),className:`inline-flex items-center gap-2 h-8 px-4 text-tiny uppercase tracking-widest rounded-full border transition-colors ${E?"border-bark bg-bark text-linen":"border-bark/30 text-bark hover:border-bark"}`,children:[A?t.jsx(sa,{size:12,strokeWidth:1.5}):null,na[k]]},k)})}),I?t.jsxs("p",{className:"text-tiny text-bark-muted mt-2 italic",children:[i("noteEditor.e2eHint")," ",t.jsx("button",{type:"button",onClick:()=>_(!0),className:"text-terracotta hover:underline",children:i("noteEditor.activateNow")})]}):L?t.jsxs("p",{className:"text-tiny text-bark-muted mt-2 italic",children:[i("noteEditor.encryptedLocked")," ",t.jsx("button",{type:"button",onClick:()=>T(!0),className:"text-terracotta hover:underline",children:i("noteEditor.unlockNow")})]}):null]}),t.jsxs("div",{className:"border border-bark/10 rounded-lg p-6 bg-linen min-h-[300px]",children:[t.jsx(Mr,{editor:v,context:"session_note",patientId:e.id,disabled:g||L||I}),t.jsx(mr,{editor:v})]}),t.jsxs("footer",{className:"mt-6 flex gap-3 justify-end",children:[t.jsx("button",{type:"button",onClick:n,disabled:g,className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-6 py-2.5 hover:bg-bark/5 transition-colors disabled:opacity-50",children:i("noteEditor.close")}),t.jsxs("button",{type:"button",onClick:O,disabled:g,className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-6 py-2.5 hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-50",children:[t.jsx(gr,{size:14,strokeWidth:1.5}),i(g?"noteEditor.saving":"noteEditor.save")]})]})]}),y?t.jsx(fr,{onClose:()=>_(!1),onCompleted:()=>{_(!1),aa().then(f)}}):null,h&&m?t.jsx(hr,{material:m,onClose:()=>T(!1),onUnlocked:()=>T(!1),onRequestRecovery:()=>{T(!1),P(!0)}}):null,x&&m?t.jsx(br,{material:m,onClose:()=>P(!1),onRecovered:k=>{f(k),P(!1)}}):null]})}class yt extends Ya{}function Ft(){return"https://api.bitacora.ai"}async function Vt(){var a;const{data:e}=await ut.auth.getSession(),s=(a=e.session)==null?void 0:a.access_token;if(!s)throw new yt("No hay sesión activa.");return{Accept:"application/json",Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}
57async function Fa(e){const s=await Vt(),a=await fetch(`${Ft()}/patients/${e}/contacts`,{method:"GET",headers:s});if(!a.ok)throw new yt(await pe(a));return await a.json()}async function oo(e,s){const a=await Vt(),r=await fetch(`${Ft()}/patients/${e}/contacts`,{method:"POST",headers:a,body:JSON.stringify(s)});if(!r.ok)throw new yt(await pe(r));return await r.json()}async function js(e,s,a){const r=await Vt(),n=await fetch(`${Ft()}/patients/${e}/contacts/${s}`,{method:"PATCH",headers:r,body:JSON.stringify(a)});if(!n.ok)throw new yt(await pe(n));return await n.json()}async function co(e,s){const a=await Vt(),r=await fetch(`${Ft()}/patients/${e}/contacts/${s}/set-primary`,{method:"PATCH",headers:a});if(!r.ok)throw new yt(await pe(r));return await r.json()}async function uo(e,s){const a=await Vt(),r=await fetch(`${Ft()}/patients/${e}/contacts/${s}`,{method:"DELETE",headers:a});if(!r.ok)throw new yt(await pe(r))}const pa={patient:"contactos.role.patient",mother:"contactos.role.mother",father:"contactos.role.father",guardian:"contactos.role.guardian",other:"contactos.role.other"},mo={phone:"contactos.channel.phone",email:"contactos.channel.email"},po={phone:"contactos.channelPlural.phone",email:"contactos.channelPlural.email"};function xo(e,s){const a=pa[e];return a?s(a):e}function fo({contact:e,onEdit:s,onSetPrimary:a,onDelete:r,onToggleWhatsApp:n}){var u;const{t:i}=W("pacientes"),[l,o]=p.useState(!1),c=p.useRef(null);p.useEffect(()=>{if(!l)return;function m(f){var y;(y=c.current)!=null&&y.contains(f.target)||o(!1)}return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[l]);const d=i(pa[e.role]),g=(u=e.label)==null?void 0:u.trim();return t.jsx("li",{className:"group relative",children:t.jsxs("div",{className:"flex items-center gap-3 py-2 px-1",children:[t.jsx("span",{className:"inline-flex w-5 justify-center text-terracotta","aria-hidden":!0,children:e.is_primary?t.jsx(ra,{size:14,strokeWidth:1.5,"aria-label":i("contactos.primaryBadgeLabel")}):null}),t.jsxs("p",{className:"flex-1 text-small text-bark",children:[t.jsx("span",{className:"text-bark-muted",children:d}),t.jsx("span",{className:"text-bark-muted",children:" · "}),t.jsx("span",{children:e.value}),g?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-bark-muted",children:" · "}),t.jsx("span",{className:"text-bark-muted italic",children:g})]}):null]}),e.channel==="phone"?t.jsxs("label",{className:"inline-flex items-center gap-2 shrink-0 cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:e.whatsapp_reminders_enabled,onChange:m=>n(e,m.target.checked),className:"accent-terracotta","aria-label":i("contactos.whatsappToggleAria",{value:e.value})}),t.jsx("span",{className:`text-tiny uppercase tracking-widest ${e.whatsapp_reminders_enabled?"text-terracotta":"text-bark-muted"}`,children:"WhatsApp"})]}):null,t.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity",children:[t.jsx("button",{type:"button",onClick:()=>s(e),className:"p-1 text-bark-muted hover:text-bark transition-colors","aria-label":i("contactos.actionEdit"),title:i("contactos.actionEdit"),children:t.jsx(ts,{size:16,strokeWidth:1.5})}),t.jsxs("div",{className:"relative",ref:c,children:[t.jsx("button",{type:"button",onClick:()=>o(m=>!m),className:"p-1 text-bark-muted hover:text-bark transition-colors","aria-label":i("contactos.actionMore"),"aria-haspopup":"menu","aria-expanded":l,title:i("contactos.actionMore"),children:t.jsx(ma,{size:16,strokeWidth:1.5})}),l?t.jsxs("div",{role:"menu",className:"absolute right-0 top-full mt-1 z-10 min-w-[12rem] bg-bone border border-bark/10 rounded-md py-1",children:[t.jsx("button",{type:"button",role:"menuitem",onClick:()=>{o(!1),e.is_primary||a(e)},disabled:e.is_primary,className:"w-full text-left px-3 py-2 text-small text-bark hover:bg-bark/5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:i("contactos.actionSetPrimary")}),t.jsx("button",{type:"button",role:"menuitem",onClick:()=>{o(!1),r(e)},className:"w-full text-left px-3 py-2 text-small text-clay hover:bg-bark/5 transition-colors",children:i("contactos.actionDelete")})]}):null]})]})]})})}var It=e=>e.type==="checkbox",Ue=e=>e instanceof Date,oe=e=>e==null;const is=e=>typeof e=="object";var se=e=>!oe(e)&&!Array.isArray(e)&&is(e)&&!Ue(e),Va=e=>se(e)&&e.target?It(e.target)?e.target.checked:e.target.value:e,Rr=(e,s)=>s.split(".").some((a,r,n)=>!isNaN(Number(a))&&e.has(n.slice(0,r).join("."))),Fr=e=>{const s=e.constructor&&e.constructor.prototype;return se(s)&&s.hasOwnProperty("isPrototypeOf")},xa=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function ae(e){if(e instanceof Date)return new Date(e);const s=typeof FileList<"u"&&e instanceof FileList;if(xa&&(e instanceof Blob||s))return e;const a=Array.isArray(e);if(!a&&!(se(e)&&Fr(e)))return e;const r=a?[]:Object.create(Object.getPrototypeOf(e));for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=ae(e[n]));return r}const ze={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Te={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ee={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},Vr="root",ls=["__proto__","constructor","prototype"],ho=/^\w*$/;var Bt=e=>ho.test(e),ee=e=>e===void 0;const bo=/[.[\]'"]/;var fa=e=>
57e.split(bo).filter(Boolean),V=(e,s,a)=>{if(!s||!se(e))return a;const r=Bt(s)?[s]:fa(s);if(r.some(i=>ls.includes(i)))return a;const n=r.reduce((i,l)=>oe(i)?void 0:i[l],e);return ee(n)||n===e?ee(e[s])?a:e[s]:n},be=e=>typeof e=="boolean",me=e=>typeof e=="function",J=(e,s,a)=>{let r=-1;const n=Bt(s)?[s]:fa(s),i=n.length,l=i-1;for(;++r<i;){const o=n[r];let c=a;if(r!==l){const d=e[o];c=se(d)||Array.isArray(d)?d:isNaN(+n[r+1])?{}:[]}if(ls.includes(o))return;e[o]=c,e=e[o]}};const Ir=Y.createContext(null);Ir.displayName="HookFormControlContext";const os=()=>Y.useContext(Ir);var Br=(e,s,a,r=!0)=>{const n={};for(const i in e)Object.defineProperty(n,i,{get:()=>{const l=i;return s._proxyFormState[l]!==Te.all&&(s._proxyFormState[l]=!r||Te.all),a&&(a[l]=!0),e[l]}});return n};const cs=xa?Y.useLayoutEffect:Y.useEffect;function yo(e){const s=os(),{control:a=s,disabled:r,name:n,exact:i}=e||{},[l,o]=Y.useState(()=>({...a._formState,defaultValues:a._defaultValues})),c=Y.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return cs(()=>a._subscribe({name:n,formState:c.current,exact:i,callback:d=>{!r&&o({...a._formState,...d,defaultValues:a._defaultValues})}}),[n,r,i]),Y.useEffect(()=>{c.current.isValid&&a._setValid(!0)},[a]),Y.useMemo(()=>Br(l,a,c.current,!1),[l,a])}var ce=e=>typeof e=="string",Ia=(e,s,a,r,n)=>ce(e)?(r&&s.watch.add(e),V(a,e,n)):Array.isArray(e)?e.map(i=>(r&&s.watch.add(i),V(a,i))):(r&&(s.watchAll=!0),a),Ba=e=>oe(e)||!is(e);const ws=(e,s)=>s.length===0&&!Array.isArray(e)&&!Fr(e);function ye(e,s,a=new WeakMap){if(e===s)return!0;if(Ba(e)||Ba(s))return Object.is(e,s);if(Ue(e)&&Ue(s))return Object.is(e.getTime(),s.getTime());const r=Object.keys(e),n=Object.keys(s);if(r.length!==n.length)return!1;if(ws(e,r)||ws(s,n))return Object.is(e,s);if(!r.length&&Array.isArray(e)!==Array.isArray(s))return!1;const i=a.get(e);if(i&&i.has(s))return!0;if(i)i.add(s);else{const l=new WeakSet;l.add(s),a.set(e,l)}for(const l of r){const o=e[l];if(!(l in s))return!1;if(l!=="ref"){const c=s[l];if(Ue(o)&&Ue(c)||(se(o)||Array.isArray(o))&&(se(c)||Array.isArray(c))?!ye(o,c,a):!Object.is(o,c
57))return!1}}return!0}function go(e){const s=os(),{control:a=s,name:r,defaultValue:n,disabled:i,exact:l,compute:o}=e||{},c=Y.useRef(n),d=Y.useRef(o),g=Y.useRef(void 0),u=Y.useRef(a),m=Y.useRef(r);d.current=o;const[f,y]=Y.useState(()=>{const S=a._getWatch(r,c.current);return d.current?d.current(S):S}),_=Y.useCallback(S=>{const L=Ia(r,a._names,S||a._formValues,!1,c.current);return d.current?d.current(L):L},[a._formValues,a._names,r]),h=Y.useCallback(S=>{if(!i){const L=Ia(r,a._names,S||a._formValues,!1,c.current);if(d.current){const I=d.current(L);ye(I,g.current)||(y(I),g.current=I)}else y(L)}},[a._formValues,a._names,i,r]);cs(()=>((u.current!==a||!ye(m.current,r))&&(u.current=a,m.current=r,h()),a._subscribe({name:r,formState:{values:!0},exact:l,callback:S=>{h(S.values)}})),[a,l,r,h]),Y.useEffect(()=>a._removeUnmounted());const T=u.current!==a,x=m.current,P=Y.useMemo(()=>{if(i)return null;const S=!T&&!ye(x,r);return T||S?_():null},[i,T,r,x,_]);return P!==null?P:f}function ko(e){const s=os(),{name:a,disabled:r,control:n=s,shouldUnregister:i,defaultValue:l,exact:o=!0}=e,c=Rr(n._names.array,a),d=Y.useMemo(()=>V(n._formValues,a,V(n._defaultValues,a,l)),[n,a,l]),g=go({control:n,name:a,defaultValue:d,exact:o}),u=yo({control:n,name:a,exact:o}),m=Y.useRef(e),f=Y.useRef(null),y=Y.useRef(n.register(a,{...e.rules,value:g,...be(e.disabled)?{disabled:e.disabled}:{}}));m.current=e;const _=Y.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!V(u.errors,a)},isDirty:{enumerable:!0,get:()=>!!V(u.dirtyFields,a)},isTouched:{enumerable:!0,get:()=>!!V(u.touchedFields,a)},isValidating:{enumerable:!0,get:()=>!!V(u.validatingFields,a)},error:{enumerable:!0,get:()=>V(u.errors,a)}}),[u,a]),h=Y.useCallback(S=>{const L=Va(S);return V(n._fields,a)||(y.current=n.register(a,{...m.current.rules,value:L})),y.current.onChange({target:{value:Va(S),name:a},type:ze.CHANGE})},[a,n]),T=Y.useCallback(()=>y.current.onBlur({target:{value:V(n._formValues,a),name:a},type:ze.BLUR}),[a,n._formValues]),x=Y.useCallback(S=>{S&&(f.current={focus:()=>me(S.focus)&&S.focus(),select:()=>me(S.select)&&S.select(),setCustomValidity:I=>me(S.setCustomValidity)&&S.setCustomValidity(I),reportValidity:()=>me(S.reportValidity)&&S.reportValidity()});const L=V(n._fields,a);L&&L._f&&S&&(L._f.ref=f.current)},[n._fields,a]),P=Y.useMemo(()=>({name:a,value:g,...be(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:h,onBlur:T,ref:x}),[a,r,u.disabled,h,T,x,g]);return Y.useEffect(()=>{const S=n._options.shouldUnregister||i;n.register(a,{...m.current.rules,...be(m.current.disabled)?{disabled:m.current.disabled}:{}});const L=(I,v)=>{const O=V(n._fields,I);O&&O._f&&(O._f.mount=v)};if(L(a,!0),S){const I=ae(V(i?n._defaultValues:n._options.values||n._defaultValues,a,V(n._options.defaultValues,a,m.current.defaultValue)));J(n._defaultValues,a,I),ee(V(n._formValues,a))&&J(n._formValues,a,I)}if(!c&&n.register(a),f.current){const I=V(n._fields,a);I&&I._f&&(I._f.ref=f.current)}return()=>{(c?S&&!n._state.action:S)?n.unregister(a):L(a,!1)}},[a,n,c,i]),Y.useEffect(()=>{n._setDisabledField({disabled:r,name:a})},[r,a,n]),Y.useMemo(()=>({field:P,formState:u,fieldState:_}),[P,u,_])}const vo=e=>e.render(ko(e));var Kt=e=>({isOnSubmit:!e||e===Te.onSubmit,isOnBlur:e===Te.onBlur,isOnChange:e===Te.onChange,isOnAll:e===Te.all,isOnTouch:e===Te.onTouched}),ja=(e,s,a)=>{if(a)return!1;if(s.watchAll||s.watch.has(e))return!0;for(const r of s.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const At=(e,s,a,r)=>{for(const n of a||Object.keys(e)){const i=V(e,n);if(i){const{_f:l,...o}=i;if(l){if(l.refs&&l.refs[0]&&s(l.refs[0],n)&&!r)return!0;if(l.ref&&s(l.ref,l.name)&&!r)return!0;if(At(o,s))break}else if(se(o)&&At(o,s))break}}};var _s=(e,s,a)=>{const r=V(e,a),n=Array.isArray(r)?r:[];return J(n,Vr,s[a]),J(e,a,n),e},ie=e=>se(e)&&!Object.keys(e).length,ds=e=>e.type==="file",ia=e=>{if(!xa)return!1;const s=e?e.ownerDocument:0;return e instanceof(s&&s.defaultView?s.defaultView.HTMLElement:HTMLElement)},us=e=>e.type==="radio",la=e=>e instanceof RegExp,zr=(e,s,a,r,n)=>s?{...a[e],types:{...a[e]&&a[e].types?a[e].types:{},[r]:n||!0}}:{};const Ns={value:!1,isValid:!1},Ss={value:!0,isValid:!0};var Ur=e=>{if(Array.isArray(e)){if(e.length>1){const s=e.filter(a=>a&&a.checked&&!a.disabled).map(a=>a.value);return{value:s,isValid:!!s.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!ee(e[0].attributes.value)?ee(e[0].value)||e[0].value===""?Ss:{value:e[0].value,isValid:!0}:Ss:Ns}return Ns};const Cs={isValid:!1,value:null};var Wr=e=>Array.isArray(e)?e.reduce((s,a)=>a&&a.checked&&!a.disabled?{isValid:!0,value:a.value}:s,Cs):Cs;function Es(e,s,a="validate"){if(ce(e)||Array.isArray(e)&&e.every(ce)||be(e)&&!e)return{type:a,message:ce(e)?e:"",ref:s}}var it=e=>se(e)&&!la(e)?e:{value:e,message:""},Ts=async(e,s,a,r,n,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:g,min:u,max:m,pattern:f,validate:y,name:_,valueAsNumber:h,mount:T}=e._f,x=V(a,_);if(!T||s.has(_))return{};const P=o?o[0]:l,S=D=>{if(n&&P.reportValidity){const C=be(D)?"":D||"";o?o.forEach(N=>N.setCustomValidity(C)):P.setCustomValidity(C),P.reportValidity()}},L={},I=us(l),v=It(l),O=I||v,k=(h||ds(l))&&ee(l.value)&&ee(x)||ia(l)&&l.value===""||x===""||Array.isArray(x)&&!x.length,E=zr.bind(null,_,r,L),A=(D,C,N,R=Ee.maxLength,X=Ee.minLength)=>{const Z=D?C:N;L[_]={type:D?R:X,message:Z,ref:l,...E(D?R:X,Z)}};if(i?!Array.isArray(x)||!x.length:c&&(!O&&(k||oe(x))||be(x)&&!x||v&&!Ur(o).isValid||I&&!Wr(o).isValid)){const{value:D,message:C}=ce(c)?{value:!!c,message:c}:it(c);if(D&&(L[_]={type:Ee.required,message:C,ref:P,...E(Ee.required,C)},!r))return S(C),L}if(!k&&(!oe(u)||!oe(m))){let D,C;const N=it(m),R=it(u);if(!oe(x)&&!isNaN(x)){const X=l.valueAsNumber||x&&+x;oe(N.value)||(D=X>N.value),oe(R.value)||(C=X<R.value)}else{const X=l.valueAsDate||new Date(x),Z=he=>new Date(new Date().toDateString()+" "+he),Ne=l.type=="time",ne=l.type=="week";ce(N.value)&&x&&(D=Ne?Z(x)>Z(N.value):ne?x>N.value:X>new Date(N.value)),ce(R.value)&&x&&(C=Ne?Z(x)<Z(R.value):ne?x<R.value:X<new Date(R.value))}if((D||C)&&(A(!!D,N.message,R.message,Ee.max,Ee.min),!r))return S(L[_].message),L}
57if((d||g)&&!k&&(ce(x)||i&&Array.isArray(x))){const D=it(d),C=it(g),N=!oe(D.value)&&x.length>+D.value,R=!oe(C.value)&&x.length<+C.value;if((N||R)&&(A(N,D.message,C.message),!r))return S(L[_].message),L}if(f&&!k&&ce(x)){const{value:D,message:C}=it(f);if(la(D)&&!x.match(D)&&(L[_]={type:Ee.pattern,message:C,ref:l,...E(Ee.pattern,C)},!r))return S(C),L}if(y){if(me(y)){const D=await y(x,a),C=Es(D,P);if(C&&(L[_]={...C,...E(Ee.validate,C.message)},!r))return S(C.message),L}else if(se(y)){let D={};for(const C in y){if(!ie(D)&&!r)break;const N=Es(await y[C](x,a),P,C);N&&(D={...N,...E(C,N.message)},S(N.message),r&&(L[_]=D))}if(!ie(D)&&(L[_]={ref:P,...D},!r))return L}}return S(!0),L},ea=e=>Array.isArray(e)?e:[e],Hr=e=>Array.isArray(e)?e.filter(Boolean):[];function jo(e,s){const a=s.slice(0,-1).length;let r=0;for(;r<a;){if(oe(e)){e=void 0;break}e=e[s[r]],r++}return e}function wo(e){for(const s in e)if(e.hasOwnProperty(s)&&!ee(e[s]))return!1;return!0}function re(e,s){if(ce(s)&&Object.prototype.hasOwnProperty.call(e,s))return delete e[s],e;const a=Array.isArray(s)?s:Bt(s)?[s]:fa(s);if(a.some(l=>ls.includes(String(l))))return e;const r=a.length===1?e:jo(e,a),n=a.length-1,i=a[n];return r&&delete r[i],n!==0&&(se(r)&&ie(r)||Array.isArray(r)&&wo(r))&&re(e,a.slice(0,-1)),e}const Kr=e=>{const s={};for(const a of Object.keys(e))if(is(e[a])&&e[a]!==null&&!Ue(e[a])){const r=Kr(e[a]);for(const n of Object.keys(r))s[`${a}.${n}`]=r[n]}else s[a]=e[a];return s},_o=Y.createContext(null);_o.displayName="HookFormContext";var Ps=()=>{let e=[];return{get observers(){return e},next:n=>{for(const i of e)i.next&&i.next(n)},subscribe:n=>(e.push(n),{unsubscribe:()=>{e=e.filter(i=>i!==n)}}),unsubscribe:()=>{e=[]}}};function qr(e,s){const a={};for(const r in e)if(e.hasOwnProperty(r)){const n=e[r],i=s[r];if(n&&se(n)&&i){const l=qr(n,i);se(l)&&(a[r]=l)}else e[r]&&(a[r]=i)}return a}var Gr=e=>e.type==="select-multiple",No=e=>us(e)||It(e),wa=e=>ia(e)&&e.isConnected,So=e=>{for(const s in e)if(me(e[s]))return!0;return!1};function Yr(e){return Array.isArray(e)||se(e)&&!So(e)}function Xr(e){return!!(e&&"_f"in e)}function Zr(e){return Array.isArray(e)?!e.some(s=>!ee(s)):!Object.keys(e).length}function za(e,s){Array.isArray(e)?e[s]=void 0:delete e[s]}function Ua(e,s={},a){for(const r in e){const n=e[r],i=a&&a[r];Yr(n)&&(!Array.isArray(n)||!Xr(i))?(s[r]=Array.isArray(n)?[]:{},Ua(n,s[r],i),Zr(s[r])&&za(s,r)):ee(n)||(s[r]=!0)}return s}function Ze(e,s,a,r){a||(a=Ua(s,{},r));for(const n in e){const i=e[n],l=r&&r[n];Yr(i)&&(!Array.isArray(i)||!Xr(l))?(ee(s)||Ba(a[n])?a[n]=Ua(i,Array.isArray(i)?[]:{},l):Ze(i,oe(s)?{}:s[n],a[n],l),Zr(a[n])&&za(a,n)):ye(i,s[n])?za(a,n):a[n]=!0}return a}var Jr=(e,{valueAsNumber:s,valueAsDate:a,setValueAs:r})=>ee(e)?e:s?e===""?NaN:e&&+e:a&&ce(e)?new Date(e):r?r(e):e;function As(e){const s=e.ref;return ds(s)?s.files:us(s)?Wr(e.refs).value:Gr(s)?[...s.selectedOptions].map(({value:a})=>a):It(s)?Ur(e.refs).value:Jr(ee(s.value)?e.ref.value:s.value,e)}var Co=(e,s,a,r)=>{const n={};for(const i of e){const l=V(s,i);l&&J(n,i,l._f)}return{criteriaMode:a,names:[...e],fields:n,shouldUseNativeValidation:r}},St=e=>ee(e)?e:la(e)?e.source:se(e)?la(e.value)?e.value.source:e.value:e;const Ls="AsyncFunction";var Eo=e=>{if(!e||!e.validate)return!1;if(me(e.validate))return e.validate.constructor.name===Ls;if(se(e.validate)){for(const s in e.validate)if(e.validate[s].constructor.name===Ls)return!0}return!1},To=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function Ds(e,s,a){const r=V(e,a);if(r||Bt(a))return{error:r,name:a};const n=a.split(".");for(;n.length;){const i=n.join("."),l=V(s,i),o=V(e,i);if(l&&!Array.isArray(l)&&a!==i)return{name:a};if(o&&o.type)return{name:i,error:o};if(o&&o.root&&o.root.type)return{name:`${i}.root`,error:o.root};n.pop()}return{name:a}}var Po=(e,s,a,r)=>{a(e);const{name:n,...i}=e,l=Object.keys(i);return!l.length||r&&l.length>=Object.keys(s).length||l.find(o=>s[o]===(!r||Te.all))},Ao=(e,s,a)=>!e||!s||e===s||ea(e).some(r=>r&&(a?r===s||r.startsWith(s+"."):r.startsWith(s)||s.startsWith(r))),Lo=(e,s,a,r,n)=>n.isOnAll?!1:!a&&n.isOnTouch?!(s||e):(a?r.isOnBlur:n.isOnBlur)?!e:(a?r.isOnChange:n.isOnChange)?e:!0,Do=(e,s)=>!Hr(V(e,s)).length&&re(e,s);const Oo={mode:Te.onSubmit,reValidateMode:Te.onChange,shouldFocusError:!0},_a="form",Qr={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function $o(e={}){let s={...Oo,...e},a={...ae(Qr),isLoading:me(s.defaultValues),errors:s.errors||{},disabled:s.disabled||!1}
57,r={},n=se(s.defaultValues)||se(s.values)?ae(s.defaultValues||s.values)||{}:{},i=s.shouldUnregister?{}:ae(n),l={action:!1,mount:!1,watch:!1,keepIsValid:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const c={},d={};let g=0,u=Kt(s.mode),m=Kt(s.reValidateMode);const f={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},y={...f};let _={...y};const h={array:Ps(),state:Ps()};let T=0;const x=s.criteriaMode===Te.all,P=(b,j)=>w=>{clearTimeout(d[b]),d[b]=setTimeout(j,w)},S=async b=>{if(!l.keepIsValid&&!s.disabled&&(y.isValid||_.isValid||b)){const j=++T;let w;s.resolver?(w=ie((await N()).errors),j===T&&L()):w=await Z({fields:r,onlyCheckValid:!0,eventType:ze.VALID}),j===T&&w!==a.isValid&&h.state.next({isValid:w})}},L=(b,j)=>{!s.disabled&&(y.isValidating||y.validatingFields||_.isValidating||_.validatingFields)&&((b||Array.from(o.mount)).forEach(w=>{w&&(j?J(a.validatingFields,w,j):re(a.validatingFields,w))}),h.state.next({validatingFields:a.validatingFields,isValidating:!ie(a.validatingFields)}))},I=()=>{a.dirtyFields=Ze(n,i,void 0,r)},v=(b,j=[],w,$,M=!0,z=!0)=>{if($&&w&&!s.disabled){if(l.action=!0,z&&Array.isArray(V(r,b))){const B=w(V(r,b),$.argA,$.argB);M&&J(r,b,B)}if(z&&Array.isArray(V(a.errors,b))){const B=w(V(a.errors,b),$.argA,$.argB);M&&J(a.errors,b,B),Do(a.errors,b)}if((y.touchedFields||_.touchedFields)&&z&&Array.isArray(V(a.touchedFields,b))){const B=w(V(a.touchedFields,b),$.argA,$.argB);M&&J(a.touchedFields,b,B)}(y.dirtyFields||_.dirtyFields)&&I(),h.state.next({name:b,isDirty:ne(b,j),dirtyFields:a.dirtyFields,errors:a.errors,isValid:a.isValid})}else J(i,b,j)},O=(b,j)=>{J(a.errors,b,j),a.errors={...a.errors},h.state.next({errors:a.errors})},k=b=>{a.errors=b,h.state.next({errors:a.errors,isValid:!1})},E=b=>{const j=Bt(b)?[b]:fa(b);let w=i,$=n;for(let M=0;M<j.length-1;M++){const z=j[M];if(w=oe(w)?w:w[z],$=oe($)?$:$[z],w===null&&$!==null)return!0}return!1},A=(b,j,w,$)=>{const M=V(r,b);if(M){if(E(b))return;const z=ee(V(i,b)),B=V(i,b,ee(w)?V(n,b):w);ee(B)||$&&$.defaultChecked||j?J(i,b,j?B:As(M._f)):Ie(b,B),l.mount&&!l.action&&(S(),z&&a.isDirty&&(y.isDirty||_.isDirty)&&(ne()||(a.isDirty=!1,h.state.next({...a}))),e.shouldUnregister&&z&&!ee(V(i,b))&&ja(b,o)&&(l.watch=!0))}},D=(b,j,w,$,M)=>{let z=!1,B=!1;const U={name:b};if(!s.disabled||$===!0){if(!w||$){const q=ye(V(n,b),j);(y.isDirty||_.isDirty)&&(B=a.isDirty,a.isDirty=U.isDirty=!q||ne(),z=B!==U.isDirty),B=!!V(a.dirtyFields,b),q!==a.isDirty?a.dirtyFields=Ze(n,i,void 0,r):q?re(a.dirtyFields,b):J(a.dirtyFields,b,!0),U.dirtyFields=a.dirtyFields,z=z||(y.dirtyFields||_.dirtyFields)&&B!==!q}if(w){const q=V(a.touchedFields,b);q||(J(a.touchedFields,b,w),U.touchedFields=a.touchedFields,z=z||(y.touchedFields||_.touchedFields)&&q!==w)}z&&M&&h.state.next(U)}return z?U:{}},C=(b,j,w,$)=>{const M=V(a.errors,b),z=(y.isValid||_.isValid)&&be(j)&&a.isValid!==j;if(s.delayError&&w?(c[b]=P(b,()=>O(b,w)),c[b](s.delayError)):(clearTimeout(d[b]),delete c[b],w?J(a.errors,b,w):re(a.errors,b),a.errors={...a.errors}),(w?!ye(M,w):M)||!ie($)||z){const B={...$,...z&&be(j)?{isValid:j}:{},errors:a.errors,name:b};a={...a,...B},h.state.next(B)}},N=async b=>(L(b,!0),await s.resolver(i,s.context,Co(b||o.mount,r,s.criteriaMode,s.shouldUseNativeValidation))),R=async b=>{const{errors:j}=await N(b);if(L(b),b){for(const w of b){const $=V(j,w);$?o.array.has(w)&&se($)&&!Object.keys($).some(M=>!Number.isNaN(Number(M)))?_s(a.errors,{[w]:$},w):J(a.errors,w,$):re(a.errors,w)}a.errors={...a.errors}}else a.errors=j;return j},X=async({name:b,eventType:j})=>{if(e.validate){const w=await e.validate({formValues:i,formState:a,name:b,eventType:j});if(se(w))for(const $ in w){const M=w[$];M&&G(`${_a}.${$}`,{message:ce(M.message)?M.message:"",type:M.type||Ee.validate})}else ce(w)||!w?G(_a,{message:w||"",type:Ee.validate}):Ut(_a);return w}return!0},Z=async({fields:b,onlyCheckValid:j,name:w,eventType:$,context:M={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(M.runRootValidation=!0,!await X({name:w,eventType:$})&&(M.valid=!1,j)))return M.valid;for(const z in b){const B=b[z];if(B){const{_f:U,...q}=B;if(U){const te=o.array.has(U.name),ue=B._f&&Eo(B._f),$e=y.validatingFields||y.isValidating||_.validatingFields||_.isValidating;ue&&$e&&L([U.name],!0);const Me=await Ts(B,o.disabled,i,x,s.shouldUseNativeValidation&&!j,te);
57if(ue&&$e&&L([U.name]),Me[U.name]&&(M.valid=!1,j)||(!j&&(V(Me,U.name)?te?_s(a.errors,Me,U.name):J(a.errors,U.name,Me[U.name]):re(a.errors,U.name)),e.shouldUseNativeValidation&&Me[U.name]))break}!ie(q)&&await Z({context:M,onlyCheckValid:j,fields:q,name:z,eventType:$})}}return M.valid},Ne=()=>{for(const b of o.unMount){const j=V(r,b);j&&(j._f.refs?j._f.refs.every(w=>!wa(w)):!wa(j._f.ref))&&qe(b)}o.unMount=new Set},ne=(b,j)=>(b&&j&&J(i,b,j),!ye(l.mount?i:n,n)),he=(b,j,w)=>Ia(b,o,{...l.mount?i:ee(j)?n:ce(b)?{[b]:j}:j},w,j),Ve=b=>Hr(V(l.mount?i:n,b,s.shouldUnregister?V(n,b,[]):[])),Ie=(b,j,w={},$=!1,M=!1)=>{const z=V(r,b);let B=j;if(z){const U=z._f;U&&(!U.disabled&&J(i,b,Jr(j,U)),B=ia(U.ref)&&oe(j)?"":j,Gr(U.ref)?[...U.ref.options].forEach(q=>q.selected=B.includes(q.value)):U.refs?It(U.ref)?U.refs.forEach(q=>{(!q.defaultChecked||!q.disabled)&&(Array.isArray(B)?q.checked=!!B.find(te=>te===q.value):q.checked=B===q.value||!!B)}):U.refs.forEach(q=>q.checked=q.value===B):ds(U.ref)?U.ref.value="":(U.ref.value=B,!U.ref.type&&!M&&h.state.next({name:b,values:$?i:ae(i)})))}(w.shouldDirty||w.shouldTouch)&&D(b,B,w.shouldTouch,w.shouldDirty,!M),w.shouldValidate&&De(b,{delayError:w.delayError})},Se=(b,j,w,$=!1,M=!1)=>{for(const z in j){if(!j.hasOwnProperty(z))return;const B=j[z],U=b+"."+z,q=V(r,U);(o.array.has(b)||se(B)||q&&!q._f)&&!Ue(B)?Se(U,B,w,$,M):Ie(U,B,w,$,M)}},Be=(b,j,w,$,M=!1)=>{const z=V(r,b),B=o.array.has(b),U=$?j:ae(j),q=V(i,b),te=ye(q,U);if(te||J(i,b,U),B)h.array.next({name:b,values:$?i:ae(i)}),(y.isDirty||y.dirtyFields||_.isDirty||_.dirtyFields)&&w.shouldDirty&&(I(),M||h.state.next({name:b,dirtyFields:a.dirtyFields,isDirty:ne(b,U)}));else{const ue=Array.isArray(U)&&!U.length||ie(U);!z||z._f||oe(U)||ue?Ie(b,U,w,$,M):Se(b,U,w,$,M)}if(!te&&!M){const ue=ja(b,o),$e=$?i:ae(i);h.state.next({...ue&&a,name:l.mount||ue?b:void 0,values:$e})}},xe=(b,j,w={})=>Be(b,j,w,!1),Ke=(b,j={})=>{const w=me(b)?b(i):b;if(!ye(i,w)){i={...i,...w};const $=Kr(w);for(const M of o.mount)M in $&&Be(M,$[M],j,!0,!0);h.state.next({...a,name:void 0,type:void 0,...g?{values:i}:{}}),j.shouldValidate&&S()}},rt=async b=>{l.mount=!0;const j=b.target;let w=j.name,$=!0;const M=V(r,w),z=B=>{$=Number.isNaN(B)||Ue(B)&&isNaN(B.getTime())||ye(B,V(i,w,B))};if(M){let B,U;const q=j.type?As(M._f):Va(b),te=b.type===ze.BLUR||b.type===ze.FOCUS_OUT,ue=!To(M._f)&&!e.validate&&!s.resolver&&!V(a.errors,w)&&!M._f.deps,$e=ue||Lo(te,V(a.touchedFields,w),a.isSubmitted,m,u),Me=ja(w,o,te);if(J(i,w,q),te){if(!j||!j.readOnly){M._f.onBlur&&M._f.onBlur(b);const _t=c[w];_t&&_t(0)}}else M._f.onChange&&M._f.onChange(b);const wt=D(w,q,te),En=!ie(wt)||Me;if(!te&&h.state.next({name:w,type:b.type,...g?{values:ae(i)}:{}}),$e)return(!ue||!a.isValid)&&(y.isValid||_.isValid)&&(s.mode==="onBlur"?te&&S():te||S()),En&&h.state.next({name:w,...Me?{}:wt});if(!s.resolver&&e.validate&&await X({name:w,eventType:b.type}),!te&&Me&&h.state.next({...a}),s.resolver){const{errors:_t}=await N([w]);if(L([w]),z(q),!$){!ie(wt)&&h.state.next(wt);return}const Tn=Ds(a.errors,r,w),bs=Ds(_t,r,Tn.name||w);B=bs.error,w=bs.name,U=ie(_t)}else L([w],!0),B=(await Ts(M,o.disabled,i,x,s.shouldUseNativeValidation))[w],L([w]),z(q),$&&(B?U=!1:(y.isValid||_.isValid)&&(U=await Z({fields:r,onlyCheckValid:!0,name:w,eventType:b.type})));$&&(M._f.deps&&(!Array.isArray(M._f.deps)||M._f.deps.length>0)&&De(M._f.deps),C(w,U,B,wt))}},Ce=(b,j)=>{if(V(a.errors,j)&&b.focus)return b.focus(),1},De=async(b,j={})=>{let w,$;const M=ea(b);if(s.resolver){const z=await R(ee(b)?b:M);w=ie(z),$=b?!M.some(B=>V(z,B)):w}else b?($=(await Promise.all(M.map(async z=>{const B=V(r,z);return await Z({fields:B&&B._f?{[z]:B}:B,eventType:ze.TRIGGER})}))).every(Boolean),!(!$&&!a.isValid)&&S()):$=w=await Z({fields:r,name:b,eventType:ze.TRIGGER});if(j.delayError&&s.delayError&&ce(b)){const z=V(a.errors,b);z?(re(a.errors,b),c[b]=P(b,()=>O(b,z)),c[b](s.delayError)):(clearTimeout(d[b]),delete c[b])}return h.state.next({...!ce(b)||(y.isValid||_.isValid)&&w!==a.isValid?{}:{name:b},...s.resolver||!b?{isValid:w}:{},errors:a.errors}),j.shouldFocus&&!$&&At(r,Ce,b?M:o.mount),$},ya=(b,j)=>{let w={...l.mount?i:n};return j&&(w=qr(j.dirtyFields?a.dirtyFields:a.touchedFields,w)),ee(b)?w:ce(b)?V(w,b):b.map($=>V(w,$))},zt=(b,j)=>({invalid:!!V((j||a).errors,b),isDirty:!!V((j||a).dirtyFields,b),error:V((j||a).errors,b),isValidating:!!V(a.validatingFields,b),isTouched:!!V((j||a).touchedFields,b)}),Ut=b=>{const j=b?ea(b):void 0;
57j==null||j.forEach(w=>re(a.errors,w)),j?j.forEach(w=>{h.state.next({name:w,errors:a.errors})}):h.state.next({errors:{}})},G=(b,j,w)=>{const $=(V(r,b,{_f:{}})._f||{}).ref,M=V(a.errors,b)||{},{ref:z,message:B,type:U,...q}=M;J(a.errors,b,{...q,...j,ref:$}),h.state.next({name:b,errors:a.errors,isValid:!1}),w&&w.shouldFocus&&$&&$.focus&&$.focus()},Q=(b,j)=>{if(me(b)){g++;const{unsubscribe:w}=h.state.subscribe({next:M=>"values"in M&&b(M.values||he(void 0,j),M)});let $=!1;return{unsubscribe:()=>{$||($=!0,g--,w())}}}return he(b,j,!0)},Oe=b=>{var j;const w=!!(!((j=b.formState)===null||j===void 0)&&j.values);w&&g++;const{unsubscribe:$}=h.state.subscribe({next:z=>{if(Ao(b.name,z.name,b.exact)&&Po(z,b.formState||y,Cn,b.reRenderRoot)){const B={...i};b.callback({values:B,...a,...z,defaultValues:n})}}});if(!w)return $;let M=!1;return()=>{M||(M=!0,g--,$())}},jt=b=>(l.mount=!0,_={..._,...b.formState},Oe({...b,formState:{...f,...b.formState}})),qe=(b,j={})=>{for(const w of b?ea(b):o.mount)o.mount.delete(w),o.array.delete(w),j.keepValue||(re(r,w),re(i,w)),!j.keepError&&re(a.errors,w),!j.keepDirty&&re(a.dirtyFields,w),!j.keepTouched&&re(a.touchedFields,w),!j.keepIsValidating&&re(a.validatingFields,w),!s.shouldUnregister&&!j.keepDefaultValue&&re(n,w);h.state.next({values:ae(i)}),h.state.next({...a,...j.keepDirty?{isDirty:ne()}:{}}),!j.keepIsValid&&S()},nt=({disabled:b,name:j})=>{if(be(b)&&l.mount||b||o.disabled.has(j)){const M=o.disabled.has(j)!==!!b;b?o.disabled.add(j):o.disabled.delete(j),M&&l.mount&&!l.action&&S()}},Ge=(b,j={})=>{let w=V(r,b);const $=be(j.disabled)||be(s.disabled),M=!o.registerName.has(b)&&w&&w._f&&!w._f.mount;return J(r,b,{...w||{},_f:{...w&&w._f?w._f:{ref:{name:b}},name:b,mount:!0,...j}}),o.mount.add(b),w&&!M?nt({disabled:be(j.disabled)?j.disabled:s.disabled,name:b}):A(b,!0,j.value),{...$?{disabled:j.disabled||s.disabled}:{},...s.progressive?{required:!!j.required,min:St(j.min),max:St(j.max),minLength:St(j.minLength),maxLength:St(j.maxLength),pattern:St(j.pattern)}:{},name:b,onChange:rt,onBlur:rt,ref:z=>{if(z){o.registerName.add(b),Ge(b,j),o.registerName.delete(b),w=V(r,b);const B=ee(z.value)&&z.querySelectorAll&&z.querySelectorAll("input,select,textarea")[0]||z,U=No(B),q=w._f.refs||[];if(U?q.find(te=>te===B):B===w._f.ref)return;J(r,b,{_f:{...w._f,...U?{refs:[...q.filter(wa),B,...Array.isArray(V(n,b))?[{}]:[]],ref:{type:B.type,name:b}}:{ref:B}}}),A(b,!1,void 0,B)}else w=V(r,b,{}),w._f&&(w._f.mount=!1),(s.shouldUnregister||j.shouldUnregister)&&!(Rr(o.array,b)&&l.action)&&o.unMount.add(b)}}},ga=()=>s.shouldFocusError&&!s.shouldUseNativeValidation&&At(r,Ce,o.mount),_n=b=>{be(b)&&(h.state.next({disabled:b}),At(r,(j,w)=>{const $=V(r,w);$&&(j.disabled=$._f.disabled||b,Array.isArray($._f.refs)&&$._f.refs.forEach(M=>{M.disabled=$._f.disabled||b}))},0,!1))},ps=(b,j)=>async w=>{let $;w&&(w.preventDefault&&w.preventDefault(),w.persist&&w.persist());let M=ae(i);if(h.state.next({isSubmitting:!0}),s.resolver){const{errors:z,values:B}=await N();L(),a.errors=z,M=ae(B)}else await Z({fields:r,eventType:ze.SUBMIT});if(o.disabled.size)for(const z of o.disabled)re(M,z);if(re(a.errors,Vr),ie(a.errors)){h.state.next({errors:{}});try{await b(M,w)}catch(z){$=z}}else j&&await j({...a.errors},w),ga(),setTimeout(ga);if(h.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:ie(a.errors)&&!$,submitCount:a.submitCount+1,errors:a.errors}),$)throw $},Nn=(b,j={})=>{V(r,b)&&(ee(j.defaultValue)?xe(b,ae(V(n,b))):(xe(b,j.defaultValue),J(n,b,ae(j.defaultValue))),j.keepTouched||re(a.touchedFields,b),j.keepDirty||(re(a.dirtyFields,b),a.isDirty=j.defaultValue?ne(b,ae(V(n,b))):ne()),j.keepError||(re(a.errors,b),y.isValid&&S()),h.state.next({...a}))},xs=(b,j={})=>{const w=b?ae(b):n,$=ae(w),M=ie(b),z=$,B=r;if(j.keepDefaultValues||(n=w),!j.keepValues){if(j.keepDirtyValues){const U=new Set([...o.mount,...Object.keys(Ze(n,i,void 0,B))]);for(const q of Array.from(U)){const te=V(a.dirtyFields,q),ue=V(i,q),$e=V(z,q);te&&!ee(ue)?J(z,q,ue):!te&&!ee($e)&&xe(q,$e)}}else{if(xa&&ee(b))for(const U of o.mount){const q=V(r,U);if(q&&q._f){const te=Array.isArray(q._f.refs)?q._f.refs[0]:q._f.ref;if(ia(te)){const ue=te.closest("form");if(ue){ue.reset();break}}}}if(j.keepFieldsRef)for(const U of o.mount)xe(U,V(z,U));else r={}}if(s.shouldUnregister){if(i=j.keepDefaultValues?ae(n):{},j.keepFieldsRef)for(const U of o.mount)J(i,U,V(z,U))}else i=ae(z);h.array.next({values:{...z}}),h.state.next({name:void 0,type:void 0,values:{...z}})}o={mount:j.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!y.isValid||!!j.keepIsValid||!!j.keepDirtyValues||!s.shouldUnregister&&!ie(z),l.watch=!!s.shouldUnregister,l.keepIsValid=!!j.keepIsValid,l.action=!1,j.keepErrors||(a.errors={}),h.state.next({submitCount:j.keepSubmitCount?a.submitCount:0,isDirty:M?!1:j.keepDirty?a.isDirty:j.keepValues?ne():!!(j.keepDefaultValues&&!ye(b,n)),isSubmitted:j.keepIsSubmitted?a.isSubmitted:!1,dirtyFields:M?{}:j.keepDirtyValues?j.keepDefaultValues&&i?Ze(n,i,void 0,B):a.dirtyFields:j.keepDefaultValues&&b?Ze(n,b,void 0,B):j.keepDirty?a.dirtyFields:{},touchedFields:j.keepTouched?a.touchedFields:{},errors:j.keepErrors?a.errors:{},isSubmitSuccessful:j.keepIsSubmitSuccessful?a.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:n})},fs=(b,j)=>xs(me(b)?b(i):b,{...s.resetOptions,...j}),Sn=(b,j={})=>{const w=V(r,b),$=w&&w._f;if($){const M=$.refs?$.refs[0]:$.ref;M.focus&&setTimeout(()=>{M.focus(),j.shouldSelect&&me(M.select)&&M.select()})}},Cn=b=>{const{name:j,type:w,values:$,...M}=b;a={...a,...M}},hs={control:{register:Ge,unregister:qe,getFieldState:zt,handleSubmit:ps,setError:G,_subscribe:Oe,_runSchema:N,_updateIsValidating:L,_focusError:ga,_getWatch:he,_getDirty:ne,_setValid:S,_setFieldArray:v,_setDisabledField:nt,_setErrors:k,_getFieldArray:Ve,_reset:xs,_resetDefaultValues:()=>me(s.defaultValues)&&s.defaultValues().then(b=>{fs(b,s.resetOptions),h.state.next({isLoading:!1})}),_removeUnmounted:Ne,_disableForm:_n,_subjects:h,_proxyFormState:y,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(b){l=b},get _defaultValues(){return n},get _names(){return o},set _names(b){o=b},get _formState(){return a},get _options(){return s},set _options(b){s={...s,...b},u=Kt(s.mode),m=Kt(s.reValidateMode)}},subscribe:jt,trigger:De,register:Ge,handleSubmit:ps,watch:Q,setValue:xe,setValues:Ke,getValues:ya,reset:fs,resetField:Nn,resetDefaultValues:(b,j={})=>
57{if(n=ae(b),!j.keepDirty){const w=Ze(n,i,void 0,r);a.dirtyFields=w,a.isDirty=!ie(w)}j.keepIsValid||S(),h.state.next({...a,defaultValues:n})},clearErrors:Ut,unregister:qe,setError:G,setFocus:Sn,getFieldState:zt};return{...hs,formControl:hs}}function en(e={}){const s=Y.useRef(void 0),a=Y.useRef(void 0),r=Y.useRef(e.formControl),[n,i]=Y.useState(()=>({...ae(Qr),isLoading:me(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:me(e.defaultValues)?void 0:e.defaultValues}));if(!s.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)s.current={...e.formControl,formState:n},e.defaultValues&&!me(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:o,...c}=$o(e);s.current={...c,formState:n}}const l=s.current.control;return l._options=e,cs(()=>{const o=l._subscribe({formState:l._proxyFormState,callback:()=>i({...l._formState,defaultValues:l._defaultValues}),reRenderRoot:!0});return i(c=>({...c,isReady:!0})),l._formState.isReady=!0,o},[l]),Y.useEffect(()=>l._disableForm(e.disabled),[l,e.disabled]),Y.useEffect(()=>{e.mode&&(l._options.mode=e.mode),e.reValidateMode&&(l._options.reValidateMode=e.reValidateMode)},[l,e.mode,e.reValidateMode]),Y.useEffect(()=>{e.errors&&(l._setErrors(e.errors),l._focusError())},[l,e.errors]),Y.useEffect(()=>{e.shouldUnregister&&l._subjects.state.next({values:l._getWatch()})},[l,e.shouldUnregister]),Y.useEffect(()=>{if(l._proxyFormState.isDirty){const o=l._getDirty();o!==n.isDirty&&l._subjects.state.next({isDirty:o})}},[l,n.isDirty]),Y.useEffect(()=>{var o;e.values&&!ye(e.values,a.current)?(l._reset(e.values,{keepFieldsRef:!0,...l._options.resetOptions}),!((o=l._options.resetOptions)===null||o===void 0)&&o.keepIsValid||l._setValid(),a.current=e.values,i(c=>({...c}))):l._resetDefaultValues()},[l,e.values]),Y.useEffect(()=>{l._state.mount||(l._setValid(),l._state.mount=!0),l._state.watch&&(l._state.watch=!1,l._subjects.state.next({...l._formState})),l._removeUnmounted()}),s.current.formState=Y.useMemo(()=>Br(n,l),[l,n]),s.current}const Os=(e,s,a)=>{if(e&&"reportValidity"in e){const r=V(a,s);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},tn=(e,s)=>{for(const a in s.fields){const r=s.fields[a];r&&r.ref&&"reportValidity"in r.ref?Os(r.ref,a,e):r.refs&&r.refs.forEach(n=>Os(n,a,e))}},Mo=(e,s)=>{s.shouldUseNativeValidation&&tn(e,s);const a={};for(const r in e){const n=V(s.fields,r),i=Object.assign(e[r]||{},{ref:n&&n.ref});if(Ro(s.names||Object.keys(e),r)){const l=Object.assign({},V(a,r));J(l,"root",i),J(a,r,l)}else J(a,r,i)}return a},Ro=(e,s)=>e.some(a=>a.startsWith(s+"."));var Fo=function(e,s){for(var a={};e.length;){var r=e[0],n=r.code,i=r.message,l=r.path.join(".");if(!a[l])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];a[l]={message:o.message,type:o.code}}else a[l]={message:i,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(g){return g.errors.forEach(function(u){return e.push(u)})}),s){var c=a[l].types,d=c&&c[r.code];a[l]=zr(l,s,a,n,d?[].concat(d,r.message):r.message)}e.shift()}return a},an=function(e,s,a){return a===void 0&&(a={}),function(r,n,i){try{return Promise.resolve((function(l,o){try{var c=Promise.resolve(e[a.mode==="sync"?"parse":"parseAsync"](r,s)).then(function(d){return i.shouldUseNativeValidation&&tn({},i),{errors:{},values:a.raw?r:d}})}catch(d){return o(d)}return c&&c.then?c.then(void 0,o):c})(0,function(l){if((function(o){return Array.isArray(o==null?void 0:o.errors)})(l))return{values:{},errors:Mo(Fo(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const Vo=["patient","mother","father","guardian","other"],Io=["phone","email"],Bo=/^\S+@\S+\.\S+$/;function zo(e){return ar({role:Ra(["patient","mother","father","guardian","other"]),channel:Ra(["phone","email"]),value:Re().min(1,e("contactos.errorRequired")).max(120,e("contactos.errorMaxLength",{max:120})),label:Re().max(60,e("contactos.errorMaxLength",{max:60})).nullable().optional(),notes:Re().max(500,e("contactos.errorMaxLength",{max:500})).nullable().optional(),is_primary:ta(),whatsapp_reminders_enabled:ta()}).refine(s=>s.channel!=="email"||Bo.test(s.value),{message:e("contactos.errorEmail"),path:["value"]})}function Uo({open:e,patientId:s,contact:a,defaultChannel:r="phone",isFirstOfChannel:n=!1,onClose:i,onSubmitCreate:l,onSubmitUpdate:o}){const{t:c}=W("pacientes"),d=p.useMemo(()=>zo(c),[c]),g=p.useRef(null);
57we(e),_e(g,e);const u=a!=null,{register:m,handleSubmit:f,formState:{errors:y,isSubmitting:_,isValid:h},reset:T,watch:x,setValue:P}=en({resolver:an(d),mode:"onChange",defaultValues:u?{role:a.role,channel:a.channel,value:a.value,label:a.label??"",notes:a.notes??"",is_primary:a.is_primary,whatsapp_reminders_enabled:a.whatsapp_reminders_enabled??!1}:{role:"patient",channel:r,value:"",label:"",notes:"",is_primary:n,whatsapp_reminders_enabled:!1}});p.useEffect(()=>{e&&T(u?{role:a.role,channel:a.channel,value:a.value,label:a.label??"",notes:a.notes??"",is_primary:a.is_primary,whatsapp_reminders_enabled:a.whatsapp_reminders_enabled??!1}:{role:"patient",channel:r,value:"",label:"",notes:"",is_primary:n,whatsapp_reminders_enabled:!1})},[e,u,a,r,n,T]);const S=x("channel"),L=x("role"),I=async v=>{var A,D;const O=((A=v.label)==null?void 0:A.trim())||null,k=((D=v.notes)==null?void 0:D.trim())||null,E=v.channel==="phone"?v.whatsapp_reminders_enabled:!1;u&&a?await o(a.id,{role:v.role,value:v.value.trim(),label:O,notes:k,is_primary:v.is_primary,whatsapp_reminders_enabled:E}):await l({channel:v.channel,role:v.role,value:v.value.trim(),label:O,notes:k,is_primary:v.is_primary,whatsapp_reminders_enabled:E})};return e?t.jsx("div",{ref:g,role:"dialog","aria-modal":"true","aria-label":c(u?"contactos.modalTitleEdit":"contactos.modalTitleNew"),className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 p-0 lg:px-4",children:t.jsxs("form",{onSubmit:f(I),className:"w-full h-full max-w-none bg-bone rounded-none p-6 space-y-5 overflow-y-auto lg:h-auto lg:max-w-md lg:rounded-md lg:overflow-visible",children:[t.jsx("header",{children:t.jsx("h2",{className:"text-h3 font-sans text-bark",children:c(u?"contactos.modalTitleEdit":"contactos.modalTitleNew")})}),t.jsxs("fieldset",{className:"space-y-2",children:[t.jsx("legend",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:c("contactos.fieldRole")}),t.jsx("div",{className:"flex flex-wrap gap-2",children:Vo.map(v=>t.jsx($s,{name:"role",value:v,checked:L===v,onChange:()=>P("role",v,{shouldValidate:!0}),label:c(pa[v])},v))})]}),t.jsxs("fieldset",{className:"space-y-2",children:[t.jsx("legend",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:c("contactos.fieldChannel")}),t.jsx("div",{className:"flex flex-wrap gap-2",children:Io.map(v=>t.jsx($s,{name:"channel",value:v,checked:S===v,onChange:()=>P("channel",v,{shouldValidate:!0}),label:c(mo[v]),disabled:u},v))})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("label",{className:"text-tiny uppercase tracking-widest text-bark-muted",htmlFor:"contact-value",children:c("contactos.fieldValue")}),t.jsx("input",{id:"contact-value",type:"text",autoComplete:"off",placeholder:c(S==="email"?"contactos.placeholderEmail":"contactos.placeholderPhone"),className:"w-full bg-linen border border-bark/15 rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark/40",...m("value")}),y.value?t.jsx("p",{role:"alert",className:"text-tiny text-clay",children:y.value.message}):null]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("label",{className:"text-tiny uppercase tracking-widest text-bark-muted",htmlFor:"contact-label",children:c("contactos.fieldLabel")}),t.jsx("input",{id:"contact-label",type:"text",autoComplete:"off",placeholder:c("contactos.placeholderL
57abel"),className:"w-full bg-linen border border-bark/15 rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark/40",...m("label")}),y.label?t.jsx("p",{role:"alert",className:"text-tiny text-clay",children:y.label.message}):null]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("label",{className:"text-tiny uppercase tracking-widest text-bark-muted",htmlFor:"contact-notes",children:c("contactos.fieldNotes")}),t.jsx(yr,{id:"contact-notes",rows:2,value:x("notes")??"",onChange:v=>P("notes",v,{shouldDirty:!0}),context:"contact_notes",patientId:s,className:"w-full bg-linen border border-bark/15 rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark/40 resize-none"}),y.notes?t.jsx("p",{role:"alert",className:"text-tiny text-clay",children:y.notes.message}):null]}),t.jsxs("label",{className:"flex items-center gap-2 text-small text-bark",children:[t.jsx("input",{type:"checkbox",...m("is_primary"),className:"rounded"}),c("contactos.fieldPrimary")]}),S==="phone"?t.jsxs("label",{className:"flex items-start gap-3 text-small text-bark",children:[t.jsx("input",{type:"checkbox",...m("whatsapp_reminders_enabled"),className:"mt-1 rounded","aria-describedby":"whatsapp-help"}),t.jsxs("span",{children:[t.jsx("span",{className:"block",children:c("contactos.whatsappReminders")}),t.jsx("span",{id:"whatsapp-help",className:"block text-tiny text-bark-muted mt-1",children:c("contactos.whatsappRemindersHelp")})]})]}):null,t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx("button",{type:"button",onClick:i,className:"h-8 px-4 text-tiny uppercase tracking-widest text-bark-muted hover:text-bark transition-colors",children:c("contactos.ctaCancel")}),t.jsx("button",{type:"submit",disabled:_||!h,className:"px-5 py-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:c("contactos.ctaSave")})]})]})}):null}function $s({name:e,value:s,checked:a,onChange:r,label:n,disabled:i}){const l="h-7 px-3 text-tiny uppercase tracking-widest rounded-full border transition-colors",o=a?`${l} border-terracotta text-terracotta`:`${l} border-bark/20 text-bark-muted hover:text-bark`;return t.jsxs("label",{className:o+(i?" opacity-40 cursor-not-allowed":" cursor-pointer"),children:[t.jsx("input",{type:"radio",name:e,value:s,checked:a,onChange:r,disabled:i,className:"sr-only"}),n]})}const Ms=["phone","email"];function sn({patientId:e,initialContacts:s,onChanged:a}){const{t:r}=W("pacientes"),[n,i]=p.useState(s??[]),[l,o]=p.useState(s==null),[c,d]=p.useState(null),[g,u]=p.useState(!1),[m,f]=p.useState(null),[y,_]=p.useState("phone"),h=p.useCallback(async()=>{o(!0),d(null);try{const E=await Fa(e);i(E)}catch(E){d(K(E,r("contactos.loadError")))}finally{o(!1)}},[e,r]);p.useEffect(()=>{if(s!=null){i(s),o(!1);return}h()},[s,h]);const T=p.useMemo(()=>n.filter(E=>E.channel==="phone"&&E.whatsapp_reminders_enabled).length,[n]),x=p.useMemo(()=>{const E={phone:[],email:[]};for(const A of n)E[A.channel].push(A);for(const A of Ms)E[A].sort((D,C)=>D.is_primary!==C.is_primary?D.is_primary?-1:1:D.role.localeCompare(C.role)||D.created_at.localeCompare(C.created_at));return E},[n]),P=E=>{f(null),_(E),u(!0)},S=E=>{f(E),_(E.channel),u(!0)},L=async E=>{try{const A=await oo(e,E);i(D=>Na(D,A)),F.success(r("contactos.addedToast")),u(!1),a==null||a()}catch(A){F.error(K(A,r("contactos.saveError")))}},I=async(E,A)=>{try{const D=await js(e,E,A);i(C=>Na(C,D)),F.success(r("contactos.updatedToast")),u(!1),a==null||a()}catch(D){F.error(K(D,r("contactos.updateError")))}},v=async E=>{try{const A=await co(e,E.id);i(D=>D.map(C=>C.id===A.id?A:C.channel===A.channel&&C.is_primary?{...C,is_primary:!1}:C)),F.success(r("contactos.primaryUpdatedToast")),a==null||a()}catch(A){F.error(K(A,r("contactos.primaryError")))}},O=async(E,A)=>{i(D=>D.map(C=>C.id===E.id?{...C,whatsapp_reminders_enabled:A}:C));try{const D=await js(e,E.id,{whatsapp_reminders_enabled:A});i(C=>Na(C,D)),a==null||a()}catch(D){i(C=>C.map(N=>N.id===E.id?{...N,whatsapp_reminders_enabled:!A}:N)),F.error(K(D,r("contactos.whatsappToggleError")))}},k=async E=>{if(await fe({title:r("contactos.confirmDeleteTitle"),description:r("contactos.confirmDeleteDescription"),confirmLabel:r("common:acciones.eliminar"),cancelLabel:r("common:acciones.cancelar"),destructive:!0}))try{await uo(e,E.id),i(D=>D.filter(C=>C.id!==E.id)),F.success(r("contactos.deletedToast")),a==null||a()}catch(D){F.error(K(D,r("contactos.deleteError")))}};return t.jsxs("section",{"aria-label":r("contactos.sectionAria"),className:"space-y-6",children:[t.jsxs("div",{className:"border-b border-bark/10 pb-2",children:[t.jsx("p",{className:"text-tiny font-medium uppercase tracking-[0.18em] text-terracotta-700",children:r("contactos.sectionAria")}),t.jsx("p",{className:"text-small text-bark-muted mt-1",children:r("contactos.sectionSubtitle")})]}),l&&n.length===0?t.jsx("p",{className:"text-tiny text-bark-muted",children:r("contactos.loadingContacts")}
57):null,c&&n.length===0?t.jsxs("div",{className:"py-2 space-y-2",children:[t.jsx("p",{className:"text-small text-clay",children:c}),t.jsx("button",{type:"button",onClick:()=>void h(),className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:r("contactos.retry")})]}):t.jsxs(t.Fragment,{children:[c?t.jsx("p",{className:"text-tiny text-clay",children:c}):null,Ms.map(E=>t.jsx(Wo,{channel:E,rows:x[E],onAdd:()=>P(E),onEdit:S,onSetPrimary:v,onDelete:k,onToggleWhatsApp:O},E))]}),T>0?t.jsx("p",{className:"text-tiny text-bark-muted border-t border-bark/10 pt-3",children:T===1?r("contactos.whatsappCostOne"):r("contactos.whatsappCostMany",{count:T})}):null,t.jsx(Uo,{open:g,patientId:e,contact:m,defaultChannel:y,isFirstOfChannel:x[y].length===0&&m==null,onClose:()=>u(!1),onSubmitCreate:L,onSubmitUpdate:I})]})}function Wo({channel:e,rows:s,onAdd:a,onEdit:r,onSetPrimary:n,onDelete:i,onToggleWhatsApp:l}){const{t:o}=W("pacientes"),c=o(e==="phone"?"contactos.emptyPhone":"contactos.emptyEmail"),d=o(e==="phone"?"contactos.addPhone":"contactos.addEmail");return t.jsxs("div",{children:[t.jsxs("header",{className:"flex items-center justify-between border-b border-bark/10 pb-2 mb-1",children:[t.jsx("h3",{className:"text-small text-bark",children:o(po[e])}),t.jsx("button",{type:"button",onClick:a,className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:d})]}),s.length===0?t.jsx("p",{className:"text-small text-bark-muted py-2",children:c}):t.jsx("ul",{children:s.map(g=>t.jsx(fo,{contact:g,onEdit:r,onSetPrimary:n,onDelete:i,onToggleWhatsApp:l},g.id))})]})}function Na(e,s){let a=!1;const r=e.map(n=>n.id===s.id?(a=!0,s):s.is_primary&&n.channel===s.channel&&n.is_primary&&n.id!==s.id?{...n,is_primary:!1}:n);return a||r.push(s),r}function Ho({open:e,patient:s,contacts:a,onContactsChanged:r,onClose:n,onUpdated:i}){const{t:l}=W("pacientes"),o=ui(),c=p.useRef(null);we(e),_e(c,e);const[d,g]=p.useState(!1);Xa(e&&!d,n);function u(x){const P=An(x.address_country)?x.address_country.toUpperCase():null,S=ys(P),L=x.document_type&&S.includes(x.document_type)?x.document_type:null,I=bi(x.gender)?x.gender:null;return{first_name:x.first_name,last_name:x.last_name,preferred_name:x.preferred_name??"",date_of_birth:x.date_of_birth??"",document_type:L,document_number:x.document_number??"",gender:I,address_street:x.address_street??"",address_city:x.address_city??"",address_country:P,health_insurance:x.health_insurance??"",health_insurance_number:x.health_insurance_number??"",educational_institution:x.educational_institution??"",educational_grade:x.educational_grade??"",school_contact:x.school_contact??"",referrer:x.referrer??"",consultation_reason:x.consultation_reason??"",evolution_time:x.evolution_time??"",current_medication:x.current_medication??"",previous_treatments:x.previous_treatments??"",medical_background:x.medical_background??"",family_background:x.family_background??"",treatment_areas:(x.treatment_areas??[]).join(", "),attending_profession:x.attending_profession??null,status:x.status,is_minor:x.is_minor,ai_consent:x.ai_consent}}const m=["active","paused","discharged","archived"],[f,y]=p.useState(()=>u(s));p.useEffect(()=>{y(u(s))},[s]);function _(x){y(P=>{const S=ys(x),L=P.document_type&&S.includes(P.document_type);return{...P,address_country:x,document_type:L?P.document_type:null,address_city:P.address_country!==x?"":P.address_city}})}if(!e)return null;function h(x,P){y(S=>({...S,[x]:P}))}async function T(x){if(x.preventDefault(),!f.first_name.trim()||!f.last_name.trim()){F.error(l("edit.errors.nameRequired"));return}g(!0);try{const P=await jr(s.id,{first_name:f.first_name.trim(),last_name:f.last_name.trim(),preferred_name:f.preferred_name.trim()||null,date_of_birth:f.date_of_birth||null,document_type:f.document_type??null,document_number:f.document_number.trim()||null,gender:f.gender,address_street:f.address_street.trim()||null,address_city:f.address_city.trim()||null,address_country:f.address_country,health_insurance:f.health_insurance.trim()||null,health_insurance_number:f.health_insurance_number.trim()||null,educational_institution:f.educational_institution.trim()||null,educational_grade:f.educational_grade.trim()||null,school_contact:f.school_contact.trim()||null,referrer:f.referrer.trim()||null,consultation_reason:f.consultation_reason.trim()||null,evolution_time:f.evolution_time.trim()||null,current_medication:f.current_medication.trim()||null,previous_treatments:f.previous_treatments.trim()||null,medical_background:f.medical_background.trim()||null,family_background:f.family_background.trim()||null,treatment_areas:Ko(f.treatment_areas),attending_profession:f.attending_profession,status:f.status,is_minor:f.is_minor,ai_consent:f.ai_consent});i(P)}catch(P){F.error(K(P,l("edit.errors.generic")))}finally{g(!1)}}return t.jsx("div",{ref:c,className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 p-0 lg:px-4",role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"bg-bone w-full h-full max-w-none max-h-none overflow-y-auto rounded-none p-6 lg:h-auto lg:max-w-3xl lg:max-h-[90vh] lg:rounded-lg lg:p-8",children:[t.jsxs("header",{className:"mb-8",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb
57-2",children:l("edit.marker")}),t.jsx("h2",{className:"text-h2 font-sans text-bark",children:l("edit.titleTemplate",{firstName:s.first_name,lastName:s.last_name})})]}),t.jsxs("form",{onSubmit:T,className:"space-y-8",children:[t.jsx(Ct,{title:l("edit.sections.personal"),children:t.jsxs(Rs,{children:[t.jsx(ge,{label:l("edit.fields.firstName"),value:f.first_name,onChange:x=>h("first_name",x)}),t.jsx(ge,{label:l("edit.fields.lastName"),value:f.last_name,onChange:x=>h("last_name",x)}),t.jsx(ge,{label:l("edit.fields.preferredName"),value:f.preferred_name,onChange:x=>h("preferred_name",x)}),t.jsx(ge,{label:l("edit.fields.birthDate"),type:"date",yearFirst:!0,max:kr(new Date),value:f.date_of_birth,onChange:x=>h("date_of_birth",x)}),t.jsx(mi,{value:f.document_type,onChange:x=>h("document_type",x),country:f.address_country}),t.jsx(ge,{label:l("edit.fields.documentNumber"),value:f.document_number,onChange:x=>h("document_number",x)}),t.jsx(Pn,{value:f.address_country,onChange:_}),t.jsx(pi,{value:f.address_city,onChange:x=>h("address_city",x),country:f.address_country}),t.jsx("div",{className:"sm:col-span-2",children:t.jsx(xi,{value:f.gender,onChange:x=>h("gender",x)})})]})}),t.jsx(Ct,{title:l("edit.sections.coverage"),children:t.jsxs(Rs,{children:[t.jsx(ge,{label:l("edit.fields.coverage"),value:f.health_insurance,onChange:x=>h("health_insurance",x)}),t.jsx(ge,{label:l("edit.fields.affiliateNumber"),value:f.health_insurance_number,onChange:x=>h("health_insurance_number",x)}),t.jsx(fi,{value:f.educational_institution,onChange:x=>h("educational_institution",x)}),t.jsx(ge,{label:l("edit.fields.gradeOrYear"),value:f.educational_grade,onChange:x=>h("educational_grade",x)}),t.jsx(ge,{label:l("edit.fields.schoolContact"),placeholder:l("edit.fields.schoolContactPlaceholder"),value:f.school_contact,onChange:x=>h("school_contact",x)}),t.jsx(ge,{label:l("edit.fields.referrer"),value:f.referrer,onChange:x=>h("referrer",x)})]})}),t.jsx(Ct,{title:l("edit.sections.contacts"),children:t.jsx(sn,{patientId:s.id,initialContacts:a??[],onChanged:r})}),t.jsxs(Ct,{title:l("edit.sections.treatment"),children:[t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:l("edit.fields.status")}),t.jsx("select",{value:f.status,onChange:x=>h("status",x.target.value),className:"mt-2 w-full h-10 border border-bark rounded-md px-3 bg-transparent text-bark text-body focus:outline-none focus:border-bark/40",children:m.map(x=>t.jsx("option",{value:x,children:l(`status.${x}`)},x))})]}),o.length>=2?t.jsx(hi,{professions:o,value:f.attending_profession,onChange:x=>h("attending_profession",x),label:l("edit.fields.attendingProfession"),hint:l("edit.fields.attendingProfessionHint")}):null,t.jsx(Et,{label:l("edit.fields.consultationReason"),rows:3,value:f.consultation_reason,onChange:x=>h("consultation_reason",x),enableVoice:!0,voicePatientId:s.id}),t.jsx(ge,{label:l("edit.fields.evolutionTime"),value:f.evolution_time,onChange:x=>h("evolution_time",x)}),t.jsx(Et,{label:l("edit.fields.currentMedication"),rows:2,value:f.current_medication,onChange:x=>h("current_medication",x)}),t.jsx(Et,{label:l("edit.fields.previousTreatments"),rows:2,value:f.previous_treatments,onChange:x=>h("previous_treatments",x),enableVoice:!0,voicePatientId:s.id}),t.jsx(Et,{label:l("edit.fields.medicalHistory"),rows:2,value:f.medical_background,onChange:x=>h("medical_background",x),enableVoice:!0,voicePatientId:s.id}),t.jsx(Et,{label:l("edit.fields.familyHistory"),rows:2,value:f.family_background,onChange:x=>h("family_background",x),enableVoice:!0,voicePatientId:s.id}),t.jsx(ge,{label:l("edit.fields.treatmentAreas"),placeholder:l("edit.fields.treatmentAreasPlaceholder"),helper:l("edit.fields.treatmentAreasHelp"),value:f.treatment_areas,onChange:x=>h("treatment_areas",x)})]}),t.jsxs(Ct,{title:l("edit.sections.privacy"),children:[t.jsxs("label",{className:"flex items-center gap-3 mb-3",children:[t.jsx("input",{type:"checkbox",checked:f.is_minor,onChange:x=>h("is_minor",x.target.checked),className:"w-4 h-4"}),t.jsx("span",{className:"text-small text-bark",children:l("edit.minor")})]}),t.jsxs("label",{className:"flex items-start gap-3",children:[t.jsx("input",{type:"checkbox",checked:f.ai_consent,onChange:x=>h("ai_consent",x.target.checked),className:"w-4 h-4 mt-0.5"}),t.jsxs("span",{className:"text-small text-bark",children:[l("edit.consentAi"),t.jsx("span",{className:"block text-tiny text-bark-muted mt-0.5",children:l("edit.consentAiHint")})]})]})]}),t.jsxs("div",{className:"flex gap-3 justify-end pt-4",children:[t.jsx("button",{type:"button",onClick:n,disabled:d,className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-6 py-2.5 hover:bg-bark/5 transition-colors disabled:opacity-50",children:l("edit.cancel")}),t.jsx("button",{type:"submit",disabled:d,className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-6 py-2.5 hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-50",children:l(d?"edit.submitting":"edit.submit")})]})]})]})})}function Ct({title:e,children:s}){return t.jsxs("section",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-3",children:e}),t.jsx("div",{className:"space-y-4",children:s})]})}function Rs({children:e}){return t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4",children:e})}function ge({label:e,value:s,onChange:a,type:r="text",placeholder:n,helper:i,yearFirst:l,max:o}){return t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:e}),r==="date"?t.jsx("div",{className:"mt-2",children:t.jsx(es,{value:s,onChange:a,yearFirst:l,max:o,ariaLabel:e,clearable:!0})}):t.jsx("input",{type:r,value:s,placeholder:n,onChange:c=>a(c.target.value),className:"mt-2 w-full h-10 border border-bark rounded-md px-3 bg-transparent text-bark text-body placeholder:text-bark-muted focus:outline-none focus:border-bark/40"}),i?t.jsx("span",{className:"mt-1 block text-tiny text-bark-muted",children:i}):null]})}function Ko(e){return e.split(/[,;]+/).map(s=>s.trim()).filter(s=>s.length>0)}function Et({label:e,value:s,onChange:a,rows:r=3,enableVoice:n,voicePatientId:i}){return t.jsxs("label",{className:"block",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:e}),n&&t.jsx(Si,{context:"patient_anamnesis",patientId:i,iconSize:12,onTranscribed:l=>{const o=l.trim();if(!o)return;const c=s?`${s.trimEnd()} ${o}`:o;a(c)}})]}),t.jsx("textarea",{value:s,onChange:l=>a(l.target.value),rows:r,className:"mt-2 w-full border border-bark rounded-md px-3 py-2 bg-transparent text-bark text-body focus:outline-none focus:border-bark/40 resize-none"})]})}function rn({current:e,onSelect:s,onClose:a,anchorClassName:r}){const{t:n}=W("sesiones"),i=p.useRef(null);return p.useEffect(()=>{function l(c){i.current&&c.target instanceof Node&&!i.current.contains(c.target)&&a()}function o(c){c.key==="Escape"&&a()}return document.addEventListener("mousedown",l),document.addEventListener("keydown",o),()=>{document.removeEventListener("mousedown",l),document.removeEventListener("keydown",o)}},[a]),t.jsx("div",{ref:i,role:"menu","aria-label":n("statusMenu.aria"),className:`absolute z-20 mt-2 min-w-[220px] rounded-md border border-bark/15 bg-bone py-1 ${r??""}`,children:Ln.map(l=>{const o=l.value===e;return t.jsxs("button",{type:"button",role:"menuitem",onClick:()=>s(l.value),className:`w-full flex items-center justify-between gap-3 px-4 py-2 text-small text-left transition-colors ${o?"text-terracotta":"text-bark hover:bg-bark/5"}`,children:[t.jsx("span",{children:l.label}
57),l.requiresReschedule?t.jsx("span",{"aria-hidden":!0,className:"text-tiny text-bark-muted",children:"→"}):null]},l.value)})})}function qo(e){switch(e){case"completed":return"text-forest";case"cancelled_billable":return"text-clay";case"rescheduled_billable":return"text-terracotta";case"cancelled_free":case"rescheduled_free":default:return"text-bark-muted"}}function Go(e){switch(e){case"paid":return{labelKey:"card.billingPaid",color:"text-forest"};case"pending":return{labelKey:"card.billingPending",color:"text-terracotta"};case"not_billable":default:return{labelKey:"card.billingFree",color:"text-bark-muted"}}}function Yo(e,s){if(!Number.isFinite(e)||e<=0)return"—";try{return e.toLocaleString("es",{style:"currency",currency:s,maximumFractionDigits:0})}catch{return`${e.toFixed(0)} ${s}`}}function Xo({session:e,price:s,currency:a,billingState:r,rescheduledToDate:n,rescheduledFromDate:i,onStatusChange:l,onRegisterPayment:o}){const c=Ot(),{t:d}=W("sesiones"),[g,u]=p.useState(!1),[m,f]=p.useState(!1),y=ua(e.status),_=qo(e.status),h=Go(r),T=d(h.labelKey),x=ft(e.status)?Yo(s,a):"—";function P(){c(`/dashboard/sesion/${e.id}`)}function S(v){u(!1),l(v)}function L(v){f(!1),v==="open"&&P(),v==="status"&&u(!0),v==="payment"&&o()}function I(v){v.target===v.currentTarget&&(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),P())}return t.jsxs("li",{className:"py-4 flex flex-wrap items-center gap-4 relative cursor-pointer hover:bg-bark/[0.02] -mx-2 px-2 rounded transition-colors",role:"button",tabIndex:0,onClick:P,onKeyDown:I,"aria-label":d("card.openAria",{date:de(e.scheduled_start)}),children:[t.jsxs("div",{className:"min-w-[180px]",children:[t.jsx("p",{className:"text-small text-bark",children:de(e.scheduled_start)}),t.jsxs("p",{className:"text-tiny text-bark-muted",children:[Fe(e.scheduled_start)," ·"," ",d("minutes",{count:e.duration_minutes})]}),i?t.jsx("p",{className:"text-tiny text-bark-muted mt-1",children:d("card.rescheduledFrom",{date:de(i)})}):null,n?t.jsx("p",{className:"text-tiny text-bark-muted mt-1",children:d("card.rescheduledTo",{date:de(n)})}):null]}),t.jsxs("div",{className:"relative",onClick:v=>v.stopPropagation(),children:[t.jsx("button",{type:"button",onClick:()=>u(v=>!v),className:`text-tiny uppercase tracking-widest px-3 py-1 border rounded-full transition-colors ${_} border-current/40 hover:bg-current/5`,"aria-haspopup":"menu","aria-expanded":g,children:y}),g?t.jsx(rn,{current:e.status,onSelect:S,onClose:()=>u(!1)}):null]}),t.jsx("div",{className:"flex-1 text-right",children:t.jsx("p",{className:"font-mono text-small text-bark",children:x})}),r==="pending"?t.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),o()},className:`text-tiny uppercase tracking-widest min-w-[110px] text-right ${h.color} hover:underline`,children:T}):t.jsx("span",{className:`text-tiny uppercase tracking-widest min-w-[110px] text-right ${h.color}`,children:T}),t.jsxs("div",{className:"relative",onClick:v=>v.stopPropagation(),children:[t.jsx("button",{type:"button","aria-label":d("card.actionsAria"),"aria-haspopup":"menu","aria-expanded":m,onClick:()=>f(v=>!v),className:"text-bark-muted hover:text-bark p-1",children:t.jsx(ma,{size:16,strokeWidth:1.5})}),m?t.jsxs("div",{role:"menu",className:"absolute right-0 z-20 mt-2 min-w-[200px] rounded-md border border-bark/15 bg-bone py-1",onMouseLeave:()=>f(!1),children:[t.jsx("button",{type:"button",role:"menuitem",onClick:()=>L("open"),className:"w-full text-left px-4 py-2 text-small text-bark hover:bg-bark/5",children:d("card.open")}),t.jsx("button",{type:"button",role:"menuitem",onClick:()=>L("status"),className:"w-full text-left px-4 py-2 text-small text-bark hover:bg-bark/5",children:d("card.changeStatus")}),t.jsx("button",{type:"button",role:"menuitem",onClick:()=>L("payment"),disabled:r!=="pending",className:"w-full text-left px-4 py-2 text-small text-bark hover:bg-bark/5 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent",children:d("card.registerPayment")})]}):null]})]})}function Zo(e){switch(e){case"completed":return"text-forest";case"cancelled_billable":return"text-clay";
57case"rescheduled_billable":return"text-terracotta";case"cancelled_free":case"rescheduled_free":default:return"text-bark-muted"}}function Jo(e){switch(e){case"paid":return{labelKey:"card.billingPaid",color:"text-forest"};case"pending":return{labelKey:"card.billingPending",color:"text-terracotta"};case"not_billable":default:return{labelKey:"card.billingFree",color:"text-bark-muted"}}}function Qo(e,s){if(!Number.isFinite(e)||e<=0)return"—";try{return e.toLocaleString("es",{style:"currency",currency:s,maximumFractionDigits:0})}catch{return`${e.toFixed(0)} ${s}`}}function ec({session:e,price:s,currency:a,billingState:r,rescheduledToDate:n,rescheduledFromDate:i,onStatusChange:l,onRegisterPayment:o}){const c=Ot(),{t:d}=W("sesiones"),[g,u]=p.useState(!1),[m,f]=p.useState(!1),y=ua(e.status),_=Zo(e.status),h=Jo(r),T=d(h.labelKey),x=ft(e.status)?Qo(s,a):"—";function P(){c(`/dashboard/sesion/${e.id}`)}function S(v){u(!1),l(v)}function L(v){f(!1),v==="open"&&P(),v==="status"&&u(!0),v==="payment"&&o()}function I(v){v.target===v.currentTarget&&(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),P())}return t.jsxs("article",{className:"bg-bone border border-bark/10 rounded-md p-5 flex flex-col gap-3 cursor-pointer hover:border-bark/30 transition-colors",role:"button",tabIndex:0,onClick:P,onKeyDown:I,"aria-label":d("card.openAria",{date:de(e.scheduled_start)}),children:[t.jsxs("header",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-body text-bark font-medium",children:de(e.scheduled_start)}),t.jsxs("p",{className:"text-tiny text-bark-muted mt-0.5",children:[Fe(e.scheduled_start)," ·"," ",d("minutes",{count:e.duration_minutes})]})]}),t.jsxs("div",{className:"relative",onClick:v=>v.stopPropagation(),children:[t.jsx("button",{type:"button","aria-label":d("card.actionsAria"),"aria-haspopup":"menu","aria-expanded":m,onClick:v=>{v.stopPropagation(),f(O=>!O)},className:"text-bark-muted hover:text-bark p-1 -mr-1",children:t.jsx(ma,{size:16,strokeWidth:1.5})}),m?t.jsxs("div",{role:"menu",className:"absolute right-0 z-20 mt-1 min-w-[200px] rounded-md border border-bark/15 bg-bone py-1",onMouseLeave:()=>f(!1),children:[t.jsx("button",{type:"button",role:"menuitem",onClick:v=>{v.stopPropagation(),L("open")},className:"w-full text-left px-4 py-2 text-small text-bark hover:bg-bark/5",children:d("card.open")}),t.jsx("button",{type:"button",role:"menuitem",onClick:v=>{v.stopPropagation(),L("status")},className:"w-full text-left px-4 py-2 text-small text-bark hover:bg-bark/5",children:d("card.changeStatus")}),t.jsx("button",{type:"button",role:"menuitem",onClick:v=>{v.stopPropagation(),L("payment")},disabled:r!=="pending",className:"w-full text-left px-4 py-2 text-small text-bark hover:bg-bark/5 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent",children:d("card.registerPayment")})]}):null]})]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsxs("div",{className:"relative",onClick:v=>v.stopPropagation(),children:[t.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),u(O=>!O)},className:`text-tiny uppercase tracking-widest px-3 py-1 border rounded-full transition-colors ${_} border-current/40 hover:bg-current/5`,"aria-haspopup":"menu","aria-expanded":g,children:y}),g?t.jsx(rn,{current:e.status,onSelect:S,onClose:()=>u(!1)}):null]}),r==="pending"?t.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),o()},className:`text-tiny uppercase tracking-widest ${h.color} hover:underline`,children:T}):t.jsx("span",{className:`text-tiny uppercase tracking-widest ${h.color}`,children:T}),t.jsx("span",{className:"ml-auto font-mono text-small text-bark",children:x})]}),i||n?t.jsxs("div",{className:"border-t border-bark/5 pt-2 space-y-0.5",children:[i?t.jsx("p",{className:"text-tiny text-bark-muted",children:d("card.rescheduledFrom",{date:de(i)})}):null,n?t.jsx("p",{className:"text-tiny text-bark-muted",children:d("card.rescheduledTo",{date:de(n)})}):null]}):null]})}function tc({open:e,session:s,billable:a,onClose:r,onConfirm:n}){const{t:i}=W("agenda"),l=p.useRef(null);
57we(e&&s!=null),Xa(e&&s!=null,r),_e(l,e&&s!=null);const[o,c]=p.useState(!1),[d,g]=p.useState(null),[u,m]=p.useState(""),[f,y]=p.useState("");if(p.useEffect(()=>{if(!e||!s)return;g(null);const h=new Date(s.scheduled_start),T=new Date(h);T.setDate(h.getDate()+7),m(T.toISOString().slice(0,10)),y(h.toISOString().slice(11,16))},[e,s]),!e||!s)return null;async function _(h){if(h.preventDefault(),!u||!f){g(i("reschedule.errors.incomplete"));return}const T=`${u}T${f}:00`;c(!0),g(null);try{await n({newDateTime:T})}catch(x){g(K(x,i("reschedule.errors.generic")))}finally{c(!1)}}return t.jsx("div",{ref:l,className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 px-4",role:"dialog","aria-modal":"true","aria-label":i("reschedule.ariaLabel"),children:t.jsxs("div",{className:"bg-bone w-full max-w-md rounded-lg p-8",children:[t.jsxs("header",{className:"mb-6",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb-2",children:i(a?"reschedule.markerBillable":"reschedule.markerFree")}),t.jsx("h2",{className:"text-h2 font-sans text-bark",children:i("reschedule.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-2",children:i("reschedule.description",{date:de(s.scheduled_start),time:Fe(s.scheduled_start)})})]}),t.jsxs("form",{onSubmit:_,className:"space-y-6",children:[t.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:i("reschedule.newDate")}),t.jsx("div",{className:"mt-2",children:t.jsx(es,{value:u,onChange:m,ariaLabel:i("reschedule.newDate")})})]}),t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:i("reschedule.newTime")}),t.jsx("input",{type:"time",value:f,onChange:h=>y(h.target.value),required:!0,className:"mt-2 w-full border border-bark rounded-md px-4 py-2.5 bg-transparent text-bark text-body focus:outline-none focus:border-bark/40"})]})]}),d?t.jsx("p",{className:"text-small text-clay",children:d}):null,t.jsxs("div",{className:"flex gap-3 pt-2",children:[t.jsx("button",{type:"button",onClick:r,disabled:o,className:"flex-1 inline-flex items-center justify-center gap-3 border border-bark text-bark uppercase tracking-widest text-tiny rounded-full px-6 py-3 hover:bg-bark hover:text-linen transition-colors disabled:opacity-50",children:i("reschedule.cancel")}),t.jsx("button",{type:"submit",disabled:o,className:"flex-1 inline-flex items-center justify-center gap-3 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-6 py-3 hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-50",children:i(o?"reschedule.submitting":"reschedule.submit")})]})]})]})})}function ac(e){return e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function qt(e,s){if(!Number.isFinite(e)||e<=0)return"—";try{return e.toLocaleString("es",{style:"currency",currency:s,maximumFractionDigits:0})}catch{return`${Math.round(e)} ${s}`}}function Sa(){return new Date().toISOString().slice(0,10)}function sc(e,s){if(!ft(e.status))return{state:"not_billable",amount:0};const a=s.find(r=>r.session_id===e.id&&r.status==="paid");return a?{state:"paid",amount:Number(a.amount??0)}:{state:"pending",amount:0}}async function rc(e){const{patient:s,profile:a,sessions:r,payments:n,defaultPrice:i,currency:l}=e,{jsPDF:o}=await Dn(async()=>{const{jsPDF:O}=await import("./jspdf.es.min-BurAA85T.js").then(k=>k.j);return{jsPDF:O}},__vite__mapDeps([0,1,2])),c=new o({unit:"pt",format:"a4"}),d=56,g=c.internal.pageSize.getWidth();let u=60;c.setFont("helvetica","normal"),c.setFontSize(9),c.setTextColor(163,85,59),c.text("§ BITÁCORA",d,u),c.setTextColor(31,42,31),c.setFontSize(18),c.setFont("helvetica","italic"),u+=30,c.text("Resumen de sesiones",d,u),c.setFont("helvetica","normal"),c.setFontSize(11),u+=22;const m=`${s.first_name} ${s.last_name}`.trim();c.text(`Paciente · ${m}`,d,u),c.setFontSize(9),c.setTextColor(120,120,120),u+=14;
57const f=(a==null?void 0:a.nombre)??(a==null?void 0:a.email)??"",y=(a==null?void 0:a.email)??"",_=(a==null?void 0:a.matricula)??"",h=[f,_?`Matrícula ${_}`:"",y].filter(Boolean).join(" · ");h&&c.text(h,d,u),u+=12,c.text(`Generado el ${Sa()}`,d,u),u+=18,c.setDrawColor(200,200,200),c.line(d,u,g-d,u),u+=22,c.setTextColor(31,42,31),c.setFontSize(9),c.setFont("helvetica","bold");const T=[{label:"Fecha",x:d},{label:"Duración",x:d+170},{label:"Estado",x:d+230},{label:"Monto",x:d+370},{label:"Cobro",x:d+440}];for(const O of T)c.text(O.label,O.x,u);c.setFont("helvetica","normal"),u+=6,c.line(d,u,g-d,u),u+=14;const x=[...r].sort((O,k)=>O.scheduled_start.localeCompare(k.scheduled_start));let P=0,S=0,L=0;c.setFontSize(10);for(const O of x){u>760&&(c.addPage(),u=60);const k=ft(O.status),E=Pt(O,i),A=sc(O,n);k&&(P+=E),A.state==="paid"&&(S+=A.amount>0?A.amount:E),A.state==="pending"&&(L+=E);const D=`${de(O.scheduled_start)} · ${Fe(O.scheduled_start)}`,C=`${O.duration_minutes} min`,N=ua(O.status),R=k?qt(E,l):"—",X=A.state==="paid"?"Cobrada":A.state==="pending"?"Por cobrar":"No facturable";c.text(D,T[0].x,u),c.text(C,T[1].x,u),c.text(N,T[2].x,u),c.text(R,T[3].x,u),c.text(X,T[4].x,u),u+=18}x.length===0&&(c.setTextColor(120,120,120),c.text("Sin sesiones registradas.",d,u),c.setTextColor(31,42,31),u+=18),u+=12,c.setDrawColor(200,200,200),c.line(d,u,g-d,u),u+=20,c.setFontSize(10),c.setFont("helvetica","bold"),c.text("Total facturado",d,u),c.text("Total cobrado",d+200,u),c.text("Pendiente de cobro",d+380,u),c.setFont("helvetica","normal"),u+=14,c.text(qt(P,l),d,u),c.text(qt(S,l),d+200,u),c.text(qt(L,l),d+380,u),c.setFontSize(8),c.setTextColor(140,140,140),c.text(`Detalle generado el ${Sa()} desde Bitácora. Sin valor fiscal.`,d,c.internal.pageSize.getHeight()-40);const I=c.output("blob"),v=`Sesiones-${ac(m)||"paciente"}-${Sa()}.pdf`;return{blob:I,filename:v}}async function nn(e){const s=await rc(e),a=URL.createObjectURL(s.blob),r=document.createElement("a");return r.href=a,r.download=s.filename,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(a),s}function Fs(e,s){if(!Number.isFinite(e)||e<=0)return`0 ${s}`;try{return e.toLocaleString("es",{style:"currency",currency:s,maximumFractionDigits:0})}catch{return`${e.toFixed(0)} ${s}`}}function ln(e,s){return s.find(a=>a.session_id===e.id&&a.status==="paid")??null}function Gt(e,s){return ft(e.status)?ln(e,s)?"paid":"pending":"not_billable"}function nc({patient:e,sessions:s,payments:a,profile:r,onCreate:n,onChanged:i}){const{t:l}=W("sesiones"),[o,c]=p.useState("all"),[d,g]=at("sesiones","list"),[u,m]=p.useState(null),[f,y]=p.useState(null),_=(r==null?void 0:r.currency)??"USD",h=(r==null?void 0:r.default_session_price)??0,T=p.useMemo(()=>[...s].sort((k,E)=>E.scheduled_start.localeCompare(k.scheduled_start)),[s]),x=p.useMemo(()=>{const k=new Map;for(const E of s)k.set(E.id,E);return k},[s]),P=p.useMemo(()=>{let k=0,E=0;for(const A of s){const D=Gt(A,a),C=Pt(A,h);if(D==="paid"){const N=ln(A,a);k+=Number((N==null?void 0:N.amount)??C)}else D==="pending"&&(E+=C)}return{cobrado:k,porCobrar:E}},[s,a,h]),S=p.useMemo(()=>o==="all"?T:T.filter(k=>{const E=Gt(k,a);return o==="pending"?E==="pending":o==="paid"?E==="paid":!0}),[o,T,a]);async function L(k,E){if(E==="rescheduled_billable"||E==="rescheduled_free"){m({session:k,billable:E==="rescheduled_billable"});return}try{await On(k.id,E),F.success(l("tab.statusUpdated")),await i()}catch{F.error(l("tab.statusError"))}}async function I(k){if(u)try{await $n(u.session.id,{newDateTime:k,billable:u.billable}),F.success(l("tab.rescheduled")),m(null),await i()}catch{F.error(l("tab.statusError"))}}async function v(k,E){try{await Ti({sessionId:k.id,patientId:k.patient_id,amount:E.amount,method:E.method,paidAt:new Date(E.paidAt).toISOString(),currency:_}),F.success(l("paymentRegistered")),y(null),await i()}catch{F.error(l("tab.statusError"))}}function O(){nn({patient:e,profile:r,sessions:s,payments:a,defaultPrice:h,currency:_})}return t.jsxs("div",{children:[t.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-8",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:s.length===1?l("tab.countOne"):l("tab.countMany",{count:s.length})}),t.jsx("p",{className:"text-tiny uppercase tracking-widest text-forest",children:l("tab.paidHeader",{amount:Fs(P.cobrado,_)})}),t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:l("tab.pendingHeader",{amount:Fs(P.porCobrar,_)})})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("button",{type:"button",onClick:O,disabled:s.length===0,title:l("tab.downloadHint"),className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-4 py-2 hover:bg-bark/5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:[t.jsx(as,{size:14,strokeWidth:1.5})," ",l("tab.download")]}),t.jsxs("button",{type:"button",onClick:n,className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors",children:[t.jsx(Lt,{size:14,strokeWidth:1.5})," ",l("tab.new")]})]})]}
57),t.jsxs("nav",{"aria-label":l("tab.filtersAria"),className:"flex flex-wrap items-center gap-2 mb-6",children:[t.jsx(Ca,{active:o==="all",onClick:()=>c("all"),children:l("tab.filterAll")}),t.jsx(Ca,{active:o==="pending",onClick:()=>c("pending"),children:l("tab.filterPending")}),t.jsx(Ca,{active:o==="paid",onClick:()=>c("paid"),children:l("tab.filterPaid")}),s.length>0?t.jsx("div",{className:"ml-auto",children:t.jsx(tt,{value:d,onChange:g,ariaLabel:l("tab.viewAria")})}):null]}),S.length===0?t.jsx("p",{className:"text-small text-bark-muted py-16 text-center",children:s.length===0?l("tab.emptyAll"):l("tab.emptyFiltered")}):d==="grid"?t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:S.map(k=>{var N,R;const E=Gt(k,a),A=Pt(k,h),D=k.rescheduled_to_session_id!=null?((N=x.get(k.rescheduled_to_session_id))==null?void 0:N.scheduled_start)??null:null,C=k.rescheduled_from_session_id!=null?((R=x.get(k.rescheduled_from_session_id))==null?void 0:R.scheduled_start)??null:null;return t.jsx(ec,{session:k,price:A,currency:_,billingState:E,rescheduledToDate:D,rescheduledFromDate:C,onStatusChange:X=>L(k,X),onRegisterPayment:()=>y(k)},k.id)})}):t.jsx("ul",{className:"border-t border-b border-bark/10 divide-y divide-bark/10",children:S.map(k=>{var N,R;const E=Gt(k,a),A=Pt(k,h),D=k.rescheduled_to_session_id!=null?((N=x.get(k.rescheduled_to_session_id))==null?void 0:N.scheduled_start)??null:null,C=k.rescheduled_from_session_id!=null?((R=x.get(k.rescheduled_from_session_id))==null?void 0:R.scheduled_start)??null:null;return t.jsx(Xo,{session:k,price:A,currency:_,billingState:E,rescheduledToDate:D,rescheduledFromDate:C,onStatusChange:X=>L(k,X),onRegisterPayment:()=>y(k)},k.id)})}),t.jsx(tc,{open:u!==null,session:(u==null?void 0:u.session)??null,billable:(u==null?void 0:u.billable)??!1,onClose:()=>m(null),onConfirm:({newDateTime:k})=>I(k)}),t.jsx(Ei,{open:f!==null,session:f,defaultAmount:f?Pt(f,h):0,currency:_,onClose:()=>y(null),onConfirm:k=>{if(f)return v(f,k)}})]})}function Ca({active:e,onClick:s,children:a}){return t.jsx("button",{type:"button",onClick:s,className:`h-8 px-4 text-tiny uppercase tracking-widest rounded-full border transition-colors ${e?"border-terracotta text-terracotta":"border-bark/20 text-bark-muted hover:text-bark"}`,children:a})}function We({title:e,view:s,children:a,footer:r}){return t.jsxs("article",{className:`bg-bone border border-bark/10 rounded-md flex flex-col ${s==="list"?"p-6":"p-5"}`,children:[t.jsx("header",{className:"mb-3",children:t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:["§ · ",e]})}),t.jsx("div",{className:"flex-1 text-small text-bark space-y-3",children:a}),r?t.jsx("footer",{className:"mt-4 pt-3 border-t border-bark/5 flex flex-wrap items-center justify-end gap-3 text-tiny uppercase tracking-widest",children:r}):null]})}function He({label:e="Ver todos",onClick:s}){return t.jsxs("button",{type:"button",onClick:s,className:"inline-flex items-center gap-1 text-terracotta hover:text-bark transition-colors",children:[e," ",t.jsx(vr,{size:12,strokeWidth:1.5})]})}function gt({label:e,onClick:s}){return t.jsx("button",{type:"button",onClick:s,className:"text-bark-muted hover:text-bark transition-colors",children:e})}function Qe(e){if(!e)return"—";const s=new Date(e);return Number.isNaN(s.getTime())?"—":s.toLocaleDateString("es",{day:"2-digit",month:"short"})}function on(e){if(!e)return"—";const s=new Date(e);return Number.isNaN(s.getTime())?"—":s.toLocaleDateString("es",{day:"2-digit",month:"long",year:"numeric"})}function ic(e){if(!e)return null;const s=new Date(e).getTime();return Number.isNaN(s)?null:Math.round((Date.now()-s)/(1e3*60*60*24))}function lc({overview:e,view:s,onNewSession:a,onSeeAll:r,onOpenSession:n}){var g;const{t:i}=W("pacientes"),l=e.upcomingSession,o=e.recentSessions.slice(0,3),c=new Date().toISOString().slice(0,7),d=((g=e.monthlySessionCounts.find(u=>u.month===c))==null?void 0:g.count)??0;return t.jsxs(We,{title:i("tabs.sesiones"),view:s,footer:t.jsxs(t.Fragment,{children:[t.jsx(gt,{label:i("cards.sesiones.newSession"),onClick:a}),t.jsx(He,{label:i("cards.common.seeAll"),onClick:r})]}),children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:i("cards.sesiones.next")}),l?t.jsxs("button",{type:"button",onClick:()=>n(l.id),className:"text-left text-bark hover:text-terracotta transition-colors",children:[on(l.scheduled_start)," ·"," ",Fe(l.scheduled_start)," · ",l.duration_minutes," min"]}):t.jsx("p",{className:"text-bark-muted",children:i("cards.sesiones.noUpcoming")})]}),o.length>0?t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:i("cards.sesiones.recent")}
57),t.jsx("ul",{className:"space-y-1",children:o.map(u=>t.jsxs("li",{className:"flex items-center justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>n(u.id),className:"text-left hover:text-terracotta transition-colors",children:[Qe(u.scheduled_start)," · ",oc(u.status,i)]}),t.jsxs("span",{className:"text-tiny text-bark-muted",children:["#",u.sessionNumber]})]},u.id))})]}):null,t.jsx("p",{className:"text-tiny text-bark-muted",children:i(d===1?"cards.sesiones.thisMonthOne":"cards.sesiones.thisMonthMany",{count:d})})]})}function oc(e,s){switch(e){case"completed":return s("cards.sesiones.statusCompleted");case"cancelled_billable":return s("cards.sesiones.statusCancelledBillable");case"cancelled_free":return s("cards.sesiones.statusCancelled");case"rescheduled_billable":return s("cards.sesiones.statusRescheduledBillable");case"rescheduled_free":return s("cards.sesiones.statusRescheduled");default:return e}}function cc(e){return e?e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim():""}function dc({patientId:e,view:s,onNewNote:a,onSeeAll:r}){const{t:n}=W("pacientes"),[i,l]=p.useState([]),[o,c]=p.useState(!0);p.useEffect(()=>{let m=!1;return pr(e).then(f=>{m||l(f)}).catch(()=>{}).finally(()=>{m||c(!1)}),()=>{m=!0}},[e]);const d=i[0]??null,g=i.slice(1,3),u=(d==null?void 0:d.privacy_level)==="private_e2e";return t.jsx(We,{title:n("tabs.notas"),view:s,footer:t.jsxs(t.Fragment,{children:[t.jsx(gt,{label:n("cards.notas.newNote"),onClick:a}),t.jsx(He,{label:n("cards.common.seeAll"),onClick:r})]}),children:o?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:n("common:estados.cargando")}):d?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:[n("cards.notas.last")," · ",Qe(d.occurred_at)," ",d.kind!=="session"?`· ${pt[d.kind].toLowerCase()}`:""]}),u?t.jsxs("p",{className:"text-bark-muted italic flex items-center gap-1",children:[t.jsx(sa,{size:12,strokeWidth:1.5})," ",n("cards.notas.encrypted")]}):t.jsx("p",{className:"text-bark italic line-clamp-5",style:{fontFamily:"serif"},children:cc(d.plain_content)||n("cards.notas.noContent")})]}),g.length>0?t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:n("cards.notas.previous")}),t.jsx("ul",{className:"flex flex-wrap gap-2",children:g.map(m=>t.jsxs("li",{className:"px-2 py-0.5 rounded-full bg-bark/5 text-tiny text-bark",children:[Qe(m.occurred_at)," · ",pt[m.kind].toLowerCase()]},m.id))})]}):null]}):t.jsx("p",{className:"text-bark-muted",children:n("cards.notas.empty")})})}function Ea(e,s){const a=Number.isFinite(e)?e:0;try{return a.toLocaleString("es",{style:"currency",currency:s,maximumFractionDigits:0})}catch{return`$${a.toLocaleString("es-UY",{maximumFractionDigits:0})}`}}function uc({overview:e,currency:s,view:a,onRegisterPayment:r,onSeeAll:n}){const{t:i}=W("pacientes"),l=e.paymentStatus,o=e.stats.incomeYtd;return t.jsxs(We,{title:i("tabs.pagos"),view:a,footer:t.jsxs(t.Fragment,{children:[t.jsx(gt,{label:i("cards.pagos.registerPayment"),onClick:r}),t.jsx(He,{label:i("cards.common.seeAllMasc"),onClick:n})]}),children:[t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:i("cards.pagos.collectedYtd")}),t.jsx("p",{className:"text-bark font-sans",children:Ea(o,s)})]}),t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:i("cards.pagos.pending")}),t.jsx("p",{className:l.pendingAmount>0?"text-terracotta font-sans":"text-bark-muted font-sans",children:Ea(l.pendingAmount,s)}),l.pendingSessionsCount>0?t.jsx("p",{className:"text-tiny text-bark-muted mt-0.5",children:i(l.pendingSessionsCount===1?"cards.pagos.pendingSessionsOne":"cards.pagos.pendingSessionsMany",{count:l.pendingSessionsCount})}):null]})]}),l.lastPaymentDate?t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:i("cards.pagos.lastPayment")}),t.jsxs("p",{className:"text-bark",children:[Qe(l.lastPaymentDate)," ·"," ",Ea(l.lastPaymentAmount??0,s)]})]}):t.jsx("p",{className:"text-tiny text-bark-muted",children:i("cards.pagos.empty")})]})}function mc({patientId:e,view:s,onNewReport:a,onSeeAll:r,onOpenReport:n}){const{t:i}=W("pacientes"),[l,o]=p.useState([]),[c,d]=p.useState(!0);p.useEffect(()=>{let m=!1;return bt({category:"informes",patient:e,sort:"created_at",dir:"desc"}).then(f=>{m||o(f)}
57).catch(()=>{}).finally(()=>{m||d(!1)}),()=>{m=!0}},[e]);const g=l.filter(m=>m.source==="generated"),u=(g.length>0?g:l).slice(0,3);return t.jsxs(We,{title:i("tabs.informes"),view:s,footer:t.jsxs(t.Fragment,{children:[t.jsx(gt,{label:i("cards.informes.generateNew"),onClick:a}),t.jsx(He,{label:i("cards.common.seeAllMasc"),onClick:r})]}),children:[c?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:i("common:estados.cargando")}):u.length===0?t.jsx("p",{className:"text-bark-muted",children:i("cards.informes.empty")}):t.jsx("ul",{className:"space-y-1",children:u.map(m=>t.jsxs("li",{className:"flex items-center justify-between gap-3",children:[t.jsx("button",{type:"button",onClick:()=>n(m.id),className:"text-left text-bark hover:text-terracotta transition-colors truncate",children:m.title||m.filename||i("cards.informes.untitled")}),t.jsx("span",{className:"text-tiny text-bark-muted whitespace-nowrap",children:Qe(m.created_at)})]},m.id))}),!c&&l.length>u.length?t.jsx("p",{className:"text-tiny text-bark-muted",children:i(l.length===1?"cards.informes.totalOne":"cards.informes.totalMany",{count:l.length})}):null]})}function pc(e,s){if(!e)return s("cards.tareas.dueNone");const a=new Date(`${e}T23:59:59`),r=Math.round((a.getTime()-Date.now())/(1e3*60*60*24));return r===0?s("cards.tareas.dueToday"):r===1?s("cards.tareas.dueTomorrow"):r>0?s("cards.tareas.dueInDays",{count:r}):s(Math.abs(r)===1?"cards.tareas.overdueOne":"cards.tareas.overdueMany",{count:Math.abs(r)})}function xc({patientId:e,view:s,onNewTask:a,onSeeAll:r}){const{t:n}=W("pacientes"),[i,l]=p.useState([]),[o,c]=p.useState(!0);p.useEffect(()=>{let m=!1;return Nr(e).then(f=>{m||l(f)}).catch(()=>{}).finally(()=>{m||c(!1)}),()=>{m=!0}},[e]);const d=i.filter(m=>m.status!=="completed"&&m.status!=="returned"&&m.status!=="cancelled"),g=i.filter(m=>m.status==="completed"||m.status==="returned"),u=d.slice(0,3);return t.jsxs(We,{title:n("tabs.deberes"),view:s,footer:t.jsxs(t.Fragment,{children:[t.jsx(gt,{label:n("cards.tareas.assign"),onClick:a}),t.jsx(He,{label:n("cards.common.seeAllMasc"),onClick:r})]}),children:[o?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:n("common:estados.cargando")}):d.length===0?t.jsx("p",{className:"text-bark-muted",children:i.length===0?n("cards.tareas.emptyNone"):n("cards.tareas.emptyPending")}):t.jsx("ul",{className:"space-y-1",children:u.map(m=>t.jsxs("li",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"text-bark truncate",children:m.title}),t.jsxs("span",{className:"text-tiny text-bark-muted whitespace-nowrap",children:[m.due_date?Qe(m.due_date):Sr[m.frequency]," ","· ",pc(m.due_date,n)]})]},m.id))}),!o&&i.length>0?t.jsx("p",{className:"text-tiny text-bark-muted",children:n("cards.tareas.completedCount",{completed:g.length,total:i.length})}):null]})}function fc({patientId:e,view:s,onNewEvaluation:a,onSeeAll:r}){const{t:n}=W("pacientes"),[i,l]=p.useState([]),[o,c]=p.useState([]),[d,g]=p.useState(!0);p.useEffect(()=>{let h=!1;return Promise.all([Cr(e),Er()]).then(([T,x])=>{h||(l(T),c(x))}).catch(()=>{}).finally(()=>{h||g(!1)}),()=>{h=!0}},[e]);const u=p.useMemo(()=>new Map(o.map(h=>[h.id,h])),[o]),m=i.filter(h=>h.status!=="archived"),f=m[0]??null,y=f?u.get(f.test_id):null,_=p.useMemo(()=>{const h=new Map;for(const x of m){const P=u.get(x.test_id);if(!P)continue;const S=h.get(x.test_id);(!S||S.iso<x.administered_at)&&h.set(x.test_id,{iso:x.administered_at,intervalDays:P.min_readmin_interval_days,code:P.code})}return Array.from(h.values()).map(x=>{const P=new Date(x.iso).getTime()+x.intervalDays*864e5,S=Math.ceil((P-Date.now())/864e5);return{code:x.code,days:S}}).sort((x,P)=>x.days-P.days)[0]??null},[m,u]);return t.jsx(We,{title:n("tabs.evaluaciones"),view:s,footer:t.jsxs(t.Fragment,{children:[t.jsx(gt,{label:n("cards.evaluaciones.apply"),onClick:a}),t.jsx(He,{label:n("cards.common.seeAll"),onClick:r})]}),children:d?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:n("common:estados.cargando")}):f?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:n("cards.evaluaciones.last")}),t.jsxs("p",{className:"text-bark",children:[(y==null?void 0:y.code)??"—"," · ",(y==null?void 0:y.name)??n("cards.evaluaciones.unknownTest")]}),t.jsxs("p",{className:"text-tiny text-bark-muted",children:[n("cards.evaluaciones.appliedOn",{date:Qe(f.administered_at)}),f.scoring_method?` · ${f.scoring_method}`:""]})]}),_?t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:n("cards.evaluaciones.nextReadmin")}),t.jsxs("p",{className:"text-bark",children:[_.code," ·"," ",_.days<=0?n("c
57ards.evaluaciones.availableNow"):n("cards.evaluaciones.inDays",{count:_.days})]})]}):null,t.jsx("p",{className:"text-tiny text-bark-muted",children:n(m.length===1?"cards.evaluaciones.loadedCountOne":"cards.evaluaciones.loadedCountMany",{count:m.length})})]}):t.jsx("p",{className:"text-bark-muted",children:n("cards.evaluaciones.empty")})})}function hc({patient:e,view:s,onGoToPlan:a}){const{t:r}=W("pacientes"),n=e.treatment_areas??[];return t.jsxs(We,{title:r("cards.plan.title"),view:s,footer:t.jsx(He,{label:r("cards.plan.seePlan"),onClick:a}),children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:r("cards.plan.areas")}),n.length===0?t.jsx("p",{className:"text-bark-muted",children:r("cards.plan.emptyAreas")}):t.jsx("ul",{className:"flex flex-wrap gap-2",children:n.slice(0,6).map(i=>t.jsx("li",{className:"px-2 py-0.5 rounded-full bg-bark/5 text-tiny text-bark",children:i},i))})]}),e.consultation_reason?t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-1",children:r("edit.fields.consultationReason")}),t.jsx("p",{className:"text-bark line-clamp-3",children:e.consultation_reason})]}):null]})}function bc(e){if(!e)return null;const s=new Date(e);if(Number.isNaN(s.getTime()))return null;const a=new Date,r=new Date(a.getFullYear(),s.getMonth(),s.getDate());return r<a&&r.setFullYear(a.getFullYear()+1),Math.ceil((r.getTime()-a.getTime())/(1e3*60*60*24))}function yc({patient:e,overview:s,view:a,onGoToAlerts:r}){var y;const{t:n}=W("pacientes"),[i,l]=p.useState([]),[o,c]=p.useState(!1);p.useEffect(()=>{let _=!1;return Fi(e.id).then(h=>{_||l(h)}).catch(()=>{}).finally(()=>{_||c(!0)}),()=>{_=!0}},[e.id]);const d=((y=s.recentSessions[0])==null?void 0:y.scheduled_start)??null,g=ic(d),u=g!==null&&g>30,m=bc(e.date_of_birth),f=m!==null&&m>=0&&m<=7;return t.jsx(We,{title:n("cards.estado.title"),view:a,footer:i.length>0?t.jsx(He,{label:n("cards.estado.seeAlerts"),onClick:r}):null,children:t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Pl,{size:14,strokeWidth:1.5,className:"text-bark-muted"}),g===null?t.jsx("span",{className:"text-bark-muted",children:n("cards.estado.noSessions")}):t.jsx("span",{className:u?"text-terracotta":"text-bark",children:n(g===1?"cards.estado.lastSessionOne":"cards.estado.lastSessionMany",{count:g})})]}),s.upcomingSession?t.jsx("p",{className:"text-tiny text-bark-muted",children:n("cards.estado.next",{date:on(s.upcomingSession.scheduled_start)})}):null,f?t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ol,{size:14,strokeWidth:1.5,className:"text-terracotta"}),t.jsx("span",{className:"text-bark",children:m===0?n("cards.estado.birthdayToday"):n(m===1?"cards.estado.birthdayInDaysOne":"cards.estado.birthdayInDaysMany",{count:m})})]}):null,o&&i.length>0?t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Mn,{size:14,strokeWidth:1.5,className:"text-terracotta"}),t.jsx("span",{className:"text-bark",children:n(i.length===1?"cards.estado.alertsCountOne":"cards.estado.alertsCountMany",{count:i.length})})]}):null]})})}function gc({patient:e,currency:s,refreshKey:a,onNewSession:r,onNewNote:n,onOpenSession:i,onGoToSessionsTab:l,onGoToTareasTab:o,onGoToPagosTab:c,onGoToPlanificacionTab:d,onGoToInformesTab:g,onGoToEvaluacionesTab:u,onGoToAlertasTab:m,onGoToNotasTab:f,onAssignTask:y,onRegisterPayment:_,onNewReport:h,onNewEvaluation:T,onOpenReport:x}){const{t:P}=W("pacientes"),[S,L]=p.useState(null),[I,v]=p.useState(!0),[O,k]=p.useState(null),[E,A]=at(`resumen-paciente:${e.id}`,"grid"),[D,C]=p.useState(0);if(p.useEffect(()=>{let Ce=!1;return v(!0),k(null),oi(e.id).then(De=>{Ce||L(De)}).catch(De=>{Ce||k(K(De,P("resumen.loadError")))}).finally(()=>{Ce||v(!1)}),()=>{Ce=!0}},[e.id,a,D,P]),I&&!S)return t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:P("common:estados.cargando")});if(O||!S)return t.jsxs("div",{className:"space-y-3",children:[t.jsx("p",{className:"text-small text-bark-muted",children:O??P("resumen.loadErrorFull")}),t.jsx("button",{type:"button",onClick:()=>C(Ce=>Ce+1),className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:P("resumen.retry")})]});const N=()=>{},R=h??N,X=T??N,Z=x??N,Ne=g??N,ne=u??N,he=m??N,Ve=d??N,Ie=o??N,Se=f??N,Be=c??l,xe=y??Ie,Ke=_??Be,rt=E==="list"?"grid grid-cols-1 gap-3":"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4";return t.jsxs("section",{className:"space-y-4",children:[t.jsxs("header",{className:"flex items-center justify-between gap-3",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:P("resumen.headerTagline")}),t.jsx(tt,{value:E,onChange:A,ariaLabel:P("resumen.viewToggle")})]}),t.jsxs("div",{className:rt,children:[t.jsx(lc,{overview:S,view:E,onNewSession:r,onSeeAll:l,onOpenSession:i}),t.jsx(dc,{patientId:e.id,view:E,onNewNote:n,onSeeAll:Se}),t.jsx(xc,{patientId:e.id,view:E,onNewTask:xe,onSeeAll:Ie}),t.jsx(uc,{overview:S,currency:s,view:E,onRegisterPayment:Ke,onSeeAll:Be}),t.jsx(mc,{patientId:e.id,view:E,onNewReport:R,onSeeAll:Ne,onOpenReport:Z}),t.jsx(fc,{patientId:e.id,view:E,onNewEvaluation:X,onSeeAll:ne}),t.jsx(hc,{patient:e,view:E,onGoToPlan:Ve}),t.jsx(yc,{patient:e,overview:S,view:E,onGoToAlerts:he})]})]})}const lt={modeBasic:"BÁSICO",modeAdvanced:"AVANZADO",ageMissing:"Ed
57ad sin registrar",attendingProfessionLabel:"Rol de atención",linkedSince:(e,s)=>`Vinculado desde ${e} · ${s} ${s===1?"sesión":"sesiones"}`,ctaNewSession:"+ Nueva sesión",ctaNewNote:"+ Nueva nota",ctaNewPayment:"+ Cobro",ctaEdit:"Editar",ctaDelete:"Eliminar",nextSessionTitle:"Próxima sesión",nextSessionEmpty:"Sin sesiones programadas",nextSessionCta:"+ Programar sesión",seeDetail:"Ver detalle",lastNoteTitle:"Última nota",lastNoteEmpty:"Aún no registraste notas",lastNoteCta:"+ Nueva nota",lastNoteFooter:(e,s)=>`— ${e} · ${s}`,paymentStatusTitle:"Estado de cobro",paymentStatusOnTime:"Al día",paymentStatusPending:e=>`Pendiente ${e}`,paymentStatusPendingSubtitle:e=>`${e} ${e===1?"sesión sin cobrar":"sesiones sin cobrar"}`,paymentStatusLast:(e,s)=>`Último cobro: ${e} · ${s}`,paymentStatusNone:"Sin cobros registrados",tagsAreas:"ÁREAS",tagsReferrer:"DERIVANTE",tagsModality:"MODALIDAD",disclosureOpen:"Ver datos personales y administrativos",disclosureClose:"Ocultar datos personales y administrativos",disclosureEmpty:"Aún no agregaste datos administrativos.",disclosureEmptyCta:"+ Agregar datos",statTotalSessionsLabel:"TOTAL SESIONES",statTotalSessionsFooter:"últ. 6 meses",statAttendanceLabel:"ASISTENCIA",statAttendanceFooter:(e,s)=>`${e} ok · ${s} cancel.`,statAttendanceEmpty:"sin datos",statIncomeLabel:"INGRESOS YTD",statIncomeFooter:e=>`vs ${e} plan`,statNotesPendingLabel:"NOTAS PENDIENTES",statNotesPendingFooterPending:"hace >24h",statNotesPendingFooterClear:"al día",timelineTitle:"ÚLTIMAS SESIONES",timelineSeeAll:"Ver todas las sesiones",sessionStatusCompleted:"Realizada",sessionStatusCancelledBillable:"Cancelada (cobrada)",sessionStatusCancelledFree:"Cancelada (sin cargo)",sessionStatusRescheduledBillable:"Reagendada (cobrada)",sessionStatusRescheduledFree:"Reagendada (sin cargo)",noteOk:"Nota",noteMissing:"Sin nota",paymentOk:"Cobrada",paymentMissing:"Pendiente",paymentNotApplicable:"No facturable",alertsTitle:"ALERTAS"},kc=["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"];function vc(e){const s=new Date(e);return Number.isNaN(s.getTime())?"":`${kc[s.getMonth()]} ${s.getFullYear()}`}function jc({patientId:e}){const{t:s}=W("pacientes"),[a,r]=p.useState(!1),[n,i]=p.useState(null),l=p.useRef(null);p.useEffect(()=>{function c(d){l.current&&!l.current.contains(d.target)&&r(!1)}return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);async function o(c){r(!1),i(c);try{const{filename:d,blob:g}=await Fn(e,c);Vn(d,g)}catch(d){F.error(K(d,s("resumen.exportError")))}finally{i(null)}}return t.jsxs("div",{className:"relative",ref:l,children:[t.jsxs("button",{type:"button",onClick:()=>r(c=>!c),disabled:n!==null,className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-3 py-2 hover:bg-bark/5 transition-colors disabled:opacity-50","aria-haspopup":"menu","aria-expanded":a,children:[t.jsx(as,{size:12,strokeWidth:1.5}),n?s("resumen.generating",{format:n==="pdf"?"PDF":"Word"}):s("resumen.exportFicha"),t.jsx(Rn,{size:12,strokeWidth:1.5})]}),a?t.jsxs("div",{role:"menu",className:"absolute right-0 mt-2 w-48 bg-bone border border-bark/15 rounded-md z-30 py-1",children:[t.jsx("button",{type:"button",role:"menuitem",onClick:()=>void o("pdf"),className:"w-full text-left px-4 py-2 text-small text-bark hover:bg-bark/5",children:s("resumen.downloadPdf")}),t.jsx("button",{type:"button",role:"menuitem",onClick:()=>void o("docx"),className:"w-full text-left px-4 py-2 text-small text-bark hover:bg-bark/5",children:s("resumen.downloadWord")})]}):null]})}function Vs(e,s){return e?e.find(a=>a.channel===s&&a.is_primary)??null:null}function wc({patient:e,totalSessions:s,contacts:a,onNewSession:r,onEdit:n,onDelete:i,onStatusChanged:l}){var T;const{t:o}=W("common"),c=sr(x=>x.patientSort),d=rr(e,c),g=Za(e.date_of_birth),u=vc(e.created_at),m=g!==null?`${g} años`:lt.ageMissing,f=(T=e.consultation_reason)==null?void 0:T.trim(),y=In(e.attending_profession)?o(Bn(e.attending_profession)):null,_=Vs(a,"ph
57one"),h=Vs(a,"email");return t.jsxs("header",{className:"flex flex-wrap items-start gap-6",children:[t.jsx(_c,{patient:e,displayName:d}),t.jsxs("div",{className:"flex-1 min-w-0 lg:min-w-[16rem]",children:[t.jsx("h1",{className:"text-h1 font-sans text-bark",children:d}),t.jsxs("p",{className:"text-small text-bark-muted mt-2",children:[m,f?` · ${f}`:""]}),t.jsx("p",{className:"text-tiny text-bark-muted mt-1",children:lt.linkedSince(u,s)}),y?t.jsxs("p",{className:"text-tiny text-bark-muted mt-1",children:[lt.attendingProfessionLabel," · ",y]}):null,_||h?t.jsxs("ul",{className:"mt-2 space-y-0.5",children:[_?t.jsx(Is,{contact:_}):null,h?t.jsx(Is,{contact:h}):null]}):null]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2 justify-start lg:justify-end",children:[t.jsx(yi,{patient:e,onChanged:l}),t.jsx(Nc,{onClick:r,children:lt.ctaNewSession}),t.jsx(jc,{patientId:e.id}),t.jsx(Bs,{icon:ts,onClick:n,label:lt.ctaEdit}),t.jsx(Bs,{icon:Ja,onClick:i,label:lt.ctaDelete,destructive:!0})]})]})}function Is({contact:e}){const{t:s}=W("pacientes"),a=e.role!=="patient";return t.jsxs("li",{className:"text-tiny text-bark-muted",children:[t.jsx("span",{className:"text-bark",children:e.value}),a?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:" · "}),t.jsx("span",{children:s(pa[e.role])})]}):null]})}function _c({patient:e,displayName:s}){const a=zn(e.photo_url,"profile-photos");return a?t.jsx("img",{src:a,alt:s,className:"w-16 h-16 rounded-full object-cover"}):t.jsxs("div",{className:"w-16 h-16 rounded-full flex items-center justify-center bg-accent text-accent-text font-medium",style:{fontSize:"18px"},"aria-hidden":!0,children:[e.first_name.charAt(0).toUpperCase(),e.last_name.charAt(0).toUpperCase()]})}function Nc({onClick:e,children:s}){return t.jsx("button",{type:"button",onClick:e,className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-4 py-2 hover:bg-terracotta hover:text-linen transition-colors",children:s})}function Bs({icon:e,onClick:s,label:a,destructive:r}){const n="inline-flex items-center gap-2 uppercase tracking-widest text-tiny rounded-full px-3 py-2 border transition-colors",i=r?`${n} border-clay/40 text-clay hover:bg-clay hover:text-linen`:`${n} border-bark/30 text-bark hover:bg-bark/5`;return t.jsxs("button",{type:"button",onClick:s,className:i,"aria-label":a,children:[t.jsx(e,{size:12,strokeWidth:1.5})," ",a]})}const Sc=/^\S+@\S+\.\S+$/,Cc=ar({first_name:Re().trim().min(1,"create.errors.firstName").max(80),last_name:Re().trim().max(80),relationship:Ra(wr),relationship_other:Re().max(80).optional().nullable(),phone:Re().max(40).optional().nullable(),email:Re().max(120).optional().nullable(),notes:Re().max(500).optional().nullable(),is_primary:ta(),whatsapp_reminders_enabled:ta()}).refine(e=>{const s=(e.phone??"").trim(),a=(e.email??"").trim();return s!==""||a!==""},{message:"guardians.errContactRequired",path:["phone"]}).refine(e=>{const s=(e.email??"").trim();return s===""||Sc.test(s)},{message:"create.errors.email",path:["email"]}).refine(e=>e.relationship!=="other"||(e.relationship_other??"").trim()!=="",{message:"guardians.errRelationshipOther",path:["relationship_other"]}).refine(e=>e.relationship==="educational_institution"||e.last_name.trim()!=="",{message:"create.errors.lastName",path:["last_name"]});function Ec({open:e,patientId:s,guardian:a,isFirstGuardian:r=!1,onClose:n,onSubmitCreate:i,onSubmitUpdate:l}){var v,O,k,E,A,D,C;const{t:o}=W("pacientes"),c=p.useRef(null);we(e),_e(c,e);const d=a!=null,{control:g,register:u,handleSubmit:m,formState:{errors:f,isSubmitting:y,isValid:_},reset:h,watch:T}=en({resolver:an(Cc),mode:"onChange",defaultValues:d?{first_name:a.first_name,last_name:a.last_name,relationship:a.relationship,relationship_other:a.relationship_other??"",phone:a.phone??"",email:a.email??"",notes:a.notes??"",is_primary:a.is_primary,whatsapp_reminders_enabled:a.whatsapp_reminders_enabled??!1}:{first_name:"",last_name:"",relationship:"mother",relationship_other:"",phone:"",email:"",notes:"",is_primary:r,whatsapp_reminders_enabled:!1}});p.useEffect(()=>{e&&h(d&&a?{first_name:a.first_name,last_name:a.last_name,relationship:a.relationship,relationship_other:a.relationship_other??"",phone:a.phone??"",email:a.email??"",notes:a.notes??"",is_primary:a.is_primary,whatsapp_reminders_enabled:a.whatsapp_reminders_enabled??!1}:{first_name:"",last_name:"",relationship:"mother",relationship_other:"",phone:"",email:"",n
57otes:"",is_primary:r,whatsapp_reminders_enabled:!1})},[e,d,a,r,h]);const x=T("relationship"),P=x==="educational_institution",S=(T("phone")??"").trim()!=="",L=N=>N?o(N):void 0,I=async N=>{const R={first_name:N.first_name,last_name:N.last_name,relationship:N.relationship,relationship_other:N.relationship==="other"&&(N.relationship_other??"").trim()||null,phone:(N.phone??"").trim()||null,email:(N.email??"").trim()||null,notes:(N.notes??"").trim()||null,is_primary:N.is_primary,whatsapp_reminders_enabled:(N.phone??"").trim()!==""?N.whatsapp_reminders_enabled:!1};d&&a?await l(a.id,R):await i(R)};return e?t.jsx("div",{ref:c,className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 px-4 py-8 overflow-y-auto",role:"dialog","aria-modal":"true","aria-label":o(d?"guardians.modalEditTitle":"guardians.modalNewTitle"),children:t.jsxs("div",{className:"bg-bone w-full max-w-xl rounded-lg p-8 sm:p-10 my-auto",children:[t.jsxs("header",{className:"mb-8 pb-6 border-b border-bark/10",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb-2",children:o(d?"guardians.modalEditTitle":"guardians.modalNewTitle")}),t.jsx("h2",{className:"text-h2 font-sans text-bark",children:o("guardians.modalHeading")}),t.jsx("p",{className:"text-small text-bark-muted mt-2 max-w-md leading-relaxed",children:o("guardians.modalSubtitle")})]}),t.jsxs("form",{onSubmit:m(I),className:"space-y-6",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-5",children:[t.jsx(Xe,{label:o(P?"create.guardians.institutionName":"create.fields.firstName"),required:!0,error:L((v=f.first_name)==null?void 0:v.message),children:t.jsx("input",{type:"text",autoFocus:!0,placeholder:P?o("guardians.institutionNamePlaceholder"):void 0,...u("first_name"),className:Ye})}),t.jsx(Xe,{label:o(P?"create.guardians.contactPerson":"create.fields.lastName"),required:!P,error:L((O=f.last_name)==null?void 0:O.message),children:t.jsx("input",{type:"text",placeholder:P?o("guardians.contactPersonPlaceholder"):void 0,...u("last_name"),className:Ye})})]}),t.jsx(Xe,{label:o(P?"guardians.fieldRoleInstitution":"create.guardians.relationship"),required:!0,error:L((k=f.relationship)==null?void 0:k.message),children:t.jsx("select",{...u("relationship"),className:Ye,children:wr.map(N=>t.jsx("option",{value:N,children:gi[N]},N))})}),x==="other"?t.jsx(Xe,{label:o("guardians.fieldWhich"),required:!0,error:L((E=f.relationship_other)==null?void 0:E.message),children:t.jsx("input",{type:"text",placeholder:o("guardians.relationshipOtherPlaceholder"),...u("relationship_other"),className:Ye})}):null,t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-5",children:[t.jsx(Xe,{label:o("create.guardians.phone"),error:L((A=f.phone)==null?void 0:A.message),children:t.jsx("input",{type:"tel",...u("phone"),className:Ye})}),t.jsx(Xe,{label:o("create.fields.email"),error:L((D=f.email)==null?void 0:D.message),children:t.jsx("input",{type:"email",...u("email"),className:Ye})})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"inline-flex items-center gap-2 text-small text-bark cursor-pointer",children:[t.jsx("input",{type:"checkbox",...u("whatsapp_reminders_enabled"),disabled:!S,className:"accent-terracotta disabled:opacity-40"}),t.jsx("span",{className:S?void 0:"text-bark-muted",children:o("guardians.whatsappReminders")})]}),t.jsx("p",{className:"text-tiny text-bark-muted mt-1 leading-relaxed",children:o(S?"guardians.whatsappRemindersHelp":"guardians.whatsappRemindersNoPhone")})]}),t.jsx(Xe,{label:o("guardians.fieldNotes"),error:L((C=f.notes)==null?void 0:C.message),children:t.jsx(vo,{name:"notes",control:g,render:({field:N})=>t.jsx(yr,{value:N.value??"",onChange:N.onChange,onBlur:N.onBlur,context:"contact_notes",patientId:s,rows:3,className:`${Ye} resize-y`})})}),t.jsxs("label",{className:"inline-flex items-center gap-2 text-small text-bark cursor-pointer",children:[t.jsx("input",{type:"checkbox",...u("is_primary"),className:"accent-terracotta"}),t.jsx("span",{children:o("guardians.markPrimary")})]}),t.jsxs("div",{className:"flex gap-3 pt-6 border-t border-bark/10",children:[t.jsx("button",{type:"button",onClick:n,disabled:y,className:"flex-1 inline-flex items-center justify-center gap-3 border border-bark text-bark uppercase tracking-widest text-tiny rounded-full px-6 py-3 hover:bg-bark hover:text-linen transition-colors disabled:opacity-50",children:o("common:acciones.cancelar")}
57),t.jsxs("button",{type:"submit",disabled:y||!_,className:"flex-1 inline-flex items-center justify-center gap-3 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-6 py-3 hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-50",children:[o(y?"common:estados.guardando":d?"common:acciones.guardar":"guardians.createSubmit"),t.jsx("span",{"aria-hidden":!0,children:"→"})]})]})]})]})}):null}const Ye="mt-2 w-full border border-bark rounded-md px-4 py-2.5 bg-transparent text-bark text-body placeholder:text-bark-muted focus:outline-none focus:border-bark/40";function Xe({label:e,required:s,error:a,children:r}){return t.jsxs("label",{className:"block",children:[t.jsxs("span",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:[e,s?" *":""]}),r,a?t.jsx("span",{className:"block mt-1 text-small text-clay",children:a}):null]})}function Tc(e){return`https://wa.me/${e.replace(/\D/g,"")}`}function Pc({patientId:e,isMinor:s,onChanged:a}){const{t:r}=W("pacientes"),[n,i]=p.useState([]),[l,o]=p.useState(!0),[c,d]=p.useState(null),[g,u]=p.useState(!1),[m,f]=p.useState(null),y=p.useCallback(async()=>{o(!0),d(null);try{const v=await ki(e);i(v)}catch(v){d(K(v,r("guardians.loadError")))}finally{o(!1)}},[e,r]);p.useEffect(()=>{y()},[y]);const _=()=>{f(null),u(!0)},h=v=>{f(v),u(!0)},T=async v=>{try{const O=await wi(e,v);i(k=>Ta(k,O)),F.success(r("contactos.addedToast")),u(!1),a==null||a()}catch(O){F.error(K(O,r("contactos.saveError")))}},x=async(v,O)=>{try{const k=await gs(e,v,O);i(E=>Ta(E,k)),F.success(r("contactos.updatedToast")),u(!1),a==null||a()}catch(k){F.error(K(k,r("contactos.updateError")))}},P=async v=>{try{const O=await _i(e,v.id);i(k=>k.map(E=>E.id===O.id?O:E.is_primary?{...E,is_primary:!1}:E)),F.success(r("contactos.primaryUpdatedToast")),a==null||a()}catch(O){F.error(K(O,r("contactos.primaryError")))}},S=async v=>{if(await fe({title:r("guardians.deleteTitle"),description:r("guardians.deleteBody",{name:Wt(v)}),confirmLabel:r("common:acciones.eliminar"),cancelLabel:r("common:acciones.cancelar"),destructive:!0}))try{await Ni(e,v.id),i(k=>k.filter(E=>E.id!==v.id)),F.success(r("contactos.deletedToast")),a==null||a()}catch(k){F.error(K(k,r("contactos.deleteError")))}},L=async(v,O)=>{i(k=>k.map(E=>E.id===v.id?{...E,whatsapp_reminders_enabled:O}:E));try{const k=await gs(e,v.id,{whatsapp_reminders_enabled:O});i(E=>Ta(E,k)),a==null||a()}catch(k){i(E=>E.map(A=>A.id===v.id?{...A,whatsapp_reminders_enabled:!O}:A)),F.error(K(k,r("contactos.whatsappToggleError")))}},I=async v=>{try{await navigator.clipboard.writeText(v),F.success(r("guardians.emailCopied"))}catch{F.error(r("guardians.emailCopyError"))}};return t.jsxs("section",{"aria-label":r("guardians.sectionAria"),className:"space-y-4",children:[t.jsxs("header",{className:"flex items-center justify-between border-b border-bark/10 pb-2",children:[t.jsx("p",{className:"text-tiny font-medium uppercase tracking-[0.18em] text-terracotta-700",children:r("guardians.sectionTitle")}),t.jsx("button",{type:"button",onClick:_,className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:r("guardians.addContact")})]}),c?t.jsx("p",{className:"text-tiny text-clay",children:c}):null,l&&n.length===0?t.jsx("p",{className:"text-small text-bark-muted py-2",children:r("contactos.loadingContacts")}):null,!l&&n.length===0?t.jsx("p",{className:"text-small text-bark-muted py-2",children:r(s?"guardians.emptyMinor":"guardians.emptyAdult")}):null,n.length>0?t.jsx("ul",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:n.map(v=>{const O=vi(v);return t.jsxs("li",{className:"bg-bone border border-bark/10 rounded-lg p-5 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsx("span",{className:"inline-flex items-center text-tiny uppercase tracking-widest text-terracotta-700 border border-terracotta-700/40 rounded-full px-2.5 py-0.5",children:ji(v)}),v.is_primary?t.jsxs("span",{className:"inline-flex items-center gap-1 text-tiny uppercase tracking-widest text-terracotta flex-shrink-0",title:r("guardians.primaryContactTitle"),children:[t.jsx(ra,{size:12,strokeWidth:1.5,"aria-hidden":!0}),r("create.guardians.primary")]}):null]}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"text-h4 font-sans text-bark truncate",title:Wt(v),children:Wt(v)}),O?t.jsx("p",{className:"text-small text-bark-muted truncate mt-0.5",children:O}):null]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsxs("div",{className:"flex items-center gap-3 text-small text-bark",children:[t.jsx(Yl,{size:14,strokeWidth:1.5,"aria-hidden":!0,
57className:"flex-shrink-0"}),v.phone?t.jsx("span",{className:"truncate",children:v.phone}):t.jsx("span",{className:"text-bark-muted",children:"—"}),v.phone?t.jsxs("span",{className:"ml-auto flex items-center gap-3 flex-shrink-0",children:[t.jsx("a",{href:`tel:${v.phone}`,className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:r("guardians.call")}),t.jsxs("a",{href:Tc(v.phone),target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:[t.jsx(ns,{size:14,strokeWidth:1.5,"aria-hidden":!0}),"WhatsApp"]})]}):null]}),v.phone?t.jsxs("label",{className:"flex items-center gap-2 pl-[26px] cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:v.whatsapp_reminders_enabled,onChange:k=>void L(v,k.target.checked),className:"accent-terracotta","aria-label":r("guardians.whatsappToggleAria",{name:Wt(v)})}),t.jsx("span",{className:`text-tiny uppercase tracking-widest ${v.whatsapp_reminders_enabled?"text-terracotta":"text-bark-muted"}`,children:r("guardians.whatsappToggleLabel")})]}):null,t.jsxs("div",{className:"flex items-center gap-3 text-small text-bark",children:[t.jsx(Tr,{size:14,strokeWidth:1.5,"aria-hidden":!0,className:"flex-shrink-0"}),v.email?t.jsx("span",{className:"truncate",children:v.email}):t.jsx("span",{className:"text-bark-muted",children:"—"}),v.email?t.jsxs("span",{className:"ml-auto flex items-center gap-3 flex-shrink-0",children:[t.jsx("a",{href:`mailto:${v.email}`,className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:r("guardians.write")}),t.jsxs("button",{type:"button",onClick:()=>void I(v.email),className:"inline-flex items-center gap-1 text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:[t.jsx(dt,{size:14,strokeWidth:1.5,"aria-hidden":!0}),r("guardians.copy")]})]}):null]})]}),v.notes?t.jsx("p",{className:"text-small text-bark-muted leading-relaxed",children:v.notes}):null,t.jsxs("div",{className:"flex items-center gap-2 pt-2 mt-auto border-t border-bark/5",children:[v.is_primary?null:t.jsxs("button",{type:"button",onClick:()=>void P(v),title:r("guardians.setPrimaryTitle"),className:"inline-flex items-center gap-1.5 text-tiny uppercase tracking-widest text-bark-muted hover:text-terracotta transition-colors",children:[t.jsx(ra,{size:14,strokeWidth:1.5,"aria-hidden":!0}),r("create.guardians.primary")]}),t.jsxs("button",{type:"button",onClick:()=>h(v),title:r("common:acciones.editar"),className:"ml-auto inline-flex items-center gap-1.5 text-tiny uppercase tracking-widest text-bark-muted hover:text-bark transition-colors",children:[t.jsx(ts,{size:14,strokeWidth:1.5,"aria-hidden":!0}),r("common:acciones.editar")]}),t.jsxs("button",{type:"button",onClick:()=>void S(v),title:r("common:acciones.eliminar"),className:"inline-flex items-center gap-1.5 text-tiny uppercase tracking-widest text-bark-muted hover:text-clay transition-colors",children:[t.jsx(Ja,{size:14,strokeWidth:1.5,"aria-hidden":!0}),r("common:acciones.eliminar")]})]})]},v.id)})}):null,t.jsx(Ec,{open:g,patientId:e,guardian:m,isFirstGuardian:n.length===0&&m==null,onClose:()=>u(!1),onSubmitCreate:T,onSubmitUpdate:x})]})}function Ta(e,s){let a=!1;const r=e.map(n=>n.id===s.id?(a=!0,s):s.is_primary&&n.is_primary&&n.id!==s.id?{...n,is_primary:!1}:n);return a||r.push(s),r}function Ac({patientId:e,initialContacts:s,onChanged:a,isMinor:r=!1}){return t.jsxs("div",{className:"py-2 space-y-12",children:[t.jsx(Pc,{patientId:e,isMinor:r,onChanged:a}),t.jsx(sn,{patientId:e,initialContacts:s,onChanged:a})]})}class st extends Ya{}function kt(){return"https://api.bitacora.ai"}async function vt(){var a;const{data:e}=await ut.auth.getSession(),s=(a=e.session)==null?void 0:a.access_token;if(!s)throw new st("No hay sesión activa.");return{Accept:"application/json",Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}async function cn(e){const s=await vt(),a=await fetch(`${kt()}/patients/${e}/relations`,{method:"GET",headers:s});if(!a.ok)throw new st(await pe(a));return await a.json()}async function Lc(e,s){const a=await vt(),r=await fetch(`${kt()}/patients/${e}/relations`,{method:"POST",headers:a,body:JSON.stringify(s)});if(!r.ok)throw new st(await pe(r));return await r.json()}async function dn(e,s,a){const r=await vt(),n=await fetch(`${kt()}/patients/${e}/relations/${s}`,{method:"PATCH",headers:r,body:JSON.stringify(a)});if(!n.ok)throw new st(await pe(n));return await n.json()}async function un(e,s){const a=await vt(),r=await fetch(`${kt()}/patients/${e}/relations/${s}/regenerate-password`,{method:"POST",headers:a});if(!r.ok)throw new st(await pe(r));return await r.json()}async function mn(e,s){const a=await vt(),r=await fetch(`${kt()}/patients/${e}/relations/${s}`,{method:"DELETE",headers:a});if(!r.ok)throw new st(await pe(r));return await r.json()}async function pn(e,s){const a=await vt(),r=await fetch(`${kt()}/patients/${e}/relations/${s}/reactivate`,{method:"POST",headers:a});if(!r.ok)throw new st(await pe(r));return await r.json()}const xn={tutor:"Padre / madre / tutor",family_contact:"Familiar",shared_colleague:"Colega derivante",institution_contact:"Institución educativa"},et={...xn,teen_patient:"El paciente mismo",adult_patient:"El paciente mismo"},zs={view_patient_resumen:"Ficha del paciente",view_upcoming_sessions:"Próximas sesiones",view_session_history:"Historial de sesiones (solo fechas)",view_tasks:"Deberes asignados al paciente",view_payments:"Pagos pen
57dientes",view_payment_history:"Historial de pagos",view_reports_signed:"Informes firmados",view_reports_drafts:"Informes en borrador",view_treatment_plan:"Plan de tratamiento",view_evaluations_results:"Resultados de evaluaciones",view_materials:"Material del paciente (audios, PDFs, devoluciones)"},H={blockTitle:"COMPARTIDO CON",emptyState:"Todavía no compartiste este paciente. Compártelo con un familiar, tutor o institución para que vean lo que tú decidas.",ctaCreate:"+ Compartir paciente",sectionActive:"Activos",sectionRevoked:"Revocados",lastVisitNever:"Sin ingresos al portal",lastVisitToday:"Ingresó hoy",lastVisitDaysAgo:e=>`Último ingreso hace ${e} ${e===1?"día":"días"}`,revokedOn:e=>`Acceso revocado el ${e}`,menu:{moreActions:"Más acciones",editPermissions:"Editar permisos",regeneratePassword:"Regenerar contraseña",revoke:"Revocar acceso",reactivate:"Reactivar acceso"},confirm:{regenerateTitle:"¿Regenerar contraseña?",regenerateBody:"La contraseña actual queda inválida inmediatamente. Verás la nueva una sola vez.",revokeTitle:"¿Revocar acceso?",revokeBody:"La persona deja de ver este paciente. Puedes reactivar el acceso después."},modal:{title:"Compartir paciente",stepIndicator:(e,s)=>`Paso ${e} de ${s}`,step1Title:"Elegir destinatario",step1Helper:"Estos son los emails ya cargados para el paciente. También puedes agregar uno nuevo.",addInstitutionLabel:"+ Email de institución",addColleagueLabel:"+ Email de colega",step2Title:"Datos del destinatario",fieldEmail:"Email",fieldFullName:"Nombre completo",fieldParentesco:"Parentesco o cargo",fieldPhone:"Teléfono",step3Title:"Qué puede ver",step3Helper:"Estos son los permisos predeterminados según el rol. Puedes ajustarlos antes de crear el acceso.",step4Title:"Crear acceso",step4Helper:"Revisa los datos y crea el acceso al portal.",step4Submit:"Crear acceso",back:"Volver",next:"Continuar",cancel:"Cancelar"},credentials:{titleNew:"Acceso creado",titleExisting:"Acceso agregado",helperNew:"Comparte estas credenciales por un canal seguro. Esta es la única vez que verás la contraseña — si la pierde, regénerala desde el menú.",helperExisting:"Esta persona ya tenía cuenta en el portal. Le diste acceso a este paciente sin tener que mandarle credenciales nuevas.",fieldUrl:"URL",fieldEmail:"Email",fieldPassword:"Contraseña",copyAll:"Copiar todo",copyDone:"Copiado",confirm:"Entendido"},regenerated:{title:"Contraseña regenerada",helper:"Esta es la única vez que verás la nueva contraseña. Pásasela al destinatario por un canal seguro."}};function Us({relation:e,onEditPermissions:s,onRegeneratePassword:a,onRevoke:r,onReactivate:n}){const i=e.revoked_at==null,l=Dc(e),o=Oc(e),c=xn[e.relation_type];return t.jsxs("li",{className:`flex items-start justify-between gap-3 py-3 border-b border-bark/5 ${i?"":"opacity-70"}`,children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("p",{className:"text-small text-bark flex items-center gap-2",children:[t.jsx(ra,{size:12,strokeWidth:1.5,className:i?"text-terracotta":"text-bark-muted","aria-hidden":!0}),t.jsx("span",{className:"font-medium",children:c}),t.jsx("span",{className:"text-bark-muted",children:"·"}),t.jsx("span",{className:"truncate",children:e.related_email})]}),e.full_name?t.jsx("p",{className:"text-tiny text-bark-muted mt-0.5",children:e.full_name}):null,t.jsx("p",{className:"text-tiny text-bark-muted mt-0.5",children:o}),i&&l.length>0?t.jsxs("p",{className:"text-tiny text-bark-muted mt-0.5 truncate",children:["Ve: ",l.join(" · ")]}):null,!i&&e.revoked_at?t.jsx("p",{className:"text-tiny text-bark-muted mt-0.5",children:H.revokedOn(e.revoked_at.slice(0,10))}):null]}),t.jsx($c,{isActive:i,onEditPermissions:()=>s(e),onRegeneratePassword:()=>a(e),onRevoke:()=>r(e),onReactivate:()=>n(e)})]})}function Dc(e){return[["view_patient_resumen","ficha"],["view_upcoming_sessions","sesiones"],["view_tasks","deberes"],["view_payments","pagos"],["view_reports_signed","informes"],["view_treatment_plan","plan"]].filter(([a])=>e.permissions[a]===!0).map(([,a])=>a)}function Oc(e){const s=e.shared_user_last_login_at;if(!s)return H.lastVisitNever;const a=new Date(s),r=Math.floor((Date.now()-a.getTime())/(1e3*60*60*24));return r<=0?H.lastVisitToday:H.lastVisitDaysAgo(r)}function $c({isActive:e,onEditPermissions:s,onRegeneratePassword:a,onRevoke:r,onReactivate:n}){const[i,l]=p.useState(!1),o=p.useRef(null);return p.useEffect(()=>{if(!i)return;const c=d=>{o.current&&!o.current.contains(d.target)&&l(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[i]),t.jsxs("div",{className:"relative",ref:o,children:[t.jsx("button",{type:"button",onClick:()=>l(c=>!c),"aria-label":H.menu.moreActions,className:"text-bark-muted hover:text-bark",children:t.jsx(ma,{size:16,strokeWidth:1.5})}),i?t.jsx("div",{className:"absolute right-0 top-6 z-10 bg-bone border border-bark/10 rounded-xl py-1 min-w-[180px] overflow-hidden",children:e?t.jsxs(t.Fragment,{children:[t.jsx(Yt,{label:H.menu.editPermissions,onClick:()=>{l(!1),s()}}),t.jsx(Yt,{label:H.menu.regeneratePassword,onClick:()=>{l(!1),a()}}),t.jsx(Yt,{label:H.menu.revoke,destructive:!0,onClick:()=>{l(!1),r()}})]}):t.jsx(Yt,{label:H.menu.reactivate,onClick:()=>{l(!1),n()}})}):null]})}function Yt({label:e,onClick:s,destructive:a}){return t.jsx("button",{type:"button",onClick:s,className:`block w-full text-left px-3 py-1.5 text-small ${a?"text-clay":"text-bark"} hover:bg-linen transition-colors`,children:e})}const Mc=["tutor","family_contact","shared_colleague","institution_contact"],Rc=["view_patient_resumen","view_upcoming_sessions","view_session_history","view_tasks","view_payments","view_payment_history","view_reports_signed","view_reports_drafts","view_treatment_plan","view_evaluations_results","view_materials"],Xt={tutor:{view_upcoming_sessions:!0,view_session_history:!1,view_tasks:!0,view_payments:!0,view_payment_history:!0,view_reports_signed:!0,view_reports_drafts:!1,view_treatment_plan:!0,view_evaluations_results:!1,view_patient_resumen:!0,view_materials:!0,view_session_notes:!1},family_contact:{view_upcoming_sessions:!0,view_session_history:!1,view_tasks:!1,view_payments:!1,view_payment_history:!1,view_reports_signed:!0,view_reports_drafts:!1,view_treatment_plan:!1,view_evaluations_results:!1,view_patient_resumen:!0,view_materials:!1,view_session_notes:!1},institution_contact:{view_upcoming_sessions:!1,view_session_history:!1,view_tasks:!1,view_payments:!1,view_payment_history:!1,view_reports_signed:!0,view_reports_drafts:!1,view_treatment_plan:!1,view_evaluations_results:!1,view_patient_resumen:!1,view_materials:!1,view_session_notes:!1},shared_colleague:{view_upcoming_sessions:!0,view_session_history:!0,view_tasks:!0,view_payments:!1,view_payment_history:!1,view_reports_signed:!0,view_reports_drafts:!1,view_treatment_plan:!0,view_evaluations_results:!0,view_patient_resumen:!0,view_materials:!0,view_session_notes:!1},adult_patient:{view_upcoming_sessions:!0,view_session_history:!0,view_tasks:!0,view_payments:!0,view_payment_history:!0,view_reports_signed:!0,view_reports_drafts:!1,view_treatment_plan:!0,view_evaluations_results:!1,view_patient_resumen:!0,view_materials:!0,view_session_notes:!1},teen_patient:{view_upcoming_sessions:!0,view_session_history:!1,view_tasks:!0,view_payments:!1,view_payment_history:!1,view_reports_signed:!0,view_reports_drafts:!1,view_treatment_plan:!0,view_evaluations_results:!1,view_patient_resumen:!0,view_materials:!0,view_session_notes:!1}},fn=14,Fc=18;function Vc(e){return e==null?{eligible:!1,reason:"unknown_age"}:e<fn?{eligible:!1,reason:"below_min_age"}:{eligible:!0,role:e>=Fc?"adult_patient":"teen_patient"}}
57function hn({value:e,onChange:s,disabled:a}){const{t:r}=W("pacientes"),n=i=>{a||s({...e,[i]:!e[i],view_session_notes:!1})};return t.jsx("ul",{className:"space-y-2",role:"group","aria-label":r("compartir.permsGroupLabel"),children:Rc.map(i=>t.jsx("li",{children:t.jsxs("label",{className:"flex items-start gap-3 text-small text-bark cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:e[i],disabled:a,onChange:()=>n(i),"aria-label":zs[i],className:"mt-1 rounded"}),t.jsx("span",{children:zs[i]})]})},i))})}const ot=["recipient","data","permissions","confirm"],Wa=/^\S+@\S+\.\S+$/;function Ic({open:e,patientAge:s,patientContacts:a,onClose:r,onSubmit:n}){const{t:i}=W("pacientes"),l=p.useRef(null);we(e),_e(l,e),Xa(e,r);const[o,c]=p.useState("recipient"),[d,g]=p.useState(null),[u,m]=p.useState(""),[f,y]=p.useState(""),[_,h]=p.useState(""),[T,x]=p.useState(Xt.tutor),[P,S]=p.useState(!1),[L,I]=p.useState(null);p.useEffect(()=>{e&&(c("recipient"),g(null),m(""),y(""),h(""),x(Xt.tutor),I(null))},[e]);const v=p.useMemo(()=>a.filter(C=>C.channel==="email").map(C=>({email:C.value,contactRole:C.role,suggestedRole:Hc(C.role)})),[a]),O=Vc(s);function k(C){g(C),x(Xt[C.role]),c("data")}function E(C){x(Xt[C]),g(N=>N&&{...N,role:C})}async function A(){if(d){S(!0),I(null);try{const C=d.role,N=Ha(C)?"family_contact":C,R=Ha(C)?"self":f.trim()||null;await n({email:d.email.trim().toLowerCase(),relation_type:N,full_name:u.trim()||null,parentesco:R,phone:_.trim()||null,permissions:Kc(T)})}catch(C){I(K(C,i("compartir.createError")))}finally{S(!1)}}}if(!e)return null;const D=d!=null&&Wa.test(d.email);return t.jsx("div",{ref:l,role:"dialog","aria-modal":"true","aria-label":H.modal.title,className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 p-0 lg:px-4",onMouseDown:C=>{C.target===C.currentTarget&&r()},children:t.jsxs("div",{className:"w-full h-full max-w-none bg-bone rounded-none p-6 space-y-5 max-h-none overflow-y-auto lg:h-auto lg:max-w-lg lg:rounded-md lg:max-h-[90vh]",children:[t.jsxs("header",{className:"space-y-1",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:H.modal.stepIndicator(ot.indexOf(o)+1,ot.length)}),t.jsx("h2",{className:"text-h3 font-sans text-bark",children:H.modal.title})]}),o==="recipient"?t.jsx(Bc,{emailSuggestions:v,selfAccess:O,onPick:k}):null,o==="data"&&d?t.jsx(zc,{recipient:d,fullName:u,parentesco:f,phone:_,onEmailChange:C=>g({...d,email:C}),onFullName:m,onParentesco:y,onPhone:h,onSelectRole:E}):null,o==="permissions"&&d?t.jsx(Uc,{role:d.role,permissions:T,onChange:x}):null,o==="confirm"&&d?t.jsx(Wc,{recipient:d,fullName:u,parentesco:f,phone:_,permissions:T,error:L}):null,t.jsxs("footer",{className:"flex items-center justify-between gap-4 pt-2 border-t border-bark/10",children:[t.jsxs("div",{className:"flex items-center gap-4",children:[o!=="recipient"?t.jsx("button",{type:"button",onClick:()=>{const C=ot.indexOf(o);c(ot[C-1])},className:"text-tiny uppercase tracking-widest text-bark-muted hover:text-bark transition-colors",children:H.modal.back}):null,t.jsx("button",{type:"button",onClick:r,className:"text-tiny uppercase tracking-widest text-bark-muted hover:text-bark transition-colors",children:H.modal.cancel})]}),o!=="confirm"?t.jsx("button",{type:"button",disabled:o==="recipient"&&d==null||o==="data"&&!D,onClick:()=>{const C=ot.indexOf(o);c(ot[C+1])},className:"px-5 py-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:H.modal.next}):t.jsx("button",{type:"button",disabled:P,onClick:()=>void A(),className:"px-5 py-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:P?"…":H.modal.step4Submit})]})]})})}function Bc({emailSuggestions:e,selfAccess:s,onPick:a}){const{t:r}=W("pacientes"),[n,i]=p.useState(null);function l(){if(n&&Wa.test(n.email.trim())){const o=n.kind==="institution"?"institution_contact":"shared_colleague";a({email:n.email.trim(),role:o})}}return t.jsxs("section",{className:"space-y-3",children:[t.jsx("h3",{className:"text-tiny uppercase tracking-widest text-terracotta",children:H.modal.step1Title}),t.jsx("p",{className:"text-small text-bark-muted",children:H.modal.step1Helper}),t.jsxs("ul",{className:"space-y-2",children:[e.map(o=>t.jsx("li",{children:t.jsxs("button",{type:"button",onClick:()=>a({email:o.email,role:o.suggestedRole}),className:"w-full text-left px-3 py-2 border border-bark/10 rounded-md hover:border-bark/30 transition-colors",children:[t.jsx("p",{className:"text-small text-bark",children:o.email}),t.jsx("p",{className:"text-tiny text-bark-muted",children:xo(o.contactRole,r)})]})},`${o.email}-${o.contactRole}`)),s.eligible?t.jsx("li",{children:t.jsxs("button",{type:"button",onClick:()=>a({email:"",role:s.role}),className:"w-full text-left px-3 py-2 border border-dashed border-bark/15 rounded-md hover:border-bark/30 transition-colors",children:[t.jsx("p",{className:"text-small text-bark",children:et[s.role]}
57),t.jsx("p",{className:"text-tiny text-bark-muted",children:r("compartir.teenEmailNext")})]})}):t.jsxs("li",{className:"px-3 py-2 border border-dashed border-bark/10 rounded-md",children:[t.jsx("p",{className:"text-small text-bark-muted",children:et.adult_patient}),t.jsx("p",{className:"text-tiny text-bark-muted",children:s.reason==="unknown_age"?r("compartir.selfNeedsBirthdate"):r("compartir.selfBelowMinAge",{age:fn})})]})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx("button",{type:"button",onClick:()=>i({kind:"institution",email:""}),className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:H.modal.addInstitutionLabel}),t.jsx("span",{className:"text-tiny text-bark-muted mx-2",children:"·"}),t.jsx("button",{type:"button",onClick:()=>i({kind:"colleague",email:""}),className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:H.modal.addColleagueLabel})]}),n?t.jsxs("div",{className:"border border-bark/10 rounded-md p-3 space-y-2",children:[t.jsx("input",{type:"email",value:n.email,onChange:o=>i({...n,email:o.target.value}),placeholder:r("compartir.emailPlaceholder"),className:"w-full bg-linen border border-bark/15 rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark/40"}),t.jsx("button",{type:"button",onClick:l,disabled:!Wa.test(n.email.trim()),className:"px-4 py-1.5 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-40",children:H.modal.next})]}):null]})}function zc({recipient:e,fullName:s,parentesco:a,phone:r,onEmailChange:n,onFullName:i,onParentesco:l,onPhone:o,onSelectRole:c}){const{t:d}=W("pacientes"),g=Ha(e.role);return t.jsxs("section",{className:"space-y-3",children:[t.jsx("h3",{className:"text-tiny uppercase tracking-widest text-terracotta",children:H.modal.step2Title}),t.jsxs("fieldset",{className:"space-y-1",children:[t.jsx("legend",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:d("compartir.roleLegend")}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[Mc.map(u=>t.jsx(Ws,{label:et[u],selected:e.role===u,onClick:()=>c(u)},u)),g?t.jsx(Ws,{label:et[e.role],selected:!0,onClick:()=>{}}):null]})]}),t.jsx(Zt,{label:H.modal.fieldEmail,required:!0,children:t.jsx("input",{type:"email",value:e.email,onChange:u=>n(u.target.value),autoComplete:"off",placeholder:d("compartir.emailPlaceholder"),className:"w-full bg-linen border border-bark/15 rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark/40"})}),t.jsx(Zt,{label:H.modal.fieldFullName,children:t.jsx("input",{type:"text",value:s,onChange:u=>i(u.target.value),autoComplete:"off",className:"w-full bg-linen border border-bark/15 rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark/40"})}),g?null:t.jsx(Zt,{label:H.modal.fieldParentesco,children:t.jsx("input",{type:"text",value:a,onChange:u=>l(u.target.value),autoComplete:"off",className:"w-full bg-linen border border-bark/15 rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark/40"})}),t.jsx(Zt,{label:H.modal.fieldPhone,children:t.jsx("input",{type:"tel",value:r,onChange:u=>o(u.target.value),autoComplete:"off",className:"w-full bg-linen border border-bark/15 rounded-md px-3 py-2 text-small text-bark focus:outline-none focus:border-bark/40"})})]})}function Uc({role:e,permissions:s,onChange:a}){return t.jsxs("section",{className:"space-y-3",children:[t.jsx("h3",{className:"text-tiny uppercase tracking-widest text-terracotta",children:H.modal.step3Title}),t.jsxs("p",{className:"text-small text-bark-muted",children:[H.modal.step3Helper," (",et[e],")."]}),t.jsx(hn,{value:s,onChange:a})]})}function Wc({recipient:e,fullName:s,parentesco:a,phone:r,permissions:n,error:i}){const{t:l}=W("pacientes"),o=Object.entries(n).filter(([c,d])=>d===!0&&c!=="view_session_notes").map(([c])=>c);return t.jsxs("section",{className:"space-y-3",children:[t.jsx("h3",{className:"text-tiny uppercase tracking-widest text-terracotta",children:H.modal.step4Title}),t.jsx("p",{className:"text-small text-bark-muted",children:H.modal.step4Helper}),t.jsxs("dl",{className:"space-y-2 text-small text-bark",children:[t.jsx(ct,{term:l("compartir.rowRole"),def:et[e.role]}),t.jsx(ct,{term:H.modal.fieldEmail,def:e.email}),s.trim()?t.jsx(ct,{term:H.modal.fieldFullName,def:s}):null,a.trim()?t.jsx(ct,{term:H.modal.fieldParentesco,def:a}):null,r.trim()?t.jsx(ct,{term:H.modal.fieldPhone,def:r}):null,t.jsx(ct,{term:l("compartir.activePerms"),def:l(o.length===1?"compartir.activePermsValueOne":"compartir.activePermsValueMany",{count:o.length})})]}),i?t.jsx("p",{className:"text-tiny text-clay",children:i}):null]})}function Zt({label:e,children:s,required:a}){return t.jsxs("label",{className:"block space-y-1",children:[t.jsxs("span",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:[e,a?" *":""]}),s]})}function ct({term:e,def:s}){return t.jsxs("div",{className:"flex items-baseline justify-between gap-3 border-b border-bark/5 pb-1",children:[t.jsx("dt",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:e}),t.jsx("dd",{className:"text-small text-bark text-right truncate",children:s})]})}function Ws({label:e,selected:s,onClick:a}){const r="h-7 px-3 text-tiny uppercase tracking-widest rounded-full border transition-colors",n=s?`${r} border-terracotta text-terracotta`:`${r} border-bark/20 text-bark-muted hover:text-bark`;return t.jsx("button",{type:"button",onClick:a,className:n,children:e})}function Ha(e){return e==="teen_patient"||e==="adult_patient"}function Hc(e){switch(e){case"mother":case"father":case"guardian":return"tutor";case"patient":case"other":default:return"family_contact"}}function Kc(e){const{view_session_notes:s,...a}=e;return a}function qc(){return typeof window>"u"?"/portal":`${window.location.origin}/portal`}function Gc({open:e,email:s,password:a,isNewAccount:r,title:n,helperOverride:i,onClose:l}){const o=p.useRef(null);
57we(e),_e(o,e);const[c,d]=p.useState(!1);if(!e)return null;const g=qc(),u=a!=null,m=n??(r?H.credentials.titleNew:H.credentials.titleExisting),f=i??(r?H.credentials.helperNew:H.credentials.helperExisting),y=async()=>{const _=u?`${H.credentials.fieldUrl}: ${g}
58${H.credentials.fieldEmail}: ${s}
59${H.credentials.fieldPassword}: ${a}`:`${H.credentials.fieldUrl}: ${g}
60${H.credentials.fieldEmail}: ${s}`;try{await navigator.clipboard.writeText(_),d(!0),setTimeout(()=>d(!1),2e3)}catch{}};return t.jsx("div",{ref:o,role:"dialog","aria-modal":"true","aria-label":m,className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 px-4",children:t.jsxs("div",{className:"w-full max-w-md bg-bone rounded-md p-6 space-y-5",children:[t.jsxs("header",{children:[t.jsx("h2",{className:"text-h3 font-sans text-bark",children:m}),t.jsx("p",{className:"text-small text-bark-muted mt-2",children:f})]}),t.jsxs("div",{className:"space-y-3",children:[t.jsx(Pa,{label:H.credentials.fieldUrl,value:g}),t.jsx(Pa,{label:H.credentials.fieldEmail,value:s}),u?t.jsx(Pa,{label:H.credentials.fieldPassword,value:a,mono:!0}):null]}),t.jsxs("div",{className:"flex items-center justify-between pt-2",children:[t.jsx("button",{type:"button",onClick:y,className:"inline-flex items-center gap-2 text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:c?t.jsxs(t.Fragment,{children:[t.jsx(Qt,{size:14,strokeWidth:1.5}),H.credentials.copyDone]}):t.jsxs(t.Fragment,{children:[t.jsx(dt,{size:14,strokeWidth:1.5}),H.credentials.copyAll]})}),t.jsx("button",{type:"button",onClick:l,className:"px-5 py-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full hover:bg-terracotta hover:text-linen transition-colors",children:H.credentials.confirm})]})]})})}function Pa({label:e,value:s,mono:a}){return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:e}),t.jsx("p",{className:`text-body ${a?"font-mono":""} text-bark break-words border border-bark/10 bg-linen px-3 py-2 rounded-md`,children:s})]})}function Yc({open:e,relation:s,onClose:a,onSubmit:r}){const{t:n}=W("pacientes"),i=p.useRef(null);we(e&&s!=null),_e(i,e&&s!=null);const[l,o]=p.useState(null),[c,d]=p.useState(!1);return p.useEffect(()=>{s&&o(s.permissions)},[s]),!e||!s||!l?null:t.jsx("div",{ref:i,role:"dialog","aria-modal":"true","aria-label":n("compartir.editPermsTitle"),className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 p-0 lg:px-4",children:t.jsxs("div",{className:"w-full h-full max-w-none bg-bone rounded-none p-6 space-y-4 max-h-none overflow-y-auto lg:h-auto lg:max-w-md lg:rounded-md lg:max-h-[90vh]",children:[t.jsxs("header",{children:[t.jsx("h2",{className:"text-h3 font-sans text-bark",children:n("compartir.editPermsTitle")}),t.jsxs("p",{className:"text-tiny text-bark-muted mt-1",children:[et[s.relation_type]," · ",s.related_email]})]}),t.jsx(hn,{value:l,onChange:o}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-bark/10",children:[t.jsx("button",{type:"button",onClick:a,className:"text-tiny uppercase tracking-widest text-bark-muted hover:text-bark transition-colors",children:H.modal.cancel}),t.jsx("button",{type:"button",disabled:c,onClick:async()=>{d(!0);try{await r({...l,view_session_notes:!1})}finally{d(!1)}},className:"px-5 py-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-40",children:c?"…":n("common:acciones.guardar")})]})]})})}function Xc(){return"https://api.bitacora.ai"}async function Zc(){var a;const{data:e}=await ut.auth.getSession(),s=(a=e.session)==null?void 0:a.access_token;if(!s)throw new Error("No hay sesión activa.");return{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}async function Jc(e){const s=await Zc(),a=await fetch(`${Xc()}/patients/${e}/sharing-matrix`,{headers:s});if(!a.ok){const r=await a.text().catch(()=>"");if(Un(a.status,r))throw new Error(Wn);let n=Hn;try{const i=JSON.parse(r);n=Kn(i,n)}catch{}throw new Error(n)}return await a.json()}function Qc(e){if(!e)return"";const s=new Date(e);return Number.isNaN(s.getTime())?"":s.toLocaleDateString("es",{day:"2-digit",month:"short",year:"numeric"})}function ed(e,s,a=3){if(e.length===0)return s("sharing.notSharedWithAnyone");const r=e.map(n=>{var i;return((i=n.full_name)==null?void 0:i.trim())||n.relation_type});return r.length<=a?r.join(", "):`${r.slice(0,a).join(", ")} ${s("sharing.andMore",{count:r.length-a})}`}function td({data:e,onOpenItems:s}){const{t:a}=W("pacientes"),r=[{key:"reports_signed",label:a("sharing.sectionReportsSigned")},{key:"tasks",label:a("sharing.sectionTasks")},{key:"materials",label:a("sharing.sectionMaterials")}];return t.jsx("div",{className:"space-y-6",children:r.map(({key:n,label:i})=>{const l=e[n];return t.jsxs("section",{children:[t.jsx("header",{className:"flex items-baseline justify-between mb-2",children:t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:[i," · ",l.length]})}),l.length===0?t.jsx("p",{className:"text-small text-bark-muted py-3 border border-dashed border-bark/15 rounded-md px-3",children:a("sharing.emptyCategory")}):t.jsx("ul",{className:"space-y-2",children:l.map(o=>t.jsxs("li",{className:"border border-bark/10 rounded-md p-3 bg-bone",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"text-small text-bark font-sans truncate",children:o.label}),o.date?t.jsx("p",{className:"text-tiny text-bark-muted mt-0.5",children:Qc(o.date)}):null]}),o.shared_with.length>0?t.jsx("button",{type:"button",onClick:()=>s(`${i} · ${o.label}`,o.shared_with.map(c=>{var d;return{id:c.relation_id,label:((d=c.full_name)==null?void 0:d.trim())||c.relation_type,meta:c.relation_type}}),a("sharing.peopleWithAccessDesc")),className:"text-tiny text-terracotta hover:text-bark text-right",children:a(o.shared_with.length===1?"sharing.peopleCountOne":"sharing.peopleCountMany",{count:o.shared_with.length})}):t.jsx("span",{className:"text-tiny text-bark-muted",children:a("sharing.notShared")})]}),o.shared_with.length>0?t.jsx("p",{className:"text-tiny text-bark-muted mt-1 truncate",children:ed(o.shared_with,a)}):null]},o.id))})]},n)})})}function ad({title:e,description:s,items:a,onClose:r}){const{t:n}=W("pacientes"),i=p.useRef(null);return we(!0),_e(i,!0),t.jsx("div",{ref:i,role:"dialog","aria-modal":"true","aria-label":e,className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 px-4",children:t.jsxs("div",{className:"bg-bone w-full max-w-lg max-h-[80vh] overflow-y-auto rounded-lg p-6",children:[t.jsxs("header",{className:"mb-4 flex items-start justify-between",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb
60-1",children:n("sharing.sharedLabel")}),t.jsx("h2",{className:"text-h3 font-sans text-bark",children:e}),s?t.jsx("p",{className:"text-small text-bark-muted mt-1",children:s}):null]}),t.jsx("button",{type:"button",onClick:r,"aria-label":n("common:acciones.cerrar"),className:"text-bark-muted hover:text-bark",children:t.jsx(nr,{size:18,strokeWidth:1.5})})]}),a.length===0?t.jsx("p",{className:"text-small text-bark-muted py-6 text-center",children:n("sharing.emptyItems")}):t.jsx("ul",{className:"space-y-2",children:a.map(l=>t.jsxs("li",{className:"border border-bark/10 rounded-md px-3 py-2 bg-linen text-small text-bark",children:[t.jsx("div",{className:"font-sans",children:l.label}),l.meta?t.jsx("div",{className:"text-tiny text-bark-muted mt-0.5",children:l.meta}):null]},l.id))})]})})}const sd={tutor:"sharing.relationTutor",family_contact:"sharing.relationFamilyContact",shared_colleague:"sharing.relationColleague",institution_contact:"sharing.relationInstitution"};function rd(e){var a;const s=(a=e.related_full_name)==null?void 0:a.trim();return s||e.related_email}function Hs(e){if(!e)return"";const s=new Date(e);return Number.isNaN(s.getTime())?"":s.toLocaleDateString("es",{day:"2-digit",month:"short",year:"numeric"})}function nd({patientId:e}){const{t:s}=W("pacientes"),[a,r]=p.useState(null),[n,i]=p.useState(!0),[l,o]=p.useState(null),[c,d]=p.useState("per_person"),[g,u]=p.useState(null);p.useEffect(()=>{let y=!1;return i(!0),Jc(e).then(_=>{y||r(_)}).catch(_=>
60{if(!y){const h=K(_,s("sharing.detailLoadError"));o(h),F.error(h)}}).finally(()=>{y||i(!1)}),()=>{y=!0}},[e,s]);const m=p.useMemo(()=>(a==null?void 0:a.relations.filter(y=>!y.revoked_at).length)??0,[a]);function f(y,_,h){u({title:y,items:_,description:h})}return n?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("common:estados.cargando")}):l||!a?t.jsx("p",{className:"text-small text-clay",children:l??s("sharing.noData")}):m===0?t.jsx("p",{className:"text-small text-bark-muted",children:s("sharing.emptyPerson")}):t.jsxs("section",{className:"space-y-5",children:[t.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:s("sharing.matrixTitle")}),t.jsx("p",{className:"text-small text-bark-muted mt-1",children:s("sharing.matrixSubtitle")})]}),t.jsxs("div",{className:"inline-flex items-center border border-bark/20 rounded-full p-0.5",children:[t.jsx("button",{type:"button",onClick:()=>d("per_person"),className:`h-7 px-4 text-tiny uppercase tracking-widest rounded-full transition-colors ${c==="per_person"?"bg-bark text-linen":"text-bark-muted hover:text-bark hover:bg-bone"}`,children:s("sharing.viewPerPerson")}),t.jsx("button",{type:"button",onClick:()=>d("per_topic"),className:`h-7 px-4 text-tiny uppercase tracking-widest rounded-full transition-colors ${c==="per_topic"?"bg-bark text-linen":"text-bark-muted hover:text-bark hover:bg-bone"}`,children:s("sharing.viewPerTopic")})]})]}),c==="per_person"?t.jsx("ul",{className:"space-y-4",children:a.relations.map(y=>t.jsx(id,{relation:y,onOpenItems:f},y.relation_id))}):t.jsx(td,{data:a.by_topic,onOpenItems:f}),g?t.jsx(ad,{title:g.title,description:g.description,items:g.items,onClose:()=>u(null)}):null]})}function id({relation:e,onOpenItems:s}){const{t:a}=W("pacientes"),r=!!e.revoked_at,n=rd(e),i=sd[e.relation_type],l=i?a(i):e.relation_type,o=e.shared_items,c=g=>a(g===1?"sharing.visibleCountOne":"sharing.visibleCountMany",{count:g});function d(g,u,m){return t.jsxs("li",{className:"flex items-center justify-between gap-3 py-1.5",children:[t.jsxs("span",{className:"flex items-center gap-2 text-small",children:[u?t.jsx(Qt,{size:14,strokeWidth:1.5,className:"text-forest","aria-label":a("sharing.visibleAria")}):t.jsx("span",{className:"text-bark-muted","aria-hidden":!0,children:"—"}),t.jsx("span",{className:u?"text-bark":"text-bark-muted",children:g})]}),t.jsx("span",{className:"text-tiny text-bark-muted",children:m})]})}return t.jsxs("li",{className:`border rounded-md p-4 ${r?"border-bark/10 bg-bark/3 opacity-70":"border-bark/10 bg-bone"}`,children:[t.jsx("header",{className:"flex items-start justify-between gap-3 mb-3",children:t.jsxs("div",{children:[t.jsxs("h4",{className:"text-body font-sans text-bark",children:[n," · ",l]}),t.jsx("p",{className:"text-tiny text-bark-muted",children:r?a("sharing.accessRevokedOn",{date:Hs(e.revoked_at)}):e.has_portal_access?a("sharing.portalAccessActive"):a("sharing.portalAccessNone")})]})}),t.jsxs("ul",{className:"divide-y divide-bark/5",children:[d(a("sharing.rowUpcomingSessions"),o.upcoming_sessions.visible,o.upcoming_sessions.count>0?c(o.upcoming_sessions.count):null),d(a("sharing.rowSessionHistory"),o.session_history.visible,o.session_history.count>0?c(o.session_history.count):null),t.jsxs("li",{className:"flex items-center justify-between gap-3 py-1.5",children:[t.jsxs("span",{className:"flex items-center gap-2 text-small",children:[o.tasks.visible?t.jsx(Qt,{size:14,strokeWidth:1.5,className:"text-forest"}):t.jsx("span",{className:"text-bark-muted",children:"—"}),t.jsx("span",{className:o.tasks.visible?"text-bark":"text-bark-muted",children:a("sharing.tasksAssigned")})]}),o.tasks.visible&&o.tasks.count>0?t.jsx("button",{type:"button",onClick:()=>s(a("sharing.tasksSeenBy",{name:n}),Array.from({length:o.tasks.count},(g,u)=>({id:`t-${u}`,label:a("sharing.taskItem",{n:u+1})})),a("sharing.tasksDetailNote")),className:"text-tiny text-terracotta hover:text-bark",children:c(o.tasks.count)}):t.jsx("span",{className:"text-tiny text-bark-muted",children:o.tasks.count>0?a(o.tasks.count===1?"sharing.hiddenCountOne":"sharing.hiddenCountMany",{count:o.tasks.count}):"—"})]}),d(a("sharing.rowMaterials"),o.materials.visible,o.materials.count>0?a(o.materials.count===1?"sharing.filesCountOne":"sharing.filesCountMany",{count:o.materials.count}):null),d(a("sharing.rowEvaluations"),o.evaluations.visible,o.evaluations.count>0?a(o.evaluations.count===1?"sharing.loadedCountOne":"sharing.loadedCountMany",{count:o.evaluations.count}):null),d(a("sharing.rowTreatmentPlan"),o.treatment_plan.visible,null),d(a("sharing.rowPatientResumen"),o.patient_resumen.visible,null)]}),o.reports_signed.length>0?t.jsxs("div",{className:"mt-3 pt-3 border-t border-bark/10",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-2",children:a("sharing.sectionReportsSigned")}),t.jsx("ul",{className:"space-y-1",children:o.reports_signed.map(g=>t.jsxs("li",{className:"flex items-center justify-between gap-3 text-small",children:[t.jsxs("span",{className:"flex items-center gap-2",children:[g.individual_toggle&&!r?t.jsx(Qt,{size:14,strokeWidth:1.5,className:"text-forest"}):t.jsx("span",{className:"text-bark-muted",children:"—"}),t.jsx("span",{className:g.individual_toggle?"text-bark":"text-bark-muted",children:g.title})]}),t.jsx("span",{className:"text-tiny text-bark-muted",children:g.status==="signed"&&g.signed_at?a("sharing.signedOn",{date:Hs(g.signed_at)}):g.status})]},g.id))})]}):null]})}const Aa=`${typeof window<"u"?window.location.origin:""}/portal/login`;function ld({patient:e,relation:s,onRelationChange:a}){const{t:r}=W("portal"),[n,i]=p.useState(null),[l,o]=p.useState(!1),c=s.revoked_at!=null;async function d(){if(await fe({title:r("admin.creds.regenConfirmTitle"),description:r("admin.creds.regenConfirmDesc"),confirmLabel:r("admin.creds.regen"),cancelLabel:r("common:acciones.cancelar")}
60)){o(!0);try{const h=await un(e.id,s.id);a(h.relation),i(h.password),F.success(r("admin.creds.regenSuccess"))}catch(h){F.error(K(h,r("admin.creds.regenError")))}finally{o(!1)}}}async function g(){o(!0);try{if(c){const _=await pn(e.id,s.id);a(_),F.success(r("admin.creds.reactivateSuccess"))}else{if(!await fe({title:r("admin.creds.pauseConfirmTitle"),description:r("admin.creds.pauseConfirmDesc"),confirmLabel:r("admin.creds.pause"),cancelLabel:r("common:acciones.cancelar")})){o(!1);return}const h=await mn(e.id,s.id);a(h),F.success(r("admin.creds.pauseSuccess"))}}catch(_){F.error(K(_,r("admin.creds.toggleError")))}finally{o(!1)}}function u(_,h){navigator.clipboard.writeText(_).then(()=>F.success(r("admin.creds.copiedSuffix",{label:h}))).catch(()=>F.error(r("admin.creds.copyError")))}const m=n?r("admin.creds.shareMessage",{url:Aa,email:s.related_email,password:n}):"",f=n?`mailto:${encodeURIComponent(s.related_email)}?subject=${encodeURIComponent(r("admin.creds.shareSubject"))}&body=${encodeURIComponent(m)}`:"",y=n&&e.phone?`https://wa.me/${e.phone.replace(/[^0-9]/g,"")}?text=${encodeURIComponent(m)}`:"";return t.jsxs("section",{"aria-label":r("admin.creds.sectionAria"),className:"space-y-5",children:[t.jsxs("header",{className:"flex items-center justify-between gap-4",children:[t.jsxs("div",{children:[t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:["§ · ",r("admin.creds.eyebrow")]}),t.jsx("h3",{className:"text-h3 font-sans text-bark mt-1",children:r("admin.creds.heading")})]}),t.jsx("button",{type:"button",disabled:l,onClick:()=>void g(),className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-4 py-2 hover:border-bark transition-colors disabled:opacity-40",children:c?t.jsxs(t.Fragment,{children:[t.jsx(le,{as:Bi,size:14})," ",r("admin.creds.reactivate")]}):t.jsxs(t.Fragment,{children:[t.jsx(le,{as:ql,size:14})," ",r("admin.creds.pause")]})})]}),t.jsxs("dl",{className:"space-y-3",children:[t.jsx(La,{label:r("admin.creds.rowStatus"),children:t.jsxs("span",{className:`inline-flex items-center gap-2 text-tiny uppercase tracking-widest ${c?"text-bark-muted":"text-bark"}`,children:[t.jsx("span",{"aria-hidden":"true",className:`h-1.5 w-1.5 rounded-full ${c?"bg-bark-muted":"bg-forest"}`}),r(c?"admin.creds.statusPaused":"admin.creds.statusActive")]})}),t.jsx(La,{label:r("admin.creds.rowEmail"),children:t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-small text-bark font-mono",children:s.related_email}),t.jsxs("button",{type:"button",onClick:()=>u(s.related_email,r("admin.creds.copyLabelEmail")),className:"text-tiny uppercase tracking-widest text-bark-muted hover:text-bark transition-colors",children:[t.jsx(le,{as:dt,size:12,className:"inline mr-1"}),r("admin.creds.copy")]})]})}),t.jsx(La,{label:r("admin.creds.rowPortalUrl"),children:t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-small text-bark font-mono break-all",children:Aa}),t.jsxs("button",{type:"button",onClick:()=>u(Aa,r("admin.creds.copyLabelPortalLink")),className:"text-tiny uppercase tracking-widest text-bark-muted hover:text-bark transition-colors",children:[t.jsx(le,{as:dt,size:12,className:"inline mr-1"}),r("admin.creds.copy")]})]})})]}),t.jsxs("div",{className:"border-t border-bark/10 pt-5 space-y-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:r("admin.creds.passwordLabel")}),t.jsx("p",{className:"text-small text-bark-muted leading-relaxed max-w-md mt-1",children:r("admin.creds.passwordHelper")})]}),t.jsxs("button",{type:"button",disabled:l||c,onClick:()=>void d(),className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:[t.jsx(le,{as:Wl,size:14})," ",r("admin.creds.regen")]})]}),n?t.jsxs("div",{className:"border border-terracotta/30 rounded-md p-5 space-y-4 bg-bone",children:[t.jsxs("div",{className:"flex items-center justify-between gap-4",children:[t.jsx("p",{className:"text-h3 font-mono text-bark tracking-wider break-all",children:n}),t.jsxs("button",{type:"button",onClick:()=>u(n,r("admin.creds.passwordLabel")),className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-4 py-2 hover:border-bark transition-colors",children:[t.jsx(le,{as:dt,size:14})," ",r("admin.creds.copy")]})]}),t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:r("admin.creds.shareNow")}),t.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[t.jsxs("a",{href:f,className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-4 py-2 hover:border-bark transition-colors",children:[t.jsx(le,{as:Tr,size:14})," ",r("admin.creds.sendEmail")]}),y?t.jsxs("a",{href:y,target:"_blank",rel:"noreferrer noopener",className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-4 py-2 hover:border-bark transition-colors",children:[t.jsx(le,{as:ns,size:14})," ",r("admin.creds.sendWhatsapp")]}):t.jsx("span",{className:"text-tiny text-bark-muted",children:r("admin.creds.noPhone")})]})]}):null]})]})}function La({label:e,children:s}){return t.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-4 gap-y-1",children:[t.jsx("dt",{className:"text-tiny uppercase tracking-widest text-bark-muted min-w-[8rem]",children:e}),t.jsx("dd",{children:s})]})}function od({patientId:e,relation:s,onRelationChange:a}){const{t:r}=W("portal"),[n,i]=p.useState(null),l=[{key:"view_upcoming_sessions",label:r("admin.visibility.sessionsLabel"),helper:r("admin.visibility.sessionsHelper")},{key:"view_tasks",label:r("admin.visibility.tasksLabel"),helper:r("admin.visibility.tasksHelper")},{key:"view_payments",label:r("admin.visibility.paymentsLabel"),helper:r("admin.visibility.paymentsHelper")},{key:"view_reports_signed",label:r("admin.visibility.reportsLabel"),helper:r("admin.visibility.reportsHelper")},{key:"view_treatment_plan",label:r("admin.visibility.planLabel"),helper:r("admin.visibility.planHelper")},{key:"view_materials",label:r("admin.visibility.materialsLabel"),helper:r("admin.visibility.materialsHelper")}];async function o(c){i(c);const d=!s.permissions[c],g={...s,permissions:{...s.permissions,[c]:d}};a(g);try{const u=cd({...s.permissions,[c]:d}),m=await dn(e,s.id,{permissions:u});a(m)}catch(u){a(s),F.error(K(u,r("admin.visibility.updateError")))}finally{i(null)}}return t.jsxs("section",{"aria-label":r("admin.visibility.sectionAria"),className:"space-y-5",children:[t.jsxs("header",{children:[t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:["§ · ",r("admin.visibility.eyebrow")]}),t.jsx("h3",{className:"text-h3 font-sans text-bark mt-1",children:r("admin.visibility.heading")}),t.jsx("p",{className:"text-small text-bark-muted mt-2 max-w-xl leading-relaxed",children:r("admin.visibility.notesNote")})]}),t.jsx("ul",{className:"divide-y divide-bark/10 border-y border-bark/10",children:l.map(c=>{const d=!!s.permissions[c.key],g=n===c.key;return t.jsxs("li",{className:"flex items-start justify-between gap-6 py-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"text-small text-bark",children:c.label}),t.jsx("p",{className:"text-tiny text-bark-muted leading-relaxed mt-1",children:c.helper})]}),t.jsx("button",{type:"button",role:"switch","aria-checked":d,"aria-label":r("admin.visibility.toggleAria",{label:c.label,status:r(d?"admin.visibility.visible":"admin.visibility.hidden")}),disabled:g,onClick:()=>void o(c.key),className:`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full border transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-terracotta disabled:opacity-50 ${d?"bg-forest border-forest":"bg-transparent border-bark/30"}`,children:t.jsx("span",{"aria-hidden":"true",className:`inline-block h-4 w-4 roun
60ded-full bg-bone transition-transform ${d?"translate-x-6":"translate-x-1"}`})})]},c.key)})})]})}function cd(e){const{view_session_notes:s,...a}=e;return a}const dd=2048,ud=.82,md=new Set(["image/png","image/jpeg","image/webp"]);async function pd(e){var r;const s={blob:e,filename:e.name,changed:!1};if(!md.has(e.type)||typeof createImageBitmap!="function"||typeof document>"u")return s;let a=null;try{a=await createImageBitmap(e,{imageOrientation:"from-image"});const{width:n,height:i}=a;if(!n||!i)return s;const l=Math.min(1,dd/Math.max(n,i)),o=Math.max(1,Math.round(n*l)),c=Math.max(1,Math.round(i*l)),d=document.createElement("canvas");d.width=o,d.height=c;const g=d.getContext("2d");if(!g)return s;g.drawImage(a,0,0,o,c);const u=await xd(d,"image/webp",ud);if(!u||u.size===0||u.size>=e.size)return s;const m=u.type||"image/webp";return{blob:u,filename:hd(e.name,fd(m)),changed:!0}}catch{return s}finally{(r=a==null?void 0:a.close)==null||r.call(a)}}function xd(e,s,a){return new Promise(r=>{if(typeof e.toBlob!="function"){r(null);return}e.toBlob(n=>r(n),s,a)})}function fd(e){return e==="image/png"?"png":e==="image/jpeg"?"jpg":"webp"}function hd(e,s){return`${e.replace(/\.[a-z0-9]+$/i,"")}.${s}`}class Je extends Ya{}function Dt(){return"https://api.bitacora.ai"}async function ha(){var a;const{data:e}=await ut.auth.getSession(),s=(a=e.session)==null?void 0:a.access_token;if(!s)throw new Je("No hay sesión activa.");return{Accept:"application/json",Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}async function bd(e){const s=await ha(),a=await fetch(`${Dt()}/patients/${e}/portal-admin/materials`,{method:"GET",headers:s});if(!a.ok)throw new Je(await pe(a));return await a.json()}async function yd(e){const s=await ha(),a=await fetch(`${Dt()}/patients/${e}/portal-admin/stats`,{method:"GET",headers:s});if(!a.ok)throw new Je(await pe(a));return await a.json()}async function gd(e,s){const a=await ha(),r=await fetch(`${Dt()}/patients/${e}/portal-admin/materials/${s}`,{method:"DELETE",headers:a});if(!r.ok)throw new Je(await pe(r))}async function kd(e,s,a,r,n){const i=await ha(),l=await pd(s),o=l.blob,c=l.filename,d=o.type||s.type,g=await fetch(`${Dt()}/patients/${e}/portal-admin/materials/upload-url`,{method:"POST",headers:i,body:JSON.stringify({filename:c,mime_type:d,size_bytes:o.size})});if(!g.ok)throw new Je(await pe(g));const{signed_upload_url:u,storage_path:m}=await g.json(),f=await fetch(u,{method:"PUT",headers:{"Content-Type":d},body:o});if(!f.ok)throw new Je(`Falló la subida al storage (${f.status}).`);const y=await fetch(`${Dt()}/patients/${e}/portal-admin/materials`,{method:"POST",headers:i,body:JSON.stringify({storage_path:m,title:r.trim()||s.name,description:void 0,mime_type:d,size_bytes:o.size,type:a})});if(!y.ok)throw new Je(await pe(y));return await y.json()}function vd(e){return e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"document"}function jd({patientId:e}){const{t:s}=W("portal"),[a,r]=p.useState([]),[n,i]=p.useState(!0),[l,o]=p.useState(null),[c,d]=p.useState(!1),[g,u]=p.useState(!1),m=p.useRef(null),f=p.useCallback(async()=>{i(!0),o(null);try{const h=await bd(e);r(h)}catch(h){o(K(h,s("admin.materials.loadError")))}finally{i(!1)}},[e,s]);p.useEffect(()=>{f()},[f]);async function y(h){const T=Array.from(h);if(T.length!==0){d(!0);try{for(const x of T){const P=vd(x.type),S=await kd(e,x,P,x.name);r(L=>[S,...L])}F.success(T.length===1?s("admin.materials.uploadedOne"):s("admin.materials.uploadedMany",{count:T.length}))}catch(x){F.error(K(x,s("admin.materials.uploadError")))}finally{d(!1),m.current&&(m.current.value="")}}}async function _(h){if(await fe({title:s("admin.materials.deleteConfirmTitle"),description:s("admin.materials.deleteConfirmDesc",{title:h.title}),confirmLabel:s("common:acciones.eliminar"),cancelLabel:s("common:acciones.cancelar"),destructive:!0}))try{await gd(e,h.id),r(x=>x.filter(P=>P.id!==h.id)),F.success(s("admin.materials.deleteSuccess"))}catch(x){F.error(K(x,s("admin.materials.deleteError")))}}return t.jsxs("section",{"aria-label":s("admin.materials.sectionAria"),className:"space-y-5",children:[t.jsxs("header",{children:[t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:["§ · ",s("admin.materials.eyebrow")]}),t.jsx("h3",{className:"text-h3 font-sans text-bark mt-1",children:s("admin.materials.heading")}),t.jsx("p",{className:"text-small text-bark-muted mt-2 max-w-xl leading-relaxed",children:s("admin.materials.desc")})]}),t.jsxs("div",{role:"region","aria-label":s("admin.materials.dropzoneAria"),onDragOver:h=>{h.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:h=>{var T;h.preventDefault(),u(!1),(T=h.dataTransfer)!=null&&T.files&&y(h.dataTransfer.files)},className:`border border-dashed rounded-md px-6 py-10 text-center transition-colors ${g?"border-terracotta bg-bone":"border-bark/25"}`,children:[t.jsx("p",{className:"text-small text-bark-muted mb-4",children:s("admin.materials.dropzoneText")}),t.jsx("input",{ref:m,type:"file",multiple:!0,className:"sr-only",onChange:h=>{h.target.files&&y(h.target.files)}}),t.jsxs("button",{type:"button",disabled:c,onClick:()=>{var h;
60return(h=m.current)==null?void 0:h.click()},className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:[t.jsx(le,{as:ss,size:14}),s(c?"admin.materials.uploading":"admin.materials.uploadButton")]})]}),l?t.jsx("p",{className:"text-small text-clay",children:l}):null,n&&a.length===0?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("admin.materials.loading")}):null,!n&&a.length===0?t.jsx("p",{className:"text-small text-bark-muted",children:s("admin.materials.empty")}):null,a.length>0?t.jsx("ul",{className:"divide-y divide-bark/10 border-y border-bark/10",children:a.map(h=>t.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[t.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[t.jsx(le,{as:wd(h.type),size:16,className:"text-bark-muted shrink-0"}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"text-small text-bark truncate",children:h.title}),t.jsxs("p",{className:"text-tiny text-bark-muted",children:[_d(h.size_bytes)," · ",Nd(h.created_at)," ·"," ",h.download_count===1?s("admin.materials.downloadsOne",{count:h.download_count}):s("admin.materials.downloadsMany",{count:h.download_count})]})]})]}),t.jsxs("button",{type:"button","aria-label":s("admin.materials.deleteAria",{title:h.title}),onClick:()=>void _(h),className:"inline-flex items-center gap-2 text-tiny uppercase tracking-widest text-bark-muted hover:text-clay transition-colors",children:[t.jsx(le,{as:Ja,size:14})," ",s("common:acciones.eliminar")]})]},h.id))}):null]})}function wd(e){switch(e){case"audio":return Fl;case"image":return Il;case"video":return zl;case"document":case"report":default:return Qa}}function _d(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Nd(e){try{return new Date(e).toLocaleDateString("es",{day:"numeric",month:"short",year:"numeric"})}catch{return e}}function Sd({patientId:e}){const{t:s}=W("portal"),[a,r]=p.useState(null),[n,i]=p.useState(!0),[l,o]=p.useState(null),c=p.useCallback(async()=>{i(!0),o(null);try{const d=await yd(e);r(d)}catch(d){o(K(d,s("admin.stats.loadError")))}finally{i(!1)}},[e,s]);return p.useEffect(()=>{c()},[c]),t.jsxs("section",{"aria-label":s("admin.stats.sectionAria"),className:"space-y-5",children:[t.jsxs("header",{children:[t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:["§ · ",s("admin.stats.eyebrow")]}),t.jsx("h3",{className:"text-h3 font-sans text-bark mt-1",children:s("admin.stats.heading")})]}),n&&!a?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("common:estados.cargando")}):null,l?t.jsx("p",{className:"text-small text-clay",children:l}):null,a?t.jsxs("ul",{className:"divide-y divide-bark/10 border-y border-bark/10",children:[t.jsx(Tt,{label:s("admin.stats.lastVisit"),value:a.last_visit_at?Cd(a.last_visit_at):s("admin.stats.neverVisited")}),t.jsx(Tt,{label:s("admin.stats.visits"),value:String(a.visits_count)}),t.jsx(Tt,{label:s("admin.stats.materialsDownloaded"),value:String(a.materials_downloaded)}),t.jsx(Tt,{label:s("admin.stats.tasksReturned"),value:String(a.tasks_completed),hint:a.tasks_open===1?s("admin.stats.openOne",{count:a.tasks_open}):s("admin.stats.openMany",{count:a.tasks_open})}),t.jsx(Tt,{label:s("admin.stats.paymentsReported"),value:String(a.payments_reported),hint:a.payments_reported>0?s("admin.stats.paymentsPending"):s("admin.stats.paymentsNone")})]}):null]})}function Tt({label:e,value:s,hint:a}){return t.jsxs("li",{className:"flex items-baseline justify-between gap-4 py-3",children:[t.jsx("span",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:e}),t.jsxs("span",{className:"text-small text-bark text-right",children:[s,a?t.jsx("span",{className:"block text-tiny text-bark-muted",children:a}):null]})]})}
60function Cd(e){try{return new Date(e).toLocaleString("es",{day:"numeric",month:"short",year:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}function Ed({patient:e}){const{t:s}=W("portal"),a=sr(m=>m.patientSort),[r,n]=p.useState([]),[i,l]=p.useState(!0),[o,c]=p.useState(null),d=p.useCallback(async()=>{l(!0),c(null);try{const m=await cn(e.id);n(m)}catch(m){c(K(m,s("admin.subtab.loadError")))}finally{l(!1)}},[e.id,s]);p.useEffect(()=>{d()},[d]);const g=p.useMemo(()=>r.find(m=>m.parentesco==="self"&&m.revoked_at==null)??null,[r]),u=p.useMemo(()=>rr({first_name:e.first_name??"",last_name:e.last_name??"",preferred_name:e.preferred_name??null},a),[e.first_name,e.last_name,e.preferred_name,a]);return i&&r.length===0?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("admin.subtab.loading")}):o?t.jsx("p",{className:"text-small text-clay",children:o}):g?t.jsxs("div",{className:"space-y-10",children:[t.jsx(ld,{patient:e,relation:g,onRelationChange:m=>n(f=>f.map(y=>y.id===m.id?m:y))}),t.jsx(od,{patientId:e.id,relation:g,onRelationChange:m=>n(f=>f.map(y=>y.id===m.id?m:y))}),t.jsx(jd,{patientId:e.id}),t.jsx(Sd,{patientId:e.id})]}):t.jsxs("div",{className:"border border-bark/15 rounded-md p-8 space-y-4",children:[t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:["§ · ",s("admin.subtab.noAccessEyebrow")]}),t.jsx("h3",{className:"text-h3 font-sans text-bark",children:s("admin.subtab.noAccessHeading",{name:u})}),t.jsx("p",{className:"text-small text-bark-muted leading-relaxed max-w-xl",children:s("admin.subtab.noAccessDesc")})]})}const Td=[{id:"matriz",labelKey:"compartir.subTabMatrix"},{id:"acceso-portal",labelKey:"compartir.subTabPortalAccess"}];function Pd({patient:e,contacts:s,onChanged:a}){const{t:r}=W("pacientes"),[n,i]=p.useState("matriz"),[l,o]=p.useState([]),[c,d]=p.useState(!0),[g,u]=p.useState(null),[m,f]=p.useState(!1),[y,_]=p.useState(null),[h,T]=p.useState(null),x=p.useMemo(()=>Za(e.date_of_birth),[e.date_of_birth]),P=p.useCallback(async()=>{d(!0),u(null);try{const A=await cn(e.id);o(A)}catch(A){u(K(A,r("compartir.loadError")))}finally{d(!1)}},[e.id,r]);p.useEffect(()=>{P()},[P]);const S=l.filter(A=>A.revoked_at==null),L=l.filter(A=>A.revoked_at!=null);async function I(A){const D=await Lc(e.id,A);o(C=>[D.relation,...C]),a==null||a(),f(!1),_({email:D.relation.related_email,password:D.password,isNewAccount:D.is_new_account})}async function v(A){if(await fe({title:H.confirm.regenerateTitle,description:H.confirm.regenerateBody,
60confirmLabel:r("compartir.regenerateConfirm"),cancelLabel:r("common:acciones.cancelar")}))try{const C=await un(e.id,A.id);o(N=>N.map(R=>R.id===C.relation.id?C.relation:R)),_({email:C.relation.related_email,password:C.password,isNewAccount:!1,title:H.regenerated.title,helper:H.regenerated.helper}),a==null||a()}catch(C){F.error(K(C,r("compartir.regenerateError")))}}async function O(A){if(await fe({title:H.confirm.revokeTitle,description:H.confirm.revokeBody,confirmLabel:r("compartir.revokeConfirm"),cancelLabel:r("common:acciones.cancelar"),destructive:!0}))try{const C=await mn(e.id,A.id);o(N=>N.map(R=>R.id===C.id?C:R)),F.success(r("compartir.revokedToast")),a==null||a()}catch(C){F.error(K(C,r("compartir.revokeError")))}}async function k(A){try{const D=await pn(e.id,A.id);o(C=>C.map(N=>N.id===D.id?D:N)),F.success(r("compartir.reactivatedToast")),a==null||a()}catch(D){F.error(K(D,r("compartir.reactivateError")))}}async function E(A){if(h)try{const D=await dn(e.id,h.id,{permissions:Ad(A)});o(C=>C.map(N=>N.id===D.id?D:N)),F.success(r("compartir.permsUpdatedToast")),T(null),a==null||a()}catch(D){F.error(K(D,r("compartir.permsError")))}}return t.jsxs("section",{"aria-label":r("compartir.blockAriaLabel"),className:"space-y-6",children:[t.jsx("nav",{"aria-label":r("compartir.subNavAriaLabel"),className:"flex gap-2 border-b border-bark/10",children:Td.map(A=>{const D=n===A.id;return t.jsx("button",{type:"button",onClick:()=>i(A.id),className:`text-tiny uppercase tracking-widest pb-3 px-1 -mb-px border-b transition-colors ${D?"text-bark border-terracotta":"text-bark-muted border-transparent hover:text-bark"}`,children:r(A.labelKey)},A.id)})}),n==="matriz"?t.jsxs("div",{className:"space-y-4",children:[t.jsxs("header",{className:"flex items-center justify-between",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:H.blockTitle}),t.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark transition-colors",children:H.ctaCreate})]}),g?t.jsx("p",{className:"text-tiny text-clay",children:g}):null,c&&l.length===0?t.jsx("p",{className:"text-tiny text-bark-muted",children:r("compartir.loadingAccesses")}):null,!c&&l.length===0?t.jsx("p",{className:"text-small text-bark-muted",children:H.emptyState}):null,S.length>0?t.jsxs("div",{children:[t.jsx("h3",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-2",children:H.sectionActive}),t.jsx("ul",{children:S.map(A=>t.jsx(Us,{relation:A,onEditPermissions:()=>T(A),onRegeneratePassword:()=>void v(A),onRevoke:()=>void O(A),onReactivate:()=>void k(A)},A.id))})]}):null,L.length>0?t.jsxs("div",{children:[t.jsx("h3",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-2",children:H.sectionRevoked}),t.jsx("ul",{children:L.map(A=>t.jsx(Us,{relation:A,onEditPermissions:()=>{},onRegeneratePassword:()=>{},onRevoke:()=>{},onReactivate:()=>void k(A)},A.id))})]}):null,!c&&l.length>0?t.jsx("div",{className:"pt-2 border-t border-bark/10",children:t.jsx(nd,{patientId:e.id},`matrix-${l.length}`)}):null]}):t.jsx(Ed,{patient:e}),t.jsx(Ic,{open:m,patientAge:x,patientContacts:s,onClose:()=>f(!1),onSubmit:I}),t.jsx(Gc,{open:y!=null,email:(y==null?void 0:y.email)??"",password:(y==null?void 0:y.password)??null,isNewAccount:(y==null?void 0:y.isNewAccount)??!1,title:y==null?void 0:y.title,helperOverride:y==null?void 0:y.helper,onClose:()=>_(null)}),t.jsx(Yc,{open:h!=null,relation:h,onClose:()=>T(null),onSubmit:E})]})}function Ad(e){const{view_session_notes:s,...a}=e;return a}function Ld({patient:e}){const{t:s}=W("plan"),a=(e==null?void 0:e.id)??null,r=p.useCallback(()=>bt({category:"planificaciones",...a?{patient:a}:{},sort:"created_at",dir:"desc"}),[a]),n=a?`library.files.planificaciones:${a}`:"library.files.planificaciones:all",{data:i,loading:l,error:o,refetch:c}=$t(n,r),d=i??[];async function g(u){if(await fe({title:s("archived.deleteTitle"),description:s("archived.deleteDescription",{name:u.title||u.filename}),confirmLabel:s("common:acciones.eliminar"),destructive:!0}))try{await Mt(u.id),mt("library."),await c(),F.success(s("archived.deleted"))}
60catch(f){F.error(K(f,s("archived.deleteError")))}}return l&&d.length===0?t.jsxs("section",{className:"space-y-3",children:[t.jsxs("h4",{className:"text-tiny uppercase tracking-widest text-bark-muted inline-flex items-center gap-2",children:[t.jsx(ka,{size:12,strokeWidth:1.5})," ",s("archived.title")]}),t.jsx("p",{className:"text-tiny text-bark-muted",children:s("common:estados.cargando")})]}):o?t.jsxs("section",{className:"space-y-3",children:[t.jsxs("h4",{className:"text-tiny uppercase tracking-widest text-bark-muted inline-flex items-center gap-2",children:[t.jsx(ka,{size:12,strokeWidth:1.5})," ",s("archived.title")]}),t.jsx("p",{className:"text-small text-clay",children:o.message||s("archived.loadError")})]}):d.length===0?null:t.jsxs("section",{className:"space-y-4",children:[t.jsxs("h4",{className:"text-tiny uppercase tracking-widest text-bark-muted inline-flex items-center gap-2",children:[t.jsx(ka,{size:12,strokeWidth:1.5})," ",s("archived.title")]}),t.jsx(Rt,{files:d,onDelete:u=>void g(u)})]})}function Dd({patient:e,sessions:s,onPatientChange:a}){const{t:r}=W("plan"),{templates:n,loading:i}=zi(),[l,o]=p.useState(!1),[c,d]=p.useState([]),[g,u]=p.useState(!0),[m,f]=p.useState(!1),[y,_]=p.useState(!1),{plan:h,loading:T,error:x,setPlan:P,reload:S}=Ui(e.id);p.useEffect(()=>{let k=!1;return u(!0),Md(e.id).then(E=>{k||d(E)}).catch(()=>{k||d([])}).finally(()=>{k||u(!1)}),()=>{k=!0}},[e.id]);const L=p.useMemo(()=>{const k=new Map;for(const E of s)k.set(E.id,E);return k},[s]),I=p.useCallback(async k=>{const E=k||null;o(!0);try{const A=await jr(e.id,{preferred_plan_template_file_id:E});a(A),F.success(r(E?"tab.templateUpdated":"tab.templateRemoved"))}catch(A){F.error(K(A,r("tab.templateSaveError")))}finally{o(!1)}},[e.id,a,r]),v=p.useCallback(k=>{P(k),F.success(r("shared.planCreated"))},[P,r]);async function O(){_(!0);try{const k=await Ki({patient_id:e.id});P(k),F.success(r("shared.planCreatedBlank"))}catch(k){F.error(k instanceof qi?k.message:K(k,r("shared.planCreateError")))}finally{_(!1)}}return t.jsxs("div",{className:"space-y-16",children:[t.jsx("section",{children:T?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:r("tab.loadingPlan")}):x?t.jsx("p",{className:"text-small text-clay",children:x}):h?t.jsx(Wi,{bundle:h,patientFirstName:e.first_name,patientLastName:e.last_name,setBundle:P,reload:S}):t.jsx(Od,{patientLabel:[e.first_name,e.last_name].filter(Boolean).join(" ").trim()||r("shared.thisPatient"),onBlank:()=>void O(),onGenerate:()=>f(!0),creatingBlank:y})}),t.jsxs("section",{children:[t.jsxs("header",{className:"mb-4",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:r("tab.preferredTemplateEyebrow")}),t.jsx("h2",{className:"text-h3 font-sans text-bark mt-1",children:r("tab.preferredTemplateTitle")}),t.jsx("p",{className:"text-small text-bark-muted mt-2 max-w-xl leading-relaxed",children:r("tab.preferredTemplateDesc")})]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[t.jsxs("select",{value:e.preferred_plan_template_file_id??"",onChange:k=>void I(k.target.value),disabled:l||i,className:"bg-bone border border-bark/15 rounded-md px-3 py-2 text-body text-bark focus:outline-none focus:border-bark/40 w-full lg:w-auto lg:min-w-[280px]",children:[t.jsx("option",{value:"",children:r("tab.noPreferredTemplate")}),n.filter(k=>k.status==="ready").map(k=>t.jsx("option",{value:k.id,children:k.title||k.filename},k.id))]}),t.jsx(Pe,{to:"/dashboard/biblioteca",className:"inline-flex items-center gap-2 text-tiny uppercase tracking-widest text-bark-muted hover:text-bark transition-colors",children:r("tab.goToLibrary")})]})]}),t.jsxs("section",{children:[t.jsxs("header",{className:"mb-4",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:r("tab.plannedSessionsEyebrow")}),t.jsx("h2",{className:"text-h3 font-sans text-bark mt-1",children:r("tab.previousPlansTitle")}),t.jsx("p",{className:"text-small text-bark-muted mt-2",children:r("tab.previousPlansDesc")})]}),g?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:r("common:estados.cargando")}):c.length===0?t.jsx($d,{}):t.jsx("ul",{className:"divide-y divide-bark/10 border-y border-bark/10",children:c.map(k=>{const E=L.get(k.plan.session_id),A=Yi(k.items);return t.jsx("li",{children:t.jsxs(Pe,{to:E?`/dashboard/sesion/${E.id}`:`/dashboard/sesion/${k.plan.session_id}`,className:"flex items-start justify-between gap-4 py-3 px-1 hover:bg-bark/[0.03] transition-colors",children:[t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block text-body text-bark truncate",children:E?Rd(E):r("tab.sessionShort",{id:k.plan.session_id.slice(0,8)})}),t.jsxs("span",{className:"block text-tiny uppercase tracking-widest text-bark-muted mt-1",children:[k.plan.origin==="generated_with_ai"?t.jsxs("span",{className:"inline-flex items-center gap-1 text-terracotta",children:[t.jsx(ht,{size:12,strokeWidth:1.5})," ",ks[k.plan.origin]]}):ks[k.plan.origin],t.jsx("span",{className:"text-bark-muted ml-2",children:r("tab.completedCount",{done:A.done,total:A.total})})]})]}),t.jsx(ir,{size:14,strokeWidth:1.5,className:"text-bark-muted mt-1"})]})},k.plan.id)})})]}),t.jsx(Ld,{patient:e}),t.jsx(Hi,{open:m,patientId:e.id,patientLabel:[e.first_name,e.last_name].filter(
60Boolean).join(" ").trim()||r("shared.patient"),preferredTemplateFileId:e.preferred_plan_template_file_id,onClose:()=>f(!1),onPlanCreated:v})]})}function Od({patientLabel:e,onBlank:s,onGenerate:a,creatingBlank:r}){const{t:n}=W("plan");return t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb-3",children:n("tab.noPlanEyebrow")}),t.jsx("h2",{className:"text-h2 font-sans text-bark leading-tight mb-4",children:n("shared.noPlanTitle",{name:e})}),t.jsx("p",{className:"text-body text-bark-muted leading-relaxed mb-8",children:n("shared.noPlanBody")}),t.jsxs("div",{className:"flex flex-wrap gap-3",children:[t.jsx("button",{type:"button",onClick:s,disabled:r,className:"inline-flex items-center gap-2 h-8 px-5 text-tiny uppercase tracking-widest rounded-full border border-bark/30 text-bark hover:border-bark transition-colors disabled:opacity-40",children:n("shared.buildManually")}),t.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center gap-2 h-8 px-5 text-tiny uppercase tracking-widest rounded-full border border-terracotta text-terracotta hover:bg-terracotta hover:text-linen transition-colors",children:[t.jsx(ht,{size:14,strokeWidth:1.5})," ",n("shared.buildWithBitacora")]})]})]})}function $d(){const{t:e}=W("plan");return t.jsx("div",{className:"border border-dashed border-bark/15 rounded-lg px-6 py-10 text-center",children:t.jsx("p",{className:"text-body text-bark-muted",children:e("tab.emptyHistory")})})}async function Md(e){const{data:s,error:a}=await ut.from("session_plans").select("*, sessions!inner(patient_id, scheduled_start)").eq("sessions.patient_id",e).order("created_at",{ascending:!1});if(a)throw a;const r=s??[];if(r.length===0)return[];const n=r.map(c=>c.id),{data:i,error:l}=await ut.from("session_plan_items").select("*").in("plan_id",n);if(l)throw l;const o=new Map;for(const c of i??[]){const d=o.get(c.plan_id)??[];d.push(c),o.set(c.plan_id,d)}return r.map(c=>{const d={id:c.id,session_id:c.session_id,professional_id:c.professional_id,origin:c.origin,template_file_id:c.template_file_id,prompt:c.prompt,web_search_enabled:c.web_search_enabled,use_briefing:c.use_briefing,notes:c.notes,claude_tokens_input:c.claude_tokens_input,claude_tokens_output:c.claude_tokens_output,generation_ms:c.generation_ms,rag_results_used:c.rag_results_used,created_at:c.created_at,updated_at:c.updated_at},g=(o.get(d.id)??[]).sort((u,m)=>u.order_index-m.order_index);return{plan:d,items:g}})}function Rd(e){const s=new Date(e.scheduled_start);return`${s.toLocaleDateString("es",{weekday:"long",day:"numeric",month:"short"})} · ${s.toLocaleTimeString("es",{hour:"2-digit",minute:"2-digit"})}`}function Fd({patient:e}){const{t:s}=W("informes"),a=Ot(),[r,n]=at("informes","grid"),i=p.useCallback(()=>bt({category:"informes",patient:e.id,sort:"created_at",dir:"desc"}),[e.id]),l=`library.files.informes:${e.id}`,{data:o,loading:c,error:d,refetch:g}=$t(l,i),u=o??[],m=p.useCallback(y=>{a(`/dashboard/informes/${y.id}`)},[a]);async function f(y){if(await fe({title:s("tab.deleteTitle"),description:s("tab.deleteBody",{name:y.title||y.filename}),confirmLabel:s("common:acciones.eliminar"),destructive:!0}))try{await Mt(y.id),mt("library."),await g(),F.success(s("tab.deleted"))}catch(h){F.error(K(h,s("tab.deleteError")))}}return t.jsxs("section",{className:"space-y-6",children:[t.jsxs("header",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:s("tab.heading")}),t.jsx("p",{className:"text-small text-bark-muted mt-1",children:s("tab.subtitle",{name:e.first_name})})]}),t.jsxs(Pe,{to:`/dashboard/informes/nuevo?patient_id=${e.id}`,state:{patientFirstName:e.first_name},className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors shrink-0",children:[t.jsx(ht,{size:14,strokeWidth:1.5})," ",s("tab.generate")]})]}),u.length>0?t.jsx("div",{className:"flex items-center",children:t.jsx("div",{className:"ml-auto",children:t.jsx(tt,{value:r,onChange:n,ariaLabel:s("list.viewToggleAria")})})}):null,c&&u.length===0?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("list.loading")}):d?t.jsx("p",{className:"text-small text-clay",children:d.message||s("list.loadError")}):u.length===0?t.jsx(Vd,{}):r==="grid"?t.jsx(Rt,{files:u,onDelete:y=>void f(y),onOpen:m}):t.jsx(rs,{files:u,onDelete:y=>void f(y),onOpen:m})]})}function Vd(){const{t:e}=W("informes");return t.jsxs("div",{className:"text-center py-12 border border-dashed border-bark/15 rounded-lg",children:[t.jsx(Qa,{size:24,strokeWidth:1.5,className:"mx-auto text-bark-muted"}),t.jsx("p",{className:"text-body text-bark mt-3",children:e("tab.empty")}),t.jsx("p",{className:"text-tiny text-bark-muted mt-1",children:e("tab.emptyHint")})]})}function Id({patient:e}){const s=Ot(),{t:a}=W("actividades"),[r,n]=at("actividades","grid"),i=p.useCallback(()=>bt({category:"actividades",patient:e.id,is_template:!1,sort:"created_at",dir:"desc"}),[e.id]),l=`library.files.actividades:${e.id}`,{data:o,loading:c,error:d,refetch:g}=$t(l,i),u=o??[],m=p.useCallback(y=>{s(`/dashboard/creador-actividades/${y.id}`)},[s]);async function f(y){if(await fe({title:a("tab.deleteTitle"),description:a("tab.deleteBody",{name:y.title||y.filename}),confirmLabel:a("common:acciones.eliminar"),destructive:!0}))try{await Mt(y.id),mt("library."),await g(),F.success(a("tab.deleted"))}catch(h){F.error(K(h,a("tab.deleteError")))}}return t.jsxs("section",{className:"space-y-6",children:[t.jsxs("header",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:a("tab.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-1",children:a("tab.subtitle",{name:e.first_name})})]}),t.jsxs(Pe,{to:`/dashboard/creador?patient_id=${e.id}`,state:{patientFirstName:e.first_name},className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors shrink-0",children:[t.jsx(ht,{size:14,strokeWidth:1.5})," ",a("tab.createNew")]})]}),u.length>0?t.jsx("div",{className:"flex items-center",children:t.jsx("div",{className:"ml-auto",children:t.jsx(tt,{value:r,onChange:n,ariaLabel:a("tab.viewAria")})})}):null,c&&u.length===0?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:a("common:estados.cargando")}):d?t.jsx("p",{className:"text-small text-clay",children:d.message||a("tab.loadError")}):u.length===0?t.jsx(Bd,{}):r==="grid"?t.jsx(Rt,{files:u,onDelete:y=>void f(y),onOpen:m}):t.jsx(rs,{files:u,onDelete:y=>void f(y),onOpen:m})]})}function Bd(){const{t:e}=W("actividades");return t.jsxs("div",{className:"text-center py-12 border border-dashed border-bark/15 rounded-lg",children:[t.jsx(lr,{size:24,strokeWidth:1.5,className:"mx-auto text-bark-muted"}),t.jsx("p",{className:"text-body text-bark mt-3",children:e("tab.emptyTitle")}),t.jsx("p",{className:"text-tiny text-bark-muted mt-1",children:e("tab.emptyBody")})]})}const bn=Math.cos,oa=Math.sin,Le=Math.sqrt,ca=Math.PI,ba=2*ca,ms={draw(e,s){const a=Le(s/ca);e.moveTo(a,0),e.arc(0,0,a,0,ba)}},zd={draw(e,s){const a=Le(s/5)/2;e.moveTo(-3*a,-a),e.lineTo(-a,-a),e.lineTo(-a,-3*a),e.lineTo(a,-3*a),e.lineTo(a,-a),e.lineTo(3*a,-a),e.lineTo(3*a,a),e.lineTo(a,a),e.lineTo(a,3*a),e.lineTo(-a,3*a),e.lineTo(-a,a),e.lineTo(-3*a,a),e.closePath()}},yn=Le(1/3),Ud=yn*2,Wd={draw(e,s){const a=Le(s/Ud),r=a*yn;e.moveTo(0,-a),e.lineTo(r,0),e.lineTo(0,a),e.lineTo(-r,0),e.closePath()}},Hd={draw(e,s){const a=Le(s),r=-a/2;e.rect(r,r,a,a)}},Kd=.8908130915292852,gn=oa(ca/10)/oa(7*ca/10),qd=oa(ba/10)*gn,Gd=-bn(ba/10)*gn,Yd={draw(e,s){const a=Le(s*Kd),r=qd*a,n=Gd*a;e.moveTo(0,-a),e.lineTo(r,n);for(let i=1;i<5;++i){const l=ba*i/5,o=bn(l),c=oa(l);e.lineTo(c*a,-o*a),e.lineTo(o*r-c*n,c*r+o*n)}e.closePath()}},Da=Le(3),Xd={draw(e,s){const a=-Le(s/(Da*3));e.moveTo(0,a*2),e.lineTo(-Da*a,-a),e.lineTo(Da*a,-a),e.closePath()}},ke=-.5,ve=Le(3)/2,Ka=1/Le(12),Zd=(Ka/2+1)*3,Jd={draw(e,s){const a=Le(s/Zd),r=a/2,n=a
60*Ka,i=r,l=a*Ka+a,o=-i,c=l;e.moveTo(r,n),e.lineTo(i,l),e.lineTo(o,c),e.lineTo(ke*r-ve*n,ve*r+ke*n),e.lineTo(ke*i-ve*l,ve*i+ke*l),e.lineTo(ke*o-ve*c,ve*o+ke*c),e.lineTo(ke*r+ve*n,ke*n-ve*r),e.lineTo(ke*i+ve*l,ke*l-ve*i),e.lineTo(ke*o+ve*c,ke*c-ve*o),e.closePath()}};function Qd(e,s){let a=null,r=Zi(n);e=typeof e=="function"?e:Ht(e||ms),s=typeof s=="function"?s:Ht(s===void 0?64:+s);function n(){let i;if(a||(a=i=r()),e.apply(this,arguments).draw(a,+s.apply(this,arguments)),i)return a=null,i+""||null}return n.type=function(i){return arguments.length?(e=typeof i=="function"?i:Ht(i),n):e},n.size=function(i){return arguments.length?(s=typeof i=="function"?i:Ht(+i),n):s},n.context=function(i){return arguments.length?(a=i??null,n):a},n}var eu=["type","size","sizeType"];function qa(){return qa=Object.assign?Object.assign.bind():function(e){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r])}return e},qa.apply(null,arguments)}function Ks(e,s){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),a.push.apply(a,r)}return a}function qs(e){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Ks(Object(a),!0).forEach(function(r){tu(e,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(a)):Ks(Object(a)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(a,r))})}return e}function tu(e,s,a){return(s=au(s))in e?Object.defineProperty(e,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[s]=a,e}function au(e){var s=su(e,"string");return typeof s=="symbol"?s:s+""}function su(e,s){if(typeof e!="object"||!e)return e;var a=e[Symbol.toPrimitive];if(a!==void 0){var r=a.call(e,s);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(e)}function ru(e,s){if(e==null)return{};var a,r,n=nu(e,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)a=i[r],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(e,a)&&(n[a]=e[a])}return n}function nu(e,s){if(e==null)return{};var a={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(s.indexOf(r)!==-1)continue;a[r]=e[r]}return a}var kn={symbolCircle:ms,symbolCross:zd,symbolDiamond:Wd,symbolSquare:Hd,symbolStar:Yd,symbolTriangle:Xd,symbolWye:Jd},iu=Math.PI/180,lu=e=>{var s="symbol".concat(Ar(e));return kn[s]||ms},ou=(e,s,a)=>{if(s==="area")return e;switch(a){case"cross":return 5*e*e/9;case"diamond":return .5*e*e/Math.sqrt(3);case"square":return e*e;case"star":{var r=18*iu;return 1.25*e*e*(Math.tan(r)-Math.tan(r*2)*Math.tan(r)**2)}case"triangle":return Math.sqrt(3)*e*e/4;case"wye":return(21-10*Math.sqrt(3))*e*e/8;default:return Math.PI*e*e/4}},cu=(e,s)=>{kn["symbol".concat(Ar(e))]=s},vn=e=>{var s=e.type,a=s===void 0?"circle":s,r=e.size,n=r===void 0?64:r,i=e.sizeType,l=i===void 0?"area":i,o=ru(e,eu),c=qs(qs({},o),{},{type:a,size:n,sizeType:l}),d="circle";typeof a=="string"&&(d=a);var g=()=>{var _=lu(d),h=Qd().type(_).size(ou(n,l,d)),T=h();if(T!==null)return T},u=c.className,m=c.cx,f=c.cy,y=Ji(c);return va(m)&&va(f)&&va(n)?p.createElement("path",qa({}
60,y,{className:Pr("recharts-symbols",u),transform:"translate(".concat(m,", ").concat(f,")"),d:g()})):null};vn.registerSymbol=cu;function da(){return da=Object.assign?Object.assign.bind():function(e){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r])}return e},da.apply(null,arguments)}function Gs(e,s){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),a.push.apply(a,r)}return a}function jn(e){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Gs(Object(a),!0).forEach(function(r){du(e,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(a)):Gs(Object(a)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(a,r))})}return e}function du(e,s,a){return(s=uu(s))in e?Object.defineProperty(e,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[s]=a,e}function uu(e){var s=mu(e,"string");return typeof s=="symbol"?s:s+""}function mu(e,s){if(typeof e!="object"||!e)return e;var a=e[Symbol.toPrimitive];if(a!==void 0){var r=a.call(e,s);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(e)}var je=32,pu={align:"center",iconSize:14,inactiveColor:"#ccc",layout:"horizontal",verticalAlign:"middle",labelStyle:{}};function xu(e){if(typeof e=="object"&&e!==null&&"strokeDasharray"in e)return String(e.strokeDasharray)}function fu(e){var s=e.data,a=e.iconType,r=e.inactiveColor,n=je/2,i=je/6,l=je/3,o=s.inactive?r:s.color,c=a??s.type;if(c==="none")return null;if(c==="plainline")return p.createElement("line",{strokeWidth:4,fill:"none",stroke:o,strokeDasharray:xu(s.payload),x1:0,y1:n,x2:je,y2:n,className:"recharts-legend-icon"});if(c==="line")return p.createElement("path",{strokeWidth:4,fill:"none",stroke:o,d:"M0,".concat(n,"h").concat(l,`
61            A`).concat(i,",").concat(i,",0,1,1,").concat(2*l,",").concat(n,`
62            H`).concat(je,"M").concat(2*l,",").concat(n,`
63            A`).concat(i,",").concat(i,",0,1,1,").concat(l,",").concat(n),className:"recharts-legend-icon"});if(c==="rect")return p.createElement("path",{stroke:"none",fill:o,d:"M0,".concat(je/8,"h").concat(je,"v").concat(je*3/4,"h").concat(-je,"z"),className:"recharts-legend-icon"});if(p.isValidElement(s.legendIcon)){var d=jn({},s);return delete d.legendIcon,p.cloneElement(s.legendIcon,d)}return p.createElement(vn,{fill:o,cx:n,cy:n,size:je,sizeType:"diameter",type:c})}function hu(e){var s=e.payload,a=e.iconSize,r=e.layout,n=e.formatter,i=e.inactiveColor,l=e.iconType,o=e.labelStyle,c={x:0,y:0,width:je,height:je},d={display:r==="horizontal"?"inline-block":"block",marginRight:10,whiteSpace:"nowrap"},g={display:"inline-block",verticalAlign:"middle",marginRight:4};return s.map((u,m)=>{var f,y,_=u.formatter||n,h=Pr({"recharts-legend-item":!0,["legend-item-".concat(m)]:!0,inactive:u.inactive});if(u.type==="none")return null;var T=typeof o=="object"?jn({},o):{};T.color=u.inactive?i:T.color||u.color,(f=T.whiteSpace)!==null&&f!==void 0||(T.whiteSpace="normal"),(y=T.overflowWrap)!==null&&y!==void 0||(T.overflowWrap="break-word");var x=_?_(u.value,u,m):u.value;return p.createElement("li",da({className:h,style:d,key:"legend-item-".concat(m)},Qi(e,u,m)),p.createElement(el,{width:a,height:a,viewBox:c,style:g,"aria-label":u.value==null?"legend icon":"".concat(u.value," legend icon")},p.createElement(fu,{data:u,iconType:l,inactiveColor:i})),p.createElement("span",{className:"recharts-legend-item-text",style:T},x))})}var bu=e=>{var s=Lr(e,pu),a=s.payload,r=s.layout,n=s.align;if(!a||!a.length)return null;var i={padding:0,margin:0,textAlign:r==="horizontal"?n:"left"};return p.createElement("ul",{className:"recharts-default-legend",style:i},p.createElement(hu,da({},s,{payload:a})))};function yu(){return Dr(tl)}var gu=al([sl,rl,nl],(e,s,a)=>({x:a.left||0,y:a.top||0,width:Math.max(e-(a.left||0)-(a.right||0),0),height:Math.max(s-(a.top||0)-(a.bottom||0),0)}));function ku(e,s){var a;if(e==="start"&&s==="start")return"";var r={start:"0",middle:"-50%",end:"-100%"},n={start:"0",middle:"-50%",end:"-100%"},i=e==="inherit"?"0":r[e],l=(a=n[s])!==null&&a!==void 0?a:"0";return"translate(".concat(i,", ").concat(l,")")}var vu=["contextPayload"];function Ga(){return Ga=Object.assign?Object.assign.bind():function(e){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r])}return e},Ga.apply(null,arguments)}function ju(e,s){return Su(e)||Nu(e,s)||_u(e,s)||wu()}
63function wu(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
64In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _u(e,s){if(e){if(typeof e=="string")return Ys(e,s);var a={}.toString.call(e).slice(8,-1);return a==="Object"&&e.constructor&&(a=e.constructor.name),a==="Map"||a==="Set"?Array.from(e):a==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a)?Ys(e,s):void 0}}function Ys(e,s){(s==null||s>e.length)&&(s=e.length);for(var a=0,r=Array(s);a<s;a++)r[a]=e[a];return r}function Nu(e,s){var a=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(a!=null){var r,n,i,l,o=[],c=!0,d=!1;try{if(i=(a=a.call(e)).next,s!==0)for(;!(c=(r=i.call(a)).done)&&(o.push(r.value),o.length!==s);c=!0);}catch(g){d=!0,n=g}finally{try{if(!c&&a.return!=null&&(l=a.return(),Object(l)!==l))return}finally{if(d)throw n}}return o}}function Su(e){if(Array.isArray(e))return e}function Xs(e,s){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);s&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),a.push.apply(a,r)}return a}function xt(e){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Xs(Object(a),!0).forEach(function(r){Cu(e,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(a)):Xs(Object(a)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(a,r))})}return e}function Cu(e,s,a){return(s=Eu(s))in e?Object.defineProperty(e,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[s]=a,e}function Eu(e){var s=Tu(e,"string");return typeof s=="symbol"?s:s+""}function Tu(e,s){if(typeof e!="object"||!e)return e;var a=e[Symbol.toPrimitive];if(a!==void 0){var r=a.call(e,s);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(e)}function Pu(e,s){if(e==null)return{};var a,r,n=Au(e,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)a=i[r],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(e,a)&&(n[a]=e[a])}return n}function Au(e,s){if(e==null)return{};var a={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(s.indexOf(r)!==-1)continue;a[r]=e[r]}return a}function Lu(e){return e.value}function Du(e){var s=e.contextPayload,a=Pu(e,vu),r=fl(s,e.payloadUniqBy,Lu),n=xt(xt({},a),{},{payload:r});return p.isValidElement(e.content)?p.cloneElement(e.content,n):typeof e.content=="function"?p.createElement(e.content,n):p.createElement(bu,n)}function Ou(e){return e==="left"||e==="right"||e==="insideLeft"||e==="insideRight"?"vertical":"horizontal"}function $u(e,s){return s==null?null:Or(s)?gu(e):pl(e)}function Mu(e,s,a){return e==="top"?{top:a.height+s}:e==="bottom"?{top:-a.height-s}:e==="left"?{left:a.width+s}:e==="right"?{left:-a.width-s}:{}}function Ru(e,s,a,r,n,i){var l=s.layout,o=s.align,c=s.verticalAlign,d,g;return(!e||(e.left===void 0||e.left===null)&&(e.right===void 0||e.right===null))&&(o==="center"&&l==="vertical"?d={left:((r||0)-i.width)/2}:d=o==="right"?{right:a&&a.right||0}:{left:a&&a.left||0}),(!e||(e.top===void 0||e.top===null)&&(e.bottom===void 0||e.bottom===null))&&(c==="middle"?g={top:((n||0)-i.height)/2}:g=c==="bottom"?{bottom:a&&a.bottom||0}:{top:a&&a.top||0}),xt(xt({},d),g)}function Fu(e){var s=e.align,a=e.layout,r=e.verticalAlign,n=e.itemSorter,i=e.position,l=e.offset,o=$r();return p.useLayoutEffect(()=>{o(xl({align:s,layout:a,verticalAlign:r,itemSorter:n,position:i,offset:l}))},[o,s,a,r,n,i,l]),null}function Vu(e){var s=e.width,a=e.height,r=$r();return p.useLayoutEffect(()=>{r(vs({width:s,height:a}))},[r,s,a]),p.useLayoutEffect(()=>()=>{r(vs({width:0,height:0}))},[r]),null}function Iu(e,s,a,r){return e==="vertical"&&s!=null?{height:s}:e==="horizontal"?{width:a||r}:null}var Bu={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",labelStyle:{},layout:"auto",verticalAlign:"bottom",offset:0};function zu(e){var s,a,r,n,i,l,o,c,d=Lr(e,Bu),g=e.layout&&e.layout!=="auto"?e.layout:Ou(d.position),u=yu(),m=ll(),f=ol(),y=Dr(he=>$u(he,d.position)),_=d.width,h=d.height,T=d.wrapperStyle,x=d.portal,P=x==null&&(d.position==null||Or(d.position)),S=cl([u]),L=ju(S,2),I=L[0],v=L[1],O=dl(),k=ul();if(O==null||k==null||d.position!=null&&y==null)return null;var E=O-((f==null?void 0:f.left)||0)-((f==null?void 0:f.right)||0),A=Iu(g,h,_,E),D=d.position==null?null:ml({viewBox:y??{x:0,y:0,width:O,height:k},position:d.position,offset:(s=d.offset)!==null&&s!==void 0?s:0}),C=Mu(d.position,(a=d.offset)!==null&&a!==void 0?a:0,I),N=g==="vertical"?((r=y==null?void 0:y.width)!==null&&r!==void 0?r:0)/2:(n=y==null?void 0:y.width)!==null&&n!==void 0?n:0,R=g==="horizontal"?((i=y==null?void 0:y.height)!==null&&i!==void 0?i:0)/2:(l=y==null?void 0:y.height)!==null&&l!==void 0?l:0,X=D?{width:"max-content",height:"max-content",maxWidth:N,maxHeight:R,overflowY:"auto",top:D.y+((o=C.top)!==null&&o!==void 0?o:0),left:D.x+((c=C.left)!==null&&c!==void 0?c:0),transform:ku(D.horizontalAnchor,D.verticalAnchor)}:Ru(T,d,f,O,k,I),Z=x?T:xt(xt({position:"absolute",width:(A==null?void 0:A.width)||_||"auto",height:(A==null?void 0:A.height)||h||"auto"},X),T),Ne=x??m;if(Ne==null||u==null)return null;var ne=p.createElement("div",{className:"recharts-legend-wrapper",style:Z,ref:v},p.createElement(Fu,{layout:g,align:d.align,verticalAlign:d.verticalAlign,itemSorter:d.itemSorter,position:d.position,offset:d.offset}),P&&p.createElement(Vu,I),p.createElement(Du,Ga({},d,{layout:g},A,{margin:f,chartWidth:O,chartHeight:k,contextPayload:u})));return wl.createPortal(ne,Ne)}var wn=p.memo(zu,il);wn.displayName="Legend";function Zs(e){return new Date(e).toLocaleDateString("es",{day:"2-digit",month:"short",year:"numeric"})}function Oa(e){const s=e.total;return typeof s=="number"?s:null}function Uu(e,s){const a={rows:[],metrics:[],allIncomplete:!1};if(e.some(o=>Oa(o.computed_metrics)!==null)){const o=e.filter(m=>Oa(m.computed_metrics)!==null&&m.computed_metrics.incomplete!==!0);if(o.length===0)return{...a,allIncomplete:!0};const c=[{key:"total",label:s}],d=new Map,g=new Map;for(const m of o){const f=m.computed_metrics.subscales;if(Array.isArray(f))for(const y of f)typeof y.id=="string"&&typeof y.total=="number"&&(d.set(y.id,typeof y.label=="string"?y.label:y.id),g.set(y.id,(g.get(y.id)??0)+1))}for(const[m,f]of g)f===o.length&&c.push({key:`sub:${m}`,label:d.get(m)??m});return{rows:o.map(m=>{const f={date:Zs(m.administered_at)};f.total=Oa(m.computed_metrics);const y=m.computed_metrics.subscales;if(Array.isArray(y))for(const _ of y)typeof _.id=="string"&&typeof _.total=="number"&&(f[`sub:${_.id}`]=_.total);return f}),metrics:c,allIncomplete:!1}}const n=new Set;for(const o of e)for(const c of Object.keys(o.raw_scores))typeof o.raw_scores[c]=="number"&&n.add(c);const i=Array.from(n).slice(0,6).map(o=>({key:o,label:o}));return{rows:e.map(o=>{const c={date:Zs(o.administered_at)};for(const d of i){const g=o.raw_scores[d.key];c[d.key]=typeof g=="number"?g:null}return c}),metrics:i,allIncomplete:!1}}const Js=["#CC785C","#3D5A40","#2C5862","#7B6B9D","#8B6F47","#A84A6F"];function Wu({patientId:e,testId:s,onClose:a}){const{t:r}=W("evaluaciones"),n=p.useRef(null);
64we(!0),_e(n,!0);const[i,l]=p.useState(null),[o,c]=p.useState(null);p.useEffect(()=>{let m=!1;return Mi(e,s).then(f=>{m||l(f)}).catch(f=>{if(!m){const y=K(f,r("comparison.loadError"));c(y),F.error(y)}}),()=>{m=!0}},[e,s,r]);const{rows:d,metrics:g,allIncomplete:u}=p.useMemo(()=>i?Uu(i.applications,r("comparison.totalLabel")):{rows:[],metrics:[],allIncomplete:!1},[i,r]);return t.jsx("div",{ref:n,role:"dialog","aria-modal":"true","aria-label":r("comparison.dialogAria"),className:"fixed inset-0 z-50 flex items-center justify-center bg-bark/40 p-0 lg:px-4",children:t.jsxs("div",{className:"bg-bone w-full h-full max-w-none max-h-none overflow-y-auto rounded-none p-6 lg:h-auto lg:max-w-3xl lg:max-h-[90vh] lg:rounded-lg lg:p-8",children:[t.jsxs("header",{className:"mb-6 flex items-start justify-between",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb-2",children:r("comparison.marker")}),t.jsx("h2",{className:"text-h2 font-sans text-bark",children:i?r("comparison.title",{code:i.test.code,name:i.test.name}):r("common:estados.cargando")}),i!=null&&i.next_admin_due_at?t.jsx("p",{className:"text-small text-bark-muted mt-2",children:i.days_until_next_admin!==null&&i.days_until_next_admin<=0?r("comparison.nextAdminNow",{date:new Date(i.next_admin_due_at).toLocaleDateString("es")}):r("comparison.nextAdminInDays",{count:i.days_until_next_admin??0,date:new Date(i.next_admin_due_at).toLocaleDateString("es")})}):null]}),t.jsx("button",{type:"button",onClick:a,"aria-label":r("common:acciones.cerrar"),className:"text-bark-muted hover:text-bark",children:t.jsx(nr,{size:18,strokeWidth:1.5})})]}),o?t.jsx("p",{className:"text-small text-bark-muted",children:o}):u?t.jsx("p",{className:"text-small text-bark-muted py-8",children:r("comparison.allIncomplete")}
64):g.length===0?t.jsx("p",{className:"text-small text-bark-muted py-8",children:r("comparison.needsNumeric")}):t.jsx("div",{className:"h-72",children:t.jsx(hl,{width:"100%",height:"100%",children:t.jsxs(bl,{data:d,margin:{top:10,right:24,left:0,bottom:0},children:[t.jsx(yl,{strokeDasharray:"3 3",stroke:"#1A1A1A",opacity:.08}),t.jsx(gl,{dataKey:"date",stroke:"#1A1A1A",fontSize:11}),t.jsx(kl,{stroke:"#1A1A1A",fontSize:11}),t.jsx(vl,{contentStyle:{background:"#FCFBF7",border:"1px solid rgba(26,26,26,0.15)",fontSize:"12px"}}),t.jsx(wn,{wrapperStyle:{fontSize:"11px",textTransform:"uppercase"}}),g.map((m,f)=>t.jsx(jl,{type:"monotone",dataKey:m.key,name:m.label,stroke:Js[f%Js.length],strokeWidth:1.5,dot:{r:3}},m.key))]})})}),i?t.jsxs("table",{className:"w-full mt-6 text-small",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"text-tiny uppercase tracking-widest text-bark-muted border-b border-bark/10",children:[t.jsx("th",{className:"text-left py-2",children:r("comparison.dateColumn")}),g.map(m=>t.jsx("th",{className:"text-right py-2",children:m.label},m.key))]})}),t.jsx("tbody",{children:d.map(m=>t.jsxs("tr",{className:"border-b border-bark/5",children:[t.jsx("td",{className:"py-2 text-bark",children:m.date}),g.map(f=>t.jsx("td",{className:"text-right py-2 text-bark-muted",children:m[f.key]!==null&&m[f.key]!==void 0?String(m[f.key]):"—"},f.key))]},String(m.date)))})]}):null]})})}function Hu({patientId:e}){const{t:s}=W("evaluaciones"),[a,r]=p.useState([]),[n,i]=p.useState([]),[l,o]=p.useState(!0),[c,d]=p.useState(!1),[g,u]=p.useState(null),m=p.useCallback(async()=>{o(!0);try{const[h,T]=await Promise.all([Cr(e),Er()]);r(h),i(T)}catch(h){F.error(K(h,s("block.loadError")))}finally{o(!1)}},[e,s]);p.useEffect(()=>{m()},[m]);const f=p.useMemo(()=>new Map(n.map(h=>[h.id,h])),[n]),y=p.useMemo(()=>{const h=new Map;for(const T of a){if(T.status==="archived")continue;const x=h.get(T.test_id)??[];x.push(T),h.set(T.test_id,x)}return h},[a]);async function _(h){try{await Ri(h),await m(),F.success(s("block.archived"))}catch(T){F.error(K(T,s("block.archiveError")))}}return t.jsxs("section",{className:"space-y-6 mt-12 border-t border-bark/10 pt-10",children:[t.jsxs("header",{className:"flex flex-wrap items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:s("block.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-1",children:a.length===0?s("block.subtitleEmpty"):a.length===1?s("block.subtitleOne"):s("block.subtitleMany",{count:a.length})})]}),t.jsxs("button",{type:"button",onClick:()=>d(!0),className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors",children:[t.jsx(Lt,{size:14,strokeWidth:1.5})," ",s("block.new")]})]}),l?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted py-8",children:s("block.loading")}):a.length===0?t.jsx("div",{className:"text-center py-12 border border-dashed border-bark/15 rounded-lg",children:t.jsx("p",{className:"text-body text-bark mt-3",children:s("block.empty")})}):t.jsx("ul",{className:"space-y-3",children:Array.from(y.entries()).map(([h,T])=>{const x=f.get(h);return t.jsxs("li",{className:"border border-bark/10 rounded-md p-4 bg-bone",children:[t.jsxs("header",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("h4",{className:"text-body text-bark font-sans",children:[(x==null?void 0:x.code)??"—"," · ",(x==null?void 0:x.name)??s("block.unknownTest")]}),t.jsx("p",{className:"text-tiny text-bark-muted mt-1",children:T.length===1?s("block.summaryOne",{date:new Date(T[0].administered_at).toLocaleDateString("es",{day:"2-digit",month:"short",year:"numeric"})}):s("block.summaryMany",{count:T.length,date:new Date(T[0].administered_at).toLocaleDateString("es",{day:"2-digit",month:"short",year:"numeric"})})})]}),T.length>1?t.jsxs("button",{type:"button",onClick:()=>u(h),className:"inline-flex items-center gap-1 text-tiny uppercase tracking-widest text-bark-muted hover:text-bark",children:[t.jsx(Ml,{size:12,strokeWidth:1.5}),s("block.compare")]}):null]}),t.jsx("ul",{className:"mt-3 space-y-1",children:T.map(P=>t.jsxs("li",{className:"text-small text-bark flex items-center justify-between border-t border-bark/5 pt-2",children:[t.jsxs("span",{children:[new Date(P.administered_at).toLocaleDateString("es",{day:"2-digit",month:"long",year:"numeric"}),P.scoring_method?` · ${P.scoring_method}`:""]}),t.jsx("button",{type:"button",onClick:()=>void _(P.id),className:"text-tiny uppercase tracking-widest text-bark-muted hover:text-bark",children:s("block.archive")})]},P.id))})]},h)})}),c?t.jsx(Xi,{patientId:e,tests:n,onClose:()=>d(!1),onCreated:()=>{d(!1),m()}}):null,g?t.jsx(Wu,{patientId:e,testId:g,onClose:()=>u(null)}):null]})}function Ku({patient:e}){const{t:s}=W("evaluaciones"),a=p.useCallback(()=>bt({category:"evaluaciones",patient:e.id,sort:"created_at",dir:"desc"}
64),[e.id]),r=`library.files.evaluaciones:${e.id}`,{data:n,loading:i,error:l,refetch:o}=$t(r,a),c=n??[];async function d(g){if(await fe({title:s("tab.deleteTitle"),description:s("tab.deleteBody",{name:g.title||g.filename}),confirmLabel:s("common:acciones.eliminar"),destructive:!0}))try{await Mt(g.id),mt("library."),await o(),F.success(s("tab.deleted"))}catch(m){F.error(K(m,s("tab.deleteError")))}}return t.jsxs("section",{className:"space-y-6",children:[t.jsxs("header",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:s("tab.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-1",children:s("tab.subtitle")})]}),t.jsxs("div",{children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-3",children:s("tab.files")}),i&&c.length===0?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("common:estados.cargando")}):l?t.jsx("p",{className:"text-small text-clay",children:l.message||s("tab.loadError")}):c.length===0?t.jsx(qu,{}):t.jsx(Rt,{files:c,onDelete:g=>void d(g)})]}),t.jsx(Hu,{patientId:e.id})]})}function qu(){const{t:e}=W("evaluaciones");return t.jsxs("div",{className:"text-center py-12 border border-dashed border-bark/15 rounded-lg",children:[t.jsx(_l,{size:24,strokeWidth:1.5,className:"mx-auto text-bark-muted"}),t.jsx("p",{className:"text-body text-bark mt-3",children:e("tab.emptyTitle")}),t.jsx("p",{className:"text-tiny text-bark-muted mt-1",children:e("tab.emptyHint")})]})}function Gu({patient:e,profile:s}){const{t:a}=W("pagos"),r=N=>a(`register.methods.${N==="mercadopago"?"mercadoPago":N}`),[n,i]=p.useState([]),[l,o]=p.useState([]),[c,d]=p.useState(!0),[g,u]=p.useState(null),[m,f]=p.useState("all"),[y,_]=p.useState(()=>new Date().getFullYear()),[h,T]=p.useState(()=>new Date().getMonth()),x=(s==null?void 0:s.currency)??"USD",P=(s==null?void 0:s.default_session_price)??0;p.useEffect(()=>{let N=!1;return d(!0),u(null),Promise.all([or({patientId:e.id}),_r({patientId:e.id})]).then(([R,X])=>{N||(i(R),o(X))}).catch(R=>{N||u(K(R,a("page.loadError")))}).finally(()=>{N||d(!1)}),()=>{N=!0}},[e.id,a]);const S=p.useMemo(()=>m==="all"?n:n.filter(N=>{const R=new Date(N.scheduled_start);return m==="year"?R.getFullYear()===y:R.getFullYear()===y&&R.getMonth()===h}),[n,m,y,h]);p.useMemo(()=>new Set,[]);const L=p.useMemo(()=>new Set(l.filter(N=>N.status==="paid").map(N=>N.session_id)),[l]),I=p.useMemo(()=>{const N=new Map;for(const R of l)R.status==="paid"&&N.set(R.session_id,R);return N},[l]),v=S.filter(N=>ft(N.status)),O=v.filter(N=>L.has(N.id)),k=v.filter(N=>!L.has(N.id)),E=O.reduce((N,R)=>{const X=I.get(R.id);return N+Number((X==null?void 0:X.amount)??R.amount??P)},0),A=k.reduce((N,R)=>N+Number(R.amount??P),0),D=p.useMemo(()=>{const N=new Map;for(const X of O){const Z=I.get(X.id);Z&&N.set(Z.method,(N.get(Z.method)??0)+1)}const R=Array.from(N.entries()).sort((X,Z)=>Z[1]-X[1])[0];return R?`${r(R[0])} · ${R[1]}`:"—"},[O,I,a]);function C(){nn({patient:e,profile:s,sessions:n,payments:l,defaultPrice:P,currency:x})}return c?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:a("pagosTab.loading")}):g?t.jsx("p",{className:"text-small text-clay",children:g}):n.length===0?t.jsxs("div",{className:"text-center py-16 border border-dashed border-bark/15 rounded-lg",children:[t.jsx("p",{className:"text-body text-bark",children:a("pagosTab.empty")}),t.jsx("p",{className:"text-tiny text-bark-muted mt-2",children:a("pagosTab.emptyHint")})]}):t.jsxs("section",{className:"space-y-8",children:[t.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:a("pagosTab.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-1",children:a("pagosTab.subtitle",{name:e.first_name})})]}),t.jsxs("button",{type:"button",onClick:C,disabled:O.length===0&&k.length===0,title:a("pagosTab.downloadTitle"),className:"inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-bark/5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:[t.jsx(as,{size:14,strokeWidth:1.5})," ",a("header.download")]})]}
64),t.jsxs("nav",{"aria-label":a("pagosTab.filtersAria"),className:"flex flex-wrap items-center gap-2",children:[t.jsx($a,{active:m==="all",onClick:()=>f("all"),children:a("pagosTab.filterAll")}),t.jsx($a,{active:m==="year",onClick:()=>f("year"),children:a("pagosTab.filterYear")}),t.jsx($a,{active:m==="month",onClick:()=>f("month"),children:a("pagosTab.filterMonth")}),m!=="all"?t.jsx("select",{value:y,onChange:N=>_(Number(N.target.value)),className:"h-8 px-4 text-tiny uppercase tracking-widest border border-bark/20 rounded-full bg-bone text-bark",children:Array.from({length:6},(N,R)=>{const X=new Date().getFullYear()-R;return t.jsx("option",{value:X,children:X},X)})}):null,m==="month"?t.jsx("select",{value:h,onChange:N=>T(Number(N.target.value)),className:"h-8 px-4 text-tiny uppercase tracking-widest border border-bark/20 rounded-full bg-bone text-bark",children:Array.from({length:12},(N,R)=>t.jsx("option",{value:R,children:new Date(2024,R,1).toLocaleDateString("es",{month:"long"})},R))}):null]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[t.jsx(Ma,{label:a("pagosTab.metricPaid"),value:Jt(E,x),accent:"forest"}),t.jsx(Ma,{label:a("pagosTab.metricPending"),value:Jt(A,x),accent:"terracotta"}),t.jsx(Ma,{label:a("pagosTab.metricTopMethod"),value:D})]}),k.length>0?t.jsxs("div",{className:"bg-bone border border-bark/10 rounded-md p-6",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb-4",children:a("pagosTab.pendingHeading",{count:k.length})}),t.jsx("ul",{className:"space-y-2",children:k.map(N=>t.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-3 py-2 border-b border-bark/5 last:border-b-0",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-small text-bark",children:de(N.scheduled_start)}),t.jsxs("p",{className:"text-tiny text-bark-muted",children:[N.duration_minutes," min · ",ua(N.status)]})]}),t.jsx("p",{className:"text-small text-bark font-mono",children:Jt(Number(N.amount??P),x)})]},N.id))})]}):null,O.length>0?t.jsxs("div",{className:"bg-bone border border-bark/10 rounded-md p-6",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-forest mb-4",children:a("pagosTab.paidHeading",{count:O.length})}),t.jsx("ul",{className:"space-y-2",children:O.slice().sort((N,R)=>R.scheduled_start.localeCompare(N.scheduled_start)).map(N=>{const R=I.get(N.id);return t.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-3 py-2 border-b border-bark/5 last:border-b-0",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-small text-bark",children:de(N.scheduled_start)}),t.jsxs("p",{className:"text-tiny text-bark-muted",children:[R?r(R.method):a("pagosTab.paidFallback"),R!=null&&R.paid_at?t.jsxs("span",{className:"ml-2 text-bark-muted/70",children:["· ",de(R.paid_at)]}):null,R!=null&&R.notes?t.jsxs("span",{className:"ml-2 italic text-bark-muted/70",children:["· ",R.notes]}):null]})]}),t.jsx("p",{className:"text-small text-bark font-mono",children:Jt(Number((R==null?void 0:R.amount)??N.amount??P),x)})]},N.id)})})]}):null,O.length===0&&k.length===0?t.jsx("p",{className:"text-small text-bark-muted text-center py-12",children:a("pagosTab.emptyPeriod")}):null]})}function $a({active:e,onClick:s,children:a}){return t.jsx("button",{type:"button",onClick:s,className:`h-8 px-4 text-tiny uppercase tracking-widest rounded-full border transition-colors ${e?"border-terracotta text-terracotta":"border-bark/20 text-bark-muted hover:text-bark"}`,children:a})}function Ma({label:e,value:s,accent:a}){const r=a==="forest"?"text-forest":a==="terracotta"?"text-terracotta":"text-bark";return t.jsxs("div",{className:"border border-bark/10 rounded-md p-5 bg-bone",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-2",children:e}),t.jsx("p",{className:`text-h2 font-sans ${r}`,children:s})]})}function Jt(e,s){if(!e||Number.isNaN(e))return`0 ${s}`;try{return e.toLocaleString("es",{style:"currency",currency:s,maximumFractionDigits:0})}catch{return`${e.toFixed(0)} ${s}`}}function Yu({patient:e}){const{t:s}=W("pacientes"),[a,r]=at(`documentos:${e.id}`,"grid"),[n,i]=p.useState(!1),l=p.useCallback(()=>bt({category:"documentos_paciente",patient:e.id,sort:"created_at",dir:"desc"}),[e.id]),o=`library.files.documentos_paciente:${e.id}`,{data:c,loading:d,error:g,refetch:u}=$t(o,l),m=c??[];async function f(_){if(await fe({title:s("documentos.deleteTitle"),description:s("documentos.deleteBody",{name:_.title||_.filename}),confirmLabel:s("common:acciones.eliminar"),destructive:!0}))try{await Mt(_.id),mt("library."),await u(),F.success(s("documentos.deletedToast"))}catch(T){F.error(K(T,s("documentos.deleteError")))}}function y(){mt("library."),u(),i(!1),F.success(s("documentos.addedToast"))}return t.jsxs("section",{className:"space-y-6",children:[t.jsxs("header",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:s("tabs.documentos")}),t.jsx("p",{className:"text-small text-bark-muted mt-1 max-w-lg leading-relaxed",children:s("documentos.description",{name:e.first_name})})]}),t.jsxs("button",{type:"button",onClick:()=>i(!0),className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors shrink-0",children:[t.jsx(ss,{size:14,strokeWidth:1.5})," ",s("documentos.upload")]})]}),m.length>0?t.jsx("div",{className:"flex items-center",children:t.jsx("div",{className:"ml-auto",children:t.jsx(tt,{value:a,onChange:r,ariaLabel:s("documentos.viewToggle")})})}):null,d&&m.length===0?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("common:estados.cargando")}):g?t.jsx("p",{className:"text-small text-clay",children:g.message||s("documentos.loadError")}):m.length===0?t.jsx(Xu,{onUploadClick:()=>i(!0)}):a==="grid"?t.jsx(Rt,{files:m,onDelete:_=>void f(_)}):t.jsx(rs,{files:m,onDelete:_=>void f(_)}),t.jsx(Gi,{open:n,onClose:()=>i(!1),onUploaded:y,defaultCategory:"documentos_paciente",defaultPatientId:e.id,lockCategory:!0})]})}function Xu({onUploadClick:e}){const{t:s}=W("pacientes");return t.jsxs("div",{className:"text-center py-16 border border-dashed border-bark/15 rounded-lg",children:[t.jsx(Qa,{size:24,strokeWidth:1.5,className:"mx-auto text-bark-muted"}),t.jsx("p",{className:"text-body text-bark mt-3",children:s("documentos.emptyTitle")}),t.jsx("p",{className:"text-tiny text-bark-muted mt-2 max-w-md mx-auto leading-relaxed",children:s("documentos.emptyBody")}),t.jsxs("button",{type:"button",onClick:e,className:"mt-6 inline-flex items-center gap-2 border border-bark/30 text-bark uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-bark/5 transition-colors",children:[t.jsx(ss,{size:14,strokeWidth:1.5})," ",s("documentos.emptyUpload")]})]})}const Qs={assigned:"bg-bark/10 text-bark",viewed:"bg-bark/10 text-bark",in_progress:"bg-terracotta/15 text-terracotta",completed:"bg-forest/15 text-forest",returned:"bg-terracotta/15 text-terracotta",overdue:"bg-terracotta/15 text-terracotta",cancelled:"bg-bark/15 text-bark-muted"};function Zu(e,s){if(!e)return s("due.none");const a=new Date(`${e}T23:59:59`),r=new Date,n=Math.round((a.getTime()-r.getTime())/(1e3*60*60*24));return n===0?s("due.today"):n===1?s("due.tomorrow"):n>0?s("due.inDays",{count:n}):s("due.overdue",{count:Math.abs(n)})}function Ju({patientId:e,patientFirstName:s}){const{t:a}=W("tareas"),[r,n]=p.useState([]),[i,l]=p.useState(!0),[o,c]=p.useState("active"),[d,g]=at("tareas","list"),[u,m]=p.useState(!1),f=p.useCallback(async()=>
64{l(!0);try{n(await Nr(e))}catch(S){F.error(K(S,a("errors.load")))}finally{l(!1)}},[e,a]);p.useEffect(()=>{f()},[f]);const y=p.useMemo(()=>o==="all"?r:o==="completed"?r.filter(S=>S.status==="completed"||S.status==="returned"):r.filter(S=>S.status!=="completed"&&S.status!=="returned"&&S.status!=="cancelled"),[r,o]);async function _(S){const L=Li(S.access_token);try{await navigator.clipboard.writeText(L),F.success(a("share.copied"))}catch{F.error(a("share.copyError"))}}function h(S){const L=Di(S.access_token,a("share.whatsappMessage",{name:s}));window.open(L,"_blank","noopener")}async function T(S){if(await fe({title:a("regenerate.confirmTitle"),description:a("regenerate.confirmBody"),confirmLabel:a("regenerate.confirm"),cancelLabel:a("common:acciones.cancelar")}))try{const I=await Oi(S.id);n(v=>v.map(O=>O.id===S.id?I:O)),F.success(a("regenerate.success"))}catch(I){F.error(K(I,a("regenerate.error")))}}async function x(S){if(await fe({title:a("cancel.confirmTitle"),description:a("cancel.confirmBody"),confirmLabel:a("cancel.confirm"),cancelLabel:a("common:acciones.volver"),destructive:!0}))try{const I=await $i(S.id);n(v=>v.map(O=>O.id===S.id?I:O)),F.success(a("cancel.success"))}catch(I){F.error(K(I,a("cancel.error")))}}function P(S){const L=S.status,I=Qs[L]??Qs.assigned;return t.jsxs("article",{className:"border border-bark/10 rounded-md p-4 bg-bone hover:border-bark/30 transition-colors",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h4",{className:"text-body text-bark font-sans truncate",children:S.title}),t.jsxs("p",{className:"text-tiny text-bark-muted mt-1",children:[S.task_type?Pi[S.task_type]:a("card.noType")," ·"," ",Sr[S.frequency]," · ",Zu(S.due_date,a)]})]}),t.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-tiny uppercase tracking-widest ${I}`,children:Ai[S.status]})]}),S.description?t.jsx("p",{className:"text-small text-bark mt-3 line-clamp-2",children:S.description}):null,S.source_activity_id?t.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-tiny uppercase tracking-widest text-bark-muted",children:[t.jsx(lr,{size:12,strokeWidth:1.5})," ",a("card.fromActivity")]}):null,t.jsxs("footer",{className:"mt-3 flex flex-wrap gap-3 text-tiny uppercase tracking-widest",children:[t.jsxs("button",{type:"button",onClick:()=>void _(S),className:"inline-flex items-center gap-1 text-bark-muted hover:text-bark",children:[t.jsx(dt,{size:12,strokeWidth:1.5})," ",a("card.copyLink")]}),t.jsxs("button",{type:"button",onClick:()=>h(S),className:"inline-flex items-center gap-1 text-bark-muted hover:text-bark",children:[t.jsx(ns,{size:12,strokeWidth:1.5})," WhatsApp"]}),S.status!=="cancelled"?t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",onClick:()=>void T(S),className:"inline-flex items-center gap-1 text-bark-muted hover:text-bark",children:[t.jsx(Sl,{size:12,strokeWidth:1.5})," ",a("card.regenerate")]}),t.jsxs("button",{type:"button",onClick:()=>void x(S),className:"inline-flex items-center gap-1 text-bark-muted hover:text-bark",children:[t.jsx(Ll,{size:12,strokeWidth:1.5})," ",a("common:acciones.cancelar")]})]}):null]})]},S.id)}return t.jsxs("section",{className:"space-y-6",children:[t.jsxs("header",{className:"flex flex-wrap items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:a("tab.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-1",children:r.length===0?a("tab.emptyAll"):r.length===1?a("tab.countOne",{count:r.length}):a("tab.countMany",{count:r.length})})]}),t.jsxs("button",{type:"button",onClick:()=>m(!0),className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors shrink-0",children:[t.jsx(Lt,{size:14,strokeWidth:1.5})," ",a("tab.newTask")]})]}),r.length>0?t.jsx("div",{className:"flex items-center",children:t.jsx("div",{className:"ml-auto",children:t.jsx(tt,{value:d,onChange:g,ariaLabel:a("viewToggleAria")})})}):null,t.jsx("div",{className:"flex items-center gap-2",children:["active","completed","all"].map(S=>{const L=o===S,I=a(S==="active"?"filters.active":S==="completed"?"filters.completed":"filters.all");return t.jsx("button",{type:"button",onClick:()=>c(S),className:`h-7 px-3 text-tiny uppercase tracking-widest rounded-full transition-colors ${L?"bg-bark text-linen":"text-bark-muted hover:bg-bark/5 hover:text-bark"}`,children:I},S)})}),i?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted py-8",children:a("common:estados.cargando")}):y.length===0?t.jsx("div",{className:"text-center py-12 border border-dashed border-bark/15 rounded-lg",children:t.jsx("p",{className:"text-body text-bark mt-3",children:a("tab.emptyFilter")})}):d==="grid"?t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:y.map(P)}):t.jsx("ul",{className:"space-y-3",children:y.map(P)}),u?t.jsx(Nl,{patientId:e,onClose:()=>m(!1),onCreated:S=>{n(L=>[S,...L]),m(!1)}}):null]})}function Qu({patientId:e}){const{t:s}=W("alertas"),{alerts:a,loading:r,error:n,reload:i}=Vi(e);return t.jsxs("section",{className:"space-y-6",children:[t.jsxs("header",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:s("tab.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-1",children:s("tab.description")})]}),r&&a.length===0?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("page.loading")}):n?t.jsx("p",{className:"text-small text-clay",children:n}):t.jsx(Ii,{alerts:a,onMutate:()=>void i()})]})}function em(e){return new Date(e).toLocaleDateString("es",{day:"2-digit",month:"short",year:"numeric"})}function tm({patient:e}){const{t:s}=W("analisis"),[a,r]=p.useState([]),[n,i]=p.useState(null),[l,o]=p.useState(!0),[c,d]=p.useState(null),g=p.useCallback(async()=>{o(!0),d(null);try{const[u,m]=await Promise.all([Cl(e.id),El(e.id)]);r(u),i(m)}catch(u){const m=K(u,s("errors.loadListFailed"));d(m),F.error(m)}finally{o(!1)}},[e.id,s]);return p.useEffect(()=>{g()},[g]),t.jsxs("section",{className:"space-y-6",children:[t.jsxs("header",{className:"flex flex-wrap items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:s("tab.title")}),t.jsx("p",{className:"text-small text-bark-muted mt-1 max-w-xl leading-relaxed",children:s("tab.intro")})]}),n!=null&&n.eligible?t.jsxs(Pe,{to:`/dashboard/analisis/nuevo?patient_id=${e.id}`,className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors",children:[t.jsx(ht,{size:14,strokeWidth:1.5})," ",s("newAnalysis")]}):null]}),l?t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("common:estados.cargando")}):c?t.jsx("p",{className:"text-small text-clay",children:c}):n&&!n.eligible?t.jsx(am,{prereq:n}):a.length===0?t.jsx(sm,{patientId:e.id}):t.jsx("ul",{className:"divide-y divide-bark/10 border-y border-bark/10",children:a.map(u=>t.jsx("li",{children:t.jsxs(Pe,{to:`/dashboard/analisis/${u.id}`,className:"flex items-center gap-4 px-1 py-3 hover:bg-bark/[0.03] transition-colors",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("p",{className:"text-body text-bark truncate",children:u.lens_book_title??s("dataOnlyMode")}),t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mt-1",children:[em(u.created_at),u.custom_focus?s("tab.focusPrefix",{focus:u.custom_focus.slice(0,60)}):""]})]}),t.jsx(ir,{size:14,strokeWidth:1.5,className:"text-bark-muted"})]})},u.id))})]})}function am({prereq:e}){const{t:s}=W("analisis"),a=e.sessions_count>=e.sessions_required,r=e.library_ready_count>0;return t.jsxs("div",{className:"border border-bark/15 rounded-md p-6 bg-bone space-y-3 max-w-xl",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:s("prereq.title")}),t.jsxs("ul",{className:"space-y-1 text-small text-bark",children:[t.jsxs("li",{children:[r?"✓":"✗"," ",s("prereq.libraryReq",{count:e.library_ready_count})]}),t.jsxs("li",{children:[a?"✓":"✗"," ",s("prereq.sessionsReq",{required:e.sessions_required,
64count:e.sessions_count})]})]}),r?null:t.jsxs(Pe,{to:"/dashboard/biblioteca",className:"inline-flex items-center gap-1 text-tiny uppercase tracking-widest text-terracotta hover:text-bark",children:[s("prereq.goToLibrary")," →"]})]})}function sm({patientId:e}){const{t:s}=W("analisis");return t.jsxs("div",{className:"text-center py-12 border border-dashed border-bark/15 rounded-lg max-w-xl mx-auto",children:[t.jsx("p",{className:"text-body text-bark",children:s("tab.emptyTitle")}),t.jsx("p",{className:"text-tiny text-bark-muted mt-2",children:s("tab.emptyHint")}),t.jsxs(Pe,{to:`/dashboard/analisis/nuevo?patient_id=${e}`,className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 mt-4 hover:bg-terracotta hover:text-linen transition-colors",children:[t.jsx(ht,{size:14,strokeWidth:1.5})," ",s("newAnalysis")]})]})}const er=[{id:"resumen",labelKey:"tabs.resumen"},{id:"actividades",labelKey:"tabs.actividades"},{id:"alertas",labelKey:"tabs.alertas"},{id:"analisis",labelKey:"tabs.analisis"},{id:"compartir",labelKey:"tabs.compartir"},{id:"contactos",labelKey:"tabs.contactos"},{id:"tareas",labelKey:"tabs.deberes"},{id:"documentos",labelKey:"tabs.documentos"},{id:"evaluaciones",labelKey:"tabs.evaluaciones"},{id:"informes",labelKey:"tabs.informes"},{id:"notas",labelKey:"tabs.notas"},{id:"pagos",labelKey:"tabs.pagos"},{id:"planificacion",labelKey:"tabs.planificacion"},{id:"sesiones",labelKey:"tabs.sesiones"}];function fp(){const{t:e}=W("pacientes"),{id:s}=qn(),a=Ot(),[r,n]=p.useState(null),[i,l]=p.useState([]),[o,c]=p.useState([]),[d,g]=p.useState([]),[u,m]=p.useState(null),[f,y]=p.useState(null),[_,h]=p.useState(!0),[T,x]=p.useState(null),[P,S]=p.useState(!1),[L,I]=Gn(),v=L.get("tab")??"",O=er.some(G=>G.id===v)?v:"resumen",[k,E]=p.useState(O),A=p.useCallback(G=>{E(G);const Q=new URLSearchParams(L);G==="resumen"?Q.delete("tab"):Q.set("tab",G),I(Q,{replace:!0})},[L,I]),[D,C]=p.useState(!1),[N,R]=p.useState(!1),[X,Z]=p.useState(null),[Ne,ne]=p.useState(!1),[he,Ve]=p.useState(null),[Ie,Se]=p.useState(0),Be=p.useRef(!1),xe=p.useCallback(async()=>{if(!s)return;h(!0),x(null);let G;try{G=await ci(s)}catch(Ge){x(K(Ge,e("detail.loadError"))),Be.current&&F.error(e("detail.partialLoadError")),h(!1);return}if(!G){S(!0),n(null),h(!1);return}n(G),Be.current=!0,S(!1);const[Q,Oe,jt,qe,nt]=await Promise.all([or({patientId:s}).catch(()=>null),pr(s).catch(()=>null),_r({patientId:s}).catch(()=>null),Yn().catch(()=>null),Fa(s).catch(()=>null)]);Q&&l(Q),Oe&&c(Oe),jt&&g(jt),qe&&y(qe),nt&&m(nt),(Q===null||Oe===null||jt===null||qe===null||nt===null)&&F.error(e("detail.partialLoadError")),Se(Ge=>Ge+1),h(!1)},[s,e]),Ke=p.useCallback(async()=>{if(s)try{const G=await Fa(s);m(G),Se(Q=>Q+1)}catch{}},[s]);p.useEffect(()=>{xe()},[xe]);async function rt(){if(!(!r||!await fe({title:e("detail.deleteTitle"),description:e("detail.deleteBody",{firstName:r.first_name,lastName:r.last_name}),confirmLabel:e("detail.deleteConfirm"),cancelLabel:e("detail.deleteCancel"),destructive:!0})))try{await di(r.id),F.success(e("detail.deletedToast")),a("/dashboard/pacientes")}catch(Q){F.error(K(Q,e("detail.deleteError")))}}const Ce=p.useCallback(G=>{const Q=i.find(Oe=>Oe.id===G);Q&&Z(Q)},[i]),De=p.useCallback(()=>{if(i.length===0){Ve({kind:"standalone",occurredAt:new Date().toISOString()});return}ne(!0)},[i.length]),ya=p.useCallback(G=>{ne(!1),G.mode==="session"?Z(G.session):Ve({kind:G.kind,occurredAt:G.occurredAt})},[]);if(_&&!r)return t.jsx(t.Fragment,{children:t.jsx("div",{className:"px-5 py-10 lg:px-12 lg:py-16",children:t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted",children:e("detail.loading")})})});if(P&&!r)return t.jsx(t.Fragment,{children:t.jsxs("div",{className:"px-5 py-10 lg:px-12 lg:py-16",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-2",children:e("detail.notFoundMarker")}),t.jsx("h1",{className:"text-h1 font-sans text-bark mb-4",children:e("detail.notFoundTitle")}),t.jsx("p",{className:"text-body text-bark-muted mb-8",children:e("detail.notFoundBody")}),t.jsx(Pe,{to:"/dashboard/pacientes",className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark",children:e("detail.backToPatients")})]})});if(T&&!r)return t.jsx(t.Fragment,{children:t.jsxs("div",{className:"px-5 py-10 lg:px-12 lg:py-16",children:[t.jsx("p",{className:"text-tiny uppercase tracking-widest text-bark-muted mb-2",children:e("detail.loadErrorMarker")}),t.jsx("h1",{className:"text-h1 font-sans text-bark mb-4",children:e("detail.loadError")}),t.jsx("p",{className:"text-body text-bark-muted mb-8",children:e("detail.loadErrorBody")}),t.jsxs("div",{className:"flex items-center gap-6",children:[t.jsx("button",{type:"button",onClick:()=>void xe(),disabled:_,className:"text-tiny uppercase tracking-widest text-terracotta hover:text-bark disabled:opacity-50",children:e("detail.retry")}),t.jsx(Pe,{to:"/dashboard/pacientes",className:"text-tiny uppercase tracking-widest text-bark-muted hover:text-bark",children:e("detail.backToPatients")})]})]})});if(!r)return null;
64const zt=(f==null?void 0:f.currency)??"USD",Ut=i.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-5 py-8 lg:px-12 lg:py-12",children:[t.jsx(Pe,{to:"/dashboard/pacientes",className:"text-tiny uppercase tracking-widest text-bark-muted hover:text-bark",children:e("detail.backShort")}),t.jsx("div",{className:"mt-6 mb-12",children:t.jsx(wc,{patient:r,totalSessions:Ut,contacts:u??void 0,onNewSession:()=>R(!0),onEdit:()=>C(!0),onDelete:rt,onStatusChanged:G=>{n(G),Se(Q=>Q+1)}})}),t.jsx("nav",{className:"flex gap-2 mb-8 overflow-x-auto pb-2 border-b border-bark/10",children:er.map(G=>{const Q=k===G.id;return t.jsx("button",{type:"button",onClick:()=>A(G.id),className:`h-8 px-4 text-tiny uppercase tracking-widest whitespace-nowrap rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-terracotta ${Q?"bg-bark text-linen":"text-bark-muted hover:text-bark hover:bg-bark/5"}`,children:e(G.labelKey)},G.id)})}),t.jsxs("section",{children:[k==="resumen"&&t.jsx(gc,{patient:r,currency:zt,refreshKey:Ie,onNewSession:()=>R(!0),onNewNote:De,onOpenSession:G=>{const Q=i.find(Oe=>Oe.id===G);Q&&Z(Q)},onOpenNote:Ce,onGoToSessionsTab:()=>A("sesiones"),onGoToTareasTab:()=>A("tareas"),onGoToPagosTab:()=>A("pagos"),onGoToPlanificacionTab:()=>A("planificacion"),onGoToInformesTab:()=>A("informes"),onGoToEvaluacionesTab:()=>A("evaluaciones"),onGoToAlertasTab:()=>A("alertas"),onGoToNotasTab:()=>A("notas")}),k==="contactos"&&t.jsx(Ac,{patientId:r.id,initialContacts:u??void 0,onChanged:()=>void Ke(),isMinor:(()=>{const G=Za(r.date_of_birth);return G!==null&&G<18})()}),k==="sesiones"&&t.jsx(nc,{patient:r,sessions:i,payments:d,profile:f,onCreate:()=>R(!0),onChanged:()=>xe()}),k==="notas"&&t.jsx(rm,{notes:o,sessions:i,onOpen:G=>Z(G),onNewNote:De}),k==="compartir"&&t.jsx(Pd,{patient:r,contacts:u??[],onChanged:Ke}),k==="planificacion"&&t.jsx(Dd,{patient:r,sessions:i,onPatientChange:G=>n(G)}),k==="informes"&&t.jsx(Fd,{patient:r}),k==="actividades"&&t.jsx(Id,{patient:r}),k==="evaluaciones"&&t.jsx(Ku,{patient:r}),k==="pagos"&&t.jsx(Gu,{patient:r,profile:f}),k==="documentos"&&t.jsx(Yu,{patient:r}),k==="tareas"&&t.jsx(Ju,{patientId:r.id,patientFirstName:r.first_name??""}),k==="alertas"&&t.jsx(Qu,{patientId:r.id}),k==="analisis"&&t.jsx(tm,{patient:r})]})]}),t.jsx(Ho,{open:D,patient:r,contacts:u??[],onContactsChanged:()=>void Ke(),onClose:()=>C(!1),onUpdated:G=>{n(G),C(!1),Se(Q=>Q+1),F.success(e("detail.patientUpdated"))}}),t.jsx(Ci,{open:N,defaultPatientId:r.id,onClose:()=>R(!1),onCreated:G=>{l(Q=>[...Q,G]),R(!1),Se(Q=>Q+1),F.success(e("detail.sessionScheduled"))},onSeriesCreated:()=>{R(!1),Se(G=>G+1),xe()}}),X?t.jsx(ao,{session:X,onClose:()=>{Z(null),xe()}}):null,Ne?t.jsx(ro,{sessions:i,onCancel:()=>ne(!1),onSubmit:ya}):null,he?t.jsx(lo,{patient:r,kind:he.kind,occurredAt:he.occurredAt,onSaved:()=>{Ve(null),xe()},onClose:()=>Ve(null)}):null]})}function rm({notes:e,sessions:s,onOpen:a,onNewNote:r}){const{t:n}=W("pacientes"),i=p.useMemo(()=>new Map(s.map(m=>[m.id,m])),[s]),[l,o]=at("notas","list"),c=p.useMemo(()=>{const m=_=>{if(_.kind==="session"&&_.session_id){const h=i.get(_.session_id);if(h)return h.scheduled_start}return _.occurred_at},f=e.map(_=>({note:_,eff:m(_)})).sort((_,h)=>new Date(h.eff).getTime()-new Date(_.eff).getTime()),y=[];for(const{note:_,eff:h}of f){const T=new Date(h),x=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}`;let P=y.find(S=>S.key===x);P||(P={key:x,label:T.toLocaleDateString("es",{month:"long",year:"numeric"}).toUpperCase(),notes:[]},y.push(P)),P.notes.push(_)}return y},[e,i]);function d(m){const f=m.session_id?i.get(m.session_id):void 0,y=m.kind==="session"&&!!f,_=m.kind==="session"&&f?f.scheduled_start:m.occurred_at,h=m.privacy_level==="private_e2e"?n("detail.noteEncrypted"):(m.plain_content||"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().slice(0,400)||n("detail.noteNoContent");return{s:f,clickable:y,iso:_,preview:h,handleOpen:()=>{f&&m.kind==="session"&&a(f)}}}function g(m){const{s:f,clickable:y,preview:_,handleOpen:h}=d(m),T=m.kind==="session"&&f?`${de(f.scheduled_start)} · ${Fe(f.scheduled_start)}`:de(m.occurred_at);return t.jsxs("article",{className:`border border-bark/10 rounded-md p-4 bg-bone transition-colors ${y?"hover:border-bark/30 cursor-pointer":""}`,onClick:h,children:[t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-terracotta mb
64-1 flex items-center flex-wrap gap-2",children:[t.jsx("span",{children:T}),m.kind!=="session"?t.jsx(tr,{kind:m.kind}):null]}),t.jsx("p",{className:"text-small text-bark line-clamp-3",children:_})]},m.id)}function u(m){const{s:f,clickable:y,iso:_,preview:h,handleOpen:T}=d(m),x=new Date(_).toLocaleDateString("es",{day:"numeric",month:"short"}),P=m.kind==="session"&&f?Fe(f.scheduled_start):null;return t.jsx("li",{children:t.jsxs("div",{className:`flex items-start gap-4 py-3 transition-colors ${y?"cursor-pointer hover:bg-bark/5":""}`,onClick:T,children:[t.jsxs("div",{className:"w-20 shrink-0 tabular-nums",children:[t.jsx("p",{className:"text-small text-bark",children:x}),P?t.jsx("p",{className:"text-tiny text-bark-muted mt-0.5",children:P}):null]}),m.kind!=="session"?t.jsx("div",{className:"shrink-0 pt-0.5",children:t.jsx(tr,{kind:m.kind})}):null,t.jsx("p",{className:"text-small text-bark-muted line-clamp-2 flex-1 min-w-0",children:h})]})},m.id)}return t.jsxs("section",{className:"space-y-8",children:[t.jsxs("header",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-h3 font-sans text-bark",children:n("detail.notesSection")}),e.length>0?t.jsx("p",{className:"text-small text-bark-muted mt-1",children:n(e.length===1?"detail.notesCountOne":"detail.notesCountMany",{count:e.length})}):null]}),e.length>0?t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[t.jsx(tt,{value:l,onChange:o,ariaLabel:n("detail.notesViewToggle")}),t.jsxs("button",{type:"button",onClick:r,className:"inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors",children:[t.jsx(Lt,{size:14,strokeWidth:1.5})," ",n("detail.newNote")]})]}):null]}),e.length===0?t.jsxs("div",{className:"text-center py-16",children:[t.jsx("p",{className:"text-body text-bark",children:n("detail.notesEmpty")}),t.jsx("p",{className:"text-small text-bark-muted mt-2 max-w-md mx-auto",children:n("detail.notesEmptyBody")}),t.jsxs("button",{type:"button",onClick:r,className:"mt-6 inline-flex items-center gap-2 border border-terracotta text-terracotta uppercase tracking-widest text-tiny rounded-full px-5 py-2 hover:bg-terracotta hover:text-linen transition-colors",children:[t.jsx(Lt,{size:14,strokeWidth:1.5})," ",n("detail.newNote")]})]}):t.jsx("div",{className:"space-y-10",children:c.map(m=>t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsxs("p",{className:"text-tiny uppercase tracking-widest text-terracotta",children:["§ · ",m.label]}),t.jsx("div",{className:"mt-2 h-px w-full bg-bark/10"})]}),l==="grid"?t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:m.notes.map(f=>g(f))}):t.jsx("ul",{className:"divide-y divide-bark/10",children:m.notes.map(f=>u(f))})]},m.key))})]})}const nm={standalone:"bg-bark/10 text-bark",phone_call:"bg-terracotta/15 text-terracotta",supervision:"bg-forest/15 text-forest",observation:"bg-bark/15 text-bark-muted"};function tr({kind:e}){return t.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-tiny uppercase tracking-widest ${nm[e]}`,children:pt[e]})}export{fp as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.