/* Bernard Health SeniorCare V4.3.25 — actualización inteligente sin pérdida de contexto */
(function(){
  'use strict';
  const VERSION='4.3.25';
  let updating=false;
  const safeToReload=()=>{
    const active=document.activeElement;
    const editing=active&&['INPUT','TEXTAREA','SELECT'].includes(active.tagName);
    const openModal=document.querySelector('.modal:not(.hidden),dialog[open],.sheet.open,.drawer.open');
    const submitting=document.querySelector('button[disabled][type="submit"],form[data-saving="true"]');
    return !editing&&!openModal&&!submitting;
  };
  const saveContext=()=>{
    try{sessionStorage.setItem('bhsc-update-context',JSON.stringify({screen:window.activeScreen||'home',scroll:window.scrollY||0,resident:window.selectedResident?.resident_key||window.selectedResident?.id||null,at:Date.now()}));}catch(_e){}
  };
  const restoreContext=()=>{
    try{
      const raw=sessionStorage.getItem('bhsc-update-context'); if(!raw)return;
      sessionStorage.removeItem('bhsc-update-context'); const ctx=JSON.parse(raw);
      if(ctx?.screen&&window.currentUser){setTimeout(()=>{window.go?.(ctx.screen,{scope:ctx.screen==='resident'?'resident':'global'},{replace:true});requestAnimationFrame(()=>scrollTo(0,Number(ctx.scroll)||0));},500);}
    }catch(_e){}
  };
  async function activateWaiting(reg){
    if(!reg?.waiting)return false;
    saveContext();
    const changed=new Promise(resolve=>{navigator.serviceWorker.addEventListener('controllerchange',()=>resolve(true),{once:true});});
    reg.waiting.postMessage({type:'SKIP_WAITING'});
    await Promise.race([changed,new Promise(r=>setTimeout(()=>r(false),5000))]);
    location.reload();
    return true;
  }
  async function check({manual=false}={}){
    if(updating)return false; updating=true;
    try{
      const reg=window.BHSC_SW_REGISTRATION||await navigator.serviceWorker?.getRegistration?.();
      if(!reg){manual&&window.showToast?.('La actualización automática no está disponible.');return false;}
      await reg.update();
      if(reg.waiting){
        if(safeToReload()) return await activateWaiting(reg);
        window.showToast?.('Nueva versión lista. Se aplicará al salir del formulario.');
        const timer=setInterval(()=>{if(safeToReload()){clearInterval(timer);activateWaiting(reg);}},1500);
        setTimeout(()=>clearInterval(timer),120000);
        return true;
      }
      manual&&window.showToast?.('Aplicación e información actualizadas.');
      return false;
    }catch(err){console.warn('[BHSC update]',err);manual&&window.showToast?.('No se pudo comprobar la versión.');return false;}
    finally{updating=false;}
  }
  navigator.serviceWorker?.addEventListener?.('message',e=>{if(e.data?.type==='BHSC_VERSION')console.info('BHSC versión activa',e.data.version);});
  addEventListener('seniorcare:user-ready',restoreContext,{once:true});
  addEventListener('online',()=>check());
  document.addEventListener('visibilitychange',()=>{if(!document.hidden)check();});
  window.BHSC_CHECK_UPDATE=check;
  window.BHSC_APP_VERSION=VERSION;
})();
