// Service Worker for Hera's Planner — 后台提醒通知
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', () => self.clients.claim());

// 接收主页面发来的通知请求
self.addEventListener('message', event => {
  if (event.data && event.data.type === 'SHOW_NOTIFICATION') {
    self.registration.showNotification(event.data.title, {
      body: event.data.body,
      icon: 'icon-180.png',
      badge: 'icon-180.png',
      requireInteraction: true,
      tag: event.data.tag || 'planner-reminder',
    });
  }
});

// 点击通知时打开页面
self.addEventListener('notificationclick', event => {
  event.notification.close();
  event.waitUntil(
    self.clients.matchAll({ type: 'window' }).then(clients => {
      if (clients.length > 0) { clients[0].focus(); }
      else { self.clients.openWindow('/'); }
    })
  );
});
