// Heritage Voice Service Worker v1.0
const CACHE_NAME = 'hv-v11';
const CACHE_STATIC = [
  '/',
  '/home.html',
  '/detail.html',
  '/map.html',
  '/player.html',
  '/qr.html',
  '/profile.html',
  '/login.html',
  '/register.html',
  '/offline.html',
  '/assets/style.css',
  '/assets/logo.svg',
  '/assets/favicon.svg',
  '/assets/vn-address.js',
];

// ── INSTALL ───────────────────────────────────────────────────
self.addEventListener('install', e => {
  e.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      return cache.addAll(CACHE_STATIC).catch(err => {
        console.warn('[SW] Cache addAll error:', err);
      });
    }).then(() => self.skipWaiting())
  );
});

// ── ACTIVATE ──────────────────────────────────────────────────
self.addEventListener('activate', e => {
  e.waitUntil(
    caches.keys().then(keys =>
      Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
    ).then(() => self.clients.claim())
  );
});

// ── FETCH — Cache First cho static, Network First cho API ─────
self.addEventListener('fetch', e => {
  const url = new URL(e.request.url);

  // Skip non-GET
  if (!['GET'].includes(e.request.method)) return;
  // Bỏ qua hoàn toàn các request POST/PUT/DELETE
  if (['POST','PUT','DELETE','PATCH'].includes(e.request.method)) return;

  // API → Network only, không cache
  if (url.pathname.startsWith('/api/')) {
    e.respondWith(fetch(e.request));
    return;
  }

  // Audio/Image → Cache first (nặng, ít thay đổi)
  if (url.pathname.startsWith('/audio/') || url.pathname.startsWith('/images/')) {
    e.respondWith(
      caches.match(e.request).then(cached => {
        if (cached) return cached;
        return fetch(e.request).then(res => {
          if (res.ok) {
            caches.open(CACHE_NAME).then(c => c.put(e.request, res.clone()));
          }
          return res;
        });
      })
    );
    return;
  }

  // Static (HTML/CSS/JS) → Cache first, update background
  e.respondWith(
    caches.match(e.request).then(cached => {
      const fetchPromise = fetch(e.request).then(res => {
        if (res.ok) {
          const resClone = res.clone();
          caches.open(CACHE_NAME).then(c => c.put(e.request, resClone));
        }
        return res;
      }).catch(() => cached);
      if (cached) {
        fetchPromise.catch(() => {});
        return cached;
      }
      return fetchPromise;
    })
  );
});

// ── PUSH NOTIFICATION ─────────────────────────────────────────
self.addEventListener('push', e => {
  const data = e.data ? e.data.json() : {};
  const title = data.title || 'Heritage Voice';
  const opts  = {
    body:    data.body || 'Bạn đang gần một điểm di sản!',
    icon:    '/assets/icon-192.png',
    badge:   '/assets/icon-192.png',
    vibrate: [200, 100, 200],
    data:    { url: data.url || '/home.html' },
    actions: [
      { action: 'open',    title: '▶ Nghe ngay' },
      { action: 'dismiss', title: 'Bỏ qua' },
    ],
  };
  e.waitUntil(self.registration.showNotification(title, opts));
});

// ── NOTIFICATION CLICK ────────────────────────────────────────
self.addEventListener('notificationclick', e => {
  e.notification.close();
  if (e.action === 'dismiss') return;
  const url = e.notification.data?.url || '/home.html';
  e.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then(list => {
      for (const client of list) {
        if (client.url.includes(self.location.origin)) {
          client.focus();
          client.navigate(url);
          return;
        }
      }
      return clients.openWindow(url);
    })
  );
});

// ── MESSAGE từ app ────────────────────────────────────────────
self.addEventListener('message', e => {
  if (e.data?.type === 'GEOFENCE_ALERT') {
    // App đang mở gửi lên SW để show notification
    const { title, body, url } = e.data;
    self.registration.showNotification('📍 ' + title, {
      body,
      icon:    '/assets/icon-192.png',
      vibrate: [200, 100, 200],
      data:    { url },
      actions: [{ action: 'open', title: '▶ Nghe ngay' }],
    });
  }

  if (e.data?.type === 'CACHE_AUDIO') {
    // Cache file audio để dùng offline
    const { url } = e.data;
    caches.open(CACHE_NAME).then(c => c.add(url));
  }

  if (e.data?.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});
