/* Bernard Health SeniorCare V4.3.14 — estabilidad de rutas médicas sin tocar otros roles */
(function(){
'use strict';
const isDoctor=()=>String(window.currentUser?.role||'').toLowerCase()==='doctor';
const screens={
  medicalDashboard:'renderMedicalDashboard',
  medicalAppointmentsDoctor:'renderMedicalAppointmentsDoctor',
  medicalHistory:'renderMedicalHistory',
  medicalConsultation:'renderMedicalConsultation',
  medicalOrders:'renderMedicalOrders',
  medicalStudies:'renderMedicalStudies',
  medicalResults:'renderMedicalResults',
  medicalPrescriptions:'renderMedicalPrescriptions',
  medicalEmergencies:'renderMedicalEmergencies',
  vitals:'renderVitals'
};
const navMap={medicalDashboard:'home',medicalAppointmentsDoctor:'home',medicalHistory:'medicalHistory',medicalConsultation:'medicalDashboard',medicalOrders:'medicalOrders',medicalStudies:'medicalDashboard',medicalResults:'medicalResults',medicalPrescriptions:'medicalPrescriptions',medicalEmergencies:'medicalDashboard',vitals:'medicalDashboard'};
function main(){return document.getElementById('mainContent')||window.main}
function setNav(screen){
  document.querySelectorAll('.nav-item').forEach(b=>b.classList.toggle('active',b.dataset.nav===navMap[screen]));
}
function errorView(message,screen){
  const m=main(); if(!m)return;
  const safe=String(message||'No se pudo cargar esta sección.');
  m.innerHTML=`<section class="doctor-essential-hero"><span>MÓDULO MÉDICO</span><h2>No se pudo cargar</h2><p>${safe.replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))}</p></section><section class="history-card"><p>La pantalla se mantuvo dentro del módulo médico. Revise la conexión y vuelva a intentar.</p><div class="form-actions"><button class="primary-btn" data-med-retry="${screen}">Reintentar</button><button class="mini-btn" data-med-home>Volver al panel médico</button></div></section>`;
  m.querySelector('[data-med-retry]')?.addEventListener('click',()=>navigate(screen));
  m.querySelector('[data-med-home]')?.addEventListener('click',()=>navigate('medicalDashboard'));
}
async function navigate(screen){
  if(!isDoctor()) return window.go?.(screen,{scope:'global'},{replace:true});
  const target=screens[screen]?screen:'medicalDashboard';
  const fn=window[screens[target]];
  window.activeScreen=target;
  setNav(target);
  window.scrollTo({top:0,behavior:'auto'});
  if(typeof fn!=='function') return errorView('La función de esta pantalla no está disponible en la versión cargada.',target);
  try{
    const result=fn();
    if(result&&typeof result.then==='function') await result;
  }catch(err){
    console.error('[BHSC V4.3.14] Error médico',target,err);
    errorView(err?.message||'No se pudo cargar la sección médica.',target);
  }
}
window.BHSC_DOCTOR_NAVIGATE=navigate;

document.addEventListener('click',e=>{
  if(!isDoctor())return;
  const doctorButton=e.target.closest('[data-doctor-go]');
  if(doctorButton){e.preventDefault();e.stopImmediatePropagation();navigate(doctorButton.dataset.doctorGo);return;}
  const nav=e.target.closest('.nav-item[data-nav]');
  if(nav){
    const target={home:'medicalDashboard',medicalHistory:'medicalHistory',medicalOrders:'medicalOrders',medicalResults:'medicalResults',medicalPrescriptions:'medicalPrescriptions'}[nav.dataset.nav];
    if(target){e.preventDefault();e.stopImmediatePropagation();navigate(target);return;}
  }
  const back=e.target.closest('[data-back],.module-back,.residents-back,.back-btn');
  if(back&&String(window.activeScreen||'').startsWith('medical')){e.preventDefault();e.stopImmediatePropagation();navigate('medicalDashboard');}
},true);

const originalToast=window.showToast;
window.showToast=function(message){
  const text=String(message||'');
  if(isDoctor()&&/load failed|failed to fetch|networkerror|schema cache|could not find the table|column .* does not exist/i.test(text)){
    errorView(text,window.activeScreen||'medicalDashboard');
    return;
  }
  return originalToast?.(message);
};

addEventListener('seniorcare:user-ready',()=>{if(isDoctor())setTimeout(()=>navigate('medicalDashboard'),220)});
addEventListener('pageshow',()=>{if(isDoctor()&&!screens[window.activeScreen])setTimeout(()=>navigate('medicalDashboard'),60)});
})();
