/* Bernard Health SeniorCare V4.3.10 — flujo médico: primera consulta, seguimiento y resumen clínico */
(function(){
'use strict';
const db=()=>window.seniorcareSupabase;
const user=()=>window.currentUser||{};
const org=()=>user().organizationId||user().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 nowLocal=()=>{const d=new Date();d.setMinutes(d.getMinutes()-d.getTimezoneOffset());return d.toISOString().slice(0,16)};
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 header=(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>`;
let cache={residents:[],histories:[],consults:[]};
async function query(table,setup){try{const r=await setup(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 load(){
 if(!db()||!org())return false;
 cache.residents=(await query('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'}));
 cache.histories=await query('seniorcare_medical_histories',q=>q.select('*').eq('organization_id',org()).eq('active',true));
 cache.consults=await query('seniorcare_medical_consultations',q=>q.select('*').eq('organization_id',org()).eq('active',true).order('created_at',{ascending:false}));
 return true;
}
const rn=k=>{const r=cache.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 opts=()=>cache.residents.length?cache.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(''):'<option value="">No hay residentes activos</option>';
const vitalText=c=>{const v=c?.exam_data?.vital_signs||{};const map=[['bp','Presión arterial'],['hr','Frecuencia cardiaca'],['rr','Frecuencia respiratoria'],['temp','Temperatura'],['spo2','Saturación O₂'],['glucose','Glucemia']];const out=map.filter(([k])=>v[k]).map(([k,l])=>`${l}: ${v[k]}`);return out.length?out.join('\n'):'Sin registro'};
function printSummary(c){
 const h=cache.histories.find(x=>String(x.resident_key)===String(c.resident_key));
 const body=`<h2>${esc(rn(c.resident_key))}</h2><h2>Motivo de consulta</h2><div class="box">${esc(c.reason||'Sin registro')}</div><h2>Signos vitales</h2><div class="box">${esc(vitalText(c))}</div><h2>Examen físico</h2><div class="box">${esc(c.physical_exam||'Sin registro')}</div><h2>Diagnósticos</h2><div class="box">${esc(c.diagnosis||'Sin registro')}</div><h2>Tratamiento</h2><div class="box">${esc(c.plan||'Sin registro')}</div><h2>Observaciones</h2><div class="box">${esc(c.exam_data?.observations||'Sin observaciones')}</div><h2>Próxima consulta</h2><div class="box">${esc(c.follow_up_date||'No indicada')}</div>${h?`<h2>Antecedentes relevantes</h2><div class="box">Personales: ${esc(h.personal_history||'Sin registro')}\nNo patológicos: ${esc(h.non_pathological_history||'Sin registro')}\nQuirúrgicos: ${esc(h.surgical_history||'Sin registro')}\nAlergias: ${esc(h.drug_allergies||'Sin registro')}</div>`:''}`;
 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>Resumen de consulta</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">Resumen de consulta · ${new Date(c.consultation_date).toLocaleString('es-CR')}</div></header>${body}<div class="foot">Documento clínico confidencial. Generado por Bernard Health SeniorCare.</div><script>onload=()=>setTimeout(()=>print(),250)<\/script></body></html>`);w.document.close();
}
async function sendSummary(c,target){
 const payload={consultation_id:c.id,reason:c.reason,vital_signs:c.exam_data?.vital_signs||{},physical_exam:c.physical_exam,diagnosis:c.diagnosis,treatment:c.plan,observations:c.exam_data?.observations||'',follow_up_date:c.follow_up_date,target,sent_at:new Date().toISOString()};
 const row={organization_id:org(),resident_key:c.resident_key,document_type:'Resumen de consulta',title:`Resumen de consulta · ${rn(c.resident_key)}`,document_data:payload,created_by:user().id,created_by_name:user().name||user().email,status:'Emitido',active:true,updated_at:new Date().toISOString()};
 const {error}=await db().from('seniorcare_medical_documents').insert(row);if(error){toast(error.message);return}
 const title=`Resumen médico disponible · ${rn(c.resident_key)}`;
 const detail=`El médico envió el resumen de la consulta del ${fmt(c.consultation_date)} para ${target==='nurse'?'Enfermería':target==='admin'?'Administración':'Administración y Enfermería'}.`;
 const alertResult=await db().from('seniorcare_alerts').insert({organization_id:org(),alert_key:`medical-summary:${c.id}:${target}:${Date.now()}`,source_key:`medical-summary:${c.id}`,title,detail,priority:'Pending',status:'Nueva',alert_type:'medical_summary',resident_key:c.resident_key,target_screen:'medicalDocuments',active:true,data:{consultation_id:c.id,target,category:'resident'}});
 if(alertResult?.error)toast('Resumen guardado, pero la alerta no pudo enviarse. Revise Alertas.');
 else toast(target==='both'?'Resumen enviado a Administración y Enfermería.':target==='nurse'?'Resumen enviado a Enfermería.':'Resumen enviado a Administración.');
}
function examBuilder(model){
 const fields=model==='systems'?['Estado general','Cabeza y cuello','Cardiovascular','Respiratorio','Abdomen','Genitourinario','Musculoesquelético','Neurológico','Piel']:['Cabeza','Cuello','Tórax','Abdomen','Pelvis','Extremidades','Columna','Piel'];
 if(model==='free')return `<label class="wide">Examen físico<textarea name="exam_free" rows="7"></textarea></label>`;
 return fields.map((n,i)=>`<div class="exam-row"><strong>${n}</strong><select name="exam_state_${i}"><option>Normal</option><option>Alterado</option><option>No evaluado</option></select><input name="exam_note_${i}" placeholder="Hallazgos u observaciones"></div>`).join('');
}
function historyFields(){return `<fieldset id="firstConsultHistory" class="wide med-vitals-block"><legend>Historia clínica inicial</legend><div class="form-grid"><label class="wide">Antecedentes personales patológicos<textarea name="personal_history"></textarea></label><label class="wide">Antecedentes personales no patológicos<textarea name="non_pathological_history"></textarea></label><label class="wide">Antecedentes quirúrgicos<textarea name="surgical_history"></textarea></label><label class="wide">Alergias a medicamentos<textarea name="drug_allergies"></textarea></label><label class="wide">Medicamentos actuales<textarea name="current_medications"></textarea></label><label class="wide">Observaciones generales<textarea name="general_notes"></textarea></label></div></fieldset>`}
window.renderMedicalHistory=async function(){
 try{await load()}catch(e){return toast(e.message)}
 const residentOptions=`<option value="">Seleccione residente</option>${opts()}`;
 window.main.innerHTML=header('RESUMEN CLÍNICO','Resumen clínico','Información general y última consulta del residente')+`<section class="form-card med-premium-form"><div class="form-grid"><label>Residente<select id="clinicalSummaryResident">${residentOptions}</select></label></div></section><section id="clinicalSummaryView" class="history-card"><p>Seleccione un residente para consultar su resumen clínico.</p></section>`;
 const sel=document.getElementById('clinicalSummaryResident'),view=document.getElementById('clinicalSummaryView');
 const draw=()=>{const key=sel.value;if(!key){view.innerHTML='<p>Seleccione un residente para consultar su resumen clínico.</p>';return}const h=cache.histories.find(x=>String(x.resident_key)===String(key));const c=cache.consults.find(x=>String(x.resident_key)===String(key));view.innerHTML=`<article class="medical-record-card clinical-summary-card"><div><strong>${esc(rn(key))}</strong><span>Resumen general</span></div></article><div class="medical-summary-grid"><article><span>Alergias</span><strong>${esc(h?.drug_allergies||'Sin registro')}</strong></article><article><span>Medicamentos actuales</span><strong>${esc(h?.current_medications||'Sin registro')}</strong></article></div><h3>Antecedentes</h3><div class="box">Personales: ${esc(h?.personal_history||'Sin registro')}\n\nNo patológicos: ${esc(h?.non_pathological_history||'Sin registro')}\n\nQuirúrgicos: ${esc(h?.surgical_history||'Sin registro')}\n\nObservaciones: ${esc(h?.general_notes||'Sin registro')}</div><h3>Última consulta</h3>${c?`<article class="medical-record-card"><div><strong>${fmt(c.consultation_date)}</strong><span>${esc(c.diagnosis||'Sin diagnóstico')}</span><small>${esc(c.reason||'Sin motivo registrado')}</small></div><div class="card-actions"><button class="mini-btn" id="summaryPdf">PDF</button></div></article><div class="box">Signos vitales:\n${esc(vitalText(c))}\n\nExamen físico:\n${esc(c.physical_exam||'Sin registro')}\n\nTratamiento:\n${esc(c.plan||'Sin registro')}\n\nObservaciones:\n${esc(c.exam_data?.observations||'Sin observaciones')}\n\nPróxima consulta: ${esc(c.follow_up_date||'No indicada')}</div>`:'<p>No hay consultas registradas para este residente.</p>'}`;if(c)document.getElementById('summaryPdf').onclick=()=>printSummary(c)};
 sel.addEventListener('change',draw);
};
window.renderMedicalConsultation=async function(){
 try{await load()}catch(e){return toast(e.message)}
 window.main.innerHTML=header('ATENCIÓN MÉDICA','Consulta médica','Primera consulta completa o control y seguimiento')+`<form id="medicalConsultFormV4310" class="form-card med-premium-form"><div class="form-grid"><label>Residente<select name="resident_key" required>${opts()}</select></label><label>Tipo de consulta<select name="consult_type"><option value="first">Primera consulta</option><option value="followup">Control o seguimiento</option></select></label><label>Fecha y hora<input type="datetime-local" name="consultation_date" value="${nowLocal()}" required></label><label class="wide">Motivo de consulta<textarea name="reason" required></textarea></label>${historyFields()}<fieldset class="wide med-vitals-block"><legend>Signos vitales</legend><div class="form-grid med-vitals-grid"><label>Presión arterial<input name="vital_bp"></label><label>Frecuencia cardiaca<input name="vital_hr"></label><label>Frecuencia respiratoria<input name="vital_rr"></label><label>Temperatura<input name="vital_temp"></label><label>Saturación O₂<input name="vital_spo2"></label><label>Glucemia<input name="vital_glucose"></label></div></fieldset><label>Modelo de examen físico<select name="exam_model"><option value="systems">Por aparatos y sistemas</option><option value="anatomical">Por zonas anatómicas</option><option value="free">Texto libre</option></select></label><div class="wide med-exam-builder" id="examBuilder4310">${examBuilder('systems')}</div><label class="wide">Diagnósticos<textarea name="diagnosis" required></textarea></label><label class="wide">Tratamiento<textarea name="plan" required></textarea></label><label class="wide">Observaciones<textarea name="observations"></textarea></label><label>Próxima consulta<input type="date" name="follow_up_date"></label></div><div class="form-actions"><button class="primary-btn">Guardar consulta</button></div></form><section class="history-card"><h3>Consultas registradas</h3>${cache.consults.length?cache.consults.map(c=>`<article class="medical-record-card"><div><strong>${esc(rn(c.resident_key))}</strong><span>${esc(c.diagnosis||'Sin diagnóstico')}</span><small>${fmt(c.consultation_date)} · ${esc(c.doctor_name||'Médico')}</small></div><div class="card-actions"><button class="mini-btn" data-pdf="${c.id}">PDF</button><button class="mini-btn" data-admin="${c.id}">Enviar a Administración</button><button class="mini-btn" data-nurse="${c.id}">Enviar a Enfermería</button><button class="mini-btn" data-both="${c.id}">Enviar a ambos</button></div></article>`).join(''):'<p>Sin consultas registradas.</p>'}</section>`;
 const f=document.getElementById('medicalConsultFormV4310'),history=document.getElementById('firstConsultHistory');
 const toggle=()=>history.style.display=f.elements.consult_type.value==='first'?'block':'none';f.elements.consult_type.onchange=toggle;toggle();
 f.elements.exam_model.onchange=e=>document.getElementById('examBuilder4310').innerHTML=examBuilder(e.target.value);
 f.addEventListener('submit',async e=>{
  e.preventDefault();const fd=new FormData(f),model=String(fd.get('exam_model')),consultType=String(fd.get('consult_type'));let physical='';const examData={findings:{},vital_signs:{bp:String(fd.get('vital_bp')||''),hr:String(fd.get('vital_hr')||''),rr:String(fd.get('vital_rr')||''),temp:String(fd.get('vital_temp')||''),spo2:String(fd.get('vital_spo2')||''),glucose:String(fd.get('vital_glucose')||'')},observations:String(fd.get('observations')||''),consult_type:consultType};
  if(model==='free')physical=String(fd.get('exam_free')||'');else{const fields=model==='systems'?['Estado general','Cabeza y cuello','Cardiovascular','Respiratorio','Abdomen','Genitourinario','Musculoesquelético','Neurológico','Piel']:['Cabeza','Cuello','Tórax','Abdomen','Pelvis','Extremidades','Columna','Piel'];fields.forEach((n,i)=>{const state=String(fd.get('exam_state_'+i)||''),note=String(fd.get('exam_note_'+i)||'');examData.findings[n]={state,note};physical+=`${n}: ${state}${note?' — '+note:''}\n`})}
  const key=String(fd.get('resident_key'));
  if(consultType==='first'){
   const historyRow={organization_id:org(),resident_key:key,chief_complaint:String(fd.get('reason')||''),personal_history:String(fd.get('personal_history')||''),non_pathological_history:String(fd.get('non_pathological_history')||''),surgical_history:String(fd.get('surgical_history')||''),drug_allergies:String(fd.get('drug_allergies')||''),current_medications:String(fd.get('current_medications')||''),general_notes:String(fd.get('general_notes')||''),updated_by:user().id,updated_by_name:user().name||user().email,updated_at:new Date().toISOString(),active:true};
   const existing=cache.histories.find(x=>String(x.resident_key)===key);const q=existing?db().from('seniorcare_medical_histories').update(historyRow).eq('id',existing.id):db().from('seniorcare_medical_histories').insert(historyRow);const hr=await q;if(hr.error&&!missing(hr.error))return toast(hr.error.message);
  }
  const row={organization_id:org(),resident_key:key,consultation_date:String(fd.get('consultation_date')),reason:String(fd.get('reason')),history:consultType==='first'?'Primera consulta':'Control o seguimiento',physical_exam:physical.trim(),exam_model:model,exam_data:examData,diagnosis:String(fd.get('diagnosis')),plan:String(fd.get('plan')),follow_up_date:fd.get('follow_up_date')||null,doctor_id:user().id,doctor_name:user().name||user().email,active:true,updated_at:new Date().toISOString()};
  const {data,error}=await db().from('seniorcare_medical_consultations').insert(row).select().single();if(error)return toast(error.message);
  const docResult=await db().from('seniorcare_medical_documents').insert({organization_id:org(),resident_key:key,document_type:'Consulta médica',title:`Consulta médica · ${rn(key)}`,document_data:{consultation_id:data.id,consult_type:consultType},created_by:user().id,created_by_name:user().name||user().email,status:'Emitido',active:true,updated_at:new Date().toISOString()});if(docResult.error){toast('La consulta se guardó, pero no se pudo crear el documento: '+docResult.error.message);return;}
  toast('Consulta médica guardada.');window.renderMedicalConsultation();
 });
 document.querySelectorAll('[data-pdf]').forEach(b=>b.onclick=()=>{const c=cache.consults.find(x=>x.id===b.dataset.pdf);if(c)printSummary(c)});
 document.querySelectorAll('[data-admin]').forEach(b=>b.onclick=()=>{const c=cache.consults.find(x=>x.id===b.dataset.admin);if(c)sendSummary(c,'admin')});
 document.querySelectorAll('[data-nurse]').forEach(b=>b.onclick=()=>{const c=cache.consults.find(x=>x.id===b.dataset.nurse);if(c)sendSummary(c,'nurse')});
 document.querySelectorAll('[data-both]').forEach(b=>b.onclick=()=>{const c=cache.consults.find(x=>x.id===b.dataset.both);if(c)sendSummary(c,'both')});
};
})();
