import { ref } from 'vue';

export const needRefresh = ref(false);
let swRegistration = null;

export async function updateServiceWorker() {
  if (swRegistration && swRegistration.waiting) {
    await swRegistration.waiting.postMessage({ type: 'SKIP_WAITING' });
  }
}

export function register() {
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      const swUrl = `/service-worker.js`;

      navigator.serviceWorker
        .register(swUrl)
        .then((registration) => {
          swRegistration = registration;
          console.log('[SW] Service Worker 注册成功:', registration.scope);

          // 如果已经有等待中的更新
          if (registration.waiting) {
            console.log('[SW] 发现未处理的新版本');
            needRefresh.value = true;
          }

          // 检查更新
          registration.addEventListener('updatefound', () => {
            const newWorker = registration.installing;
            console.log('[SW] 发现新版本');

            newWorker.addEventListener('statechange', () => {
              if (newWorker.state === 'installed') {
                if (navigator.serviceWorker.controller) {
                  // 新的 Service Worker 已安装，提示用户刷新
                  console.log('[SW] 新版本可用，请刷新页面');
                  needRefresh.value = true;
                } else {
                  // 首次安装
                  console.log('[SW] 内容已缓存，可离线使用');
                }
              }
            });
          });

          // 定期检查更新
          setInterval(() => {
            registration.update();
          }, 60 * 60 * 1000); // 每小时检查一次
        })
        .catch((error) => {
          console.error('[SW] Service Worker 注册失败:', error);
        });

      // 监听 Service Worker 控制器变化
      navigator.serviceWorker.addEventListener('controllerchange', () => {
        console.log('[SW] 控制器已更改，页面将刷新');
        window.location.reload();
      });
    });
  }
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready
      .then((registration) => {
        registration.unregister();
      })
      .catch((error) => {
        console.error(error.message);
      });
  }
}


// 请求通知权限
export function requestNotificationPermission() {
  if ('Notification' in window && 'serviceWorker' in navigator) {
    Notification.requestPermission().then((permission) => {
      if (permission === 'granted') {
        console.log('[SW] 通知权限已授予');
      }
    });
  }
}

// 后台同步
export function registerBackgroundSync(tag = 'sync-data') {
  if ('serviceWorker' in navigator && 'SyncManager' in window) {
    navigator.serviceWorker.ready.then((registration) => {
      return registration.sync.register(tag);
    }).then(() => {
      console.log('[SW] 后台同步已注册:', tag);
    }).catch((err) => {
      console.error('[SW] 后台同步注册失败:', err);
    });
  }
}
