const CACHE='seniorcare-enterprise-v4.3.77';
const VERSION='4.3.77';
const APP_SHELL=[
  './',
  './index.html',
  './manifest.webmanifest',
  './assets/icon-192.png',
  './assets/logo.png?v=4.3.77',
  './styles.css?v=4.3.70',
  './medical-appointments-v4364.css?v=4.3.67',
  './medical-results-archive-v4373.css?v=4.3.73',
  './vendor/supabase-2.109.0.js?v=4.3.64',
  './storage-privacy-v4325.js?v=4.3.64',
  './config.js?v=4.3.64',
  './supabase-core.js?v=4.3.64',
  './database-compatibility-v4321.js?v=4.3.64',
  './supervisor.js?v=4.3.64',
  './medical-global-v431.js?v=4.3.64',
  './app.js?v=4.3.77',
  './seniorcare-complete-enhancements.js?v=4.3.77',
  './seniorcare-workflow-v120.js?v=4.3.77',
  './pull-to-refresh.js?v=4.3.64',
  './smart-update-v420.js?v=4.3.64',
  './admin-assignment-attendance-v147.js?v=4.3.64',
  './staff-packages-v148.js?v=4.3.64',
  './access-control-v162.js?v=4.3.64',
  './navigation-stability-v167.js?v=4.3.64',
  './staff-add-button-fix-v172.js?v=4.3.64',
  './staff-save-stay-v174.js?v=4.3.64',
  './staff-code-final-v184.js?v=4.3.75',
  './seniorcare-data-core-v204.js?v=4.3.75',
  './clinical-sync-final-v214.js?v=4.3.64',
  './residents-cloud-sync-v311.js?v=4.3.68',
  './alerts-cloud-sync-v321.js?v=4.3.64',
  './medications-cloud-sync-v322.js?v=4.3.64',
  './care-plan-realtime-v328.js?v=4.3.64',
  './nutrition-plan-realtime-v329.js?v=4.3.64',
  './clinical-global-core-v331.js?v=4.3.64',
  './attendance-global-realtime-v334.js?v=4.3.64',
  './staff-global-v342.js?v=4.3.68',
  './supervisor-global-v351.js?v=4.3.64',
  './organization-access-global-v355.js?v=4.3.64',
  './nurse-admin-global-v360.js?v=4.3.64',
  './deletion-global-v361.js?v=4.3.64',
  './nursing-handoff-global-v362.js?v=4.3.64',
  './alerts-global-v405.js?v=4.3.64',
  './assistant-global-v370.js?v=4.3.64',
  './operational-global-v380.js?v=4.3.64',
  './commercial-hardening-v400.js?v=4.3.64',
  './operational-privacy-responsive-v402.js?v=4.3.64',
  './staff-account-link-v413.js?v=4.3.64',
  './doctor-role-entry-v432.js?v=4.3.64',
  './doctor-essential-v436.js?v=4.3.67',
  './doctor-routing-guard-v438.js?v=4.3.64',
  './doctor-navigation-clean-v439.js?v=4.3.64',
  './doctor-clinical-flow-v4310.js?v=4.3.64',
  './doctor-form-ux-v4311.js?v=4.3.64',
  './doctor-workflow-v4312.js?v=4.3.72',
  './medical-results-archive-v4373.js?v=4.3.73',
  './doctor-stability-v4314.js?v=4.3.64',
  './doctor-admin-nurse-medical-orders-v4318.js?v=4.3.64',
  './compatibility-hardening-v4318.js?v=4.3.64',
  './attendance-monthly-report-v4320.js?v=4.3.64',
  './supervisor-profile-commercial-v4323.js?v=4.3.64',
  './supervisor-commercial-modules-v4324.js?v=4.3.64',
  './hardening-v4325.js?v=4.3.64',
  './medication-alerts-v4326.js?v=4.3.64',
  './medical-appointments-v4364.js?v=4.3.67'
];

self.addEventListener('install',event=>{
  event.waitUntil((async()=>{
    const cache=await caches.open(CACHE);
    for(const url of APP_SHELL){
      const response=await fetch(new Request(url,{cache:'reload'}));
      if(!response||!response.ok)throw new Error(`No se pudo precargar ${url} (${response?.status||'sin respuesta'})`);
      await cache.put(url,response.clone());
    }
    await self.skipWaiting();
  })());
});

self.addEventListener('activate',event=>{
  event.waitUntil((async()=>{
    const keys=await caches.keys();
    await Promise.all(keys.filter(key=>key!==CACHE).map(key=>caches.delete(key)));
    await self.clients.claim();
  })());
});

async function networkFirst(request,fallback){
  const cache=await caches.open(CACHE);
  try{
    const response=await fetch(request);
    if(response&&(response.ok||response.type==='opaque'))await cache.put(request,response.clone());
    return response;
  }catch(error){
    return (await cache.match(request))||(fallback?await cache.match(fallback):null)||new Response('Sin conexión',{status:503,statusText:'Offline'});
  }
}

self.addEventListener('fetch',event=>{
  if(event.request.method!=='GET')return;
  const url=new URL(event.request.url);
  if(url.origin!==self.location.origin)return;
  if(event.request.mode==='navigate'){event.respondWith(networkFirst(event.request,'./index.html'));return;}
  if(/\.(?:js|css)$/i.test(url.pathname)){event.respondWith(networkFirst(event.request));return;}
  event.respondWith((async()=>{
    const cache=await caches.open(CACHE);
    const cached=await cache.match(event.request);
    if(cached)return cached;
    try{
      const response=await fetch(event.request);
      if(response&&(response.ok||response.type==='opaque'))await cache.put(event.request,response.clone());
      return response;
    }catch(error){return new Response('',{status:504,statusText:'Offline'});}
  })());
});

self.addEventListener('message',event=>{
  if(event.data?.type==='SKIP_WAITING')self.skipWaiting();
  if(event.data?.type==='GET_VERSION')event.source?.postMessage({type:'BHSC_VERSION',version:VERSION});
});


self.addEventListener('push',event=>{
  event.waitUntil((async()=>{
    let payload={};
    try{payload=event.data?.json?.()||{};}catch(_){try{payload={body:event.data?.text?.()||''};}catch(__){payload={};}}
    const data=payload.data||{};
    const title=payload.title||'Dosis de medicamento pendiente';
    const options={
      body:payload.body||'Abra SeniorCare para revisar y confirmar la dosis.',
      icon:'./assets/icon-192.png',
      badge:'./assets/icon-192.png',
      tag:payload.tag||`bhsc-med-${data.doseId||'pending'}`,
      renotify:payload.renotify!==false,
      requireInteraction:payload.requireInteraction!==false,
      vibrate:Array.isArray(payload.vibrate)?payload.vibrate:[250,120,250,120,350],
      data:{url:data.url||`./?medDose=${encodeURIComponent(data.doseId||'')}`,doseId:data.doseId||null}
    };
    await self.registration.showNotification(title,options);
  })());
});

self.addEventListener('notificationclick',event=>{
  event.notification.close();
  const doseId=event.notification.data?.doseId||null;
  const target=new URL(event.notification.data?.url||'./',self.location.origin).href;
  event.waitUntil((async()=>{
    const clientsList=await self.clients.matchAll({type:'window',includeUncontrolled:true});
    for(const client of clientsList){
      if(new URL(client.url).origin===self.location.origin){
        await client.focus();
        client.postMessage({type:'OPEN_MEDICATION_DOSE',doseId});
        return;
      }
    }
    if(self.clients.openWindow)await self.clients.openWindow(target);
  })());
});
