/* Bernard Health SeniorCare V1.1.0 — cierre funcional solicitado */
(function(){
  'use strict';

  const SHIFTS=['Matutino','Vespertino','Nocturno'];
  let scCareShift=localStorage.getItem('seniorcare-care-shift')||'Matutino';
  let scInactiveFilter='Todos';
  let scReportDraft=null;

  const savedInactive=JSON.parse(localStorage.getItem('seniorcare-inactive-residents')||'null');
  if(Array.isArray(savedInactive)) inactiveResidents.splice(0,inactiveResidents.length,...savedInactive);
  inactiveResidents.forEach((r,i)=>{
    r.classification=r.classification||(['Baja','Traslado','Fallecido'][i%3]);
    r.inactiveDate=r.inactiveDate||new Date(Date.now()-(i+2)*86400000).toISOString();
    r.residentData=r.residentData||{id:r.id,name:r.name,age:r.age,room:r.room,status:'Estable',risk:'Riesgo medio',diet:'Corriente',contact:'Sin familiar · Sin teléfono',dx:'Antecedentes conservados del expediente',allergy:'Ninguna conocida'};
  });
  function saveInactive(){localStorage.setItem('seniorcare-inactive-residents',JSON.stringify(inactiveResidents));}
  saveInactive();

  let attendanceLog=JSON.parse(localStorage.getItem('seniorcare-attendance-log')||'[]');
  function saveAttendanceLog(){localStorage.setItem('seniorcare-attendance-log',JSON.stringify(attendanceLog));}
  // Compartir el registro de asistencia con los flujos operativos cargados después.
  window.attendanceLog=attendanceLog;
  window.saveAttendanceLog=saveAttendanceLog;
  let coverageChanges=JSON.parse(localStorage.getItem('seniorcare-coverage-changes')||'[]');
  function saveCoverageChanges(){localStorage.setItem('seniorcare-coverage-changes',JSON.stringify(coverageChanges));}
  let dietPlans=JSON.parse(localStorage.getItem('seniorcare-diet-plans')||'{}');
  function saveDietPlans(){localStorage.setItem('seniorcare-diet-plans',JSON.stringify(dietPlans));}
  // Compartir los planes nutricionales con el módulo V1.2.x.
  window.dietPlans=dietPlans;
  window.saveDietPlans=saveDietPlans;
  let dischargeReports=JSON.parse(localStorage.getItem('seniorcare-discharge-reports')||'[]');
  function saveDischargeReports(){localStorage.setItem('seniorcare-discharge-reports',JSON.stringify(dischargeReports));}

  function careKey(residentId,shift){return `${residentId}:${shift}`;}
  Object.keys(carePlans).forEach(k=>{
    if(/^\d+$/.test(k)&&Array.isArray(carePlans[k])){
      carePlans[careKey(k,'Matutino')]=carePlans[k].map(t=>({...t,shift:'Matutino',completedAt:t.done?(t.completedAt||new Date().toISOString()):null}));
      delete carePlans[k];
    }
  });
  getCareTasks=function(residentId,shift=scCareShift){
    const key=careKey(residentId,shift);
    if(!carePlans[key]) carePlans[key]=defaultCareTasks.map(name=>({id:Date.now()+Math.random(),name,done:false,shift,completedAt:null,completedBy:null,notes:''}));
    return carePlans[key];
  };
  saveCarePlans();

  function daysUntil(date){if(!date)return null;return Math.max(0,Math.ceil((new Date(date)-Date.now())/86400000));}
  function escapeHtml(v){return String(v??'').replace(/[&<>'"]/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[m]));}
  function downloadText(filename,text,type='text/csv;charset=utf-8'){
    const blob=new Blob([text],{type}); const url=URL.createObjectURL(blob); const a=document.createElement('a');a.href=url;a.download=filename;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
  }
  function csvCell(v){return `"${String(v??'').replace(/"/g,'""')}"`;}
  function printable(title,html){
    const w=window.open('','_blank','noopener'); if(!w)return;
    w.document.write(`<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(title)}</title><style>body{font:15px Arial;color:#221938;padding:30px}h1{color:#6a2dcc}h2{margin-top:28px}.box{border:1px solid #ddd;border-radius:12px;padding:14px;margin:10px 0}.grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}.muted{color:#6f687e}table{width:100%;border-collapse:collapse}th,td{border:1px solid #ddd;padding:8px;text-align:left}@media print{button{display:none}}</style></head><body>${html}<script>setTimeout(()=>window.print(),250)<\/script></body></html>`);w.document.close();
  }

  const oldRenderResidentDetail=renderResidentDetail;
  renderResidentDetail=function(){
    oldRenderResidentDetail();
    const grid=main.querySelector('.module-grid');
    if(grid){
      grid.insertAdjacentHTML('beforeend',residentModuleCard('report','amber','Egreso / epicrisis','Resumen final para familia','reports'));
    }
    const hero=main.querySelector('.profile-hero');
    const adminRole=['admin','administrator'].includes(String(currentUser?.role||'').toLowerCase());
    if(hero&&adminRole){
      const inactive=selectedResident?.status==='Inactivo';
      const deleteAction=document.getElementById('deleteResidentButton')?'':'<button class="danger-outline-btn resident-delete-btn-v4368" id="deleteResidentButton">Eliminar residente</button>';
      hero.insertAdjacentHTML('beforeend',inactive
        ?'<div class="resident-admin-actions"><span class="status danger">Residente inactivo</span></div>'
        :`<div class="resident-admin-actions"><button class="secondary-btn" id="residentDischargeButton">Preparar egreso</button><button class="danger-soft-btn" id="residentDeactivateButton">Inactivar residente</button>${deleteAction}</div>`
      );
    }
  };

  renderUsersAccess=function(){
    if(!['admin','supervisor'].includes(currentUser?.role)){main.innerHTML=pageHeader('ACCESO RESTRINGIDO','Sin autorización','Este módulo está disponible únicamente para administración.');return;}
    const activeCodes=accessCodes.filter(c=>!c.used&&new Date(c.expires)>new Date());
    main.innerHTML=pageHeader('SEGURIDAD Y PERMISOS','Usuarios y accesos','Gestione cuentas, roles y códigos de inscripción')+`
    <section class="access-summary"><article><span>Usuarios activos</span><strong>${users.filter(u=>u.active!==false).length}</strong></article><article><span>Códigos disponibles</span><strong>${activeCodes.length}</strong></article><article><span>Roles configurados</span><strong>7</strong></article></section>
    <section class="form-card access-generator"><h3>Generar código de inscripción</h3><p>Todos los códigos tienen una vigencia fija de 7 días y se utilizan una sola vez para activar la cuenta.</p><form id="accessCodeForm" class="form-grid"><label>Rol<select name="role"><option value="nurse">Enfermería</option><option value="assistant">Asistente</option><option value="cook">Cocina</option><option value="cleaning">Limpieza</option><option value="maintenance">Mantenimiento</option><option value="security">Seguridad</option><option value="doctor">Médico</option><option value="admin">Administrador</option></select></label><input name="days" type="hidden" value="7"><div class="wide form-actions"><button class="primary-btn" type="submit">${svg.plus} Generar código</button></div></form></section>
    <section class="history-card"><h3>Códigos de acceso</h3><div class="access-code-list">${accessCodes.length?accessCodes.map(c=>`<article class="access-code-card ${c.used?'used':''}"><div><span>${ROLE_LABELS[c.role]}</span><strong>${c.code}</strong><small>${c.used?'Utilizado':new Date(c.expires)>new Date()?`Vence ${fmtDate(c.expires)} · ${daysUntil(c.expires)} días`:'Vencido'}</small></div>${!c.used?`<button class="mini-btn" data-copy-code="${c.code}">Copiar</button>`:''}</article>`).join(''):empty('No hay códigos generados')}</div></section>
    <section class="history-card"><h3>Usuarios registrados</h3><div class="user-access-list">${users.map(u=>`<article class="user-access-card"><div class="avatar">${u.name.split(' ').map(x=>x[0]).slice(0,2).join('')}</div><div><strong>${u.name}</strong><span>${ROLE_LABELS[u.role]} · @${u.username}</span><small>${u.active===false?'Acceso desactivado':'Acceso activo'}</small></div>${u.id!==currentUser.id?`<button class="mini-btn" data-toggle-user="${u.id}">${u.active===false?'Activar':'Desactivar'}</button>`:'<span class="status ok">Sesión actual</span>'}</article>`).join('')}</div></section>`;
  };

  renderVitals=function(){
    const residentOptions=residentScoped?[selectedResident]:residents;
    const allRecords=(residentScoped?getResidentVitals(selectedResident.id).map(v=>({...v,residentId:selectedResident.id,residentName:selectedResident.name})):residents.flatMap(r=>getResidentVitals(r.id).map(v=>({...v,residentId:r.id,residentName:r.name})))).sort((a,b)=>new Date(b.date)-new Date(a.date));
    const records=allRecords.filter(r=>!r.archived), archived=allRecords.filter(r=>r.archived), latest=residentScoped?records[0]:null;
    main.innerHTML=pageHeader('CONTROL CLÍNICO','Signos vitales',residentScoped?`Registro para ${selectedResident.name}`:'Registro y evolución de todos los residentes')+`
    ${residentScoped&&latest?`<section class="summary-strip"><article><span>Última PA</span><strong>${latest.sys}/${latest.dia}</strong></article><article><span>Saturación</span><strong>${latest.spo2}%</strong></article><article><span>Temperatura</span><strong>${latest.temp} °C</strong></article></section>`:''}
    <form class="form-card" id="vitalsForm"><input type="hidden" name="recordId"><div class="form-grid">${residentScoped?`<input type="hidden" name="residentId" value="${selectedResident.id}"><label>Residente<input value="${selectedResident.name}" disabled></label>`:`<label>Residente<select name="residentId">${residentOptions.map(r=>`<option value="${r.id}">${r.name}</option>`).join('')}</select></label>`}<div class="bp-pair wide"><label>Presión sistólica<input name="sys" type="number" required placeholder="120"></label><label>Presión diastólica<input name="dia" type="number" required placeholder="80"></label></div><label>Frecuencia cardíaca<input name="hr" type="number" required></label><label>Temperatura<input name="temp" type="number" step="0.1" required></label><label>Saturación O₂<input name="spo2" type="number" required></label><label>Glucemia<input name="glu" type="number"></label><label>Peso (kg)<input name="weight" type="number" step="0.1"></label><label>Dolor<select name="pain"><option>0 - Sin dolor</option><option>1-3 Leve</option><option>4-6 Moderado</option><option>7-10 Severo</option></select></label><label class="wide">Observaciones<textarea name="obs" rows="3"></textarea></label></div><div class="form-actions"><button type="button" class="secondary-btn hidden" id="cancelVitalEdit">Cancelar edición</button><button class="primary-btn">Guardar signos</button></div></form>
    <section class="history-card"><h3>Registros anteriores</h3>${records.length?records.map(r=>`<article class="history-entry"><div><strong>${r.residentName}</strong><span>${fmtDate(r.date)} · ${summarizeVital(r)}</span></div><div class="card-actions"><button class="mini-btn" data-vital-view="${r.id}" data-vital-resident="${r.residentId}">Ver</button><button class="mini-btn" data-vital-edit="${r.id}" data-vital-resident="${r.residentId}">Editar</button><button class="mini-btn" data-vital-archive="${r.id}" data-vital-resident="${r.residentId}">Archivar</button><button class="icon-delete" data-vital-delete="${r.id}" data-vital-resident="${r.residentId}">×</button></div></article>`).join(''):empty('No hay signos registrados.')}${archived.length?`<details><summary>Archivados (${archived.length})</summary>${archived.map(r=>`<article class="history-entry"><div><strong>${r.residentName}</strong><span>${fmtDate(r.date)}</span></div><button class="mini-btn" data-vital-restore="${r.id}" data-vital-resident="${r.residentId}">Restaurar</button></article>`).join('')}</details>`:''}</section>`;
  };

  renderInactiveResidents=function(){
    const itemKey=r=>String(r?.resident_key??r?.residentData?.resident_key??r?.residentData?.id??r?.id??'');
    inactiveResidents.forEach(r=>{if(!itemKey(r)){const key=crypto.randomUUID?.()||`inactive-${Date.now()}-${Math.random().toString(16).slice(2)}`;r.id=key;r.resident_key=key;r.residentData=r.residentData||{};r.residentData.id=r.residentData.id||key;r.residentData.resident_key=key;}});
    saveInactive();
    const visible=inactiveResidents.filter(r=>scInactiveFilter==='Todos'||r.classification===scInactiveFilter);
    const counts=Object.fromEntries(['Todos','Baja','Traslado','Fallecido'].map(k=>[k,k==='Todos'?inactiveResidents.length:inactiveResidents.filter(r=>r.classification===k).length]));
    main.innerHTML=pageHeader('GESTIÓN DE RESIDENTES','Residentes inactivos','Bajas, traslados y fallecimientos con expediente conservado')+`
    <div class="inactive-filters">${Object.keys(counts).map(k=>`<button class="filter-chip ${scInactiveFilter===k?'active':''}" data-inactive-filter="${k}">${k} ${counts[k]}</button>`).join('')}</div>
    <div class="toolbar"><label class="searchbox">${svg.search}<input id="inactiveSearch" placeholder="Buscar residente inactivo"></label><button class="primary-btn" data-go="admissions">${svg.plus} Nueva admisión</button></div>
    <div class="resident-grid">${visible.length?visible.map(r=>{const key=itemKey(r);return `<article class="resident-card inactive-card"><div class="avatar muted-avatar">${r.name.split(' ').map(x=>x[0]).slice(0,2).join('')}</div><div><strong>${r.name}</strong><span>${r.age} años · ${r.room}</span><small>${r.classification} · ${r.reason}</small></div>${statusPill(r.classification)}<div class="card-actions">${r.classification!=='Fallecido'?`<button class="mini-btn" data-reactivate-resident="${key}">Reactivar</button>`:`<button class="mini-btn" data-discharge-report="${key}">Ver cierre</button>`}<button class="mini-btn danger-outline" data-inactive-delete="${key}">Eliminar</button></div></article>`}).join(''):empty('No hay residentes en esta clasificación.')}</div>`;
    setTimeout(()=>{const input=document.getElementById('inactiveSearch');input?.addEventListener('input',e=>document.querySelectorAll('.inactive-card').forEach(c=>c.style.display=c.textContent.toLowerCase().includes(e.target.value.toLowerCase())?'':'none'));},0);
  };

  renderCare=function(){
    const role=currentUser?.role||'admin';
    if(role==='admin'&&!residentScoped){
      const pending=residents.flatMap(r=>SHIFTS.flatMap(shift=>getCareTasks(r.id,shift).filter(t=>!t.done).map(t=>({...t,resident:r,shift}))));
      const completed=residents.flatMap(r=>SHIFTS.flatMap(shift=>getCareTasks(r.id,shift).filter(t=>t.done).map(t=>({...t,resident:r,shift}))));
      main.innerHTML=pageHeader('SEGUIMIENTO OPERATIVO','Cuidados pendientes','Revisión de tareas programadas y ejecución por turno')+`
      <section class="care-review-summary"><article><span>Pendientes</span><strong>${pending.length}</strong></article><article><span>Completados</span><strong>${completed.length}</strong></article><article><span>Residentes con pendientes</span><strong>${new Set(pending.map(x=>x.resident.id)).size}</strong></article></section>
      <div class="care-review-list">${pending.length?pending.map(t=>`<article><div><strong>${t.resident.name}</strong><span>${t.shift} · ${t.name}</span></div><span class="status warn">Pendiente</span><button class="mini-btn" data-open-care-resident="${t.resident.id}" data-care-shift-open="${t.shift}">Revisar</button></article>`).join(''):empty('Todos los cuidados programados están completados.')}</div>
      <section class="history-card"><h3>Últimos cuidados completados</h3>${completed.slice(0,12).map(t=>`<div class="history-line"><b>${t.resident.name} · ${t.name}</b><span>${t.shift} · ${t.completedAt?fmtDate(t.completedAt):'Completado'}</span></div>`).join('')||empty('No hay cuidados completados.')}</section>`;
      return;
    }
    const resident=selectedResident||residents[0]; const tasks=getCareTasks(resident.id,scCareShift); const done=tasks.filter(t=>t.done).length;
    main.innerHTML=pageHeader('CUIDADOS DIARIOS','Plan de cuidados',`${role==='admin'?'Configuración individual':'Ejecución del turno'} de ${resident.name}`)+`
    <section class="care-resident-strip"><div><strong>${resident.name}</strong><span>${resident.room} · ${resident.diet}</span></div><span class="status ok">${done}/${tasks.length} completadas</span></section>
    <div class="care-controls">${role==='admin'?`<select id="careResidentSelect">${residents.map(r=>`<option value="${r.id}" ${r.id===resident.id?'selected':''}>${r.name}</option>`).join('')}</select>`:''}<select id="careShiftSelect">${SHIFTS.map(s=>`<option ${s===scCareShift?'selected':''}>${s}</option>`).join('')}</select>${role==='admin'?'<button class="secondary-btn" id="addCareTask">+ Añadir tarea</button>':''}<button class="primary-btn" id="saveCarePlan">Guardar plan</button></div>
    <div class="care-task-grid">${tasks.map(t=>`<article class="care-task-item ${t.done?'done':''}"><label><input type="checkbox" data-care-check="${t.id}" ${t.done?'checked':''}><span>${t.name}</span><small>${t.done?`Completada${t.completedAt?` · ${fmtDate(t.completedAt)}`:''}`:'Pendiente de realizar'}</small></label>${role==='admin'?`<button class="icon-delete" data-sc-care-delete="${t.id}">×</button>`:''}</article>`).join('')}</div>`;
  };

  const baseRenderWounds=renderWounds;
  renderWounds=function(){
    const role=currentUser?.role||'admin';
    if(role!=='admin'&&(!residentScoped||!selectedResident)){
      return baseRenderWounds();
    }
    const all=residents.flatMap(r=>getResidentWounds(r.id).map(w=>({...w,residentId:r.id,residentName:r.name}))).sort((a,b)=>new Date(b.date)-new Date(a.date));
    if(role==='admin'&&!residentScoped){
      main.innerHTML=pageHeader('HISTORIAL CLÍNICO','Curaciones','Seguimiento de procedimientos programados desde cada expediente')+`
      <section class="history-card"><h3>Historial de curaciones</h3>${all.length?all.map(w=>`<article class="history-entry ${w.archived?'archived':''}"><div><strong>${w.residentName} · ${w.area}</strong><span>${fmtDate(w.date)} · ${w.status||'Sin estado'} · ${w.obs||'Sin observaciones'}</span></div><div class="card-actions"><button class="mini-btn" data-wound-view="${w.id}" data-wound-resident="${w.residentId}">Ver</button>${w.archived?`<button class="mini-btn" data-wound-restore="${w.id}" data-wound-resident="${w.residentId}">Restaurar</button>`:`<button class="mini-btn" data-wound-archive="${w.id}" data-wound-resident="${w.residentId}">Archivar</button>`}<button class="icon-delete" data-wound-delete="${w.id}" data-wound-resident="${w.residentId}">×</button></div></article>`).join(''):empty('No hay curaciones registradas.')}</section>`;
      return;
    }
    const r=selectedResident; const records=getResidentWounds(r.id).filter(x=>!x.archived);
    main.innerHTML=pageHeader('PROCEDIMIENTOS','Curaciones',`Programación y registro para ${r.name}`)+`
    <form class="form-card" id="woundForm"><input type="hidden" name="recordId"><input type="hidden" name="residentId" value="${r.id}"><div class="form-grid"><label>Residente<input value="${r.name}" disabled></label><label>Área<input name="area" required></label><label>Tamaño<input name="size"></label><label>Exudado<select name="exudate"><option>Sin exudado</option><option>Escaso</option><option>Moderado</option><option>Abundante</option></select></label><label>Dolor<input name="pain"></label><label>Próxima curación<input name="next" type="date"></label><label>Estado<select name="status"><option>Programada</option><option>Realizada</option><option>En seguimiento</option><option>Cerrada</option></select></label><label class="wide">Procedimiento<textarea name="procedure" rows="3"></textarea></label><label class="wide">Observaciones<textarea name="obs" rows="3"></textarea></label></div><div class="form-actions"><button type="button" class="secondary-btn hidden" id="cancelWoundEdit">Cancelar edición</button><button class="primary-btn">Guardar curación</button></div></form>
    <section class="history-card"><h3>Historial del expediente</h3>${records.length?records.map(w=>`<article class="history-entry"><div><strong>${w.area}</strong><span>${fmtDate(w.date)} · ${w.status}</span></div><div class="card-actions"><button class="mini-btn" data-wound-view="${w.id}" data-wound-resident="${r.id}">Ver</button><button class="mini-btn" data-wound-edit="${w.id}" data-wound-resident="${r.id}">Editar</button><button class="mini-btn" data-wound-archive="${w.id}" data-wound-resident="${r.id}">Archivar</button><button class="icon-delete" data-wound-delete="${w.id}" data-wound-resident="${r.id}">×</button></div></article>`).join(''):empty('No hay curaciones en este expediente.')}</section>`;
  };

  renderNutrition=function(){
    const role=currentUser?.role||'admin';
    if(role==='admin'&&!residentScoped){
      main.innerHTML=pageHeader('NUTRICIÓN','Dietas de residentes','Listado general, indicaciones de ingreso y cambios por enfermería')+`
      <div class="diet-list">${residents.map(r=>{const p=dietPlans[r.id]||{base:r.diet,texture:'Según tolerancia',restrictions:'Sin restricciones adicionales',changes:[]};return `<article class="diet-card"><div><strong>${r.name}</strong><span>${r.room}</span></div><div><span>Dieta actual</span><strong>${p.current||p.base||r.diet}</strong></div><div><span>Textura</span><strong>${p.texture||'Sin definir'}</strong></div><div><span>Último cambio</span><strong>${p.changes?.[0]?`${p.changes[0].author} · ${fmtDate(p.changes[0].date)}`:'Sin cambios'}</strong></div><button class="mini-btn" data-open-nutrition-resident="${r.id}">Ver / editar</button></article>`}).join('')}</div>`;
      return;
    }
    const r=selectedResident; const p=dietPlans[r.id]||{base:r.diet,current:r.diet,texture:'Normal',restrictions:'',allergies:r.allergy,changes:[]}; dietPlans[r.id]=p;saveDietPlans();
    main.innerHTML=pageHeader('NUTRICIÓN INDIVIDUAL','Plan nutricional',`${r.name} · indicación base y cambios clínicos`)+`
    ${role==='admin'?`<section class="form-card"><h3>Indicación al ingreso</h3><div class="form-grid"><label>Dieta base<input id="dietBase" value="${escapeHtml(p.base||r.diet)}"></label><label>Textura<input id="dietTexture" value="${escapeHtml(p.texture||'Normal')}"></label><label>Restricciones<input id="dietRestrictions" value="${escapeHtml(p.restrictions||'')}"></label><label>Alergias<input id="dietAllergies" value="${escapeHtml(p.allergies||r.allergy)}"></label></div><div class="form-actions"><button class="primary-btn" id="saveDietPlan">Guardar indicación</button></div></section>`:''}
    <section class="form-card"><h3>Cambio temporal por enfermería</h3><div class="form-grid"><label>Nueva dieta<input id="dietChangeValue" placeholder="Ej. blanda, líquidos claros"></label><label>Turno<select id="dietChangeShift">${SHIFTS.map(s=>`<option>${s}</option>`).join('')}</select></label><label class="wide">Motivo / observación<textarea id="dietChangeReason" rows="3"></textarea></label></div><div class="form-actions"><button class="primary-btn" id="saveDietChange">Registrar cambio</button></div></section>
    <section class="history-card"><h3>Historial de cambios</h3>${p.changes?.length?p.changes.map(c=>`<div class="history-line"><b>${c.value}</b><span>${c.shift} · ${c.author} · ${fmtDate(c.date)} · ${c.reason}</span></div>`).join(''):empty('No hay cambios de dieta registrados.')}</section>`;
  };

  renderStaff=function(){
    const today=(window.BHSC_LOCAL_DATE?window.BHSC_LOCAL_DATE():new Intl.DateTimeFormat('en-CA',{timeZone:'America/Costa_Rica'}).format(new Date())); const todays=attendanceLog.filter(x=>x.date===today);
    const presentCount=staffMembers.filter(m=>todays.some(x=>x.staffId===m.id&&x.clockIn&&!x.clockOut)).length;
    main.innerHTML=pageHeader('GESTIÓN DE PERSONAL','Personal y turnos','Colaboradores, horarios y control de entrada/salida')+`
    <section class="staff-dashboard-pro"><article><span>Colaboradores</span><strong>${staffMembers.length}</strong><small>Registrados</small></article><article><span>En turno</span><strong>${presentCount}</strong><small>Con entrada activa</small></article><article><span>Registros hoy</span><strong>${todays.length}</strong><small>Entradas y salidas</small></article><button class="primary-btn staff-add-pro" id="addStaff">${svg.plus} Añadir personal</button></section>
    <div class="attendance-export"><button class="secondary-btn" id="exportAttendanceCsv">Descargar Excel/CSV</button><button class="secondary-btn" id="printAttendance">Imprimir / PDF</button><button class="secondary-btn" id="shareAttendance">Compartir</button></div>
    <form class="form-card staff-form hidden" id="staffForm"><input type="hidden" name="staffId"><div class="form-grid"><label>Nombre completo<input name="name" required></label><label>Puesto o función<select name="role"><option>Enfermera</option><option>Asistente</option><option>Cuidador</option><option>Cocina</option><option>Limpieza</option><option>Mantenimiento</option><option>Administración</option></select></label><label>Horario<input name="shift" placeholder="06:00–14:00" required></label><label>Estado<select name="status"><option>En turno</option><option>Próximo</option><option>Libre</option><option>Ausente</option></select></label><label class="wide">Asignación principal<input name="assignment" placeholder="Habitaciones, tareas o responsabilidades"></label></div><div class="form-actions"><button type="button" class="secondary-btn" id="cancelStaff">Cancelar</button><button class="primary-btn">Guardar colaborador</button></div></form>
    <div class="staff-grid-pro">${staffMembers.map(m=>{const log=todays.find(x=>x.staffId===m.id);const active=log?.clockIn&&!log?.clockOut;return `<article class="staff-card-pro"><div class="staff-card-pro-head"><div class="avatar staff-avatar">${m.name.split(' ').map(x=>x[0]).slice(0,2).join('')}</div><div><strong>${m.name}</strong><span>${m.role}</span></div>${statusPill(active?'Presente':'Fuera de turno')}</div><div class="staff-card-pro-body"><div><span>Horario</span><strong>${m.shift}</strong></div><div><span>Entrada</span><strong>${log?.clockIn?new Date(log.clockIn).toLocaleTimeString('es-CR',{hour:'2-digit',minute:'2-digit'}):'Sin marcar'}</strong></div><div><span>Salida</span><strong>${log?.clockOut?new Date(log.clockOut).toLocaleTimeString('es-CR',{hour:'2-digit',minute:'2-digit'}):'Sin marcar'}</strong></div></div><div class="staff-card-pro-actions">${!log?.clockIn?`<button class="primary-btn" data-clock-in="${m.id}">Marcar entrada</button>`:!log.clockOut?`<button class="secondary-btn" data-clock-out="${m.id}">Marcar salida</button>`:'<span class="status ok">Jornada cerrada</span>'}<button class="mini-btn" data-staff-edit="${m.id}">Editar</button><button class="icon-delete" data-staff-delete="${m.id}">×</button></div></article>`}).join('')}</div>`;
  };

  renderHandoff=function(){
    const role=currentUser?.role||'admin';
    if(role==='admin'){
      main.innerHTML=pageHeader('COBERTURA DE PERSONAL','Cambios de último momento','Resolución administrativa de ausencias y reemplazos')+`
      <form class="form-card" id="coverageForm"><div class="form-grid"><label>Colaborador ausente<select id="coverageAbsent">${staffMembers.map(m=>`<option value="${m.id}">${m.name} · ${m.role}</option>`).join('')}</select></label><label>Reemplazo<select id="coverageReplacement">${staffMembers.map(m=>`<option value="${m.id}">${m.name} · ${m.role}</option>`).join('')}</select></label><label>Turno afectado<select id="coverageShift">${SHIFTS.map(s=>`<option>${s}</option>`).join('')}</select></label><label>Fecha<input id="coverageDate" type="date" value="${(window.BHSC_LOCAL_DATE?window.BHSC_LOCAL_DATE():new Intl.DateTimeFormat('en-CA',{timeZone:'America/Costa_Rica'}).format(new Date()))}"></label><label class="wide">Motivo y resolución<textarea id="coverageReason" rows="3"></textarea></label></div><div class="form-actions"><button type="button" class="primary-btn" id="saveCoverage">Registrar cambio</button></div></form>
      <section class="history-card"><h3>Cambios registrados</h3>${coverageChanges.length?coverageChanges.map(c=>`<div class="history-line"><b>${c.absent} → ${c.replacement}</b><span>${c.shift} · ${c.date} · ${c.reason}</span></div>`).join(''):empty('No hay cambios de cobertura registrados.')}</section>`;
      return;
    }
    const permitted=['nurse','assistant'].includes(role);
    main.innerHTML=pageHeader('CONTINUIDAD DEL CUIDADO','Entrega de turno',permitted?'Entrega formal entre enfermería y asistentes':'Acceso restringido')+(permitted?`
    <form class="form-card handoff-form-pro" id="handoffForm"><div class="handoff-form-title"><div><span>NUEVA ENTREGA</span><h3>Registrar entrega clínica</h3></div><span class="handoff-lock">Registro permanente</span></div><div class="form-grid"><label>Área<select name="area"><option>Enfermería</option><option>Asistentes</option></select></label><label>Turno que entrega<select name="shift" required>${SHIFTS.map(s=>`<option>${s}</option>`).join('')}</select></label><label>Turno que recibe<select name="incomingShift" required>${SHIFTS.map(s=>`<option>${s}</option>`).join('')}</select></label><label>Entrega el turno<input name="author" value="${escapeHtml(currentUser?.name||'')}" required></label><label>Recibe el turno<input name="receiver" required></label><label class="wide">Novedades del turno<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">La ficha quedará cerrada y no podrá modificarse.</div><div class="form-actions"><button class="primary-btn">Entregar y cerrar turno</button></div></form>
    <section class="handoff-history-section"><div class="handoff-history-title"><div><span>HISTORIAL</span><h3>Entregas registradas</h3></div><b>${handoffRecords.length}</b></div><div class="handoff-record-grid">${handoffRecords.length?handoffRecords.map((r,i)=>`<button class="handoff-record-card" data-handoff-view="${i}"><div class="handoff-record-top"><span class="handoff-shift">${r.area||'Área clínica'} · ${r.shift}</span><span class="handoff-closed">Cerrado</span></div><strong>${r.author} → ${r.receiver}</strong><p>${String(r.news||'').slice(0,110)}</p><div class="handoff-record-foot"><span>${fmtDate(r.date)}</span><span>Ver ficha ›</span></div></button>`).join(''):empty('No hay entregas registradas.')}</div></section>`:empty('La entrega de turno solo está disponible para enfermería y asistentes.'));
  };

  function reportData(type,resident){
    const r=resident||selectedResident||residents[0]; const vitals=getResidentVitals(r.id), wounds=getResidentWounds(r.id), notes=nursingNotes[r.id]||[], nutrition=getNutritionRecords(r.id), care=SHIFTS.flatMap(s=>getCareTasks(r.id,s));
    const common={resident:r,date:new Date().toLocaleString('es-CR'),vitals,wounds,notes,nutrition,care,medications:meds.filter(m=>m.resident===r.name),appointments:appointments.filter(a=>a.resident===r.name),incidents:incidents.filter(i=>i.resident===r.name)};
    const titles={daily:'Reporte diario del hogar',meds:'Hoja de medicamentos',vitals:'Signos vitales',care:'Cuidados diarios',wounds:'Curaciones',incidents:'Incidentes',appointments:'Citas y traslados',attendance:'Asistencia del personal',epicrisis:'Epicrisis / resumen de egreso'};
    return {...common,title:titles[type]||type,type};
  }
  function editableReportHtml(data){
    const r=data.resident, last=data.vitals[0];
    const heading=`<h2>${escapeHtml(data.title)}</h2><p><strong>Residente:</strong> ${escapeHtml(r.name)} · ${r.age} años · ${escapeHtml(r.room)}</p><p><strong>Fecha:</strong> ${escapeHtml(data.date)}</p>`;
    let body='';
    if(data.type==='meds') body=`<h3>Medicamentos</h3>${data.medications.length?`<ul>${data.medications.map(m=>`<li>${escapeHtml(m.drug)} · ${escapeHtml(medicationScheduleLabel(m))} · ${escapeHtml(m.route)}</li>`).join('')}</ul>`:'<p>Sin medicamentos registrados.</p>'}`;
    else if(data.type==='vitals') body=`<h3>Signos vitales</h3>${data.vitals.length?`<table><tr><th>Fecha</th><th>PA</th><th>FC</th><th>Temp.</th><th>SpO₂</th></tr>${data.vitals.slice(0,20).map(v=>`<tr><td>${escapeHtml(fmtDate(v.date))}</td><td>${v.sys}/${v.dia}</td><td>${v.hr}</td><td>${v.temp}</td><td>${v.spo2}%</td></tr>`).join('')}</table>`:'<p>Sin registros.</p>'}`;
    else if(data.type==='care') body=`<h3>Cuidados diarios</h3><p>Completados: ${data.care.filter(x=>x.done).length} de ${data.care.length}.</p><ul>${data.care.map(t=>`<li>${escapeHtml(t.shift||'Turno')} · ${escapeHtml(t.name)} · ${t.done?'Completado':'Pendiente'}</li>`).join('')}</ul>`;
    else if(data.type==='wounds') body=`<h3>Curaciones</h3>${data.wounds.length?`<ul>${data.wounds.map(w=>`<li>${escapeHtml(fmtDate(w.date))} · ${escapeHtml(w.area)} · ${escapeHtml(w.status||'')} · ${escapeHtml(w.obs||'')}</li>`).join('')}</ul>`:'<p>Sin curaciones registradas.</p>'}`;
    else if(data.type==='incidents') body=`<h3>Incidentes</h3>${data.incidents.length?`<ul>${data.incidents.map(i=>`<li>${escapeHtml(i.date)} · ${escapeHtml(i.type)} · ${escapeHtml(i.status)} · ${escapeHtml(i.action||'')}</li>`).join('')}</ul>`:'<p>Sin incidentes registrados.</p>'}`;
    else if(data.type==='appointments') body=`<h3>Citas y traslados</h3>${data.appointments.length?`<ul>${data.appointments.map(a=>`<li>${escapeHtml(a.date)} ${escapeHtml(a.time)} · ${escapeHtml(a.type)} · ${escapeHtml(a.place)} · ${escapeHtml(a.transport)}</li>`).join('')}</ul>`:'<p>Sin citas registradas.</p>'}`;
    else if(data.type==='attendance') body=`<h3>Asistencia del personal</h3><table><tr><th>Fecha</th><th>Colaborador</th><th>Puesto</th><th>Entrada</th><th>Salida</th></tr>${attendanceLog.map(x=>`<tr><td>${x.date}</td><td>${escapeHtml(x.name)}</td><td>${escapeHtml(x.role)}</td><td>${x.clockIn?new Date(x.clockIn).toLocaleTimeString('es-CR'):''}</td><td>${x.clockOut?new Date(x.clockOut).toLocaleTimeString('es-CR'):''}</td></tr>`).join('')}</table>`;
    else if(data.type==='epicrisis') body=`<h3>Resumen clínico</h3><p>Diagnósticos: ${escapeHtml(r.dx)}. Alergias: ${escapeHtml(r.allergy)}. Dieta: ${escapeHtml(r.diet)}.</p><h3>Condición actual</h3><p>${last?`Últimos signos: PA ${last.sys}/${last.dia}, FC ${last.hr}, temperatura ${last.temp} °C, saturación ${last.spo2}%.`:'Sin signos vitales recientes.'}</p><h3>Tratamiento y cuidados</h3><p>${data.medications.length?data.medications.map(m=>`${escapeHtml(m.drug)} (${escapeHtml(medicationScheduleLabel(m))})`).join('; '):'Sin medicamentos registrados.'}</p><h3>Eventos relevantes</h3><p>${data.incidents.length?data.incidents.map(i=>escapeHtml(i.type)).join('; '):'Sin incidentes registrados.'}</p><h3>Condición de egreso / cierre</h3><p>Edite aquí la condición clínica al egreso, recomendaciones, pertenencias entregadas, destino y comunicación con la familia.</p><h3>Firma responsable</h3><p>Nombre: ______________________________ &nbsp;&nbsp; Firma: ______________________________</p>`;
    else body=`<h3>Resumen del día</h3><p>Estado general: ${escapeHtml(r.status)}. ${last?`PA ${last.sys}/${last.dia}, FC ${last.hr}, temperatura ${last.temp} °C, SpO₂ ${last.spo2}%.`:''}</p><p>Medicamentos registrados: ${data.medications.length}. Cuidados completados: ${data.care.filter(x=>x.done).length}/${data.care.length}. Incidentes: ${data.incidents.length}. Citas: ${data.appointments.length}.</p><h3>Observaciones</h3><p>Edite esta sección con las novedades relevantes del día.</p>`;
    return `<div class="report-editor" contenteditable="true" id="editableReport">${heading}${body}</div>`;
  }
  renderReports=function(){
    const reports=[['Reporte diario del hogar','daily'],['Hoja de medicamentos','meds'],['Signos vitales','vitals'],['Cuidados diarios','care'],['Curaciones','wounds'],['Incidentes','incidents'],['Citas y traslados','appointments'],['Asistencia del personal','attendance'],['Epicrisis / resumen de egreso','epicrisis']];
    main.innerHTML=pageHeader('DOCUMENTACIÓN Y CONTROL','Reportes','Informes autollenados, editables y exportables')+`
    <section class="report-help"><strong>¿Cómo funciona?</strong><p>Seleccione un reporte. El sistema lo llena con la información registrada. Puede editar el texto antes de imprimirlo o guardarlo como PDF.</p></section>
    <label class="report-resident-select">Residente<select id="reportResidentSelect">${residents.map(r=>`<option value="${r.id}" ${selectedResident?.id===r.id?'selected':''}>${r.name}</option>`).join('')}</select></label>
    <div class="report-grid">${reports.map(([name,key],i)=>`<button type="button" data-sc-report="${key}"><span class="quick-icon ${i%3===0?'lilac':i%3===1?'mint':'amber'}">${svg.report}</span><div><strong>${name}</strong><small>Autollenado · editable · PDF</small></div><b>›</b></button>`).join('')}</div><section id="reportPreview" class="report-preview hidden"></section>`;
  };

  const oldBindActions=bindActions;
  bindActions=function(){
    oldBindActions();
    document.querySelectorAll('[data-inactive-filter]').forEach(b=>b.addEventListener('click',()=>{scInactiveFilter=b.dataset.inactiveFilter;renderInactiveResidents();bindActions();}));
    document.querySelectorAll('[data-reactivate-resident]').forEach(b=>b.addEventListener('click',async()=>{
      const id=String(b.dataset.reactivateResident||'');
      if(typeof window.BHSC_REACTIVATE_INACTIVE_RESIDENT==='function'){await window.BHSC_REACTIVATE_INACTIVE_RESIDENT(id);return;}
      const itemKey=r=>String(r?.resident_key??r?.residentData?.resident_key??r?.residentData?.id??r?.id??'');
      const idx=inactiveResidents.findIndex(r=>itemKey(r)===id); if(idx<0)return; const item=inactiveResidents[idx];
      if(item.classification==='Fallecido'){showToast('Un expediente por defunción no puede reactivarse.');return;}
      const stableKey=itemKey(item);
      const previousStatus=item.previousStatus&&item.previousStatus!=='Inactivo'?item.previousStatus:'Estable';
      const restored={...(item.residentData||item),id:item.residentData?.id??stableKey,resident_key:item.residentData?.resident_key??stableKey,status:previousStatus,inactiveClassification:'',inactiveReason:''};
      if(!residents.some(r=>String(r?.resident_key??r?.id??'')===stableKey))residents.push(restored);
      inactiveResidents.splice(idx,1);saveResidents();saveInactive();selectedResident=restored;residentScoped=false;showToast('Residente reactivado con su expediente.');renderInactiveResidents();bindActions();
    }));
    document.querySelectorAll('[data-discharge-report]').forEach(b=>b.addEventListener('click',()=>{const id=String(b.dataset.dischargeReport||'');const item=inactiveResidents.find(r=>String(r?.resident_key??r?.residentData?.resident_key??r?.residentData?.id??r?.id??'')===id);if(!item)return;const data=reportData('epicrisis',item.residentData||item);openRecordModal('Epicrisis / cierre de expediente',editableReportHtml(data),'<button class="primary-btn" id="printInactiveClosure">Imprimir / PDF</button>');setTimeout(()=>document.getElementById('printInactiveClosure')?.addEventListener('click',()=>printable(data.title,document.getElementById('editableReport')?.innerHTML||'')),0);}));
    document.getElementById('careShiftSelect')?.addEventListener('change',e=>{scCareShift=e.target.value;localStorage.setItem('seniorcare-care-shift',scCareShift);renderCare();bindActions();});
    document.querySelectorAll('[data-open-care-resident]').forEach(b=>b.addEventListener('click',()=>{selectedResident=residents.find(r=>String(r?.resident_key??r?.id??'')===String(b.dataset.openCareResident)||String(r.id)===String(b.dataset.openCareResident))||selectedResident;scCareShift=b.dataset.careShiftOpen||'Matutino';residentScoped=true;renderCare();bindActions();}));
    document.querySelectorAll('[data-care-check]').forEach(el=>el.addEventListener('change',()=>{const t=getCareTasks(selectedResident.id,scCareShift).find(x=>x.id===Number(el.dataset.careCheck));if(t){t.done=el.checked;t.completedAt=t.done?new Date().toISOString():null;t.completedBy=t.done?(currentUser?.name||'Usuario'):null;saveCarePlans();renderCare();bindActions();}}));
    document.getElementById('addCareTask')?.addEventListener('click',()=>{const name=prompt('Nombre de la nueva tarea:');if(name?.trim()){getCareTasks(selectedResident.id,scCareShift).push({id:Date.now(),name:name.trim(),done:false,shift:scCareShift,completedAt:null});saveCarePlans();renderCare();bindActions();}});
    document.querySelectorAll('[data-sc-care-delete]').forEach(b=>b.addEventListener('click',()=>{const key=careKey(selectedResident.id,scCareShift);carePlans[key]=getCareTasks(selectedResident.id,scCareShift).filter(t=>t.id!==Number(b.dataset.scCareDelete));saveCarePlans();renderCare();bindActions();}));
    document.getElementById('careResidentSelect')?.addEventListener('change',e=>{selectedResident=residents.find(r=>String(r?.resident_key??r?.id??'')===String(e.target.value)||String(r.id)===String(e.target.value))||selectedResident;renderCare();bindActions();});

    document.querySelectorAll('[data-open-nutrition-resident]').forEach(b=>b.addEventListener('click',()=>{selectedResident=residents.find(r=>String(r?.resident_key??r?.id??'')===String(b.dataset.openNutritionResident)||String(r.id)===String(b.dataset.openNutritionResident))||selectedResident;residentScoped=true;renderNutrition();bindActions();}));
    document.getElementById('saveDietPlan')?.addEventListener('click',()=>{const p=dietPlans[selectedResident.id]||{changes:[]};p.base=document.getElementById('dietBase').value.trim();p.current=p.current||p.base;p.texture=document.getElementById('dietTexture').value.trim();p.restrictions=document.getElementById('dietRestrictions').value.trim();p.allergies=document.getElementById('dietAllergies').value.trim();dietPlans[selectedResident.id]=p;selectedResident.diet=p.current||p.base;saveDietPlans();saveResidents();showToast('Plan nutricional guardado.');});
    document.getElementById('saveDietChange')?.addEventListener('click',()=>{const value=document.getElementById('dietChangeValue').value.trim(),reason=document.getElementById('dietChangeReason').value.trim();if(!value||!reason){showToast('Indique dieta y motivo.');return;}const p=dietPlans[selectedResident.id]||{base:selectedResident.diet,changes:[]};p.current=value;p.changes=p.changes||[];p.changes.unshift({date:new Date().toISOString(),value,reason,shift:document.getElementById('dietChangeShift').value,author:currentUser?.name||'Enfermería'});dietPlans[selectedResident.id]=p;selectedResident.diet=value;saveDietPlans();saveResidents();renderNutrition();bindActions();showToast('Cambio de dieta registrado.');});

    document.querySelectorAll('[data-clock-in]').forEach(b=>b.addEventListener('click',()=>{const staffId=Number(b.dataset.clockIn),m=staffMembers.find(x=>x.id===staffId);attendanceLog.push({id:Date.now(),staffId,name:m?.name,role:m?.role,date:(window.BHSC_LOCAL_DATE?window.BHSC_LOCAL_DATE():new Intl.DateTimeFormat('en-CA',{timeZone:'America/Costa_Rica'}).format(new Date())),clockIn:new Date().toISOString(),clockOut:null});saveAttendanceLog();renderStaff();bindActions();showToast('Hora de entrada registrada.');}));
    document.querySelectorAll('[data-clock-out]').forEach(b=>b.addEventListener('click',()=>{const log=[...attendanceLog].reverse().find(x=>x.staffId===Number(b.dataset.clockOut)&&x.clockIn&&!x.clockOut);if(log){log.clockOut=new Date().toISOString();saveAttendanceLog();renderStaff();bindActions();showToast('Hora de salida registrada.');}}));
    document.getElementById('exportAttendanceCsv')?.addEventListener('click',()=>{const rows=[['Fecha','Colaborador','Puesto','Entrada','Salida','Horas']];attendanceLog.forEach(x=>{const hours=x.clockOut?((new Date(x.clockOut)-new Date(x.clockIn))/3600000).toFixed(2):'';rows.push([x.date,x.name,x.role,x.clockIn?new Date(x.clockIn).toLocaleTimeString('es-CR'):'',x.clockOut?new Date(x.clockOut).toLocaleTimeString('es-CR'):'',hours]);});downloadText('asistencia-seniorcare.csv','\ufeff'+rows.map(r=>r.map(csvCell).join(',')).join('\n'));});
    document.getElementById('printAttendance')?.addEventListener('click',()=>{const rows=attendanceLog.map(x=>`<tr><td>${x.date}</td><td>${escapeHtml(x.name)}</td><td>${escapeHtml(x.role)}</td><td>${x.clockIn?new Date(x.clockIn).toLocaleTimeString('es-CR'):''}</td><td>${x.clockOut?new Date(x.clockOut).toLocaleTimeString('es-CR'):''}</td></tr>`).join('');printable('Asistencia del personal',`<h1>Asistencia del personal</h1><table><tr><th>Fecha</th><th>Colaborador</th><th>Puesto</th><th>Entrada</th><th>Salida</th></tr>${rows}</table>`);});
    document.getElementById('shareAttendance')?.addEventListener('click',async()=>{const text=attendanceLog.map(x=>`${x.date} · ${x.name} · Entrada ${x.clockIn?new Date(x.clockIn).toLocaleTimeString('es-CR'):''} · Salida ${x.clockOut?new Date(x.clockOut).toLocaleTimeString('es-CR'):'pendiente'}`).join('\n')||'Sin registros';if(navigator.share){await navigator.share({title:'Asistencia SeniorCare',text});}else{await navigator.clipboard.writeText(text);showToast('Resumen copiado para compartir.');}});

    document.getElementById('saveCoverage')?.addEventListener('click',()=>{const absent=staffMembers.find(m=>m.id===Number(document.getElementById('coverageAbsent').value)),replacement=staffMembers.find(m=>m.id===Number(document.getElementById('coverageReplacement').value)),reason=document.getElementById('coverageReason').value.trim();if(!absent||!replacement||absent.id===replacement.id||!reason){showToast('Complete un reemplazo válido.');return;}coverageChanges.unshift({id:Date.now(),absent:absent.name,replacement:replacement.name,shift:document.getElementById('coverageShift').value,date:document.getElementById('coverageDate').value,reason});saveCoverageChanges();renderHandoff();bindActions();showToast('Cambio de cobertura registrado.');});

    document.querySelectorAll('[data-sc-report]').forEach(b=>b.addEventListener('click',()=>{const resident=residents.find(r=>String(r?.resident_key??r?.id??'')===String(document.getElementById('reportResidentSelect').value)||String(r.id)===String(document.getElementById('reportResidentSelect').value))||selectedResident;scReportDraft=reportData(b.dataset.scReport,resident);const box=document.getElementById('reportPreview');box.classList.remove('hidden');box.innerHTML=`<div class="report-preview-actions"><button class="secondary-btn" id="closeScReport">Cerrar</button><button class="secondary-btn" id="downloadScReport">Descargar texto</button><button class="primary-btn" id="printScReport">Imprimir / PDF</button></div>${editableReportHtml(scReportDraft)}`;box.scrollIntoView({behavior:'smooth',block:'start'});document.getElementById('closeScReport').onclick=()=>box.classList.add('hidden');document.getElementById('downloadScReport').onclick=()=>downloadText('reporte-seniorcare.txt',document.getElementById('editableReport').innerText,'text/plain;charset=utf-8');document.getElementById('printScReport').onclick=()=>printable(scReportDraft.title,document.getElementById('editableReport').innerHTML);}));
    document.getElementById('residentDischargeButton')?.addEventListener('click',()=>{residentScoped=true;activeScreen='reports';renderReports();bindActions();setTimeout(()=>document.querySelector('[data-sc-report="epicrisis"]')?.click(),50);});
    document.getElementById('residentDeactivateButton')?.addEventListener('click',()=>{const classification=prompt('Clasificación: Baja, Traslado o Fallecido','Baja');if(!classification)return;const normalized=classification.trim().toLowerCase();const map={baja:'Baja',traslado:'Traslado',fallecido:'Fallecido',defuncion:'Fallecido',defunción:'Fallecido'};const type=map[normalized];if(!type){showToast('Use Baja, Traslado o Fallecido.');return;}const reason=prompt('Motivo u observación:','');if(reason===null)return;if(!confirm(`¿Confirma ${type.toLowerCase()} de ${selectedResident.name}? El expediente se conservará.`))return;const stableKey=String(selectedResident?.resident_key??selectedResident?.id??'').trim();if(!stableKey){showToast('No se pudo identificar de forma segura al residente.');return;}const previousStatus=selectedResident.status&&selectedResident.status!=='Inactivo'?selectedResident.status:'Estable';inactiveResidents.unshift({id:stableKey,resident_key:stableKey,name:selectedResident.name,age:selectedResident.age,room:selectedResident.room,reason:reason.trim()||type,status:'Inactivo',classification:type,previousStatus,inactiveDate:new Date().toISOString(),residentData:{...selectedResident,resident_key:stableKey,status:'Inactivo'}});selectedResident.status='Inactivo';selectedResident.inactiveClassification=type;selectedResident.inactiveReason=reason.trim()||type;residents=residents.filter(r=>String(r?.resident_key??r?.id??'')!==stableKey);saveResidents();saveInactive();showToast('Residente inactivado correctamente.');renderResidentDetail();bindActions();});

    document.getElementById('admissionForm')?.addEventListener('submit',e=>{const fd=new FormData(e.currentTarget);const plan=String(fd.get('nutritionPlan')||'').trim();setTimeout(()=>{if(selectedResident&&plan){dietPlans[selectedResident.id]={base:selectedResident.diet,current:selectedResident.diet,texture:'Según indicación',restrictions:plan,allergies:selectedResident.allergy,changes:[]};saveDietPlans();}},0);});
  };

  const oldRenderHome=renderHome;
  renderHome=function(){oldRenderHome();if(['admin','nurse','assistant'].includes(currentUser?.role)){const welcome=main.querySelector('.admin-welcome');const staff=staffMembers.find(m=>m.name.toLowerCase().includes((currentUser?.name||'').split(' ')[0]?.toLowerCase()))||staffMembers[0];const today=(window.BHSC_LOCAL_DATE?window.BHSC_LOCAL_DATE():new Intl.DateTimeFormat('en-CA',{timeZone:'America/Costa_Rica'}).format(new Date())),log=attendanceLog.find(x=>x.staffId===staff?.id&&x.date===today);if(welcome&&staff)welcome.insertAdjacentHTML('afterend',`<section class="self-clock-card"><div><span>CONTROL DE ASISTENCIA</span><strong>${staff.name}</strong><small>${log?.clockIn?`Entrada ${new Date(log.clockIn).toLocaleTimeString('es-CR',{hour:'2-digit',minute:'2-digit'})}`:'Entrada no registrada'}${log?.clockOut?` · Salida ${new Date(log.clockOut).toLocaleTimeString('es-CR',{hour:'2-digit',minute:'2-digit'})}`:''}</small></div>${!log?.clockIn?`<button class="primary-btn" data-clock-in="${staff.id}">Marcar entrada</button>`:!log.clockOut?`<button class="secondary-btn" data-clock-out="${staff.id}">Marcar salida</button>`:'<span class="status ok">Jornada cerrada</span>'}</section>`);}
  };

  const oldRenderMore=renderMore;
  renderMore=function(){oldRenderMore();if(currentUser?.role==='admin'){const hand=main.querySelector('[data-go="handoff"] strong');if(hand)hand.textContent='Cobertura de ausencias';const wound=main.querySelector('[data-go="wounds"] small');if(wound)wound.textContent='Historial de procedimientos';const nutrition=main.querySelector('[data-go="nutrition"] small');if(nutrition)nutrition.textContent='Dietas y cambios clínicos';}}

  const oldRenderAdmissions=renderAdmissions;
  renderAdmissions=function(){oldRenderAdmissions();const form=document.getElementById('admissionForm');if(form){form.querySelector('.form-grid').insertAdjacentHTML('beforeend','<label class="wide">Indicaciones nutricionales iniciales<textarea name="nutritionPlan" rows="3" placeholder="Textura, restricciones, suplementos y observaciones"></textarea></label>');}}

  const oldAdmissionSave=saveResidents;
  saveResidents=function(){oldAdmissionSave();};

  const oldRender=render;
  render=function(){oldRender();};
  window.renderVitals=renderVitals;window.renderCare=renderCare;window.renderInactiveResidents=renderInactiveResidents;window.renderWounds=renderWounds;window.renderNutrition=renderNutrition;window.renderStaff=renderStaff;window.renderHandoff=renderHandoff;window.renderReports=renderReports;window.renderUsersAccess=renderUsersAccess;window.bindActions=bindActions;
})();
