/* global self, clients */
self.addEventListener('push', (event) => {
  let data = { title: 'سامانه تحویل ماندگار', body: 'اعلان جدید دارید.', url: '/notifications' };
  try { data = { ...data, ...event.data.json() }; } catch { /* payload پیش‌فرض */ }
  event.waitUntil(self.registration.showNotification(data.title, {
    body: data.body,
    icon: '/images/mandegar-logo.jpg',
    badge: '/images/mandegar-logo.jpg',
    dir: 'rtl', lang: 'fa', data: { url: data.url }, tag: data.url, renotify: true
  }));
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  event.waitUntil(clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windows) => {
    const url = event.notification.data?.url || '/notifications';
    for (const client of windows) {
      if ('focus' in client) { client.navigate(url); return client.focus(); }
    }
    return clients.openWindow(url);
  }));
});
