// Firebase Cloud Messaging Service Worker
// This file MUST be in the public/ directory (served at /firebase-messaging-sw.js)

importScripts("https://www.gstatic.com/firebasejs/10.12.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/10.12.0/firebase-messaging-compat.js");

firebase.initializeApp({
  apiKey: "AIzaSyBZV7KBLRJSTApahfrO8lBesmIM3zNRSaY",
  authDomain: "sweet-home-b2766.firebaseapp.com",
  projectId: "sweet-home-b2766",
  storageBucket: "sweet-home-b2766.firebasestorage.app",
  messagingSenderId: "602865114600",
  appId: "1:602865114600:web:ed9b6754940507a6ab585d",
  measurementId: "G-M2V95NBJLX",
});

const messaging = firebase.messaging();

// Handle background messages
messaging.onBackgroundMessage((payload) => {
  console.log("[FCM SW] Background message:", payload);
  const title = payload.notification?.title || payload.data?.title || "Sweet Home";
  const options = {
    body: payload.notification?.body || payload.data?.body || "",
    icon: payload.notification?.icon || "/logo.png",
    badge: "/logo.png",
    data: payload.data,
    tag: "sweethome-notification",
  };
  self.registration.showNotification(title, options);
});

// Handle notification click
self.addEventListener("notificationclick", (event) => {
  event.notification.close();
  const url = event.notification.data?.url || "/";
  event.waitUntil(clients.openWindow(url));
});
