/**
 * ======================================================
 * Admin Firebase Cloud Messaging (FCM)
 * Auto bootstrap + manual initialization support
 * ======================================================
 */

/**
 * ------------------------------------------------------
 * AUTO BOOTSTRAP (runs on every admin page load)
 * ------------------------------------------------------
 */
(async function bootstrapFCM() {
  // Browser capability checks
  if (!("Notification" in window)) {
    return;
  }

  if (!("serviceWorker" in navigator)) {
    return;
  }

  if (!window.fcmConfig) {
    return;
  }

  try {
    // STEP 1: Register Service Worker (always first)
    const registration = await navigator.serviceWorker.register(
      "/firebase-messaging-sw.js",
    );
    await navigator.serviceWorker.ready;

    // STEP 2: Permission handling
    if (Notification.permission === "granted") {
      await initializeAdminFCM();
    }
  } catch (error) {
    // Handle bootstrap errors silently or send to error tracking
  }
})();

/**
 * ------------------------------------------------------
 * INITIALIZE FCM (token + listeners)
 * ------------------------------------------------------
 */
async function initializeAdminFCM() {
  try {
    // Load Firebase config from backend
    const response = await fetch(fcmConfig.firebaseConfigUrl);
    const firebaseConfig = await response.json();

    // Initialize Firebase once
    if (!firebase.apps.length) {
      firebase.initializeApp(firebaseConfig);
    }

    const messaging = firebase.messaging();

    // Request permission if needed
    let permission = Notification.permission;
    if (permission === "default") {
      permission = await Notification.requestPermission();
    }

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

    // Get FCM token
    const token = await messaging.getToken({
      vapidKey:
        "BN6-F79dwYSWJvnUXcJvo1P48BhqzoSNGeRVBLqgW3Jl4ujMbWtXd1gSlHGzUJf00OPr58ruvDqOX9eW_Qfouaw",
    });

    if (!token) {
      return;
    }

    // Save token to backend
    await saveTokenToBackend(token);

    // Foreground message listener
    messaging.onMessage((payload) => {
      showNotification(payload);
    });
  } catch (error) {
    // Handle initialization errors silently or send to error tracking
  }
}

/**
 * ------------------------------------------------------
 * SAVE TOKEN TO BACKEND
 * ------------------------------------------------------
 */
async function saveTokenToBackend(token) {
  try {
    const response = await fetch(fcmConfig.saveTokenUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ token }),
    });
    const result = await response.json();

    if (!result.success) {
      // Handle token save failure silently or report
    }
  } catch (error) {
    // Handle fetch errors silently or report
  }
}

/**
 * ------------------------------------------------------
 * FOREGROUND NOTIFICATION DISPLAY
 * ------------------------------------------------------
 */
function showNotification(payload) {
  const title = payload.notification?.title || "New Message";
  const body = payload.notification?.body || "You have a new message";
  const link = payload.fcmOptions?.link || "/admin/messages";

  const options = {
    body,
    icon: fcmConfig.faviconUrl,
    badge: fcmConfig.faviconUrl,
    tag: "admin-notification",
    requireInteraction: true,
    data: { link },
  };

  if (Notification.permission === "granted") {
    const notification = new Notification(title, options);

    notification.onclick = (event) => {
      event.preventDefault();
      window.focus();
      window.location.href = link;
      notification.close();
    };
  }
}

/**
 * ------------------------------------------------------
 * EXPOSE MANUAL TRIGGER (for Settings page button)
 * ------------------------------------------------------
 */
window.initializeAdminFCM = initializeAdminFCM;
