/// <reference lib="webworker" />

import { initializeApp } from 'firebase/app'
import {  getMessaging, onBackgroundMessage } from 'firebase/messaging/sw';
import { firebaseConfig } from "./utils/firebase";
import type { NotificationData } from './types';
import type { MessagePayload } from 'firebase/messaging';

declare const self: ServiceWorkerGlobalScope;

const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);

// 1. 监听安装事件
self.addEventListener('install', (event) => {
  console.log('新版本 Service Worker 安装中...');
  // 强制跳过等待阶段，直接进入激活阶段
  self.skipWaiting();
});

self.addEventListener('activate', (event) => {
  // 确保新 SW 立即获得对所有页面的控制权
  event.waitUntil(self.clients.claim());
  console.debug('actived!');
});

// 核心：处理后台消息
onBackgroundMessage(messaging, (payload: MessagePayload) => {
  const data = payload.data as NotificationData;
  console.log('[sw.js] 收到后台消息: ', JSON.stringify(payload));
  const notificationTitle = data.title;
  const notificationOptions = {
    body: data.body,
    icon: data.icon, // 你的图标
    data: { url: data.url } // 携带点击跳转的 URL
  };
  self.registration.showNotification(notificationTitle, notificationOptions);
});

self.addEventListener('notificationclick', ev => {
  const url = ev.notification.data.url;
  if (!url) return;
  open(url);
});

console.log('sw', self);