// lib/firebase.ts
import { initializeApp, getApps, getApp } from "firebase/app";
import { getMessaging, isSupported, Messaging } from "firebase/messaging";

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY!,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN!,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID!,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET!,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID!,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID!,
  measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID!,
};

const app = getApps().length ? getApp() : initializeApp(firebaseConfig);

// Initialize messaging as null initially
let messaging: Messaging | null = null;

// Initialize messaging only on client side and when supported
const initializeMessaging = async (): Promise<Messaging | null> => {
  if (typeof window === "undefined") return null;
  
  try {
    const supported = await isSupported();
    if (!supported) {
      console.warn("Firebase Messaging is not supported in this browser");
      return null;
    }
    
    // Check if service worker is available
    if (!('serviceWorker' in navigator)) {
      console.warn("Service Worker is not supported in this browser");
      return null;
    }
    
    // Initialize messaging if not already done
    if (!messaging) {
      messaging = getMessaging(app);
    }
    
    return messaging;
  } catch (error) {
    console.error("Error initializing Firebase Messaging:", error);
    return null;
  }
};

const getFirebaseMessaging = async (): Promise<Messaging | null> => {
  if (typeof window === "undefined") return null;
  
  try {
    const supported = await isSupported();
    if (!supported) return null;

    const registration = await navigator.serviceWorker.getRegistration();
    if (!registration) {
      console.warn("Service Worker not registered yet.");
      return null;
    }
    
    return await initializeMessaging();
  } catch (error) {
    console.error("Error getting Firebase Messaging:", error);
    return null;
  }
};

export { app, getFirebaseMessaging, messaging, initializeMessaging };