"use client";

import { useEffect, useState } from "react";
import { useFirebaseNotifications } from "@/src/hooks/useFirebaseNotifications";

export default function NotificationsBoot({
  onFallbackToPolling,
  onPushReady,
}) {
  const [userId, setUserId] = useState(null);
  const [lang, setLang] = useState("ar");
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    try {
      if (typeof window === "undefined") return;
      const storedUserId = localStorage.getItem("userId");
      const storedLang = localStorage.getItem("lang") ?? "ar";
      setUserId(storedUserId);
      setLang(storedLang);
      setIsReady(true);
    } catch (error) {
      setIsReady(true);
    }
  }, []);

  const { permission, isSupported, requestPermission, initListeners } =
    useFirebaseNotifications({ userId, lang });

  useEffect(() => {
    if (!isReady) return;

    const run = async () => {
      try {
        // If FCM is not supported at all, fallback
        if (isSupported === false) {
          onFallbackToPolling?.();
          return;
        }

        // لا نطلب requestPermission() هنا: المتصفح يسمح فقط من user gesture
        // إذا كانت الصلاحية ممنوحة مسبقاً نفعّل الـ listeners، وإلا نعتمد على polling
        if (permission !== "granted") {
          onFallbackToPolling?.();
          return;
        }

        // Now wire listeners
        const ok = await initListeners();
        if (ok) {
          onPushReady?.();
        } else {
          onFallbackToPolling?.();
        }
      } catch (error) {
        console.error("NotificationsBoot error:", error);
        onFallbackToPolling?.();
      }
    };

    run();
  }, [
    isReady,
    permission,
    isSupported,
    requestPermission,
    initListeners,
    onFallbackToPolling,
    onPushReady,
  ]);

  return null;
}
