/* Bernard Health SeniorCare V4.3.11 — formularios médicos expansibles, estudios guiados y envío visible */
(function(){
'use strict';
const db=()=>window.seniorcareSupabase;
const u=()=>window.currentUser||{};
const org=()=>u().organizationId||u().organization_id;
const esc=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
const toast=t=>window.showToast?.(t);
const fmt=d=>d?new Date(d).toLocaleString('es-CR'):'—';
const missing=e=>{const m=String(e?.message||'').toLowerCase();return e?.code==='PGRST205'||m.includes('schema cache')||m.includes('could not find the table')};
const pageHeader=(e,t,s)=>window.pageHeader?.(e,t,s)||`<section class="page-head"><small>${esc(e)}</small><h2>${esc(t)}</h2><p>${esc(s)}</p></section>`;

function autoSize(el){
 if(!el||el.dataset.autoGrow==='1')return;
 el.dataset.autoGrow='1';
 el.rows=Math.max(Number(el.rows)||3,3);
 const resize=()=>{el.style.height='auto';el.style.height=Math.max(el.scrollHeight,96)+'px'};
 el.addEventListener('input',resize,{passive:true});
 el.addEventListener('change',resize,{passive:true});
 requestAnimationFrame(resize);
}
function enhance(root=document){
 root.querySelectorAll('textarea').forEach(autoSize);
 root.querySelectorAll('.med-exam-builder input[name^="exam_note_"]').forEach(input=>{
   if(input.dataset.upgraded==='1')return;
   const ta=document.createElement('textarea');
   [...input.attributes].forEach(a=>ta.setAttribute(a.name,a.value));
   ta.value=input.value||'';ta.rows=3;ta.dataset.upgraded='1';
   input.replaceWith(ta);autoSize(ta);
 });
 const consultation=document.getElementById('medicalConsultFormV4310');
 if(consultation&&!document.getElementById('medicalSendHelp4311')){
   const note=document.createElement('section');
   note.id='medicalSendHelp4311';note.className='medical-send-help';
   note.innerHTML='<strong>Resumen de consulta</strong><span>Después de guardar, el resumen aparece debajo con botones visibles para PDF, Administración, Enfermería o ambos.</span>';
   consultation.insertAdjacentElement('afterend',note);
 }
 document.querySelectorAll('.medical-record-card .card-actions').forEach(a=>a.classList.add('medical-send-actions'));
}
const observer=new MutationObserver(m=>m.forEach(x=>x.addedNodes.forEach(n=>{if(n.nodeType===1)enhance(n)})));
addEventListener('DOMContentLoaded',()=>{enhance();observer.observe(document.body,{subtree:true,childList:true})});

const LABS=[
 'Hemograma completo','Glicemia','Hemoglobina glicosilada','Perfil lipídico','Función renal (urea y creatinina)','Electrolitos','Pruebas de función hepática','Examen general de orina','Urocultivo','Proteína C reactiva','TSH y T4 libre','Vitamina B12','Vitamina D','Coagulación','Coprológico','Otro laboratorio'
];
const IMAGES=[
 'Radiografía de tórax','Radiografía de abdomen','Radiografía de columna','Radiografía de extremidad','Ultrasonido abdominal','Ultrasonido renal y vías urinarias','Ultrasonido prostático','Ultrasonido de tejidos blandos','Doppler venoso','Doppler arterial','Tomografía axial computarizada','Resonancia magnética','Mamografía','Densitometría ósea','Otro estudio de imagen'
];
function options(list){return list.map(x=>`<option value="${esc(x)}">${esc(x)}</option>`).join('')}
async function safeSelect(table,build){try{const r=await build(db().from(table));if(r.error){if(missing(r.error))return [];throw r.error}return r.data||[]}catch(e){if(missing(e))return [];throw e}}
async function registerStudyDocument(row,name,clinicalNote,imageSummary){
 const docResult=await db().from('seniorcare_medical_documents').insert({organization_id:org(),resident_key:row.resident_key,document_type:'Solicitud de estudio',title:`${row.order_type} · ${name}`,document_data:{order_id:row.id,study_name:name,clinical_note:clinicalNote,image_clinical_summary:imageSummary,priority:row.priority,due_date:row.due_date},created_by:u().id,created_by_name:u().name||u().email,status:'Emitido',active:true,updated_at:new Date().toISOString()});if(docResult.error)throw docResult.error;
 const alertResult=await db().from('seniorcare_alerts').insert({organization_id:org(),alert_key:`medical-study:${row.id}:${Date.now()}`,source_key:`medical-study:${row.id}`,title:`Nueva solicitud médica · ${name}`,detail:`${row.order_type} solicitado para seguimiento por Administración y Enfermería.`,priority:row.priority==='Urgente'?'Critical':'Pending',status:'Nueva',alert_type:'medical_order',resident_key:row.resident_key,target_screen:'medicalOrders',active:true,data:{order_id:row.id,target:'both',category:'resident'}});if(alertResult.error)throw alertResult.error;
}
function printStudy(o,residentName){
 const w=open('','_blank');if(!w)return toast('El navegador bloqueó la ventana de impresión.');
 const d=o.data||{};
 w.document.write(`<!doctype html><html><head><meta charset="utf-8"><title>Solicitud médica</title><style>body{font-family:Arial,sans-serif;color:#17324d;margin:34px}header{border-bottom:3px solid #6f2bd9;padding-bottom:14px;margin-bottom:24px}h1{margin:0;font-size:24px}h2{font-size:17px;margin:22px 0 8px}.meta{color:#65758a;font-size:12px}.box{border:1px solid #d9e3ea;border-radius:10px;padding:14px;white-space:pre-wrap}.foot{margin-top:40px;border-top:1px solid #ccd7df;padding-top:12px;font-size:11px;color:#607385}</style></head><body><header><h1>Bernard Health SeniorCare</h1><div class="meta">Solicitud de ${esc(o.order_type)} · ${fmt(o.created_at)}</div></header><h2>Paciente</h2><div class="box">${esc(residentName)}</div><h2>Estudio solicitado</h2><div class="box">${esc(d.study_name||o.detail||'')}</div>${d.clinical_note?`<h2>Observaciones</h2><div class="box">${esc(d.clinical_note)}</div>`:''}${d.image_clinical_summary?`<h2>Resumen clínico</h2><div class="box">${esc(d.image_clinical_summary)}</div>`:''}<h2>Prioridad</h2><div class="box">${esc(o.priority||'Normal')}</div><div class="foot">Documento clínico confidencial. Generado por Bernard Health SeniorCare.</div><script>onload=()=>setTimeout(()=>print(),250)<\/script></body></html>`);w.document.close();
}
window.renderMedicalStudies=async function(){
 if(!db()||!org())return;
 let residents=[],orders=[];
 try{
  residents=(await safeSelect('seniorcare_residents',q=>q.select('*').eq('organization_id',org()).eq('active',true))).map(r=>({...r,resident_key:String(r?.resident_key??r?.data?.resident_key??r?.id??r?.data?.id??'')})).filter(r=>r.resident_key).sort((a,b)=>(a.full_name||a.resident_name||a.data?.name||a.data?.full_name||'').localeCompare(b.full_name||b.resident_name||b.data?.name||b.data?.full_name||'','es',{sensitivity:'base'}));
  orders=await safeSelect('seniorcare_medical_orders',q=>q.select('*').eq('organization_id',org()).eq('active',true).in('order_type',['Laboratorio','Imagen']).order('created_at',{ascending:false}));
 }catch(e){return toast(e.message)}
 const rn=k=>{const r=residents.find(x=>String(x.resident_key)===String(k));return r?.full_name||r?.resident_name||r?.data?.name||r?.data?.full_name||'Residente'};
 const ropts=residents.map(r=>`<option value="${esc(r.resident_key)}">${esc(r.full_name||r.resident_name||r.data?.name||r.data?.full_name||'Residente')}${r.room||r.data?.room?` · ${esc(r.room||r.data?.room)}`:''}</option>`).join('');
 window.main.innerHTML=pageHeader('EXÁMENES Y ESTUDIOS','Solicitudes diagnósticas','Seleccione el estudio, agregue observaciones y envíelo a Enfermería y Administración')+`<form id="medicalStudyForm4311" class="form-card med-premium-form"><div class="form-grid"><label>Residente<select name="resident_key" required>${ropts}</select></label><label>Tipo<select name="order_type" id="studyType4311"><option>Laboratorio</option><option>Imagen</option></select></label><label>Prioridad<select name="priority"><option>Normal</option><option>Preferente</option><option>Urgente</option></select></label><label>Fecha límite<input type="date" name="due_date"></label><label class="wide">Examen o estudio<select name="study_name" id="studyName4311" required>${options(LABS)}</select></label><label class="wide hidden" id="otherStudyWrap4311">Especifique el estudio<input name="other_study" placeholder="Nombre del examen o estudio"></label><label class="wide">Observaciones<textarea name="clinical_note" rows="4" placeholder="Indicaciones, preparación, sospecha clínica u observaciones relevantes"></textarea></label><label class="wide hidden" id="imageSummaryWrap4311">Resumen clínico para el estudio de imagen<textarea name="image_clinical_summary" rows="5" placeholder="Resumen breve del caso, hallazgos o pregunta clínica para Radiología"></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.length?orders.map(o=>`<article class="medical-record-card"><div><strong>${esc(rn(o.resident_key))} · ${esc(o.order_type)}</strong><span>${esc(o.data?.study_name||o.detail||'')}</span><small>${esc(o.priority||'Normal')} · ${fmt(o.created_at)} · ${esc(o.status||'Pendiente')}</small></div><div class="card-actions medical-send-actions"><button class="mini-btn" data-study-print="${o.id}">PDF</button></div></article>`).join(''):'<p>No hay solicitudes de exámenes o imágenes.</p>'}</section>`;
 const form=document.getElementById('medicalStudyForm4311'),type=document.getElementById('studyType4311'),name=document.getElementById('studyName4311'),other=document.getElementById('otherStudyWrap4311'),image=document.getElementById('imageSummaryWrap4311');
 const refresh=()=>{const isImage=type.value==='Imagen';name.innerHTML=options(isImage?IMAGES:LABS);image.classList.toggle('hidden',!isImage);other.classList.toggle('hidden',!name.value.startsWith('Otro'));enhance(form)};
 type.onchange=refresh;name.onchange=()=>other.classList.toggle('hidden',!name.value.startsWith('Otro'));refresh();
 form.addEventListener('submit',async e=>{e.preventDefault();const fd=new FormData(form);let study=String(fd.get('study_name')||'');if(study.startsWith('Otro'))study=String(fd.get('other_study')||'').trim();if(!study)return toast('Escriba el nombre del estudio.');const clinical=String(fd.get('clinical_note')||'').trim(),imageSummary=String(fd.get('image_clinical_summary')||'').trim(),detail=[study,clinical&&`Observaciones: ${clinical}`,imageSummary&&`Resumen clínico: ${imageSummary}`].filter(Boolean).join('\n');const payload={organization_id:org(),resident_key:String(fd.get('resident_key')),order_type:String(fd.get('order_type')),priority:String(fd.get('priority')),due_date:fd.get('due_date')||null,detail,status:'Pendiente',doctor_id:u().id,doctor_name:u().name||u().email,active:true,updated_at:new Date().toISOString(),data:{study_name:study,clinical_note:clinical,image_clinical_summary:imageSummary}};const {data,error}=await db().from('seniorcare_medical_orders').insert(payload).select().single();if(error)return toast(error.message);await registerStudyDocument(data,study,clinical,imageSummary);toast('Solicitud enviada a Enfermería y Administración.');window.renderMedicalStudies()});
 document.querySelectorAll('[data-study-print]').forEach(b=>b.onclick=()=>{const o=orders.find(x=>String(x.id)===String(b.dataset.studyPrint));if(o)printStudy(o,rn(o.resident_key))});
 enhance(window.main);
};

const originalConsult=window.renderMedicalConsultation;
if(typeof originalConsult==='function')window.renderMedicalConsultation=async function(){await originalConsult();enhance(window.main);setTimeout(()=>enhance(window.main),80)};
const originalHistory=window.renderMedicalHistory;
if(typeof originalHistory==='function')window.renderMedicalHistory=async function(){await originalHistory();enhance(window.main)};
const originalResults=window.renderMedicalResults;
if(typeof originalResults==='function')window.renderMedicalResults=async function(){await originalResults();enhance(window.main)};
const originalRx=window.renderMedicalPrescriptions;
if(typeof originalRx==='function')window.renderMedicalPrescriptions=async function(){await originalRx();enhance(window.main)};
})();
