'use client';

import { useEffect } from 'react';
import { toast } from 'sonner';

const STORAGE_KEY = 'notif.permission.prompted.v1';

export const NotificationsPermission = () => {
  useEffect(() => {
    if (typeof window === 'undefined') return;
    if (!('Notification' in window)) return;

    // Only ask once; tweak logic to your taste.
    const prompted = localStorage.getItem(STORAGE_KEY) === '1';
    console.log('NotificationsPermission', {
      supported: true,
      permission: Notification.permission,
      prompted,
    });
    if (prompted) return;

    if (Notification.permission === 'default') {
      toast('Enable system notifications?', {
        id: 'enable-notifications',
        description: 'Get a native notification at lunch time (optional).',
        action: {
          label: 'Enable',
          onClick: () => {
            // Must be called during the click handler.
            const p = Notification.requestPermission();
            p.then((perm) => {
              localStorage.setItem(STORAGE_KEY, '1');
              if (perm === 'granted') {
                toast.success('System notifications enabled');
              } else {
                toast('Okay, we will use in-app toasts instead.');
              }
            }).catch(() => {
              localStorage.setItem(STORAGE_KEY, '1');
              toast('Failed to request notification permission.');
            });
          },
        },
        cancel: {
          label: 'Not now',
          onClick: () => {
            localStorage.setItem(STORAGE_KEY, '1');
          },
        },
      });
    }
  }, []);

  return null;
};
