/* Bernard Health SeniorCare Enterprise V3.6.0
   Enlace global Administrador ↔ Enfermería */
(()=>{
  'use strict';
  const VERSION='3.6.0';
  const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
  const role=()=>String(window.currentUser?.role||'').toLowerCase();
  const isNurse=()=>role()==='nurse';
  const isAdmin=()=>role()==='admin';
  const today=()=>(window.BHSC_LOCAL_DATE?window.BHSC_LOCAL_DATE():new Intl.DateTimeFormat('en-CA',{timeZone:'America/Costa_Rica'}).format(new Date()));
  const flat=o=>Object.values(o||{}).flat();
  const currentStaff=()=>{
    const uid=String(window.currentUser?.id||'');
    const name=String(window.currentUser?.name||'').toLowerCase();
    return (window.staffMembers||[]).find(m=>String(m.linkedUserId||'')===uid)
      ||(window.staffMembers||[]).find(m=>String(m.name||'').toLowerCase()===name)
      ||null;
  };
  const myAttendance=()=>{
    const me=currentStaff();
    const ids=new Set([String(me?.id||''),String(window.currentUser?.id||''),`user:${window.currentUser?.id||''}`]);
    return [...(window.attendanceLog||[])].filter(x=>ids.has(String(x.staffId||x.staff_key||''))||String(x.name||x.staff_name||'').toLowerCase()===String(window.currentUser?.name||'').toLowerCase()).sort((a,b)=>String(b.date||b.work_date||'').localeCompare(String(a.date||a.work_date||'')));
  };
  const currentAttendance=()=>myAttendance().find(x=>String(x.date||x.work_date)===today()&&!x.clockOut&&!x.clock_out)||myAttendance().find(x=>String(x.date||x.work_date)===today())||null;
  const fmtTime=v=>v?new Date(v).toLocaleTimeString('es-CR',{hour:'2-digit',minute:'2-digit'}):'—';
  const countToday=(records,dateField='date')=>records.filter(x=>{const raw=x?.[dateField]||x?.recorded_at||x?.created_at;return raw&&(window.BHSC_LOCAL_DATE?window.BHSC_LOCAL_DATE(new Date(raw)):new Intl.DateTimeFormat('en-CA',{timeZone:'America/Costa_Rica'}).format(new Date(raw)))===today()}).length;
  const notesFlat=()=>flat(window.nursingNotes||nursingNotes||{});
  const openWounds=()=>flat(window.woundRecords||woundRecords||{}).filter(x=>String(x.status||'').toLowerCase()!=='archivada').length;
  const openIncidents=()=>[...(window.incidents||incidents||[])].filter(x=>String(x.status||'').toLowerCase()!=='resuelto').length;
  const pendingMeds=()=>[...(window.meds||meds||[])].filter(x=>String(x.status||'').toLowerCase()==='pendiente').length;
  const pendingCare=()=>flat(window.carePlans||carePlans||{}).filter(x=>!x.done).length;
  const nurseStaff=()=>[...(window.staffMembers||[])].filter(x=>/enfermer/i.test(String(x.role||'')));
  const presentNurses=()=>nurseStaff().filter(m=>window.getAttendanceState?.(m.id)?.present).length;

  function nurseHome(){
    const me=currentStaff();
    const log=currentAttendance();
    const first=String(window.currentUser?.name||'Enfermería').split(' ')[0];
    main.innerHTML=`
      <section class="admin-welcome role-welcome nurse-welcome nurse-global-hero">
        <div><span class="eyebrow">PANEL DE ENFERMERÍA</span><h2>${greeting()}, ${esc(first)}</h2><p>Registre la atención clínica y compártala en tiempo real con Administración.</p></div>
        <div class="admin-mark">${svg.heart}</div>
      </section>
      <section class="self-clock-card final-clock nurse-clock-card-v134">
        <div><span>MI JORNADA</span><strong>${esc(me?.name||window.currentUser?.name||'Enfermería')}</strong><small>${log?.clockIn||log?.clock_in?`Entrada ${fmtTime(log.clockIn||log.clock_in)}`:'Entrada no registrada'}${log?.clockOut||log?.clock_out?` · Salida ${fmtTime(log.clockOut||log.clock_out)}`:''}</small></div>
        <div class="self-clock-actions">${!(log?.clockIn||log?.clock_in)?'<button class="clock-btn clock-in" id="selfClockIn">Marcar entrada</button>':!(log?.clockOut||log?.clock_out)?'<button class="clock-btn clock-out" id="selfClockOut">Marcar salida</button>':'<span class="status ok">Jornada cerrada</span>'}</div>
      </section>
      <section class="admin-metrics nurse-global-metrics">
        ${metric('bottle','amber','Medicamentos pendientes',pendingMeds(),'Dosis por administrar','medications')}
        ${metric('heart','blue','Signos de hoy',countToday(flat(window.vitalRecords||vitalRecords||{})),'Controles registrados','vitals')}
        ${metric('wound','rose','Curaciones activas',openWounds(),'Procedimientos en seguimiento','wounds')}
        ${metric('report','lilac','Notas de hoy',countToday(notesFlat()),'Evolución de enfermería','nursing')}
        ${metric('alert','rose','Incidentes abiertos',openIncidents(),'Requieren seguimiento','incidents')}
        ${metric('care','mint','Cuidados pendientes',pendingCare(),'Plan asignado por Administración','care')}
      </section>
      <section class="quick-section"><div class="quick-heading"><h2>Trabajo clínico</h2></div><div class="quick-grid">
        ${quick('users','lilac','Residentes','Expedientes e indicaciones','residents')}
        ${quick('heart','blue','Signos vitales','Registrar controles','vitals')}
        ${quick('bottle','amber','Medicamentos','Administrar y documentar','medications')}
        ${quick('wound','rose','Curaciones','Procedimientos y evolución','wounds')}
        ${quick('report','lilac','Notas de enfermería','Evolución por residente','nursing')}
        ${quick('exchange','mint','Entrega de turno','Continuidad del cuidado','handoff')}
      </div></section>`;
  }

  function nurseMore(){
    main.innerHTML=pageHeader('HERRAMIENTAS CLÍNICAS','Más','Funciones disponibles para Enfermería')+`
      <div class="more-grid nurse-global-more">
        ${moduleCard('heart','blue','Signos vitales','Controles e historial','vitals')}
        ${moduleCard('bottle','amber','Medicamentos','Administración y seguimiento','medications')}
        ${moduleCard('wound','rose','Curaciones','Procedimientos y heridas','wounds')}
        ${moduleCard('report','lilac','Notas de enfermería','Evolución clínica','nursing')}
        ${moduleCard('care','mint','Plan de cuidados','Consultar y completar tareas','care')}
        ${moduleCard('food','rose','Plan nutricional','Consultar indicaciones e ingesta','nutrition')}
        ${moduleCard('alert','rose','Incidentes','Registrar y dar seguimiento','incidents')}
        ${moduleCard('calendar','blue','Citas y traslados','Agenda del residente','agenda')}
        ${moduleCard('exchange','lilac','Entrega de turno','Continuidad clínica','handoff')}
        ${moduleCard('clock','mint','Mi asistencia','Entrada, salida e historial','staff')}
      </div>`;
  }

  function nurseAttendance(){
    const rows=myAttendance(),log=currentAttendance();
    main.innerHTML=pageHeader('CONTROL DE ASISTENCIA','Mi jornada','Registro personal sincronizado con Administración')+`
      <section class="nurse-self-attendance-v168"><div class="nurse-self-attendance-copy-v168"><span>JORNADA ACTUAL</span><h3>${esc(window.currentUser?.name||'Enfermería')}</h3><p>${log?.clockIn||log?.clock_in?`Entrada ${fmtTime(log.clockIn||log.clock_in)}`:'Entrada no registrada'}${log?.clockOut||log?.clock_out?` · Salida ${fmtTime(log.clockOut||log.clock_out)}`:''}</p></div><div class="nurse-self-attendance-actions-v168">${!(log?.clockIn||log?.clock_in)?'<button class="clock-btn clock-in" id="selfClockIn">Marcar entrada</button>':!(log?.clockOut||log?.clock_out)?'<button class="clock-btn clock-out" id="selfClockOut">Marcar salida</button>':'<span class="status ok">Jornada cerrada</span>'}</div></section>
      <section class="history-card nurse-attendance-history-v168"><div class="nurse-attendance-history-head-v168"><div><span>HISTORIAL PERSONAL</span><h3>Mis marcas</h3></div><strong>${rows.length}</strong></div><div class="attendance-table-wrap"><table class="attendance-history-table"><thead><tr><th>Fecha</th><th>Entrada</th><th>Salida</th></tr></thead><tbody>${rows.length?rows.map(x=>`<tr><td>${esc(String(x.date||x.work_date||''))}</td><td>${fmtTime(x.clockIn||x.clock_in)}</td><td>${fmtTime(x.clockOut||x.clock_out)}</td></tr>`).join(''):'<tr><td colspan="3" class="attendance-empty-cell">No hay marcas registradas.</td></tr>'}</tbody></table></div></section>`;
  }

  function nurseHandoff(){
    const records=[...(window.handoffRecords||handoffRecords||[])];
    main.innerHTML=pageHeader('CONTINUIDAD DEL CUIDADO','Entrega de turno','Registre una entrega clínica sincronizada con Administración')+`
      <form class="form-card handoff-form-pro" id="nurseGlobalHandoffForm"><div class="handoff-form-title"><div><span>NUEVA ENTREGA</span><h3>Registrar cambio de turno</h3></div><span class="handoff-lock">Registro permanente</span></div><div class="form-grid">
        <label>Turno que entrega<select name="shift" required><option value="">Seleccione</option><option>Matutino</option><option>Vespertino</option><option>Nocturno</option></select></label>
        <label>Turno que recibe<select name="incomingShift" required><option value="">Seleccione</option><option>Matutino</option><option>Vespertino</option><option>Nocturno</option><option>Sin relevo</option></select></label>
        <label>Entrega el turno<input name="author" value="${esc(window.currentUser?.name||'')}" readonly></label>
        <label>Recibe el turno<input name="receiver" placeholder="Nombre o Sin relevo" required></label>
        <label class="wide">Novedades clínicas<textarea name="news" rows="5" required></textarea></label>
        <label class="wide">Medicamentos o cuidados pendientes<textarea name="pending" rows="4"></textarea></label>
        <label class="wide">Indicaciones especiales<textarea name="instructions" rows="3"></textarea></label>
      </div><div class="handoff-warning">Al guardar, la ficha quedará cerrada y será visible para Administración.</div><div class="form-actions"><button class="primary-btn" type="submit">Entregar y cerrar turno</button></div></form>
      <section class="handoff-history-section"><div class="handoff-history-title"><div><span>HISTORIAL COMPARTIDO</span><h3>Entregas registradas</h3></div><b>${records.length}</b></div><div class="handoff-record-grid">${records.length?records.map((r,i)=>`<button class="handoff-record-card" data-handoff-view="${i}"><div class="handoff-record-top"><span class="handoff-shift">${esc(r.shift||'Turno')}</span><span class="handoff-closed">Cerrado</span></div><strong>${esc(r.author||'Enfermería')} <span>→</span> ${esc(r.receiver||'Sin relevo')}</strong><p>${esc(String(r.news||'Sin novedades').slice(0,110))}</p><div class="handoff-record-foot"><span>${esc(fmtDate(r.date))}</span><span>Ver ficha ›</span></div></button>`).join(''):empty('No hay entregas registradas.')}</div></section>`;
  }

  function addAdminNurseLink(){ /* V3.6.3: centralizado en Alertas */ }

  const previousHome=window.renderHome;
  const previousMore=window.renderMore;
  const previousStaff=window.renderStaff;
  const previousHandoff=window.renderHandoff;
  window.renderHome=function(){if(isNurse())nurseHome();else{previousHome();if(isAdmin())addAdminNurseLink();}};
  window.renderMore=function(){if(isNurse())nurseMore();else previousMore();};
  window.renderStaff=function(){if(isNurse())nurseAttendance();else previousStaff();};
  window.renderHandoff=function(){if(isNurse())nurseHandoff();else previousHandoff();};
  try{renderHome=window.renderHome;renderMore=window.renderMore;renderStaff=window.renderStaff;renderHandoff=window.renderHandoff;}catch(_){ }

  document.addEventListener('submit',e=>{
    if(!isNurse()||e.target?.id!=='nurseGlobalHandoffForm')return;
    e.preventDefault();e.stopImmediatePropagation();
    const f=new FormData(e.target);
    if(!confirm('¿Confirma la entrega del turno?'))return;
    const item={id:crypto.randomUUID?.()||String(Date.now()),date:new Date().toISOString(),shift:String(f.get('shift')||''),incomingShift:String(f.get('incomingShift')||''),author:String(window.currentUser?.name||''),receiver:String(f.get('receiver')||'').trim(),news:String(f.get('news')||'').trim(),pending:String(f.get('pending')||'').trim(),instructions:String(f.get('instructions')||'').trim(),locked:true};
    handoffRecords.unshift(item);window.saveHandoffs?.();
    window.renderHandoff();window.bindActions?.();window.showToast?.('Turno entregado y sincronizado.');
  },true);

  window.BHSC_NURSE_ADMIN_GLOBAL={version:VERSION};
  console.info(`Administrador ↔ Enfermería Global ${VERSION} listo`);
})();
