(()=>{
'use strict';
const VERSION='4.3.21';
let channel=null, checking=false, lastReason='';
const db=()=>window.seniorcareSupabase;
const user=()=>window.currentUser;
const roleKey=r=>({administrator:'admin',administrador:'admin',admin:'admin',nurse:'nurse',enfermeria:'nurse',enfermera:'nurse',assistant:'assistant',asistente:'assistant',caregiver:'assistant',cook:'cook',cocina:'cook',security:'security',seguridad:'security',cleaning:'cleaning',miscelanea:'cleaning',maintenance:'maintenance',mantenimiento:'maintenance',supervisor:'supervisor'}[String(r||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'')]||String(r||'').toLowerCase());
function messageFor(reason){
 const m={profile_inactive:'Esta cuenta está bloqueada individualmente. Comuníquese con la administración.',organization_inactive:'La residencia está suspendida por el Supervisor. Toda la estructura permanece bloqueada hasta su reactivación.',license_inactive:'La licencia de esta residencia no está activa.',license_expired:'La licencia de esta residencia está vencida.',module_disabled:'El módulo correspondiente a esta cuenta no está contratado o está desactivado.',profile_missing:'No se encontró el perfil de acceso.'};
 return m[reason]||'El acceso a la plataforma está bloqueado.';
}
async function status(){
 if(!db()||!user()?.id)return {allowed:true};
 if(roleKey(user()?.role)==='supervisor')return {allowed:true,role:'supervisor'};
 const result=window.BHSC_CALL_RPC
  ?await window.BHSC_CALL_RPC(['bh_get_my_platform_access_v4321','bh_get_my_platform_access_v355'],{})
  :await db().rpc('bh_get_my_platform_access_v355');
 if(result.error){
  if(window.BHSC_DIRECT_PLATFORM_ACCESS_FALLBACK)return window.BHSC_DIRECT_PLATFORM_ACCESS_FALLBACK();
  throw result.error;
 }
 const data=result.data;
 return Array.isArray(data)?(data[0]||{}):(data||{});
}
async function enforce({silent=false}={}){
 if(checking||!user()?.id||!db())return true;
 checking=true;
 try{
  const s=await status();
  window.BHSC_PLATFORM_ACCESS=s;
  if(s.allowed===true){lastReason='';return true;}
  const reason=String(s.reason||'access_denied');
  if(lastReason===reason&&silent)return false;
  lastReason=reason;
  try{await db().auth.signOut({scope:'local'});}catch(_){ }
  window.currentUser=null;
  window.renderAuth?.(messageFor(reason));
  return false;
 }catch(e){
  console.error('No se pudo validar el acceso global:',e?.message||e);
  if(!silent)window.showToast?.(window.BHSC_DATABASE_FRIENDLY_ERROR?.(e,'No se pudo verificar el acceso.')||'No se pudo verificar el acceso.');
  return false;
 }finally{checking=false}
}
function wire(){
 if(channel||!db()||!user()?.id||roleKey(user()?.role)==='supervisor')return;
 const org=user()?.organizationId||user()?.organization_id;
 channel=db().channel(`bhsc-platform-access-${user().id}`)
  .on('postgres_changes',{event:'UPDATE',schema:'public',table:'profiles',filter:`id=eq.${user().id}`},()=>enforce())
  .on('postgres_changes',{event:'UPDATE',schema:'public',table:'organizations',filter:`id=eq.${org}`},()=>enforce())
  .on('postgres_changes',{event:'UPDATE',schema:'public',table:'licenses',filter:`organization_id=eq.${org}`},()=>enforce())
  .on('postgres_changes',{event:'*',schema:'public',table:'organization_module_subscriptions',filter:`organization_id=eq.${org}`},()=>enforce())
  .subscribe();
}
async function init(){await enforce();wire();}
window.BHSC_VALIDATE_PLATFORM_ACCESS=enforce;
window.addEventListener('seniorcare:session-ready',init);
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')enforce({silent:true})});
window.addEventListener('focus',()=>enforce({silent:true}));
setTimeout(init,1600);
console.info(`Acceso global organización/licencia/módulos ${VERSION} listo`);
})();
