/**
 * Browser notification utilities for StreamFlow
 */

/**
 * Request notification permission from the user
 */
export const requestNotificationPermission = async () => {
  if (!('Notification' in window)) {
    console.log('This browser does not support notifications');
    return false;
  }

  if (Notification.permission === 'granted') {
    return true;
  }

  if (Notification.permission !== 'denied') {
    const permission = await Notification.requestPermission();
    return permission === 'granted';
  }

  return false;
};

/**
 * Show a notification for the currently playing channel
 * @param {Object} channel - The channel object
 * @param {string} type - 'tv' or 'radio'
 */
export const showChannelNotification = async (channel, type = 'tv') => {
  if (!channel) return;

  // Request permission if not already granted
  const hasPermission = await requestNotificationPermission();
  if (!hasPermission) return;

  try {
    // Use service worker notification if available (better for PWA)
    if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
      const registration = await navigator.serviceWorker.ready;
      
      await registration.showNotification('StreamFlow IPTV', {
        body: `Now playing: ${channel.name}`,
        icon: '/icons/icon-192x192.svg',
        badge: '/icons/icon-72x72.svg',
        tag: 'now-playing',
        renotify: true,
        vibrate: [200, 100, 200],
        data: {
          url: type === 'tv' ? '/live-tv' : '/radio',
          channelId: channel.id
        },
        actions: [
          {
            action: 'open',
            title: 'Open Player'
          }
        ]
      });
    } else {
      // Fallback to regular notification
      const notification = new Notification('StreamFlow IPTV', {
        body: `Now playing: ${channel.name}`,
        icon: '/icons/icon-192x192.svg',
        badge: '/icons/icon-72x72.svg',
        tag: 'now-playing',
        renotify: true
      });

      // Auto-close after 4 seconds
      setTimeout(() => notification.close(), 4000);
    }
  } catch (error) {
    console.error('Failed to show notification:', error);
  }
};

/**
 * Check if notifications are supported and enabled
 */
export const isNotificationSupported = () => {
  return 'Notification' in window;
};

/**
 * Get current notification permission status
 */
export const getNotificationPermission = () => {
  if (!isNotificationSupported()) return 'unsupported';
  return Notification.permission;
};
