import { initializeApp } from "firebase/app";
import { MessagePayload, getMessaging, getToken, isSupported, onMessage } from "firebase/messaging";

const firebaseConfig = {
  apiKey: "AIzaSyClSUwvvFh0e14wi-Sv-w1Ob8lC5Pc7lbY",
  authDomain: "zomatoclone-50115.firebaseapp.com",
  projectId: "zomatoclone-50115",
  storageBucket: "zomatoclone-50115.firebasestorage.app",
  messagingSenderId: "684009463367",
  appId: "1:684009463367:web:85caba1b3707bffeb6db62",
  measurementId: "G-4R9T7F7R0R"
};

// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);


export const getFirebaseMessageToken = async () => {
  const isSupport = await isSupported();
  if (isSupport) {
    const messaging = getMessaging(firebaseApp);
    try {
      let registration;
      if (typeof window !== "undefined" && "serviceWorker" in navigator) {
        registration = await navigator.serviceWorker.getRegistration();
      }
      let tokenId = await getToken(messaging, {
        vapidKey: 'BHJSnlkXOu12CjWGWI1MrXvmxCSSWLynIm8miDcPKVr5m_2JTiGMXj1_A7oEPKWmx-b_CcEeIpR2eyxovVvnW9o',
        serviceWorkerRegistration: registration,
      });
      return tokenId;
    } catch (error) {
      return '';
    }
  }
  return '';
};


export const onMessageListener = (setNotificationData: (data: any) => void) => {
  try {
    if ("serviceWorker" in navigator && typeof window !== "undefined" && "Notification" in window) {
      const fcmmessaging = getMessaging(firebaseApp);

      const unsubscribe = onMessage(fcmmessaging, (payload: any) => {
        setNotificationData(payload);
      });

      return () => unsubscribe();
    }
  } catch (error) {
    console.error('Error in onMessageListener:', error);
  }
};

export default firebaseApp