(()=>{
'use strict';
if(window.__deletionGlobalV361)return;window.__deletionGlobalV361=true;
const db=()=>window.seniorcareSupabase;
const toast=m=>window.showToast?window.showToast(m):alert(m);
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
async function decorateOrganizations(){
 document.querySelectorAll('.supervisor-org-card').forEach(card=>{
  if(card.querySelector('[data-delete-org-v361]'))return;
  const open=card.querySelector('[data-sg-open]'); if(!open)return;
  const id=open.dataset.sgOpen; const name=card.querySelector('h3')?.textContent?.trim()||'esta organización';
  const actions=card.querySelector('.supervisor-org-actions'); if(!actions)return;
  actions.insertAdjacentHTML('beforeend',`<button class="danger-action-btn" data-delete-org-v361="${esc(id)}" data-name="${esc(name)}">Eliminar definitivamente</button>`);
 });
}
async function decorateAdmins(){
 document.querySelectorAll('.supervisor-admin-list article').forEach(card=>{
  if(card.querySelector('[data-delete-admin-v361]'))return;
  const toggle=card.querySelector('[data-sg-admin]');if(!toggle)return;
  const id=toggle.dataset.sgAdmin; const org=toggle.dataset.org||''; const name=card.querySelector('h3')?.textContent?.trim()||'este administrador';
  toggle.insertAdjacentHTML('afterend',`<button class="danger-action-btn" data-delete-admin-v361="${esc(id)}" data-org="${esc(org)}" data-name="${esc(name)}">Eliminar</button>`);
 });
}
function decorateStaff(){
 document.querySelectorAll('.global-staff-card').forEach(card=>{
  const old=card.querySelector('[data-staff-global-delete]'); if(!old||card.querySelector('[data-delete-staff-v361]'))return;
  const id=old.dataset.staffGlobalDelete; const name=card.querySelector('.staff-name strong')?.textContent?.trim()||'este colaborador';
  const linked=(window.staffMembers||[]).find(x=>String(x.id)===String(id))?.linkedUserId||'';
  const btn=old.cloneNode(true); btn.removeAttribute('data-staff-global-delete'); btn.setAttribute('data-delete-staff-v361',id); btn.setAttribute('data-linked-user',linked); btn.setAttribute('data-name',name); btn.setAttribute('aria-label','Eliminar definitivamente'); old.replaceWith(btn);
 });
}
const wrap=(name,decorator)=>{const original=window[name];if(typeof original!=='function'||original.__v361)return;const wrapped=async function(...args){const out=await original.apply(this,args);setTimeout(decorator,0);return out};wrapped.__v361=true;window[name]=wrapped;};
wrap('renderSupervisorOrganizations',decorateOrganizations);wrap('renderSupervisorAdmins',decorateAdmins);wrap('renderStaffGlobal',decorateStaff);wrap('renderStaff',decorateStaff);
const observer=new MutationObserver(()=>{if(window.currentUser?.role==='supervisor'){decorateOrganizations();decorateAdmins();}if(window.currentUser?.role==='admin'||window.currentUser?.role==='administrator')decorateStaff();});observer.observe(document.documentElement,{subtree:true,childList:true});
document.addEventListener('click',async e=>{
 const org=e.target.closest?.('[data-delete-org-v361]');
 if(org){e.preventDefault();e.stopImmediatePropagation();const name=org.dataset.name;const typed=prompt(`Esta acción eliminará definitivamente la organización, sus usuarios y todos sus datos.\n\nEscriba exactamente: ${name}`);if(typed!==name){if(typed!==null)toast('El nombre no coincide. No se eliminó.');return;}try{org.disabled=true;const q=window.BHSC_CALL_RPC?await window.BHSC_CALL_RPC(['bh_delete_organization_complete_v361'],{p_org_id:org.dataset.deleteOrgV361}):await db().rpc('bh_delete_organization_complete_v361',{p_org_id:org.dataset.deleteOrgV361});if(q.error)throw q.error;toast('Organización eliminada definitivamente.');await window.renderSupervisorOrganizations?.();}catch(x){toast(x.message||'No se pudo eliminar la organización.')}finally{org.disabled=false}return;}
 const adm=e.target.closest?.('[data-delete-admin-v361]');
 if(adm){e.preventDefault();e.stopImmediatePropagation();if(!confirm(`¿Eliminar definitivamente la cuenta de ${adm.dataset.name}? Los demás administradores y la organización seguirán funcionando.`))return;try{adm.disabled=true;const q=window.BHSC_CALL_RPC?await window.BHSC_CALL_RPC(['bh_delete_profile_access_v4321','bh_delete_profile_access_v3'],{p_target:adm.dataset.deleteAdminV361}):await db().rpc('bh_delete_profile_access_v3',{p_target:adm.dataset.deleteAdminV361});if(q.error)throw q.error;toast('Administrador eliminado.');await window.renderSupervisorAdmins?.();}catch(x){toast(x.message||'No se pudo eliminar el administrador.')}finally{adm.disabled=false}return;}
 const staff=e.target.closest?.('[data-delete-staff-v361]');
 if(staff){e.preventDefault();e.stopImmediatePropagation();if(!confirm(`¿Eliminar definitivamente a ${staff.dataset.name}? Se conservará el historial clínico y de asistencia para auditoría.`))return;try{staff.disabled=true;const q=window.BHSC_CALL_RPC?await window.BHSC_CALL_RPC(['bh_delete_staff_member_v4321','bh_delete_staff_member_v361'],{p_staff_key:String(staff.dataset.deleteStaffV361),p_linked_user:staff.dataset.linkedUser||null}):await db().rpc('bh_delete_staff_member_v361',{p_staff_key:String(staff.dataset.deleteStaffV361),p_linked_user:staff.dataset.linkedUser||null});if(q.error)throw q.error;const arr=(window.staffMembers||[]).filter(x=>String(x.id)!==String(staff.dataset.deleteStaffV361));window.staffMembers=arr;try{staffMembers=arr}catch(_){};window.saveStaff?.();toast('Colaborador eliminado.');window.renderStaffGlobal?.();}catch(x){toast(x.message||'No se pudo eliminar el colaborador.')}finally{staff.disabled=false}return;}
},true);
setTimeout(()=>{decorateOrganizations();decorateAdmins();decorateStaff()},1200);
console.info('Eliminación global V3.6.1 lista');
})();
