/* Bernard Health SeniorCare V1.5.1 — deslizar para sincronizar y actualizar */
(function(){
  'use strict';
  const isTouchDevice = matchMedia('(pointer: coarse)').matches || navigator.maxTouchPoints > 0;

  let startY=0,pulling=false,distance=0,refreshing=false;
  const threshold=72;
  const indicator=document.createElement('div');
  indicator.id='seniorcarePullRefresh';
  indicator.setAttribute('aria-live','polite');
  indicator.innerHTML='<span class="ptr-spinner" aria-hidden="true"></span><strong>Deslice para actualizar</strong>';
  document.body.appendChild(indicator);
  const label=indicator.querySelector('strong');

  function reset(){
    pulling=false;distance=0;
    indicator.classList.remove('visible','ready','loading');
    indicator.style.transform='translate(-50%, -110%)';
    label.textContent='Deslice para actualizar';
  }

  async function refreshApp(){
    if(refreshing)return;
    refreshing=true;
    indicator.classList.add('loading');
    indicator.classList.remove('ready');
    label.textContent='Sincronizando información…';
    try{
      await window.syncSeniorCareAll?.({render:false});
      await window.syncSeniorCareAttendance?.();
      const versionChanged=await window.BHSC_CHECK_UPDATE?.({manual:true});
      if(versionChanged)return;
      await fetch('./index.html?refresh='+Date.now(),{cache:'no-store'}).catch(()=>{});
      label.textContent='Información actualizada';
      await new Promise(r=>setTimeout(r,350));
    }catch(err){
      console.warn('No se pudo completar la actualización:',err);
      label.textContent='No se pudo actualizar';
      await new Promise(r=>setTimeout(r,700));
    }finally{
      const currentScreen=window.activeScreen||'home';
      const currentScroll=window.scrollY||0;
      try{
        if(typeof window.renderScreen==='function')window.renderScreen();
        if(typeof window.bindActions==='function')window.bindActions();
        if(typeof window.setActiveNav==='function')window.setActiveNav(currentScreen);
        requestAnimationFrame(()=>window.scrollTo({top:currentScroll,behavior:'auto'}));
      }catch(err){console.warn('No se pudo redibujar la pantalla actual:',err);}
      refreshing=false;
      reset();
    }
  }

  addEventListener('touchstart',e=>{
    if(refreshing||window.scrollY>2||e.touches.length!==1)return;
    startY=e.touches[0].clientY;pulling=true;distance=0;
  },{passive:true});

  addEventListener('touchmove',e=>{
    if(!pulling||window.scrollY>2)return;
    distance=Math.max(0,e.touches[0].clientY-startY);
    if(distance<6)return;
    if(e.cancelable)e.preventDefault();
    const shown=Math.min(112,distance*.55);
    indicator.classList.add('visible');
    indicator.style.transform=`translate(-50%, ${shown-92}px)`;
    if(distance>=threshold){indicator.classList.add('ready');label.textContent='Suelte para actualizar';}
    else{indicator.classList.remove('ready');label.textContent='Deslice para actualizar';}
  },{passive:false});

  addEventListener('touchend',()=>{
    if(!pulling)return;
    if(distance>=threshold)refreshApp();else reset();
  },{passive:true});
  addEventListener('touchcancel',reset,{passive:true});

  // Soporte para laptop/escritorio: arrastre con mouse o trackpad desde la parte superior.
  let pointerStartY=0,pointerPulling=false,wheelDistance=0,wheelTimer=null;

  if(!isTouchDevice){
    addEventListener('pointerdown',e=>{
      if(refreshing||window.scrollY>2||e.button!==0)return;
      pointerStartY=e.clientY;pointerPulling=true;distance=0;
    });

    addEventListener('pointermove',e=>{
      if(!pointerPulling||window.scrollY>2)return;
      distance=Math.max(0,e.clientY-pointerStartY);
      if(distance<6)return;
      const shown=Math.min(112,distance*.55);
      indicator.classList.add('visible');
      indicator.style.transform=`translate(-50%, ${shown-92}px)`;
      if(distance>=threshold){indicator.classList.add('ready');label.textContent='Suelte para actualizar';}
      else{indicator.classList.remove('ready');label.textContent='Deslice para actualizar';}
    });

    addEventListener('pointerup',()=>{
      if(!pointerPulling)return;
      pointerPulling=false;
      if(distance>=threshold)refreshApp();else reset();
    });
    addEventListener('pointercancel',()=>{pointerPulling=false;reset();});

    // Trackpad/rueda: gesto descendente acumulado estando arriba de la página.
    addEventListener('wheel',e=>{
      if(refreshing||window.scrollY>2||e.deltaY>=0)return;
      wheelDistance=Math.min(130,wheelDistance+Math.abs(e.deltaY));
      indicator.classList.add('visible');
      indicator.style.transform=`translate(-50%, ${Math.min(112,wheelDistance*.55)-92}px)`;
      if(wheelDistance>=threshold){indicator.classList.add('ready');label.textContent='Suelte para actualizar';}
      else{indicator.classList.remove('ready');label.textContent='Deslice para actualizar';}
      clearTimeout(wheelTimer);
      wheelTimer=setTimeout(()=>{
        if(wheelDistance>=threshold)refreshApp();
        else reset();
        wheelDistance=0;
      },180);
    },{passive:true});
  }
})();
