/* Bernard Health SeniorCare Enterprise V3.7.0 — Asistente Global */
(function(){
  'use strict';

  const VERSION='3.7.3';
  const role=()=>String(window.currentUser?.role||'').toLowerCase();
  const isAssistant=()=>role()==='assistant';
  const esc=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
  const normalize=v=>String(v||'').normalize('NFD').replace(/[\u0300-\u036f]/g,'').toLowerCase().trim();
  const stableResidentKey=r=>String(window.residentKey?.(r)||r?.resident_key||r?.id||'').trim();
  const localDay=()=>new Date().toLocaleDateString('en-CA',{timeZone:'America/Costa_Rica'});
  const staffList=()=>Array.isArray(window.staffMembers)?window.staffMembers:[];
  const residentsList=()=>Array.isArray(window.residents)?window.residents:[];
  const attendanceList=()=>Array.isArray(window.attendanceLog)?window.attendanceLog:[];
  const careStore=()=>window.carePlans||{};
  const nutritionStore=()=>window.nutritionRecords||{};
  const incidentsList=()=>Array.isArray(window.incidents)?window.incidents:[];
  const appointmentsList=()=>Array.isArray(window.appointments)?window.appointments:[];


  const FORBIDDEN_ASSISTANT_SCREENS=new Set(['medications','wounds','nursing','medicalNotes','reports','admissions','inactive','staff','inventory','usersAccess']);

  function removeForbiddenAssistantControls(scope=document){
    if(!isAssistant())return;
    const selectors=[
      '.family-whatsapp-btn','#familyWhatsAppButton','[data-family-whatsapp]',
      '#residentDischargeButton','#residentDeactivateButton','.resident-admin-actions',
      '[data-go="medications"]','[data-resident-go="medications"]',
      '[data-go="wounds"]','[data-resident-go="wounds"]',
      '[data-go="nursing"]','[data-resident-go="nursing"]',
      '[data-go="medicalNotes"]','[data-resident-go="medicalNotes"]',
      '[data-go="reports"]','[data-resident-go="reports"]'
    ];
    scope.querySelectorAll?.(selectors.join(',')).forEach(el=>el.remove());
    scope.querySelectorAll?.('.module-card,.quick-card,.report-grid button').forEach(el=>{
      const text=normalize(el.textContent);
      if(text.includes('medicamento')||text.includes('curacion')||text.includes('nota de enfermeria')||text.includes('nota medica')||text.includes('egreso')||text.includes('epicrisis')) el.remove();
    });
  }

  function enforceAssistantRoute(){
    if(!isAssistant())return true;
    const screen=String(window.activeScreen||'');
    if(!FORBIDDEN_ASSISTANT_SCREENS.has(screen))return true;
    window.residentScoped=false;
    window.activeScreen='home';
    renderAssistantHome();
    window.showToast?.('Esta función no está habilitada para el perfil Asistente.');
    return false;
  }

  function currentStaff(){
    const uid=String(window.currentUser?.id||'');
    const name=normalize(window.currentUser?.name||window.currentUser?.full_name);
    return staffList().find(m=>String(m.linkedUserId||m.linked_user_id||'')===uid)
      || staffList().find(m=>normalize(m.name)===name)
      || null;
  }

  function assignedResidents(){
    const member=currentStaff();
    let rows=[];
    try{rows=window.getAssignedResidentsForStaff?.(member)||[];}catch(_){rows=[];}
    const map=window.residentAssignments||{};
    if(!rows.length&&member){
      const aliases=[String(member.id||''),String(member.linkedUserId||member.linked_user_id||''),String(window.currentUser?.id||'')].filter(Boolean);
      const keys=[...new Set(aliases.flatMap(k=>Array.isArray(map[k])?map[k]:[]).map(String))];
      rows=residentsList().filter(r=>keys.includes(String(r.id))||keys.includes(stableResidentKey(r)));
    }
    return [...new Map(rows.map(r=>[stableResidentKey(r),r])).values()].filter(Boolean);
  }

  function myAttendance(){
    const uid=String(window.currentUser?.id||'');
    const key=`user:${uid}`;
    return [...attendanceList()].reverse().find(x=>String(x.date)===localDay()&&(String(x.staffId)===key||String(x.userId||'')===uid))||null;
  }
  const time=v=>v?new Date(v).toLocaleTimeString('es-CR',{hour:'2-digit',minute:'2-digit'}):'No registrada';

  function taskRows(){
    const assigned=new Set(assignedResidents().map(stableResidentKey));
    const out=[];
    for(const [key,tasks] of Object.entries(careStore())){
      const split=String(key).split(':');
      const shift=split.pop()||'Matutino';
      const residentKey=split.join(':');
      if(!assigned.has(residentKey)||!Array.isArray(tasks))continue;
      const resident=assignedResidents().find(r=>stableResidentKey(r)===residentKey);
      tasks.forEach(task=>out.push({resident,shift,task}));
    }
    return out;
  }

  function todayNutritionCount(){
    const assigned=new Set(assignedResidents().map(stableResidentKey));
    return Object.entries(nutritionStore()).flatMap(([key,list])=>{
      const residentKey=String(key).split(':')[0];
      return assigned.has(residentKey)&&Array.isArray(list)?list:[];
    }).filter(x=>new Date(x.date||x.recordedAt||x.recorded_at||0).toLocaleDateString('en-CA',{timeZone:'America/Costa_Rica'})===localDay()).length;
  }

  const original={
    home:window.renderHome,
    more:window.renderMore,
    residents:window.renderResidents,
    resident:window.renderResidentDetail,
    care:window.renderCare,
    bind:window.bindActions
  };

  function renderAssistantHome(){
    if(!isAssistant())return original.home?.();
    const first=(window.currentUser?.name||window.currentUser?.full_name||'Asistente').split(' ')[0];
    const assigned=assignedResidents();
    const pending=taskRows().filter(x=>!x.task?.done).length;
    const log=myAttendance();
    const openIncidents=incidentsList().filter(i=>i.status!=='Resuelto'&&assigned.some(r=>String(i.resident||i.residentName||'')===String(r.name))).length;
    window.main.innerHTML=`
      <section class="admin-welcome role-welcome assistant-global-hero">
        <div><span class="eyebrow">PANEL DE ASISTENTE</span><h2>${window.greeting?.()||'Bienvenido'}, ${esc(first)}</h2><p>Consulte sus residentes asignados, ejecute los cuidados del turno y registre las novedades operativas.</p></div>
        <div class="admin-mark">${window.svg?.care||''}</div>
      </section>
      <section class="self-clock-card final-clock assistant-global-clock">
        <div><span>CONTROL DE ASISTENCIA</span><strong>${esc(window.currentUser?.name||window.currentUser?.full_name||'Asistente')}</strong><small>${log?.clockIn?`Entrada ${time(log.clockIn)}`:'Entrada no registrada'}${log?.clockOut?` · Salida ${time(log.clockOut)}`:''}</small></div>
        <div class="self-clock-actions">${!log?.clockIn?'<button class="clock-btn clock-in" data-self-clock-in>Marcar entrada</button>':!log.clockOut?'<button class="clock-btn clock-out" data-self-clock-out>Marcar salida</button>':'<span class="status ok">Jornada cerrada</span>'}</div>
      </section>
      <section class="admin-metrics assistant-global-metrics">
        ${window.metric('users','lilac','Residentes asignados',assigned.length,'Solo los asignados por Administración','residents')}
        ${window.metric('care','mint','Cuidados pendientes',pending,'Planes por residente y turno','care')}
        ${window.metric('food','rose','Ingestas de hoy',todayNutritionCount(),'Alimentación e hidratación','nutrition')}
        ${window.metric('alert','rose','Incidentes abiertos',openIncidents,'Reportes enviados a Administración','incidents')}
        ${window.metric('calendar','blue','Agenda',appointmentsList().length,'Citas y traslados','agenda')}
        ${window.metric('exchange','lilac','Entrega de turno',(window.handoffRecords||[]).filter(x=>x.authorRole==='assistant').length,'Respaldo para Administración','handoff')}
      </section>
      <section class="assistant-global-actions">
        <button class="quick-card" data-go="residents"><span class="quick-icon lilac">${window.svg?.users||''}</span><div><strong>Mis residentes</strong><small>Indicaciones y expediente permitido</small></div><b>›</b></button>
        <button class="quick-card" data-go="care"><span class="quick-icon mint">${window.svg?.care||''}</span><div><strong>Cuidados del turno</strong><small>Marcar únicamente tareas asignadas</small></div><b>›</b></button>
        <button class="quick-card" data-go="nutrition"><span class="quick-icon rose">${window.svg?.food||''}</span><div><strong>Alimentación</strong><small>Registrar ingesta e hidratación</small></div><b>›</b></button>
        <button class="quick-card" data-go="incidents"><span class="quick-icon rose">${window.svg?.alert||''}</span><div><strong>Reportar incidente</strong><small>Se enviará al Centro de Alertas</small></div><b>›</b></button>
        <button class="quick-card" data-go="handoff"><span class="quick-icon lilac">${window.svg?.exchange||''}</span><div><strong>Entrega de turno</strong><small>Novedades, pendientes e indicaciones</small></div><b>›</b></button>
      </section>`;
  }

  function renderAssistantMore(){
    if(!isAssistant())return original.more?.();
    window.main.innerHTML=window.pageHeader('HERRAMIENTAS DEL ASISTENTE','Más','Funciones operativas habilitadas para su cuenta')+`
      <div class="more-grid assistant-global-more">
        ${window.moduleCard('users','lilac','Residentes asignados','Consultar indicaciones individuales','residents')}
        ${window.moduleCard('heart','blue','Signos vitales','Registrar controles permitidos','vitals')}
        ${window.moduleCard('care','mint','Cuidados diarios','Ejecutar tareas del turno','care')}
        ${window.moduleCard('food','rose','Alimentación','Registrar ingesta e hidratación','nutrition')}
        ${window.moduleCard('alert','rose','Incidentes','Reportar novedades a Administración','incidents')}
        ${window.moduleCard('calendar','blue','Citas y traslados','Consultar agenda','agenda')}
        ${window.moduleCard('exchange','lilac','Entrega de turno','Registrar continuidad del cuidado','handoff')}
      </div>`;
  }

  function renderAssistantResidents(){
    if(!isAssistant())return original.residents?.();
    const assigned=assignedResidents();
    const stable=assigned.filter(r=>normalize(r.status).includes('estable')).length;
    window.main.innerHTML=window.pageHeader('RESIDENTES ASIGNADOS','Mis residentes','Solo los residentes asignados por Administración')+`
      <section class="assistant-assignment-summary"><article><span>Asignados</span><strong>${assigned.length}</strong></article><article><span>Estables</span><strong>${stable}</strong></article><article><span>En observación</span><strong>${Math.max(0,assigned.length-stable)}</strong></article></section>
      <section class="residents-actions"><label class="searchbox residents-search">${window.svg?.search||''}<input id="residentSearch" placeholder="Buscar por nombre o habitación"></label></section>
      <div class="resident-grid professional-resident-grid">${assigned.length?assigned.map(r=>`<button class="resident-card professional-resident-card" data-resident="${esc(String(r.id))}"><div class="avatar">${esc((r.name||'R').split(' ').map(x=>x[0]).slice(0,2).join(''))}</div><div class="resident-card-copy"><strong>${esc(r.name)}</strong><span>${esc(r.age)} años · ${esc(r.room||'Sin habitación')}</span><small>${esc(r.diet||'Sin dieta registrada')}</small></div>${window.statusPill(r.status)}<b class="resident-arrow">›</b></button>`).join(''):window.empty('No tiene residentes asignados. Administración debe definir la asignación en Personal y turnos.')}</div>`;
    setTimeout(()=>document.getElementById('residentSearch')?.addEventListener('input',e=>{
      document.querySelectorAll('.professional-resident-card').forEach(card=>card.style.display=normalize(card.textContent).includes(normalize(e.target.value))?'':'none');
    }),0);
  }

  function renderAssistantCare(){
    if(!isAssistant())return original.care?.();
    if(window.residentScoped&&window.selectedResident){
      const allowed=assignedResidents().some(r=>stableResidentKey(r)===stableResidentKey(window.selectedResident));
      if(!allowed){window.residentScoped=false;return renderAssistantResidents();}
      original.care?.();
      document.querySelectorAll('[data-care328-edit],[data-care328-save],[data-care328-add],#editCarePlan,#saveCarePlan,#addCarePlanOption').forEach(x=>x.remove());
      return;
    }
    const rows=taskRows();
    const pending=rows.filter(x=>!x.task?.done);
    window.main.innerHTML=window.pageHeader('CUIDADOS ASIGNADOS','Cuidados del turno','Tareas definidas por Administración para sus residentes asignados')+`
      <section class="care-review-summary"><article><span>Residentes asignados</span><strong>${assignedResidents().length}</strong></article><article><span>Pendientes</span><strong>${pending.length}</strong></article><article><span>Completados hoy</span><strong>${rows.filter(x=>x.task?.done).length}</strong></article></section>
      <div class="care-review-list">${pending.length?pending.map(x=>`<article><div><strong>${esc(x.resident?.name||'Residente')}</strong><span>${esc(x.shift)} · ${esc(x.task?.name||'Tarea')}</span></div><span class="status warn">Pendiente</span><button class="mini-btn" data-assistant370-care="${esc(stableResidentKey(x.resident))}" data-assistant370-shift="${esc(x.shift)}">Abrir</button></article>`).join(''):window.empty(rows.length?'No hay cuidados pendientes.':'No existen tareas asignadas para sus residentes.')}</div>`;
  }

  function renderAssistantResident(){
    if(!isAssistant())return original.resident?.();
    if(!window.selectedResident||!assignedResidents().some(r=>stableResidentKey(r)===stableResidentKey(window.selectedResident))){
      window.residentScoped=false;return renderAssistantResidents();
    }
    original.resident?.();
    document.querySelectorAll('.family-whatsapp-btn,#familyWhatsAppButton,[data-family-whatsapp]').forEach(x=>x.remove());
    const allowed=['vitals','care','nutrition','agenda','incidents'];
    document.querySelectorAll('[data-resident-go]').forEach(btn=>{if(!allowed.includes(btn.dataset.residentGo))btn.remove();});
    document.querySelectorAll('[data-go="medicalNotes"],[data-go="medications"],[data-go="wounds"],[data-go="nursing"],[data-go="reports"],[data-resident-go="medicalNotes"],[data-resident-go="medications"],[data-resident-go="wounds"],[data-resident-go="nursing"],[data-resident-go="reports"]').forEach(x=>x.remove());
    removeForbiddenAssistantControls(window.main);
    const hero=window.main.querySelector('.profile-hero');
    if(hero&&!hero.querySelector('.assistant-readonly-note'))hero.insertAdjacentHTML('beforeend','<span class="assistant-readonly-note">Acceso operativo del Asistente</span>');
  }

  function bindAssistant(){
    original.bind?.();
    if(!isAssistant())return;
    if(!enforceAssistantRoute())return;
    removeForbiddenAssistantControls(document);
    document.querySelectorAll('[data-assistant370-care]').forEach(btn=>btn.addEventListener('click',e=>{
      e.preventDefault();e.stopImmediatePropagation();
      const r=assignedResidents().find(x=>stableResidentKey(x)===String(btn.dataset.assistant370Care));
      if(!r)return;
      localStorage.setItem('seniorcare-care-shift',btn.dataset.assistant370Shift||'Matutino');
      window.go?.('care',{resident:r,scope:'resident'});
    },true));
  }


  document.addEventListener('click',event=>{
    if(!isAssistant())return;
    const target=event.target.closest('[data-go],[data-resident-go],#residentDischargeButton,#residentDeactivateButton,.family-whatsapp-btn,#familyWhatsAppButton,[data-family-whatsapp]');
    if(!target)return;
    const screen=target.dataset.go||target.dataset.residentGo||'';
    if(FORBIDDEN_ASSISTANT_SCREENS.has(screen)||target.matches('#residentDischargeButton,#residentDeactivateButton,.family-whatsapp-btn,#familyWhatsAppButton,[data-family-whatsapp]')){
      event.preventDefault();
      event.stopImmediatePropagation();
      target.remove();
      window.showToast?.('Esta función no está habilitada para el perfil Asistente.');
    }
  },true);

  const assistantObserver=new MutationObserver(()=>{
    if(isAssistant())removeForbiddenAssistantControls(document);
  });
  assistantObserver.observe(document.documentElement,{childList:true,subtree:true});

  window.renderHome=renderAssistantHome;
  window.renderMore=renderAssistantMore;
  window.renderResidents=renderAssistantResidents;
  window.renderCare=renderAssistantCare;
  window.renderResidentDetail=renderAssistantResident;
  window.bindActions=bindAssistant;
  if(isAssistant())document.body.classList.add('assistant-role');
  window.addEventListener('seniorcare:user-ready',()=>{document.body.classList.toggle('assistant-role',isAssistant());});
  window.BHSC_ASSISTANT_GLOBAL_VERSION=VERSION;
  console.info(`Asistente Global ${VERSION} listo`);
})();
