"use client";

import { useEffect, useRef } from "react";
import { useAuth } from "@/lib/auth/AuthContext";
import { useToken } from "@/lib/auth/useToken";
import { notificationsApi } from "@/lib/api/notifications";
import {
  getFirebaseConfig,
  onForegroundMessage,
  requestFcmToken,
} from "@/lib/firebase/messaging";

const STORAGE_KEY = "biznie_fcm_token";

/**
 * Mounts once inside the authenticated layout. Registers the browser FCM token
 * with the V2 backend on login, and shows foreground notifications via the
 * native Notification API.
 */
export default function FCMRegister() {
  const { user, isAuthenticated } = useAuth();
  const { token, ready } = useToken();
  const lastSyncedFor = useRef<string | null>(null);
  const unsubRef = useRef<(() => void) | null>(null);

  useEffect(() => {
    if (!ready || !isAuthenticated || !token || !user) return;
    if (!getFirebaseConfig()) return;

    const key = `${user.id}:${token}`;
    if (lastSyncedFor.current === key) return;

    let cancelled = false;

    (async () => {
      const fcmToken = await requestFcmToken();
      if (cancelled || !fcmToken) return;

      const stored = typeof window !== "undefined" ? window.localStorage.getItem(STORAGE_KEY) : null;
      if (stored !== fcmToken) {
        try {
          await notificationsApi.registerFcm(token, { fcm_token: fcmToken, device_type: "web" });
          if (typeof window !== "undefined") window.localStorage.setItem(STORAGE_KEY, fcmToken);
        } catch {
          /* noop */
        }
      }
      lastSyncedFor.current = key;

      unsubRef.current = await onForegroundMessage((payload) => {
        if (typeof window === "undefined" || !("Notification" in window)) return;
        if (Notification.permission !== "granted") return;
        const title = payload.notification?.title ?? (payload.data as Record<string, string> | undefined)?.title ?? "Biznie";
        const body = payload.notification?.body ?? (payload.data as Record<string, string> | undefined)?.body ?? "";
        try {
          new Notification(title, { body, icon: "/favicon.ico", tag: "biznie-notification" });
        } catch {
          /* noop */
        }
      });
    })();

    return () => {
      cancelled = true;
      if (unsubRef.current) {
        unsubRef.current();
        unsubRef.current = null;
      }
    };
  }, [ready, isAuthenticated, token, user]);

  return null;
}
