/* Bernard Health SeniorCare V4.3.12 — estudios, resultados, recetas y urgencias */
(function(){
'use strict';
const db=()=>window.seniorcareSupabase;
const user=()=>window.currentUser||{};
const org=()=>user().organizationId||user().organization_id;
const role=()=>String(user().role||'');
const main=()=>window.main||document.getElementById('mainContent');
const esc=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
const toast=t=>window.showToast?.(t);
const header=(e,t,s)=>window.pageHeader?.(e,t,s)||`<h2>${esc(t)}</h2>`;
const fmt=d=>d?new Date(d).toLocaleString('es-CR'):'—';
let residents=[],orders=[],results=[],prescriptions=[];
const missing=e=>e?.code==='PGRST205'||/schema cache|could not find the table/i.test(String(e?.message||''));
async function q(table,build){const r=await build(db().from(table));if(r.error){if(missing(r.error))return[];throw r.error}return r.data||[]}
async function load(){
 residents=await q('seniorcare_residents',x=>x.select('*').eq('organization_id',org()).eq('active',true));
 orders=await q('seniorcare_medical_orders',x=>x.select('*').eq('organization_id',org()).eq('active',true).order('created_at',{ascending:false}));
 results=await q('seniorcare_medical_results',x=>x.select('*').eq('organization_id',org()).eq('active',true).order('result_date',{ascending:false}));
 for(const r of results){if(r.file_path){const sg=await db().storage.from('medical-results').createSignedUrl(r.file_path,3600);if(!sg.error)r.file_url=sg.data.signedUrl}}
 prescriptions=await q('seniorcare_medical_prescriptions',x=>x.select('*').eq('organization_id',org()).eq('active',true).order('issued_at',{ascending:false}));
}
const rname=r=>r?.full_name||r?.resident_name||r?.name||r?.data?.name||r?.data?.full_name||'Residente';
const resident=k=>residents.find(r=>String(r?.resident_key??r?.data?.resident_key??r?.id??r?.data?.id??'')===String(k));
const data=r=>r?.data||{};
const val=(r,...keys)=>{for(const k of keys){if(r?.[k]!=null&&r[k]!=='')return r[k];if(data(r)?.[k]!=null&&data(r)[k]!=='')return data(r)[k]}return''};
const dob=r=>val(r,'birth_date','date_of_birth','dob','fecha_nacimiento','birthDate');
const age=r=>{const direct=val(r,'age','edad');if(direct)return direct;const d=dob(r);if(!d)return'';const b=new Date(d),n=new Date();let a=n.getFullYear()-b.getFullYear();const m=n.getMonth()-b.getMonth();if(m<0||(m===0&&n.getDate()<b.getDate()))a--;return a};
const weight=r=>val(r,'weight','peso','weight_kg','peso_kg');
const phone=r=>val(r,'phone','mobile','cellphone','telefono','celular','responsible_phone','contact_phone');
const opts=()=>residents.length?residents.map(r=>`<option value="${esc(r?.resident_key??r?.data?.resident_key??r?.id??r?.data?.id??'')}">${esc(rname(r))}</option>`).join(''):'<option value="">No hay residentes activos</option>';
const patientHeader=r=>`<div class="medical-patient-header"><div><small>Paciente</small><strong>${esc(rname(r))}</strong></div><div><small>Fecha de nacimiento</small><strong>${esc(dob(r)||'No registrada')}</strong></div><div><small>Edad</small><strong>${esc(age(r)||'—')}</strong></div><div><small>Peso</small><strong>${esc(weight(r)?`${weight(r)} kg`:'—')}</strong></div><div><small>Celular</small><strong>${esc(phone(r)||'—')}</strong></div><div><small>Fecha actual</small><strong>${esc(new Date().toLocaleDateString('es-CR'))}</strong></div></div>`;
function printDoc(title,r,body){const w=open('','_blank');if(!w)return toast('El navegador bloqueó la ventana de impresión.');w.document.write(`<!doctype html><html><head><meta charset="utf-8"><title>${esc(title)}</title><style>body{font-family:Arial,sans-serif;color:#17324d;margin:30px}header{display:flex;justify-content:space-between;gap:20px;border-bottom:3px solid #6d36d7;padding-bottom:14px}.brand{font-size:24px;font-weight:700;color:#6d36d7}.meta{font-size:12px;color:#617083}.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:18px 0}.cell,.box{border:1px solid #dcd5ea;border-radius:10px;padding:10px}.box{white-space:pre-wrap;margin:10px 0}.foot{margin-top:35px;border-top:1px solid #ddd;padding-top:10px;font-size:11px;color:#687181}@media print{button{display:none}}</style></head><body><header><div><div class="brand">Bernard Health SeniorCare</div><div>${esc(title)}</div></div><div class="meta">${new Date().toLocaleString('es-CR')}</div></header><div class="grid"><div class="cell"><b>Paciente</b><br>${esc(rname(r))}</div><div class="cell"><b>Fecha de nacimiento</b><br>${esc(dob(r)||'No registrada')}</div><div class="cell"><b>Edad</b><br>${esc(age(r)||'—')}</div><div class="cell"><b>Peso</b><br>${esc(weight(r)?`${weight(r)} kg`:'—')}</div><div class="cell"><b>Celular</b><br>${esc(phone(r)||'—')}</div><div class="cell"><b>Fecha actual</b><br>${esc(new Date().toLocaleDateString('es-CR'))}</div></div>${body}<div class="foot">Documento clínico confidencial. Médico: ${esc(user().name||user().email||'')}</div><script>onload=()=>setTimeout(()=>print(),250)<\/script></body></html>`);w.document.close()}
const labs=['Hemograma completo','Glicemia','Hemoglobina glicosilada','Perfil lipídico','Función renal','Electrolitos','Pruebas hepáticas','Examen general de orina','Urocultivo','Proteína C reactiva','TSH y T4 libre','Coagulación','Vitamina B12','Vitamina D','Otro laboratorio'];
const images=['Radiografía de tórax','Radiografía de abdomen','Radiografía de columna','Radiografía de extremidad','Ultrasonido abdominal','Ultrasonido pélvico','Ultrasonido renal y vías urinarias','Ultrasonido de próstata','Doppler vascular','Tomografía','Resonancia magnética','Mamografía','Densitometría ósea','Otro estudio de imagen'];
window.renderMedicalStudies=async function(){
 try{await load()}catch(e){return toast(e.message)}
 const m=main(); if(!m)return;
 const choices=list=>list.map((x,i)=>`<label class="medical-study-option-v4353"><input type="checkbox" name="study_items" value="${esc(x)}"><span><b>${esc(x)}</b><small>Agregar a esta orden</small></span></label>`).join('');
 const orderStudies=o=>{const d=o.data||{};const arr=Array.isArray(d.study_names)?d.study_names.filter(Boolean):[];if(arr.length)return arr;const one=d.study_name||'';if(one)return [one];const match=String(o.detail||'').match(/(?:Exámenes?|Estudios?) solicitados?:\s*([^\n]+)/i);return match?match[1].split(/\s*;\s*|\s*,\s*/).filter(Boolean):[]};
 const studyText=o=>{const arr=orderStudies(o);return arr.length?arr.join(' · '):(o.detail||'')};
 m.innerHTML=header('EXÁMENES Y ESTUDIOS','Solicitudes diagnósticas','Seleccione varios exámenes o estudios y envíelos juntos en una sola orden')+`
 <form id="studyForm4312" class="form-card med-premium-form"><div class="form-grid">
 <label>Paciente<select name="resident_key" required>${opts()}</select></label>
 <label>Tipo<select name="order_type" id="studyType4312"><option value="Laboratorio">Laboratorio</option><option value="Imagen">Estudio de imagen</option></select></label>
 <label>Prioridad<select name="priority"><option>Normal</option><option>Preferente</option><option>Urgente</option></select></label>
 <div id="studyPatient4312" class="wide"></div>
 <fieldset class="wide medical-study-selector-v4353" id="labChoice4312"><legend>Exámenes de laboratorio</legend><p>Puede marcar varios exámenes para incluirlos en la misma orden.</p><div class="medical-study-grid-v4353">${choices(labs)}</div></fieldset>
 <label class="wide hidden" id="imageSummary4312">Resumen clínico<textarea name="clinical_summary" data-auto-grow placeholder="Información clínica relevante para Radiología"></textarea></label>
 <fieldset class="wide medical-study-selector-v4353 hidden" id="imageChoice4312"><legend>Estudios de imagen</legend><p>Puede marcar varios estudios para incluirlos en la misma orden.</p><div class="medical-study-grid-v4353">${choices(images)}</div></fieldset>
 <label class="wide hidden" id="otherStudy4312">Especifique el otro examen o estudio<input name="other_study" placeholder="Nombre del examen o estudio"></label>
 <label class="wide">Observaciones<textarea name="observations" data-auto-grow placeholder="Observaciones adicionales para toda la orden"></textarea></label>
 </div><div class="form-actions"><button class="primary-btn">Enviar solicitud</button></div></form>
 <section class="history-card"><h3>Solicitudes emitidas</h3>${orders.filter(o=>['Laboratorio','Imagen'].includes(o.order_type)).map(o=>`<article class="medical-record-card"><div><strong>${esc(rname(resident(o.resident_key)))} · ${esc(o.order_type)}</strong><span>${esc(studyText(o))}</span><small>${fmt(o.created_at)} · ${esc(o.priority||'Normal')}</small></div><button class="mini-btn" data-study-pdf="${o.id}">PDF</button></article>`).join('')||'<p>No hay solicitudes registradas.</p>'}</section>`;
 const form=document.getElementById('studyForm4312'),type=document.getElementById('studyType4312'),sel=form.elements.resident_key,labBox=document.getElementById('labChoice4312'),imageBox=document.getElementById('imageChoice4312'),imageSummary=document.getElementById('imageSummary4312'),otherWrap=document.getElementById('otherStudy4312');
 const drawPatient=()=>document.getElementById('studyPatient4312').innerHTML=patientHeader(resident(sel.value));
 const selectedValues=()=>[...form.querySelectorAll('input[name="study_items"]:checked')].map(x=>x.value);
 const updateOther=()=>{const selected=selectedValues();otherWrap.classList.toggle('hidden',!selected.some(x=>/^Otro /i.test(x)))};
 const toggle=()=>{const img=type.value==='Imagen';labBox.classList.toggle('hidden',img);imageSummary.classList.toggle('hidden',!img);imageBox.classList.toggle('hidden',!img);form.querySelectorAll('input[name="study_items"]').forEach(x=>{if((img&&!imageBox.contains(x))||(!img&&!labBox.contains(x)))x.checked=false});updateOther()};
 sel.onchange=drawPatient;type.onchange=toggle;form.addEventListener('change',e=>{if(e.target.matches('input[name="study_items"]'))updateOther()});drawPatient();toggle();window.BHSC_AUTO_GROW?.(m);
 form.onsubmit=async e=>{e.preventDefault();const f=new FormData(form),isImg=f.get('order_type')==='Imagen';let studies=selectedValues().filter(x=>!/^Otro /i.test(x));const other=String(f.get('other_study')||'').trim();if(selectedValues().some(x=>/^Otro /i.test(x))&&other)studies.push(other);studies=[...new Set(studies)];if(!studies.length){toast('Seleccione al menos un examen o estudio.');return}const summary=String(f.get('clinical_summary')||'').trim(),obs=String(f.get('observations')||'').trim();const list=studies.map((x,i)=>`${i+1}. ${x}`).join('\n');const detail=isImg?`Resumen clínico: ${summary||'Sin resumen adicional'}\nEstudios solicitados:\n${list}\nObservaciones: ${obs||'Sin observaciones'}`:`Exámenes solicitados:\n${list}\nObservaciones: ${obs||'Sin observaciones'}`;const row={organization_id:org(),resident_key:String(f.get('resident_key')),order_type:String(f.get('order_type')),priority:String(f.get('priority')),detail,status:'Pendiente',doctor_id:user().id,doctor_name:user().name||user().email,active:true,updated_at:new Date().toISOString(),data:{study_name:studies.join(', '),study_names:studies,study_count:studies.length,clinical_summary:summary,observations:obs}};const {error}=await db().from('seniorcare_medical_orders').insert(row);if(error)return toast(error.message);toast(`${studies.length} ${isImg?'estudio(s) de imagen':'examen(es)'} enviados en una sola orden.`);window.renderMedicalStudies()};
 m.querySelectorAll('[data-study-pdf]').forEach(b=>b.onclick=()=>{const o=orders.find(x=>x.id===b.dataset.studyPdf),r=resident(o.resident_key),d=o.data||{},studies=orderStudies(o),list=studies.length?`<ol>${studies.map(x=>`<li>${esc(x)}</li>`).join('')}</ol>`:`<div class="box">${esc(o.detail||'')}</div>`;printDoc(o.order_type==='Imagen'?'Solicitud de estudios de imagen':'Solicitud de laboratorio',r,`${o.order_type==='Imagen'?`<h2>Resumen clínico</h2><div class="box">${esc(d.clinical_summary||'Sin resumen adicional')}</div><h2>Estudios solicitados</h2>${list}`:`<h2>Exámenes solicitados</h2>${list}`}<h2>Observaciones</h2><div class="box">${esc(d.observations||'Sin observaciones')}</div>`)})
};
window.renderMedicalPrescriptions=async function(){
 try{await load()}catch(e){return toast(e.message)} const m=main();if(!m)return;
 m.innerHTML=header('RECETAS','Receta médica','Formato libre, sencillo y membretado')+`<form id="rxForm4312" class="form-card med-premium-form"><div class="form-grid"><label>Paciente<select name="resident_key" required>${opts()}</select></label><div id="rxPatient4312" class="wide"></div><label class="wide">Prescripción e indicaciones<textarea name="instructions" data-auto-grow required placeholder="Escriba aquí la receta completa y las indicaciones"></textarea></label></div><div class="form-actions"><button class="primary-btn">Guardar receta</button></div></form><section class="history-card"><h3>Recetas emitidas</h3>${prescriptions.map(p=>`<article class="medical-record-card"><div><strong>${esc(rname(resident(p.resident_key)))}</strong><span>${esc(p.instructions||p.data?.free_text||'')}</span><small>${fmt(p.issued_at)}</small></div><button class="mini-btn" data-rx-pdf="${p.id}">PDF</button></article>`).join('')||'<p>No hay recetas.</p>'}</section>`;
 const f=document.getElementById('rxForm4312'),sel=f.elements.resident_key,draw=()=>document.getElementById('rxPatient4312').innerHTML=patientHeader(resident(sel.value));sel.onchange=draw;draw();window.BHSC_AUTO_GROW?.(m);
 f.onsubmit=async e=>{e.preventDefault();const fd=new FormData(f),txt=String(fd.get('instructions'));const row={organization_id:org(),resident_key:String(fd.get('resident_key')),medication:'Receta libre',dose:'Según prescripción',frequency:'Según prescripción',instructions:txt,doctor_id:user().id,doctor_name:user().name||user().email,status:'Vigente',issued_at:new Date().toISOString(),active:true,updated_at:new Date().toISOString(),data:{free_text:txt}};const {error}=await db().from('seniorcare_medical_prescriptions').insert(row);if(error)return toast(error.message);toast('Receta guardada.');window.renderMedicalPrescriptions()};
 m.querySelectorAll('[data-rx-pdf]').forEach(b=>b.onclick=()=>{const p=prescriptions.find(x=>x.id===b.dataset.rxPdf),r=resident(p.resident_key);printDoc('Receta médica',r,`<h2>Prescripción e indicaciones</h2><div class="box">${esc(p.instructions||p.data?.free_text||'')}</div>`)})
};
window.renderMedicalResults=async function(){
 try{await load()}catch(e){return toast(e.message)} const m=main();if(!m)return;const canUpload=['administrator','admin','nurse'].includes(role());
 m.innerHTML=header('RESULTADOS','Resultados enviados al médico',canUpload?'Suba PDF o imágenes para revisión médica':'Consulte los estudios recibidos e ingrese su interpretación')+`${canUpload?`<form id="resultUpload4312" class="form-card"><div class="form-grid"><label>Paciente<select name="resident_key" required>${opts()}</select></label><label>Tipo<select name="result_type"><option>Laboratorio</option><option>Imagen</option><option>Otro</option></select></label><label>Fecha<input type="date" name="result_date" value="${(window.BHSC_LOCAL_DATE?window.BHSC_LOCAL_DATE():new Intl.DateTimeFormat('en-CA',{timeZone:'America/Costa_Rica'}).format(new Date()))}"></label><label class="wide">Nombre del examen o estudio<input name="study_name" required placeholder="Ej.: Hemograma completo, radiografía de tórax"></label><label class="wide">Archivo PDF o imagen<input type="file" name="file" accept="application/pdf,image/*" required></label><label class="wide">Observaciones<textarea name="summary" data-auto-grow></textarea></label></div><div class="form-actions"><button class="primary-btn">Enviar estudio al médico</button></div></form>`:''}<section class="history-card"><h3>Estudios recibidos</h3>${results.map(r=>`<article class="medical-record-card"><div><strong>${esc(rname(resident(r.resident_key)))} · ${esc(r.study_name||r.result_type||'Estudio')}</strong><span>${esc(r.summary||r.result_type||'')}</span><small>${esc(r.result_date||'')} · ${esc(r.status||'Pendiente')}</small>${r.file_url?`<a class="mini-btn" href="${esc(r.file_url)}" target="_blank" rel="noopener">Abrir archivo</a>`:''}</div>${role()==='doctor'?`<button class="mini-btn" data-result-review="${r.id}">Interpretar</button>`:''}</article>`).join('')||'<p>No hay resultados enviados.</p>'}</section>`;window.BHSC_AUTO_GROW?.(m);
 document.getElementById('resultUpload4312')?.addEventListener('submit',async e=>{e.preventDefault();const f=new FormData(e.currentTarget),file=f.get('file'),studyName=String(f.get('study_name')||'').trim()||String(file?.name||'Resultado clínico').replace(/\.[^.]+$/,'');if(!studyName)return toast('Indique el nombre del examen o estudio.');const ext=(file.name.split('.').pop()||'bin').toLowerCase(),path=`${org()}/${f.get('resident_key')}/${Date.now()}-${crypto.randomUUID()}.${ext}`;const up=await db().storage.from('medical-results').upload(path,file,{upsert:false,contentType:file.type});if(up.error)return toast(up.error.message);const row={organization_id:org(),resident_key:String(f.get('resident_key')),study_name:studyName,result_type:String(f.get('result_type')),result_date:String(f.get('result_date')),status:'Pendiente',summary:String(f.get('summary')||''),interpretation:'',file_path:path,file_name:file.name,file_type:file.type,uploaded_by:user().id,uploaded_by_name:user().name||user().email,active:true,updated_at:new Date().toISOString()};const ins=await db().from('seniorcare_medical_results').insert(row);if(ins.error)return toast(ins.error.message);toast('Estudio enviado al médico.');window.renderMedicalResults()});
 m.querySelectorAll('[data-result-review]').forEach(b=>b.onclick=async()=>{const r=results.find(x=>x.id===b.dataset.resultReview),text=prompt('Interpretación médica:',r.interpretation||'');if(text===null)return;const {error}=await db().from('seniorcare_medical_results').update({interpretation:text,status:'Revisado',reviewed_by:user().id,reviewed_by_name:user().name||user().email,updated_at:new Date().toISOString()}).eq('id',r.id);if(error)return toast(error.message);toast('Resultado revisado.');window.renderMedicalResults()})
};
window.renderMedicalEmergencies=async function(){
 const all=window.BHSC_GET_ALERTS?.()||[];const urgent=all.filter(a=>{const p=String(a.priority||'').toLowerCase(),t=String(a.type||a.alert_type||'').toLowerCase();return (p.includes('alta')||p.includes('crít')||p.includes('urgent'))&&!t.includes('staff')&&!t.includes('operational')});const m=main();if(!m)return;m.innerHTML=header('URGENCIAS','Pacientes que requieren atención inmediata','Nombre, motivo y síntomas reportados')+`<section class="history-card">${urgent.map(a=>`<article class="medical-record-card emergency-card"><div><strong>${esc(a.resident_name||a.title||'Paciente')}</strong><span><b>Motivo:</b> ${esc(a.reason||a.title||'Atención inmediata')}</span><span><b>Síntomas:</b> ${esc(a.symptoms||a.detail||'Sin detalle adicional')}</span><small>${fmt(a.created||a.created_at)}</small></div></article>`).join('')||'<p>No hay urgencias clínicas activas.</p>'}</section>`
};
function injectAdminAccess(){if(!['administrator','admin','nurse'].includes(role())||window.activeScreen!=='more')return;const m=main();if(!m||m.querySelector('[data-medical-upload-access]'))return;const grid=m.querySelector('.more-grid')||m.querySelector('.module-grid');if(!grid)return;const card=document.createElement('button');card.className='module-card';card.dataset.medicalUploadAccess='1';card.innerHTML=`<span class="quick-icon blue">${window.svg?.report||'RM'}</span><div><strong>Enviar resultados al médico</strong><small>Subir PDF o imágenes de laboratorio y estudios</small></div><b>›</b>`;card.onclick=()=>window.go?.('medicalResults',{scope:'global'});grid.appendChild(card)}
const obs=new MutationObserver(()=>injectAdminAccess());obs.observe(document.documentElement,{subtree:true,childList:true});
addEventListener('seniorcare:user-ready',()=>setTimeout(injectAdminAccess,400));
})();
