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

const firebaseConfig = {
  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",
};

// Initialize Firebase (avoid duplicate init in SSR)
const app =
  getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];

// Get messaging instance (only works in browser)
let messaging = null;
if (typeof window !== "undefined" && "serviceWorker" in navigator) {
  try {
    messaging = getMessaging(app);
  } catch (e) {}
}

// Request notification permission and get FCM token
export async function requestNotificationPermission() {
  if (typeof window === "undefined") return null;

  try {
    const permission = await Notification.requestPermission();
    if (permission !== "granted") {
      return null;
    }

    const registration = await navigator.serviceWorker.register(
      "/firebase-messaging-sw.js"
    );

    const token = await getToken(messaging, {
      vapidKey:
        "BGZ4Fo8rRhoTdStLGlCySDZOnAX4ekCA0e3HDWXL5uEi2kOnXynYjbaDbY15002phUrFqxBpPPFHgfH2VhrmFDU",
      serviceWorkerRegistration: registration,
    });

    // Send token to backend
    if (token) {
      try {
        const authToken = localStorage.getItem("auth_token");

        if (authToken) {
          const apiBase =
            process.env.NEXT_PUBLIC_API_URL ||
            "https://45.93.137.91.nip.io/api";

          await fetch(`${apiBase}/User/SetFCMToken`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${authToken}`,
            },
            body: JSON.stringify({
              token,
              deviceType: 2,
            }),
          });
        }
      } catch (err) {}
    }

    return token;
  } catch (err) {
    return null;
  }
}

// Listen for foreground messages
export function onForegroundMessage(callback) {
  if (!messaging) return () => {};

  return onMessage(messaging, (payload) => {
    callback(payload);
  });
}

export { app, messaging };