const CACHE_NAME = 'cyrene-v2';
const ASSETS_TO_CACHE = [
  '/',
  '/index.html',
];

// Install: 缓存核心资源，立即激活
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.addAll(ASSETS_TO_CACHE);
    })
  );
  // 立即激活新 SW，不等待旧 SW 释放
  self.skipWaiting();
});

// Activate: 清理所有旧版本缓存，立即接管所有页面
self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) => {
      return Promise.all(
        keys.filter(key => key !== CACHE_NAME).map(key => {
          console.log('[SW] 清理旧缓存:', key);
          return caches.delete(key);
        })
      );
    })
  );
  // 立即接管所有页面（无需刷新）
  self.clients.claim();
});

// 检测新 SW 更新并通知客户端
self.addEventListener('message', (event) => {
  if (event.data?.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

// Fetch: HTML 导航请求使用 networkFirst，静态资源使用 cacheFirst
self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);

  // WebSocket 连接不缓存
  if (url.pathname.startsWith('/ws')) {
    event.respondWith(fetch(event.request));
    return;
  }

  // 导航请求（HTML 页面）：网络优先，避免旧缓存引用不存在的 hash 资源 → 白屏
  const isNavigation =
    event.request.mode === 'navigate' ||
    (event.request.headers.get('Accept') || '').includes('text/html');

  if (isNavigation) {
    event.respondWith(networkFirstForHTML(event.request));
  } else if (url.pathname.startsWith('/api/')) {
    // API 请求：网络优先，失败时返回离线 JSON
    event.respondWith(networkFirst(event.request));
  } else {
    // 静态资源（JS/CSS/图片等）：缓存优先
    event.respondWith(cacheFirst(event.request));
  }
});

async function cacheFirst(request) {
  const cached = await caches.match(request);
  if (cached) return cached;
  try {
    const response = await fetch(request);
    if (response.ok) {
      const cache = await caches.open(CACHE_NAME);
      cache.put(request, response.clone());
    }
    return response;
  } catch (e) {
    // 返回离线页面（HTML 请求）
    if (request.headers.get('Accept')?.includes('text/html')) {
      return caches.match('/offline.html');
    }
    throw e;
  }
}

async function networkFirstForHTML(request) {
  try {
    const response = await fetch(request);
    if (response.ok) {
      const cache = await caches.open(CACHE_NAME);
      cache.put(request, response.clone());
    }
    return response;
  } catch (e) {
    const cached = await caches.match(request);
    if (cached) return cached;
    // 最终 fallback：离线页面
    const offline = await caches.match('/offline.html');
    if (offline) return offline;
    return new Response('离线状态，请检查网络连接', {
      status: 503,
      headers: { 'Content-Type': 'text/plain; charset=utf-8' },
    });
  }
}

async function networkFirst(request) {
  try {
    const response = await fetch(request);
    const cache = await caches.open(CACHE_NAME);
    cache.put(request, response.clone());
    return response;
  } catch (e) {
    const cached = await caches.match(request);
    if (cached) return cached;
    return new Response(JSON.stringify({ error: '离线状态，请检查网络连接' }), {
      status: 503,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

// Push 通知
self.addEventListener('push', (event) => {
  const data = event.data?.json() || { title: 'Cyrene', body: '新消息' };
  event.waitUntil(
    self.registration.showNotification(data.title, {
      body: data.body,
      icon: '/images/Cyrene_Avatar/2nd_Form/Cyrene-2F-N-Happy-1.png',
      badge: '/images/Cyrene_Avatar/2nd_Form/Cyrene-2F-N-Happy-1.png',
      data: data.data || {},
    })
  );
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const sessionId = event.notification.data?.session_id;
  const targetUrl = sessionId ? `/#/session/${sessionId}` : '/';
  event.waitUntil(
    clients.matchAll({ type: 'window' }).then((clientList) => {
      for (const client of clientList) {
        if (client.url.includes(targetUrl) && 'focus' in client) {
          return client.focus();
        }
      }
      if (clients.openWindow) return clients.openWindow(targetUrl);
    })
  );
});
