/* Bernard Health SeniorCare Enterprise V3.6.3
   Centro Global de Alertas: residentes y personal */
(()=>{
  'use strict';
  const VERSION='4.0.5';
  const ALERTS='seniorcare_alerts';
  const NOTES='seniorcare_nursing_notes';
  const HANDOFFS='seniorcare_handoff_records';
  const INCIDENTS='seniorcare_incident_records';
  let channels=[];
  let syncing=false;
  let activeTab='resident';
  const db=()=>window.seniorcareSupabase||null;
  const me=()=>window.currentUser||null;
  const org=()=>me()?.organizationId||me()?.organization_id||null;
  const role=()=>String(me()?.role||'').toLowerCase();
  const isAdmin=()=>role()==='admin';
  const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
  const now=()=>new Date().toISOString();
  const fmt=v=>{try{return new Date(v).toLocaleString('es-CR',{dateStyle:'medium',timeStyle:'short'})}catch(_){return String(v||'')}};
  const alertList=()=>Array.isArray(window.BHSC_GET_ALERTS?.())?window.BHSC_GET_ALERTS():[];
  const roleLabel=v=>({nurse:'Enfermería',assistant:'Asistentes',security:'Seguridad',cook:'Cocina',cleaning:'Miscelánea',maintenance:'Mantenimiento',admin:'Administración'}[String(v||'').toLowerCase()]||String(v||'Personal'));
  const categoryOf=a=>{
    const explicit=a.category||a.data?.category;
    if(explicit==='staff'||explicit==='resident')return explicit;
    const type=String(a.type||a.alert_type||'').toLowerCase();
    if(['handoff','staff_incident','attendance','operational','operational_incident','staff_note'].includes(type))return 'staff';
    if(type==='incident'&&!a.residentId&&!a.residentKey&&!a.data?.resident_key)return 'staff';
    return 'resident';
  };
  const priorityClass=p=>String(p||'').toLowerCase()==='alta'?'danger':String(p||'').toLowerCase()==='informativa'?'ok':'warn';
  const iconFor=a=>{
    const t=String(a.type||'').toLowerCase();
    if(t==='nursing_note')return 'report';
    if(t==='handoff')return 'exchange';
    if(t==='staff_incident'||t==='incident')return 'alert';
    if(t==='medication')return 'bottle';
    if(t==='wound')return 'wound';
    if(t==='appointment')return 'calendar';
    if(t==='care')return 'care';
    return 'bell';
  };
  function sourceAlert({key,title,detail,priority='Informativa',type='general',category='resident',residentKey=null,residentName='',target=null,created=now(),author='',authorRole='',sourceTable='',sourceId='',meta={}},existing){
    return {
      organization_id:org(),alert_key:key,source_key:key,title,detail,priority,
      status:existing?.status||'Nueva',alert_type:type,resident_key:residentKey||null,
      target_screen:target,created_at:created,
      data:{id:key,sourceKey:key,title,detail,priority,status:existing?.status||'Nueva',type,category,residentId:residentKey||null,residentKey:residentKey||null,residentName,target,created,author,authorRole,sourceTable,sourceId,...meta},
      active:true,updated_at:now(),updated_by:me()?.id||null
    };
  }
  async function syncSourceAlerts(){
    if(syncing||!db()||!org())return;
    syncing=true;
    try{
      const [notesRes,handoffRes,incidentRes,alertsRes]=await Promise.all([
        db().from(NOTES).select('*').eq('organization_id',org()).eq('active',true).order('recorded_at',{ascending:false}).limit(250),
        db().from(HANDOFFS).select('*').eq('organization_id',org()).eq('active',true).order('recorded_at',{ascending:false}).limit(250),
        db().from(INCIDENTS).select('*').eq('organization_id',org()).eq('active',true).order('occurred_at',{ascending:false}).limit(250),
        db().from(ALERTS).select('alert_key,status,active,updated_at').eq('organization_id',org())
      ]);
      for(const r of [notesRes,handoffRes,incidentRes,alertsRes])if(r.error)throw r.error;
      const existing=new Map((alertsRes.data||[]).map(x=>[String(x.alert_key),x]));
      const rows=[];
      const maySync=key=>existing.get(String(key))?.active!==false;
      for(const n of notesRes.data||[]){
        const key=`nursing_note:${n.note_key}`;
        if(!maySync(key))continue;
        const text=String(n.note_text||n.data?.note||'').trim();
        const clinical=String(n.clinical_status||n.data?.status||'').trim();
        rows.push(sourceAlert({key,title:'Nota de enfermería',detail:`${n.resident_name||'Residente'} · ${n.author_name||'Enfermería'} · ${clinical||n.shift_name||'Evolución'}${text?` · ${text.slice(0,150)}`:''}`,priority:/requiere|observación|urgente/i.test(clinical)?'Alta':'Informativa',type:'nursing_note',category:'resident',residentKey:n.resident_key,residentName:n.resident_name,target:'nursing',created:n.recorded_at||n.created_at,author:n.author_name,authorRole:'nurse',sourceTable:NOTES,sourceId:n.note_key,meta:{shift:n.shift_name,clinicalStatus:clinical}},existing.get(key)));
      }
      for(const h of handoffRes.data||[]){
        const key=`handoff:${h.handoff_key}`;
        if(!maySync(key))continue;
        const d=h.data||{};
        const pending=String(d.pending||'').trim();
        const authorRole=h.author_role||d.authorRole||'';
        const status=h.record_status||d.recordStatus||'submitted';
        rows.push(sourceAlert({key,title:`Entrega de turno · ${roleLabel(authorRole)}`,detail:`${h.author_name||'Personal'} → ${h.receiver_name||'Sin relevo'} · ${h.outgoing_shift||'Turno'}${pending?` · Pendientes: ${pending.slice(0,130)}`:''}`,priority:pending?'Pendiente':'Informativa',type:'handoff',category:'staff',target:null,created:h.recorded_at||h.created_at,author:h.author_name,authorRole,sourceTable:HANDOFFS,sourceId:h.handoff_key,meta:{incomingShift:h.incoming_shift,recordStatus:status,news:d.news||'',pending, instructions:d.instructions||''}},existing.get(key)));
      }
      for(const i of incidentRes.data||[]){
        const d=i.data||{};
        const authorRole=d.authorRole||d.author_role||d.role||'';
        const hasResident=!!String(i.resident_key||i.resident_name||d.resident||'').trim();
        const staffRole=/security|seguridad|cook|cocina|cleaning|limpieza|miscel|maintenance|mantenimiento/i.test(authorRole);
        if(hasResident&&!staffRole)continue; // ya lo maneja el flujo clínico conectado
        const key=`staff_incident:${i.incident_key}`;
        if(!maySync(key))continue;
        rows.push(sourceAlert({key,title:`Incidente del personal · ${roleLabel(authorRole)}`,detail:`${d.author||d.authorName||'Personal'} · ${i.incident_type||d.type||'Incidente'} · ${(i.description||d.description||'').slice(0,160)}`,priority:String(i.severity||d.level||'').toLowerCase()==='alta'?'Alta':'Pendiente',type:'staff_incident',category:'staff',target:'incidents',created:i.occurred_at||i.created_at,author:d.author||d.authorName||'',authorRole,sourceTable:INCIDENTS,sourceId:i.incident_key,meta:{status:i.status||d.status||'',action:i.action_taken||d.action||''}},existing.get(key)));
      }
      if(rows.length){const {error}=await db().from(ALERTS).upsert(rows,{onConflict:'organization_id,alert_key'});if(error)throw error;}
      await window.BHSC_ALERTS_PULL?.({render:isAdmin()&&window.activeScreen==='alerts'});
    }catch(e){console.error('[BHSC Global Alerts sync]',e);}finally{syncing=false;}
  }
  async function updateAlert(id,patch,message){
    const row={...patch,updated_at:now(),updated_by:me()?.id||null};
    const {error}=await db().from(ALERTS).update(row).eq('organization_id',org()).eq('alert_key',String(id));
    if(error){window.showToast?.(error.message);return;}
    await window.BHSC_ALERTS_PULL?.({render:false});
    renderGlobalAlerts();window.showToast?.(message);
  }
  async function deleteAlert(id){
    const {error}=await db().from(ALERTS).update({active:false,status:'Eliminada',updated_at:now(),updated_by:me()?.id||null}).eq('organization_id',org()).eq('alert_key',String(id));
    if(error){window.showToast?.(error.message);return false;}
    await window.BHSC_ALERTS_PULL?.({render:false});renderGlobalAlerts();window.showToast?.('Alerta eliminada definitivamente del centro.');
    return true;
  }
  async function deleteShownAlerts(){
    const all=alertList();
    const shown=activeTab==='staff'?all.filter(a=>categoryOf(a)==='staff'&&a.status!=='Archivada'):activeTab==='archived'?all.filter(a=>a.status==='Archivada'):all.filter(a=>categoryOf(a)==='resident'&&a.status!=='Archivada');
    if(!shown.length){window.showToast?.('No hay alertas para eliminar.');return;}
    if(!confirm(`¿Eliminar las ${shown.length} alertas visibles de esta sección? Esta acción no elimina el registro clínico u operativo original.`))return;
    const keys=shown.map(a=>String(a.id)).filter(Boolean);
    const {error}=await db().from(ALERTS).update({active:false,status:'Eliminada',updated_at:now(),updated_by:me()?.id||null}).eq('organization_id',org()).in('alert_key',keys);
    if(error){window.showToast?.(error.message);return;}
    await window.BHSC_ALERTS_PULL?.({render:false});renderGlobalAlerts();window.showToast?.(`${keys.length} alertas eliminadas.`);
  }
  async function refreshAlerts(button){
    if(button){button.disabled=true;button.textContent='Actualizando…';}
    try{
      await syncSourceAlerts();
      await window.BHSC_ALERTS_PULL?.({render:false});
      renderGlobalAlerts();
      window.showToast?.('Alertas actualizadas.');
    }catch(e){window.showToast?.(e?.message||'No se pudieron actualizar las alertas.');}
    finally{if(button){button.disabled=false;button.textContent='Actualizar';}}
  }
  function detailText(a){return a.detail||a.data?.detail||'';}
  function card(a){
    const cat=categoryOf(a),status=String(a.status||'Nueva'),archived=status==='Archivada';
    const icon=window.svg?.[iconFor(a)]||window.svg?.bell||'';
    const author=a.author||a.data?.author||'';
    const authorRole=a.authorRole||a.data?.authorRole||'';
    return `<article class="global-alert-card ${archived?'is-archived':''}" data-global-alert="${esc(a.id)}"><div class="global-alert-icon ${cat==='staff'?'staff':'resident'}">${icon}</div><div class="global-alert-main"><div class="global-alert-title-row"><strong>${esc(a.title||'Alerta')}</strong><span class="status ${priorityClass(a.priority)}">${esc(a.priority||'Pendiente')}</span></div><p>${esc(detailText(a))}</p><div class="global-alert-meta"><span>${esc(fmt(a.created))}</span><span>${esc(status)}</span>${author?`<span>${esc(author)}${authorRole?` · ${esc(roleLabel(authorRole))}`:''}</span>`:''}</div></div><div class="global-alert-actions">${a.target?`<button class="mini-btn" data-ga-open="${esc(a.id)}">Abrir</button>`:''}<button class="mini-btn" data-ga-status="${esc(a.id)}" data-status="Vista" ${status!=='Nueva'?'disabled':''}>Vista</button><button class="mini-btn" data-ga-status="${esc(a.id)}" data-status="En seguimiento" ${archived?'disabled':''}>Seguimiento</button><button class="mini-btn" data-ga-status="${esc(a.id)}" data-status="Resuelta" ${status==='Resuelta'||archived?'disabled':''}>Resolver</button><button class="mini-btn" data-ga-status="${esc(a.id)}" data-status="Archivada" ${archived?'disabled':''}>Archivar</button><button class="icon-delete" data-ga-delete="${esc(a.id)}" title="Eliminar">×</button></div></article>`;
  }
  function renderGlobalAlerts(){
    if(!isAdmin())return previousAlerts?.();
    const root=document.getElementById('mainContent');if(!root)return;
    const all=alertList();
    const resident=all.filter(a=>categoryOf(a)==='resident'&&a.status!=='Archivada');
    const staff=all.filter(a=>categoryOf(a)==='staff'&&a.status!=='Archivada');
    const archived=all.filter(a=>a.status==='Archivada');
    const shown=activeTab==='staff'?staff:activeTab==='archived'?archived:resident;
    const newCount=all.filter(a=>a.status==='Nueva').length;
    const high=all.filter(a=>a.status!=='Archivada'&&a.status!=='Resuelta'&&a.priority==='Alta').length;
    root.innerHTML=window.pageHeader('CENTRO OPERATIVO','Alertas','Seguimiento central de residentes y personal')+`<section class="global-alert-summary"><article><span>Nuevas</span><strong>${newCount}</strong></article><article><span>Alta prioridad</span><strong>${high}</strong></article><article><span>Residentes</span><strong>${resident.length}</strong></article><article><span>Personal</span><strong>${staff.length}</strong></article></section><div class="global-alert-tabs"><button data-ga-tab="resident" class="${activeTab==='resident'?'active':''}">Alertas de residentes <b>${resident.length}</b></button><button data-ga-tab="staff" class="${activeTab==='staff'?'active':''}">Alertas del personal <b>${staff.length}</b></button><button data-ga-tab="archived" class="${activeTab==='archived'?'active':''}">Archivadas <b>${archived.length}</b></button></div><section class="global-alert-panel"><div class="global-alert-panel-head"><div><span>${activeTab==='staff'?'PERSONAL':activeTab==='archived'?'ARCHIVO':'RESIDENTES'}</span><h3>${activeTab==='staff'?'Reportes, incidentes y entregas de turno':activeTab==='archived'?'Alertas cerradas y archivadas':'Alertas clínicas por residente'}</h3></div><div class="global-alert-head-actions"><button class="secondary-btn" id="gaSyncNow">Actualizar</button><button class="danger-action-btn" id="gaDeleteShown">Eliminar todas</button></div></div><div class="global-alert-list">${shown.length?shown.map(card).join(''):window.empty?.('No hay alertas en esta sección.')||'<p>Sin alertas.</p>'}</div></section>`;
  }
  function findAlert(id){return alertList().find(a=>String(a.id)===String(id));}
  function openAlert(a){
    if(!a?.target)return;
    const residents=window.residents||[];
    const key=String(a.residentKey||a.residentId||a.data?.residentKey||a.data?.residentId||'');
    const r=residents.find(x=>String(window.residentKey?.(x)||x.resident_key||x.id)===key)||residents.find(x=>String(x.name||'')===String(a.residentName||a.data?.residentName||''));
    updateAlert(a.id,{status:a.status==='Nueva'?'Vista':a.status},'Alerta abierta.').then(()=>window.go?.(a.target,r?{resident:r,scope:'resident'}:{scope:'global'}));
  }
  function wire(){
    if(!db()||!org()||channels.length)return;
    for(const table of [NOTES,HANDOFFS,INCIDENTS]){
      const ch=db().channel(`bhsc-global-alerts-${table}-${org()}`).on('postgres_changes',{event:'*',schema:'public',table,filter:`organization_id=eq.${org()}`},()=>setTimeout(syncSourceAlerts,180)).subscribe();
      channels.push(ch);
    }
    syncSourceAlerts();
  }
  const previousAlerts=window.renderAlerts||(()=>{try{return renderAlerts()}catch(_){}});
  const previousMore=window.renderMore;
  const previousHandoff=window.renderHandoff;
  window.renderAlerts=renderGlobalAlerts;
  window.renderMore=function(){previousMore?.();if(isAdmin())document.querySelectorAll('[data-go="handoff"]').forEach(x=>x.closest('.module-card,button')?.remove());};
  window.renderHandoff=function(){if(isAdmin()){activeTab='staff';window.activeScreen='alerts';renderGlobalAlerts();window.bindActions?.();}else previousHandoff?.();};
  try{renderAlerts=renderGlobalAlerts;renderMore=window.renderMore;renderHandoff=window.renderHandoff;}catch(_){ }
  document.addEventListener('click',e=>{
    if(!isAdmin())return;
    const tab=e.target.closest('[data-ga-tab]');if(tab){e.preventDefault();activeTab=tab.dataset.gaTab;renderGlobalAlerts();return;}
    const sync=e.target.closest('#gaSyncNow');if(sync){e.preventDefault();refreshAlerts(sync);return;}
    const delAll=e.target.closest('#gaDeleteShown');if(delAll){e.preventDefault();deleteShownAlerts();return;}
    const open=e.target.closest('[data-ga-open]');if(open){e.preventDefault();openAlert(findAlert(open.dataset.gaOpen));return;}
    const state=e.target.closest('[data-ga-status]');if(state){e.preventDefault();updateAlert(state.dataset.gaStatus,{status:state.dataset.status},`Alerta: ${state.dataset.status}.`);return;}
    const del=e.target.closest('[data-ga-delete]');if(del){e.preventDefault();if(confirm('¿Eliminar esta alerta del Centro de Alertas?'))deleteAlert(del.dataset.gaDelete);return;}
  },true);
  window.addEventListener('seniorcare:user-ready',()=>setTimeout(wire,400));
  window.addEventListener('focus',()=>{if(org())syncSourceAlerts()});
  setTimeout(wire,1300);
  window.BHSC_GLOBAL_ALERTS={version:VERSION,sync:syncSourceAlerts,render:renderGlobalAlerts};
  console.info(`Centro Global de Alertas ${VERSION} listo`);
})();
