/* Bernard Health SeniorCare Enterprise 3.2.1 — alertas en Supabase y Realtime */
(function(){
  'use strict';
  const TABLE='seniorcare_alerts';
  const VERSION='3.2.1';
  const db=()=>window.seniorcareSupabase||null;
  const user=()=>window.currentUser||null;
  const org=()=>user()?.organizationId||user()?.organization_id||null;
  let channel=null, startedOrg=null, pulling=false, pushing=false, suppress=false, timer=null, lastSignature='';
  const now=()=>new Date().toISOString();
  const clean=v=>String(v??'').trim();
  const list=()=>Array.isArray(window.BHSC_GET_ALERTS?.())?window.BHSC_GET_ALERTS():[];
  const signature=rows=>JSON.stringify((rows||[]).map(a=>({id:String(a.id),sourceKey:a.sourceKey||'',title:a.title||'',detail:a.detail||'',priority:a.priority||'',status:a.status||'',type:a.type||'',residentId:a.residentId??null,target:a.target||'',created:a.created||''})).sort((a,b)=>String(a.id).localeCompare(String(b.id))));
  const rowOf=a=>({
    organization_id:org(), alert_key:clean(a.id)||`${Date.now()}-${Math.random()}`,
    source_key:a.sourceKey||null,title:a.title||'Alerta',detail:a.detail||'',priority:a.priority||'Pendiente',
    status:a.status||'Nueva',alert_type:a.type||'general',resident_key:a.residentId!=null?String(a.residentId):null,
    target_screen:a.target||null,created_at:a.created||now(),data:a,active:true,updated_at:now(),updated_by:user()?.id||null
  });
  const fromRow=r=>({...(r.data||{}),id:(r.data&&r.data.id)!=null?r.data.id:r.alert_key,sourceKey:r.source_key||r.data?.sourceKey,title:r.title||r.data?.title||'Alerta',detail:r.detail||r.data?.detail||'',priority:r.priority||r.data?.priority||'Pendiente',status:r.status||r.data?.status||'Nueva',type:r.alert_type||r.data?.type||'general',residentId:r.data?.residentId??r.resident_key??null,target:r.target_screen||r.data?.target||null,created:r.created_at||r.data?.created||now()});
  async function pull({render=true}={}){
    if(pulling||!db()||!org())return;
    pulling=true;
    try{
      const {data,error}=await db().from(TABLE).select('*').eq('organization_id',org()).eq('active',true).order('created_at',{ascending:false});
      if(error)throw error;
      const rows=(data||[]).map(fromRow);
      suppress=true;
      window.BHSC_SET_ALERTS?.(rows,{render});
      lastSignature=signature(rows);
    }catch(e){console.error('[BHSC Alerts pull]',e);}finally{suppress=false;pulling=false;}
  }
  async function push(){
    if(suppress||pushing||!db()||!org())return;
    const rows=list();
    const sig=signature(rows);
    if(sig===lastSignature)return;
    pushing=true;
    try{
      if(rows.length){
        const {error}=await db().from(TABLE).upsert(rows.map(rowOf),{onConflict:'organization_id,alert_key'});
        if(error)throw error;
      }
      lastSignature=sig;
    }catch(e){console.error('[BHSC Alerts push]',e);}finally{pushing=false;}
  }
  function schedulePush(){clearTimeout(timer);timer=setTimeout(()=>push(),180);}
  async function remove(alertId){
    if(!db()||!org())return;
    const {error}=await db().from(TABLE).update({active:false,updated_at:now(),updated_by:user()?.id||null}).eq('organization_id',org()).eq('alert_key',String(alertId));
    if(error)console.error('[BHSC Alerts delete]',error);
  }
  async function start(){
    const organization=org(); if(!db()||!organization)return;
    if(startedOrg===organization&&channel)return;
    startedOrg=organization;
    await pull({render:true});
    if(channel){try{await db().removeChannel(channel)}catch(_){}}
    channel=db().channel(`bhsc-alerts-${organization}`).on('postgres_changes',{event:'*',schema:'public',table:TABLE,filter:`organization_id=eq.${organization}`},()=>pull({render:true})).subscribe(status=>console.info('[BHSC Alerts realtime]',status));
  }
  window.BHSC_ALERTS_PUSH=schedulePush;
  window.BHSC_ALERT_DELETE=remove;
  window.BHSC_ALERTS_PULL=pull;
  window.BHSC_ALERTS_STATUS=()=>({version:VERSION,organizationId:org(),startedOrg,connected:!!channel,count:list().length});
  window.addEventListener('seniorcare:user-ready',()=>setTimeout(start,250));
  window.addEventListener('focus',()=>{if(startedOrg)pull({render:true});});
  document.addEventListener('visibilitychange',()=>{if(!document.hidden&&startedOrg)pull({render:true});});
})();
