/* Bernard Health SeniorCare V1.6.2 — control de acceso con acciones independientes */
(function(){
  'use strict';

  const db=()=>window.seniorcareSupabase;
  const toast=m=>window.showToast?.(m);
  const norm=v=>String(v||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'').replace(/\s+/g,' ').trim();
  const roleNorm=v=>({enfermera:'nurse',enfermeria:'nurse',asistente:'assistant',administracion:'admin',administrador:'admin'})[norm(v)]||norm(v);
  let profiles=[];
  let guardTimer=null;

  async function rpc(name,args){
    const client=db();
    if(!client) throw new Error('No hay conexión con Supabase.');
    const aliases={
      bh_list_manageable_profiles_v3:['bh_list_manageable_profiles_v4321','bh_list_manageable_profiles_v3'],
      bh_set_profile_active_v3:['bh_set_profile_active_v4321','bh_set_profile_active_v3'],
      bh_delete_profile_access_v3:['bh_delete_profile_access_v4321','bh_delete_profile_access_v3'],
      bh_get_my_access_status_v3:['bh_get_my_access_status_v4321','bh_get_my_access_status_v3']
    };
    const result=window.BHSC_CALL_RPC
      ?await window.BHSC_CALL_RPC(aliases[name]||[name],args||{})
      :await client.rpc(name,args||{});
    if(result.error) throw result.error;
    // Las funciones de listado devuelven varias filas. No reducirlas a la primera.
    if(name==='bh_list_manageable_profiles_v3') return Array.isArray(result.data)?result.data:(result.data?[result.data]:[]);
    return Array.isArray(result.data)?result.data[0]:result.data;
  }

  async function loadProfiles(){
    if(!db()||!currentUser||!['admin','supervisor'].includes(currentUser.role)) return [];
    const data=await rpc('bh_list_manageable_profiles_v3');
    profiles=Array.isArray(data)?data:(data?[data]:[]);
    return profiles;
  }

  function profileForMember(member){
    const direct=member?.linkedUserId||member?.userId||member?.profileId;
    if(direct){
      const p=profiles.find(x=>String(x.id)===String(direct));
      if(p) return p;
    }
    const name=norm(member?.name), role=roleNorm(member?.role);
    return profiles.find(p=>norm(p.full_name)===name&&roleNorm(p.role)===role)
      || profiles.find(p=>norm(p.full_name)===name)
      || null;
  }

  async function setActive(profile,next){
    if(!profile?.id) throw new Error('La ficha no está vinculada a una cuenta real.');
    const action=next?'reactivar':'suspender';
    if(!confirm(`¿Desea ${action} el acceso de ${profile.full_name||'esta persona'}?`)) return false;
    const row=await rpc('bh_set_profile_active_v3',{p_target:profile.id,p_active:next});
    if(!row||String(row.id)!==String(profile.id)||row.active!==next){
      throw new Error('Supabase no confirmó el cambio de estado.');
    }
    profile.active=next;
    toast(next?'Cuenta reactivada correctamente.':'Cuenta suspendida correctamente.');
    return true;
  }

  async function deleteAccess(profile,member){
    if(!profile?.id) throw new Error('La ficha no está vinculada a una cuenta real.');
    if(!confirm(`¿Eliminar definitivamente el acceso de ${profile.full_name||member?.name||'esta persona'}?\n\nNo podrá volver a entrar. El historial se conservará.`)) return false;
    await rpc('bh_delete_profile_access_v3',{p_target:profile.id});
    if(member){
      window.staffMembers=(staffMembers||[]).filter(x=>String(x.id)!==String(member.id));
      window.staffMembers=staffMembers;
      window.saveStaff?.();
      if(window.residentAssignments){
        delete window.residentAssignments[String(member.id)];
        window.saveResidentAssignments?.();
      }
      try{await window.pushStaffToCloud?.();}catch(_e){}
      try{await window.pushAssignmentsToCloud?.();}catch(_e){}
    }
    toast('Cuenta eliminada y acceso revocado.');
    return true;
  }

  function actionBox(profile,member){
    const box=document.createElement('div');
    box.className='access-actions-v162';
    if(!profile){
      box.innerHTML='<span class="status warn">Cuenta sin vincular</span>';
      return box;
    }
    const active=profile.active!==false;
    box.innerHTML=`
      <span class="status ${active?'ok':'danger'}">${active?'Acceso activo':'Acceso suspendido'}</span>
      <button type="button" class="secondary-btn" data-v162-suspend ${active?'':'disabled'}>Suspender</button>
      <button type="button" class="secondary-btn" data-v162-reactivate ${active?'disabled':''}>Reactivar</button>
      <button type="button" class="secondary-btn danger-outline" data-v162-delete>Eliminar</button>`;

    box.querySelector('[data-v162-suspend]').onclick=async ev=>{
      ev.preventDefault();ev.stopImmediatePropagation();
      try{if(await setActive(profile,false)) await refreshCurrent();}
      catch(e){toast(e.message||'No se pudo suspender la cuenta.');}
    };
    box.querySelector('[data-v162-reactivate]').onclick=async ev=>{
      ev.preventDefault();ev.stopImmediatePropagation();
      try{if(await setActive(profile,true)) await refreshCurrent();}
      catch(e){toast(e.message||'No se pudo reactivar la cuenta.');}
    };
    box.querySelector('[data-v162-delete]').onclick=async ev=>{
      ev.preventDefault();ev.stopImmediatePropagation();
      try{if(await deleteAccess(profile,member)) await refreshCurrent();}
      catch(e){toast(e.message||'No se pudo eliminar la cuenta.');}
    };
    return box;
  }

  function renderStaffAccessSummary(){
    if(currentUser?.role!=='admin') return;
    document.querySelector('.staff-access-summary-v166')?.remove();
    const members=Array.isArray(staffMembers)?staffMembers:[];
    let active=0,suspended=0,unlinked=0;
    members.forEach(member=>{
      const profile=profileForMember(member);
      if(!profile){unlinked+=1;return;}
      if(profile.active===false)suspended+=1;else active+=1;
    });
    const section=document.createElement('section');
    section.className='staff-access-summary-v166';
    section.innerHTML=`
      <article><span>CUENTAS ACTIVAS</span><strong>${active}</strong><small>Con acceso al sistema</small></article>
      <article><span>CUENTAS SUSPENDIDAS</span><strong>${suspended}</strong><small>Acceso bloqueado</small></article>
      <article><span>SIN VINCULAR</span><strong>${unlinked}</strong><small>Sin cuenta asociada</small></article>`;
    const anchor=document.querySelector('.staff-kpi-grid');
    if(anchor)anchor.insertAdjacentElement('afterend',section);
  }

  function installEditDelegation(){
    if(window.__staffEditDelegationV166)return;
    window.__staffEditDelegationV166=true;
    document.addEventListener('click',ev=>{
      const btn=ev.target.closest('[data-edit-staff-v148]');
      if(!btn)return;
      ev.preventDefault();
      ev.stopPropagation();
      const member=(staffMembers||[]).find(m=>String(m.id)===String(btn.dataset.editStaffV148));
      const form=document.getElementById('staffFormFinal');
      if(!member||!form){toast('No se pudo abrir la ficha del trabajador.');return;}
      if(form.elements.staffId)form.elements.staffId.value=member.id;
      if(form.elements.name)form.elements.name.value=member.name||'';
      if(form.elements.role)form.elements.role.value=member.role||'Asistente';
      if(form.elements.shift)form.elements.shift.value=member.shift||'';
      if(form.elements.assignment)form.elements.assignment.value=member.assignment||'';
      if(form.elements.status)form.elements.status.value=member.status||'Próximo';
      form.classList.remove('hidden');
      form.scrollIntoView({behavior:'smooth',block:'start'});
    },true);
  }

  function patchStaffCards(){
    if(currentUser?.role!=='admin') return;
    const linkedIds=new Set();
    document.querySelectorAll('.staff-profile-card').forEach(card=>{
      card.querySelectorAll('.access-actions-v155,.access-actions-v156,.access-actions-v157,.access-actions-v160,.access-actions-v162').forEach(x=>x.remove());
      const staffId=card.dataset.staffId;
      const member=(staffMembers||[]).find(m=>String(m.id)===String(staffId));
      if(!member) return;
      const profile=profileForMember(member);
      if(profile) linkedIds.add(String(profile.id));
      card.appendChild(actionBox(profile,member));
    });

    document.querySelector('.orphan-access-v162')?.remove();
    const orphans=profiles.filter(p=>!linkedIds.has(String(p.id))&&!['admin','administrator','supervisor'].includes(roleNorm(p.role)));
    if(!orphans.length){renderStaffAccessSummary();return;}
    const section=document.createElement('section');
    section.className='history-card orphan-access-v162';
    section.innerHTML='<h3>Cuentas sin ficha laboral</h3><p class="muted-copy">Estas cuentas aún pueden iniciar sesión. Gestione su acceso desde aquí.</p><div class="orphan-access-list"></div>';
    const list=section.querySelector('.orphan-access-list');
    orphans.forEach(p=>{
      const row=document.createElement('article');
      row.className='orphan-access-row';
      row.innerHTML=`<div><strong>${p.full_name||p.username||'Usuario'}</strong><span>${p.username||''} · ${p.role||''}</span></div>`;
      row.appendChild(actionBox(p,null));
      list.appendChild(row);
    });
    (document.querySelector('.staff-directory-pro')||document.querySelector('.history-card'))?.insertAdjacentElement('afterend',section);
    renderStaffAccessSummary();
  }

  function patchSupervisorAdmins(){
    if(currentUser?.role!=='supervisor') return;
    document.querySelectorAll('[data-admin-toggle],[data-atoggle]').forEach(oldBtn=>{
      const id=oldBtn.dataset.adminToggle||oldBtn.dataset.atoggle;
      const profile=profiles.find(p=>String(p.id)===String(id));
      if(!profile) return;
      const holder=oldBtn.parentElement;
      if(!holder) return;
      holder.querySelectorAll('[data-admin-toggle],[data-atoggle],[data-v157-admin-delete],.access-actions-v162').forEach(x=>x.remove());
      holder.appendChild(actionBox(profile,null));
    });
  }

  async function refreshCurrent(){
    await loadProfiles();
    if(currentUser?.role==='admin'&&typeof window.renderStaff==='function'){
      await window.renderStaff();
      window.bindActions?.();
      patchStaffCards();
      return;
    }
    if(currentUser?.role==='supervisor'&&typeof window.renderSupervisorAdmins==='function'){
      await window.renderSupervisorAdmins();
      patchSupervisorAdmins();
    }
  }

  function installWrappers(){
    if(typeof window.renderStaff==='function'&&!window.__renderStaffBaseV162){
      window.__renderStaffBaseV162=window.renderStaff;
      window.renderStaff=async function(){
        try{await loadProfiles();}catch(e){toast(e.message||'No se pudieron cargar las cuentas.');}
        await window.__renderStaffBaseV162();
        patchStaffCards();
      };
    }
    if(typeof window.renderSupervisorAdmins==='function'&&!window.__renderSupervisorAdminsBaseV162){
      window.__renderSupervisorAdminsBaseV162=window.renderSupervisorAdmins;
      window.renderSupervisorAdmins=async function(){
        try{await loadProfiles();}catch(e){toast(e.message||'No se pudieron cargar los administradores.');}
        await window.__renderSupervisorAdminsBaseV162();
        patchSupervisorAdmins();
      };
    }
  }

  async function validateCurrentAccess(){
    if(!currentUser?.id||!db()) return true;
    try{
      const {data:userData,error:userError}=await db().auth.getUser();
      if(userError){
        console.warn('Validación de acceso pospuesta:',userError.message||userError);
        return true;
      }
      if(!userData?.user){
        try{await db().auth.signOut({scope:'local'});}catch(_e){}
        currentUser=null;
        window.renderAuth?.('La sesión ya no es válida. Inicie sesión nuevamente.');
        return false;
      }
      let row;
      try{row=await rpc('bh_get_my_access_status_v3');}
      catch(error){
        console.warn('No se pudo confirmar el estado de acceso; se conserva la pantalla actual:',error?.message||error);
        return true;
      }
      if(row&&row.active===true) return true;
      try{await db().auth.signOut({scope:'local'});}catch(_e){}
      currentUser=null;
      window.renderAuth?.('Esta cuenta está suspendida o eliminada. Comuníquese con la administración.');
      return false;
    }catch(error){
      console.warn('Validación de acceso no concluyente; no se cambia de pantalla:',error?.message||error);
      return true;
    }
  }

  function installRealtime(){
    if(!db()||window.__accessChannelV162) return;
    window.__accessChannelV162=db().channel('bh-profiles-access-v162')
      .on('postgres_changes',{event:'UPDATE',schema:'public',table:'profiles'},payload=>{
        if(String(payload.new?.id)===String(currentUser?.id)) validateCurrentAccess();
        else window.__seniorCareProfilesDirty=true;
      })
      .on('postgres_changes',{event:'DELETE',schema:'public',table:'profiles'},payload=>{
        if(String(payload.old?.id)===String(currentUser?.id)) validateCurrentAccess();
        else window.__seniorCareProfilesDirty=true;
      })
      .subscribe();
  }

  function init(){
    installWrappers();
    installEditDelegation();
    installRealtime();
    validateCurrentAccess();
    if(guardTimer){clearInterval(guardTimer);guardTimer=null;}
    setTimeout(()=>{loadProfiles().then(()=>{patchStaffCards();patchSupervisorAdmins();}).catch(()=>{});},500);
  }

  document.addEventListener('DOMContentLoaded',init,{once:true});
  setTimeout(init,1400);
  document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')validateCurrentAccess();});
  window.addEventListener('focus',()=>{validateCurrentAccess();});
})();
