/**
 * Soug Hanana — Service Worker
 * Handles PWA caching + Web Push notifications with vibration & sound
 */

const CACHE  = 'sh-v3';
const STATIC = ['/'];

// ─── Lifecycle ────────────────────────────────────────────────────────────────

self.addEventListener('install', (e) => {
  self.skipWaiting();
  e.waitUntil(
    caches.open(CACHE).then(c => c.addAll(STATIC).catch(() => {}))
  );
});

self.addEventListener('activate', (e) => {
  e.waitUntil(
    Promise.all([
      self.clients.claim(),
      caches.keys().then(keys =>
        Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
      ),
    ])
  );
});

// ─── Fetch (cache-first for static assets, network-first otherwise) ──────────

self.addEventListener('fetch', (e) => {
  if (e.request.method !== 'GET') return;

  const url = e.request.url;
  // Skip push/API/livewire routes — always network
  if (url.includes('/push/') || url.includes('/api/') || url.includes('/livewire')) return;

  // Cache-first for fonts, images, compiled assets
  if (/\.(woff2?|ttf|eot|svg|png|jpg|webp|ico|css|js)(\?|$)/.test(url)) {
    e.respondWith(
      caches.match(e.request).then(cached => {
        if (cached) return cached;
        return fetch(e.request).then(res => {
          if (res.ok) {
            const clone = res.clone();
            caches.open(CACHE).then(c => c.put(e.request, clone));
          }
          return res;
        }).catch(() => cached);
      })
    );
    return;
  }

  // Network-first for HTML / dynamic pages
  e.respondWith(
    fetch(e.request).catch(() => caches.match(e.request))
  );
});

// ─── CSRF Token Storage (forwarded from page via postMessage) ─────────────────

let _csrfToken = null;

self.addEventListener('message', (e) => {
  if (e.data?.type === 'SET_CSRF_TOKEN') {
    _csrfToken = e.data.token;
  }
});

// ─── Push Notification ────────────────────────────────────────────────────────

self.addEventListener('push', (e) => {
  if (!e.data) return;

  let payload;
  try {
    payload = e.data.json();
  } catch {
    payload = {
      type:  'generic',
      title: 'Soug Hanana',
      body:  e.data.text() || 'New notification',
      data:  { url: '/' },
    };
  }

  const { title, body, icon, badge, vibrate, tag, data, type } = payload;

  const options = {
    body:               body  || '',
    icon:               icon  || '/icon-192x192.png',
    badge:              badge || '/badge-72x72.png',
    // Vibration pattern: burst × 2 for sales, triple-pulse for loans
    vibrate:            vibrate || (type === 'loan_payment'
                          ? [200, 100, 200, 100, 400]
                          : [100, 50,  100, 50,  200]),
    tag:                tag || type || 'sh-notification',
    renotify:           true,
    requireInteraction: false,
    silent:             false,
    timestamp:          Date.now(),
    data:               { ...(data || {}), type },
    actions: type === 'loan_payment'
      ? [{ action: 'view', title: '📋 View Loans' }]
      : [{ action: 'view', title: '🧾 View Sales' }],
  };

  e.waitUntil(
    // Show system notification first, then relay to open windows
    self.registration.showNotification(title, options).then(() =>
      self.clients
        .matchAll({ type: 'window', includeUncontrolled: true })
        .then(clients => clients.forEach(c => c.postMessage({ type: 'PUSH_RECEIVED', payload })))
    )
  );
});

// ─── Notification Click ───────────────────────────────────────────────────────

self.addEventListener('notificationclick', (e) => {
  e.notification.close();

  const url = e.notification.data?.url || '/';

  e.waitUntil(
    self.clients
      .matchAll({ type: 'window', includeUncontrolled: true })
      .then(clients => {
        const existing = clients.find(c => new URL(c.url).origin === self.location.origin);
        if (existing) {
          return existing.focus().then(w => w.navigate(url));
        }
        return self.clients.openWindow(url);
      })
  );
});

// ─── Subscription Auto-Renewal ────────────────────────────────────────────────

self.addEventListener('pushsubscriptionchange', (e) => {
  e.waitUntil(
    fetch('/push/key', { credentials: 'include' })
      .then(r => r.json())
      .then(json => self.registration.pushManager.subscribe({
        userVisibleOnly:      true,
        applicationServerKey: urlBase64ToUint8Array(json.key),
      }))
      .then(sub => {
        const headers = { 'Content-Type': 'application/json' };
        if (_csrfToken) headers['X-CSRF-TOKEN'] = _csrfToken;
        return fetch('/push/subscribe', {
          method:      'POST',
          credentials: 'include',
          headers,
          body:        JSON.stringify(sub),
        });
      })
      .catch(err => console.error('[SW] Subscription renewal failed:', err))
  );
});

// ─── Utility ─────────────────────────────────────────────────────────────────

function urlBase64ToUint8Array(base64) {
  const padding = '='.repeat((4 - (base64.length % 4)) % 4);
  const b64     = (base64 + padding).replace(/-/g, '+').replace(/_/g, '/');
  const raw     = atob(b64);
  return Uint8Array.from([...raw].map(c => c.charCodeAt(0)));
}
