/**
 * 文件职责：订单大厅声音播放与桌面通知。
 */

/** 通知动作选项。 */
interface NotificationActionsOptions {
  isSoundEnabled: { value: boolean };
}

/** 创建通知动作。 */
export function createNotificationActions(options: NotificationActionsOptions) {
  let newOrderAudio: HTMLAudioElement | null = null;
  let urgeAudio: HTMLAudioElement | null = null;
  let isPlaying = false;

  // 1. 懒初始化音频（需要用户交互后才能播放）
  function initAudio(): void {
    if (!newOrderAudio) {
      newOrderAudio = new Audio('/sounds/new-order.mp3');
      newOrderAudio.loop = true;
    }
    if (!urgeAudio) {
      urgeAudio = new Audio('/sounds/urge.mp3');
    }
  }

  // 2. 播放新订单提示音（循环播放直到接单）
  function playNewOrderSound(): void {
    if (!options.isSoundEnabled.value || isPlaying) return;
    initAudio();
    isPlaying = true;
    newOrderAudio?.play().catch(() => {
      // 浏览器可能阻止自动播放
      isPlaying = false;
    });
  }

  // 3. 停止新订单提示音
  function stopNewOrderSound(): void {
    if (newOrderAudio) {
      newOrderAudio.pause();
      newOrderAudio.currentTime = 0;
    }
    isPlaying = false;
  }

  // 4. 播放催单提示音（播放一次）
  function playUrgeSound(): void {
    if (!options.isSoundEnabled.value) return;
    initAudio();
    urgeAudio?.play().catch(() => {});
  }

  // 5. 显示桌面通知
  function showDesktopNotification(title: string, body: string): void {
    if (Notification.permission === 'granted') {
      // eslint-disable-next-line no-new
      new Notification(title, { body, icon: '/favicon.ico' });
    }
  }

  // 6. 请求桌面通知权限
  function requestNotificationPermission(): void {
    if ('Notification' in window && Notification.permission === 'default') {
      Notification.requestPermission();
    }
  }

  return {
    playNewOrderSound,
    stopNewOrderSound,
    playUrgeSound,
    showDesktopNotification,
    requestNotificationPermission,
  };
}
