// Push Notification Service Worker
// 캐싱 없음 — Push 수신 전용

self.addEventListener('push', function(event) {
  var data = { title: '알림', body: '새 알림이 있습니다.', url: '/' };
  if (event.data) {
    try { data = Object.assign(data, event.data.json()); } catch(e) {}
  }
  event.waitUntil(
    self.registration.showNotification(data.title, {
      body: data.body,
      icon: '/static/img/icon-192.png',
      badge: '/static/img/badge-72.png',
      data: { url: data.url || '/' },
      tag: 'tk-notification-' + Date.now(),
      renotify: true
    })
  );
  // 메인 페이지에 뱃지 갱신 신호 전송
  self.clients.matchAll({ type: 'window' }).then(function(clients) {
    clients.forEach(function(client) {
      client.postMessage({ type: 'NOTIFICATION_RECEIVED' });
    });
  });
});

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  var url = (event.notification.data && event.notification.data.url) || '/';
  event.waitUntil(
    self.clients.matchAll({ type: 'window' }).then(function(clients) {
      for (var i = 0; i < clients.length; i++) {
        if (clients[i].url.includes(self.location.origin)) {
          clients[i].navigate(url);
          return clients[i].focus();
        }
      }
      return self.clients.openWindow(url);
    })
  );
});
