// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getMessaging , getToken,onMessage } from "firebase/messaging";

// import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
 apiKey: "AIzaSyC14hS0_idUIRS9JEigObmT-_CGl3zb8Fo",
  authDomain: "thirukalyanam-c8e1c.firebaseapp.com",
  projectId: "thirukalyanam-c8e1c",
  storageBucket: "thirukalyanam-c8e1c.firebasestorage.app",
  messagingSenderId: "433615056618",
  appId: "1:433615056618:web:309a920f408ba826907193",
  measurementId: "G-1L93F6DS7K"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
// const analytics = getAnalytics(app);

// Initialize Firebase Cloud Messaging and get a reference to the service
export const messaging = getMessaging(app);



// 🔔 Foreground notification handler
export const listenToMessages = () => {
  onMessage(messaging, (payload) => {
    console.log("🔥 Foreground FCM:", payload);

    if (Notification.permission === "granted" && payload.notification) {
      const notification = new Notification(
        payload.notification.title,
        {
          body: payload.notification.body,
          icon: "/favicon.ico",
          data: {
            url: "/notification",
          },
        }
      );

      // ✅ Handle click
      notification.onclick = () => {
        window.focus();
        window.location.href = "/notification";
      };
    }
  });
};



export const generateToken = async () => {
  try {
    const permission = await Notification.requestPermission();
    console.log("Notification permission:", permission);

    if (permission !== "granted") {
      return null;
    }

    const token = await getToken(messaging, {
      vapidKey: "BK8tzfEX7yITqrGmWXH-GFYZMXLbVntdfPiOqosyTgCLtHDZm6Rp-K1ro6CPbdMLFgmTa4Fwtc8F2HGFp4Hex7A",
    });

    console.log("FCM Token:", token);
    localStorage.setItem("fcm_token", token);
    return token; // ✅ MUST return
  } catch (error) {
    console.error("FCM error:", error);
    return null;
  }
};
