/* Bernard Health SeniorCare V4.3.9 — navegación médica limpia y sin asistencia */
(function(){
  'use strict';
  const isDoctor=()=>String(window.currentUser?.role||'').toLowerCase()==='doctor';
  const goDoctorHome=()=>{
    if(!isDoctor()) return;
    if(Array.isArray(window.navigationStack)) window.navigationStack=[];
    if(typeof window.go==='function') window.go('medicalDashboard',{scope:'global'},{replace:true});
    setTimeout(()=>window.renderMedicalDashboard?.(),0);
  };

  // El botón Volver dentro de cualquier pantalla médica siempre regresa al panel médico esencial.
  document.addEventListener('click',event=>{
    if(!isDoctor()) return;
    const back=event.target.closest('[data-back], .module-back, .residents-back, .back-btn');
    if(!back) return;
    const screen=String(window.activeScreen||'');
    if(!screen.startsWith('medical') && !['vitals','alerts'].includes(screen)) return;
    event.preventDefault();
    event.stopImmediatePropagation();
    goDoctorHome();
  },true);

  // Evita que cualquier módulo antiguo vuelva a mostrar el dashboard administrativo o asistencia al médico.
  let repairing=false;
  const repair=()=>{
    if(repairing||!isDoctor()) return;
    const main=document.getElementById('mainContent');
    if(!main) return;
    const screen=String(window.activeScreen||'');
    const text=main.textContent||'';
    const oldDoctorHome=screen==='home'||/CONTROL DE ASISTENCIA/i.test(text)||/Residentes activos/i.test(text);
    if(oldDoctorHome){
      repairing=true;
      goDoctorHome();
      setTimeout(()=>{repairing=false},80);
      return;
    }
    // Protección adicional: nunca mostrar tarjetas de asistencia dentro del rol médico.
    main.querySelectorAll('.self-clock-card,.final-clock,[data-clock-in],[data-clock-out]').forEach(el=>el.remove());
  };

  const observer=new MutationObserver(()=>queueMicrotask(repair));
  const start=()=>{
    observer.observe(document.documentElement,{childList:true,subtree:true});
    repair();
  };
  if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',start,{once:true}); else start();
  addEventListener('seniorcare:user-ready',()=>setTimeout(repair,250));
  addEventListener('popstate',()=>setTimeout(goDoctorHome,0));
})();
