/* Bernard Health SeniorCare V4.3.67 — panel médico principal premium */
(function(){
'use strict';
const CR_TZ='America/Costa_Rica';
const esc=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
const role=()=>String(window.currentUser?.role||'');
const go=s=>{ if(typeof window.go==='function') window.go(s,{scope:'global'},{replace:true}); };
const heroIcon='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 3h6v3h3v6h-3v3H9v-3H6V6h3V3Z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><path d="M8 17.5c1.1 1.6 2.4 2.5 4 2.5s2.9-.9 4-2.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>';
function costaRicaHour(){
  try{
    const parts=new Intl.DateTimeFormat('en-US',{timeZone:CR_TZ,hour:'2-digit',hourCycle:'h23'}).formatToParts(new Date());
    return Number(parts.find(part=>part.type==='hour')?.value||0);
  }catch(_){return new Date().getHours();}
}
function greeting(){const h=costaRicaHour();return h<12?'Buenos días':h<19?'Buenas tardes':'Buenas noches';}
function doctorGreetingName(){
  const raw=String(window.currentUser?.name||'').trim().replace(/^dra?\.?\s*/i,'');
  const first=raw.split(/\s+/).filter(Boolean)[0]||'';
  return first?`Dr. ${first}`:'Doctor';
}
function todayLabel(){
  try{return new Intl.DateTimeFormat('es-CR',{timeZone:CR_TZ,weekday:'long',day:'numeric',month:'long',year:'numeric'}).format(new Date()).replace(/^./,c=>c.toUpperCase());}
  catch(_){return new Date().toLocaleDateString('es-CR',{weekday:'long',day:'numeric',month:'long',year:'numeric'});}
}
function btn(screen,icon,title,desc){return `<button class="doctor-essential-card" data-doctor-go="${screen}"><span class="doctor-essential-icon">${icon}</span><div><strong>${esc(title)}</strong><small>${esc(desc)}</small></div><b>›</b></button>`}
window.renderMedicalDashboard=async function(){
  if(role()!=='doctor') return;
  const main=window.main||document.getElementById('mainContent');
  if(!main) return;
  main.innerHTML=`
  <section class="doctor-essential-hero doctor-dashboard-premium">
    <div class="doctor-dashboard-copy">
      <span class="doctor-dashboard-eyebrow">PANEL MÉDICO</span>
      <h2>${esc(greeting())}, ${esc(doctorGreetingName())}</h2>
      <p>Seleccione la función clínica que necesita y consulte sus pacientes y citas asignadas.</p>
      <div class="doctor-dashboard-date"><span aria-hidden="true">▣</span>${esc(todayLabel())}</div>
    </div>
    <div class="doctor-dashboard-mark">${heroIcon}</div>
    <i class="doctor-dashboard-orb one"></i><i class="doctor-dashboard-orb two"></i>
  </section>
  <section class="doctor-essential-grid">
    ${btn('medicalHistory','RC','Resumen clínico','Datos generales, antecedentes, alergias y medicamentos')}
    ${btn('medicalConsultation','CM','Consulta médica','Motivo, signos, examen, diagnóstico y tratamiento')}
    ${btn('medicalAppointmentsDoctor','AG','Mi agenda','Citas y pacientes asignados por Administración')}
    ${btn('medicalOrders','IM','Indicaciones médicas','Enviar indicaciones a Enfermería y Administración')}
    ${btn('medicalStudies','EX','Exámenes y estudios','Solicitar laboratorios y estudios de imagen')}
    ${btn('medicalResults','RL','Resultados','Consultar y registrar resultados clínicos')}
    ${btn('medicalPrescriptions','Rx','Recetas','Emitir recetas y generar PDF')}
    ${btn('vitals','SV','Signos vitales','Revisar los signos registrados del paciente')}
    ${btn('medicalEmergencies','UR','Urgencias','Pacientes que requieren atención inmediata')}
  </section>`;
  main.querySelectorAll('[data-doctor-go]').forEach(b=>b.addEventListener('click',()=>go(b.dataset.doctorGo)));
};
function forceDoctorHome(){
  if(role()==='doctor'){
    const bad=['home','residents','resident','medications','agenda','medicalDocuments','medicalAssessments'];
    if(bad.includes(window.activeScreen)) go('medicalDashboard');
  }
}
addEventListener('seniorcare:user-ready',()=>setTimeout(()=>{if(role()==='doctor')go('medicalDashboard')},180));
addEventListener('popstate',()=>setTimeout(forceDoctorHome,50));
})();
