/* Bernard Health SeniorCare V4.3.18 — indicaciones y urgencias auditadas */
(function(){
'use strict';
const VERSION='4.3.18';
const db=()=>window.seniorcareSupabase;
const user=()=>window.currentUser||{};
const org=()=>user().organizationId||user().organization_id;
const role=()=>String(user().role||'').toLowerCase();
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 friendly=(error,fallback='No se pudo completar la operación.')=>window.BHSC_FRIENDLY_ERROR?.(error,fallback)||(error?.message||fallback);
const readRetry=task=>window.BHSC_WITH_RETRY?window.BHSC_WITH_RETRY(task,2,650):task();
const header=(eyebrow,title,sub,back)=>window.pageHeader?.(eyebrow,title,sub,back)||`<section class="page-head"><h2>${esc(title)}</h2><p>${esc(sub||'')}</p></section>`;
const fmt=d=>d?new Date(d).toLocaleString('es-CR'):'—';
const isDoctor=()=>role()==='doctor';
const isCareReceiver=()=>['administrator','admin','nurse'].includes(role());
const canReadMedical=()=>['doctor','administrator','admin','nurse','supervisor'].includes(role());
let residents=[],orders=[];
const residentKey=r=>String(r?.resident_key??r?.data?.resident_key??r?.id??r?.data?.id??'').trim();
const residentName=r=>r?.full_name||r?.resident_name||r?.data?.name||r?.data?.full_name||'Residente';
function statusBadge(s){return `<span class="med-status ${String(s||'Pendiente').toLowerCase().replace(/\s+/g,'-')}">${esc(s||'Pendiente')}</span>`;}
function rname(k){const r=residents.find(x=>residentKey(x)===String(k));return residentName(r);}
function opts(){return residents.length?residents.map(r=>`<option value="${esc(residentKey(r))}">${esc(residentName(r))} ${r.room||r.data?.room?`· ${esc(r.room||r.data?.room)}`:''}</option>`).join(''):'<option value="">No hay residentes activos</option>';}
async function loadResidents(){
 if(!db()||!org()||!canReadMedical())return false;
 const rr=await readRetry(()=>db().from('seniorcare_residents').select('*').eq('organization_id',org()).eq('active',true));
 if(rr.error)throw rr.error;
 residents=(rr.data||[]).map(r=>({...r,resident_key:residentKey(r)})).filter(r=>r.resident_key).sort((a,b)=>residentName(a).localeCompare(residentName(b),'es',{sensitivity:'base'}));
 return true;
}
async function loadOrders(){
 if(!db()||!org()||!canReadMedical())return false;
 const oo=await readRetry(()=>db().from('seniorcare_medical_orders').select('*').eq('organization_id',org()).eq('active',true).order('created_at',{ascending:false}));
 if(oo.error)throw oo.error; orders=oo.data||[];
 return true;
}
function normalizedTarget(o){
 const t=String(o?.data?.target||o?.target||'both').toLowerCase();
 if(['nursing','nurse','enfermeria','enfermería'].includes(t))return 'nursing';
 if(['administration','administrator','admin','administracion','administración'].includes(t))return 'administration';
 return 'both';
}
function orderVisibleToRole(o){
 const t=normalizedTarget(o),r=role();
 if(['doctor','supervisor'].includes(r))return true;
 if(r==='nurse')return t==='both'||t==='nursing';
 if(['admin','administrator'].includes(r))return t==='both'||t==='administration';
 return false;
}
function orderDetail(o){return o.detail||o.description||o.title||o.study_name||o.data?.study_name||o.data?.indication||'Sin detalle';}
function targetText(o){const t=normalizedTarget(o);if(t==='nursing')return 'Enfermería';if(t==='administration')return 'Administración';return 'Administración y Enfermería';}
async function updateOrderStatus(id,status){
 try{
  if(!isCareReceiver())return toast('Este usuario no puede actualizar indicaciones.');
  const current=orders.find(o=>String(o.id)===String(id));
  if(!current||!orderVisibleToRole(current))return toast('La indicación no está asignada a este módulo.');
  const patch={status,updated_at:new Date().toISOString()};
  if(status==='Leída')Object.assign(patch,{acknowledged_by:user().id,acknowledged_by_name:user().name||user().email,acknowledged_at:new Date().toISOString()});
  if(status==='Completada')Object.assign(patch,{completed_by:user().id,completed_by_name:user().name||user().email,completed_at:new Date().toISOString()});
  const {error}=await db().from('seniorcare_medical_orders').update(patch).eq('id',id).eq('organization_id',org()).eq('active',true);
  if(error)throw error;
  toast('Indicación actualizada.');
  window.renderMedicalOrders?.();
 }catch(error){toast(friendly(error,'No se pudo actualizar la indicación.'));}
}

async function createMedicalOrder(e){
 e.preventDefault();
 const form=e.currentTarget;
 const button=form.querySelector('[type="submit"]');
 try{
  const fd=new FormData(form);
  const target=String(fd.get('target')||'both');
  const resident_key=String(fd.get('resident_key')||'').trim();
  const detail=String(fd.get('detail')||'').trim();
  if(!resident_key)return toast('Seleccione un residente.');
  if(!detail)return toast('Escriba la indicación médica.');
  if(button){button.disabled=true;button.textContent='Enviando…';}
  const row={organization_id:org(),resident_key,order_type:String(fd.get('order_type')||'Indicación'),priority:String(fd.get('priority')||'Normal'),detail,status:'Pendiente',doctor_id:user().id,doctor_name:user().name||user().email,active:true,updated_at:new Date().toISOString(),data:{target}};
  const {data,error}=await db().from('seniorcare_medical_orders').insert(row).select().single();
  if(error)throw error;
  try{
   const alertResult=await db().from('seniorcare_alerts').insert({organization_id:org(),alert_key:`medical-order:${data.id}:${Date.now()}`,source_key:`medical-order:${data.id}`,title:`Indicación médica · ${rname(row.resident_key)}`,detail:row.detail,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:data.id,target,category:'resident'}});
   if(alertResult?.error)toast('Indicación guardada, pero la alerta no pudo enviarse. Revise Alertas.');
   else toast('Indicación enviada.');
  }catch(_error){toast('Indicación guardada, pero la alerta no pudo enviarse. Revise Alertas.');}
  window.renderMedicalOrders?.();
 }catch(error){toast(friendly(error,'No se pudo enviar la indicación.'));}
 finally{if(button&&document.contains(button)){button.disabled=false;button.textContent='Enviar indicación';}}
}

window.renderMedicalOrders=async function(){
 try{await Promise.all([loadResidents(),loadOrders()]);}catch(e){const m=main();if(m)m.innerHTML=header('INDICACIONES MÉDICAS','Indicaciones médicas','No se pudieron cargar las indicaciones','more')+`<section class="history-card"><p>${esc(friendly(e,'Error de conexión.'))}</p><button class="primary-btn" onclick="window.renderMedicalOrders()">Reintentar</button></section>`;return;}
 const m=main(); if(!m)return;
 const list=orders.filter(orderVisibleToRole);
 m.innerHTML=header('INDICACIONES MÉDICAS','Indicaciones médicas',isDoctor()?'Emitir indicaciones para Administración y Enfermería':'Órdenes médicas asignadas a este módulo','more')+`
 ${isDoctor()?`<form id="medicalOrderDoctor4317" class="form-card med-premium-form"><div class="form-grid">
  <label>Residente<select name="resident_key" required>${opts()}</select></label>
  <label>Tipo<select name="order_type"><option>Indicación</option><option>Laboratorio</option><option>Imagen</option><option>Cuidados especiales</option><option>Control de signos</option><option>Dieta</option><option>Traslado</option></select></label>
  <label>Prioridad<select name="priority"><option>Normal</option><option>Preferente</option><option>Urgente</option></select></label>
  <label>Enviar a<select name="target"><option value="both">Administración y Enfermería</option><option value="nursing">Enfermería</option><option value="administration">Administración</option></select></label>
  <label class="wide">Indicación médica<textarea name="detail" data-auto-grow required placeholder="Escriba la indicación completa"></textarea></label>
 </div><div class="form-actions"><button class="primary-btn" ${residents.length?'':'disabled'}>Enviar indicación</button></div></form>`:''}
 <section class="history-card medical-orders-received"><h3>${isDoctor()?'Indicaciones emitidas':'Indicaciones médicas'}</h3>
 ${list.length?list.map(o=>`<article class="medical-record-card"><div><strong>${esc(rname(o.resident_key))} · ${esc(o.order_type||'Indicación')}</strong><span>${esc(orderDetail(o))}</span><small>${fmt(o.created_at)} · Dr(a). ${esc(o.doctor_name||'Médico')} · Para ${esc(targetText(o))}</small></div><div class="card-actions">${statusBadge(o.status)}${isCareReceiver()?`<button class="mini-btn" data-med-status="Leída" data-id="${esc(o.id)}">Leída</button><button class="mini-btn" data-med-status="En ejecución" data-id="${esc(o.id)}">En ejecución</button><button class="mini-btn" data-med-status="Completada" data-id="${esc(o.id)}">Completada</button><button class="mini-btn" data-med-status="Requiere aclaración" data-id="${esc(o.id)}">Aclaración</button>`:''}</div></article>`).join(''):'<p>No hay indicaciones médicas asignadas.</p>'}
 </section>`;
 document.getElementById('medicalOrderDoctor4317')?.addEventListener('submit',createMedicalOrder);
 m.querySelectorAll('[data-med-status]').forEach(b=>b.addEventListener('click',()=>updateOrderStatus(b.dataset.id,b.dataset.medStatus)));
 window.BHSC_AUTO_GROW?.(m);
};
async function createUrgency(e){
 e.preventDefault();
 const form=e.currentTarget;
 const button=form.querySelector('[type="submit"]');
 try{
  const fd=new FormData(form);
  const resident_key=String(fd.get('resident_key')||'').trim();
  const reason=String(fd.get('reason')||'').trim();
  const symptoms=String(fd.get('symptoms')||'').trim();
  if(!resident_key)return toast('Seleccione un paciente.');
  if(!reason||!symptoms)return toast('Complete motivo y síntomas.');
  if(button){button.disabled=true;button.textContent='Enviando…';}
  const key=`medical-urgency:${resident_key}:${Date.now()}`;
  const row={organization_id:org(),alert_key:key,source_key:key,title:`Urgencia médica · ${rname(resident_key)}`,detail:`Motivo: ${reason}\nSíntomas: ${symptoms}`,priority:'Critical',status:'Nueva',alert_type:'medical_urgency',resident_key,target_screen:'medicalEmergencies',active:true,data:{category:'resident',target:'doctor',reason,symptoms,reported_by:user().name||user().email,reported_role:role(),resident_name:rname(resident_key)}};
  const {error}=await db().from('seniorcare_alerts').insert(row);
  if(error)throw error;
  toast('Urgencia enviada al médico.');
  form.reset();
 }catch(error){toast(friendly(error,'No se pudo enviar la urgencia.'));}
 finally{if(button&&document.contains(button)){button.disabled=false;button.textContent='Enviar urgencia al médico';}}
}

window.renderMedicalUrgencyNotify=async function(){
 try{await loadResidents();}catch(e){const m=main();if(m)m.innerHTML=header('URGENCIAS MÉDICAS','Notificar urgencia al médico','No se pudieron cargar los residentes','more')+`<section class="history-card"><p>${esc(friendly(e,'Error de conexión.'))}</p><button class="primary-btn" onclick="window.renderMedicalUrgencyNotify()">Reintentar</button></section>`;return;}
 const m=main(); if(!m)return;
 m.innerHTML=header('URGENCIAS MÉDICAS','Notificar urgencia al médico','Reporte inmediato de un paciente que requiere valoración','more')+`<form id="medicalUrgencyForm4317" class="form-card med-premium-form"><div class="form-grid"><label>Paciente<select name="resident_key" required>${opts()}</select></label><label>Prioridad<input value="Urgente" readonly></label><label class="wide">Motivo<textarea name="reason" data-auto-grow required placeholder="Ej.: caída, fiebre, dolor torácico, desaturación..."></textarea></label><label class="wide">Síntomas<textarea name="symptoms" data-auto-grow required placeholder="Describa síntomas, signos observados y hora de inicio"></textarea></label></div><div class="form-actions"><button class="primary-btn" ${residents.length?'':'disabled'}>Enviar urgencia al médico</button></div></form>`;
 document.getElementById('medicalUrgencyForm4317')?.addEventListener('submit',createUrgency);
 window.BHSC_AUTO_GROW?.(m);
};
window.renderMedicalEmergencies=async function(){
 const m=main(); if(!m)return;
 try{await loadResidents();}catch(_){residents=[];}
 let items=[];
 try{
  const {data,error}=await db().from('seniorcare_alerts').select('*').eq('organization_id',org()).eq('active',true).eq('alert_type','medical_urgency').order('created_at',{ascending:false});
  if(error)throw error;
  items=data||[];
 }catch(e){
  const all=window.BHSC_GET_ALERTS?.()||[];
  items=all.filter(a=>String(a.alert_type||a.type||'').toLowerCase()==='medical_urgency');
 }
 m.innerHTML=header('URGENCIAS','Urgencias','Pacientes que requieren atención inmediata')+`<section class="history-card">${items.length?items.map(a=>{const d=a.data||{};return `<article class="medical-record-card emergency-card"><div><strong>${esc(d.resident_name||rname(a.resident_key)||a.title||'Paciente')}</strong><span><b>Motivo:</b> ${esc(d.reason||a.title||'Atención inmediata')}</span><span><b>Síntomas:</b> ${esc(d.symptoms||a.detail||'Sin detalle')}</span><small>${fmt(a.created_at||a.created)}</small></div></article>`}).join(''):'<p>No hay urgencias clínicas activas.</p>'}</section>`;
};
function injectAdminNurseLinks(){
 if(!isCareReceiver()||window.activeScreen!=='more')return;
 const m=main(); if(!m)return;
 const grid=m.querySelector('.more-grid,.module-grid')||m;
 if(!m.querySelector('[data-medical-urgency-access]')){
  const card=document.createElement('button');
  card.className='module-card medical-admin-card-v4317';
  card.dataset.medicalUrgencyAccess='1';
  card.innerHTML='<span class="quick-icon rose">UR</span><div><strong>Notificar urgencia al médico</strong><small>Paciente, motivo y síntomas</small></div><b>›</b>';
  card.onclick=()=>window.go?.('medicalUrgencyNotify',{scope:'global'})||window.renderMedicalUrgencyNotify?.();
  grid.appendChild(card);
 }
 m.querySelectorAll('[data-medical-upload-access]').forEach(c=>c.classList.add('medical-admin-card-v4317'));
}
const obs=new MutationObserver(()=>injectAdminNurseLinks());
obs.observe(document.documentElement,{subtree:true,childList:true});
addEventListener('seniorcare:user-ready',()=>setTimeout(injectAdminNurseLinks,400));
console.info(`BHSC ${VERSION} indicaciones y urgencias médicas listo`);
})();
