import { useEffect } from 'react';
import { buchhaltungApi } from '../../services/buchhaltung';
import { useNotification } from '../../contexts/NotificationContext';
import { usePermissionContext } from '../../contexts/PermissionContext';

const SESSION_KEY = 'buchhaltung-pending-notified';

/**
 * Invisible component — checks for pending (entwurf) transactions once per session
 * and shows a notification toast if any exist.
 */
function BuchhaltungPendingNotifier() {
  const { showNotificationToast } = useNotification();
  const { hasPermission } = usePermissionContext();

  useEffect(() => {
    if (!hasPermission('buchhaltung:view')) return;
    if (sessionStorage.getItem(SESSION_KEY)) return;

    sessionStorage.setItem(SESSION_KEY, '1');

    buchhaltungApi.getPendingCount().then(count => {
      if (count > 0) {
        showNotificationToast(
          `${count} offene Buchung${count > 1 ? 'en' : ''} ausstehend`,
          'warning',
        );
      }
    }).catch(() => { /* ignore */ });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return null;
}

export default BuchhaltungPendingNotifier;
