(()=>{
  'use strict';
  const db=()=>window.seniorcareSupabase;
  const me=()=>window.currentUser||{};
  const esc=s=>String(s??'').replace(/[&<>\"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;'}[c]||c));
  const toast=m=>window.showToast?.(m)||alert(m);
  const isAdmin=()=>['admin','administrator','supervisor'].includes(String(me().role||''));
  function enhance(){
    if(!isAdmin())return;
    document.querySelectorAll('.staff-card-pro,.staff-profile-card').forEach(card=>{
      if(card.dataset.linkV413==='1')return;
      const key=card.dataset.staffId||card.querySelector('[data-create-staff-code]')?.dataset.createStaffCode;
      if(!key)return;
      const linked=card.dataset.linkedUserId||card.querySelector('[data-linked-user-id]')?.dataset.linkedUserId||'';
      if(linked)return;
      const host=card.querySelector('.staff-card-actions,.staff-profile-actions,.form-actions')||card;
      const b=document.createElement('button');
      b.type='button'; b.className='secondary-btn'; b.textContent='Vincular cuenta existente';
      b.dataset.linkExistingV413=String(key);
      host.appendChild(b); card.dataset.linkV413='1';
    });
  }
  async function doLink(staffKey){
    const email=prompt('Correo exacto de la cuenta que desea vincular:');
    if(!email)return;
    const client=db(); if(!client) return toast('No hay conexión con Supabase.');
    const {data,error}=window.BHSC_CALL_RPC?await window.BHSC_CALL_RPC(['bh_link_existing_staff_account_v4321','administrator_link_existing_staff_account_v413'],{p_staff_key:String(staffKey),p_email:String(email).trim().toLowerCase()}):await client.rpc('administrator_link_existing_staff_account_v413',{p_staff_key:String(staffKey),p_email:String(email).trim().toLowerCase()});
    if(error)return toast(error.message||'No se pudo vincular la cuenta.');
    const row=Array.isArray(data)?data[0]:data;
    toast(row?.message||'Cuenta vinculada correctamente.');
    try{await window.pullStaff?.();}catch(_){ }
    try{await window.loadStaffFromCloud?.();}catch(_){ }
    try{window.renderStaffGlobal?.();window.renderStaff?.();window.bindActions?.();}catch(_){location.reload();}
  }
  document.addEventListener('click',e=>{
    const b=e.target.closest?.('[data-link-existing-v413]');
    if(!b)return;
    e.preventDefault();e.stopPropagation();
    doLink(b.dataset.linkExistingV413);
  },true);
  const obs=new MutationObserver(()=>enhance());
  obs.observe(document.documentElement,{subtree:true,childList:true});
  document.addEventListener('DOMContentLoaded',enhance);
  window.addEventListener('seniorcare:user-ready',()=>setTimeout(enhance,250));
})();
