'use client';

import { useEffect, useRef } from 'react';
import { useAuth } from '@/components/id/auth-provider';
import { usePublicSettings } from '@/components/id/public-settings-provider';
import { registerFirebasePush, subscribeFirebaseForegroundMessages } from '@/lib/firebase-push';

export function FirebasePushBridge() {
  const { token, user, isPinLocked, isLoading, isContentReady } = useAuth();
  const { firebaseConfig } = usePublicSettings();
  const registeredRef = useRef(false);

  useEffect(() => {
    if (!token || !user?.id || isPinLocked || isLoading || !isContentReady || !firebaseConfig) {
      registeredRef.current = false;
      return;
    }

    if (registeredRef.current) return;

    let cancelled = false;
    const timer = window.setTimeout(() => {
      void registerFirebasePush(token, firebaseConfig)
        .then((fcmToken) => {
          if (!cancelled && fcmToken) {
            registeredRef.current = true;
          }
        })
        .catch(() => undefined);
    }, 1200);

    return () => {
      cancelled = true;
      window.clearTimeout(timer);
    };
  }, [firebaseConfig, isContentReady, isLoading, isPinLocked, token, user?.id]);

  useEffect(() => {
    if (!firebaseConfig || !token || isPinLocked) return undefined;

    const unsubscribe = subscribeFirebaseForegroundMessages((payload) => {
      if (!('Notification' in window) || Notification.permission !== 'granted') return;
      const notification = new Notification(payload.title, {
        body: payload.message
      });
      notification.onclick = () => {
        window.focus();
        notification.close();
      };
    });

    return unsubscribe;
  }, [firebaseConfig, isPinLocked, token]);

  return null;
}
