<script setup lang="ts">
import { computed } from 'vue'
import { Bell, BellFilled } from '@element-plus/icons-vue'
import { useDesktopNotification } from '../composables/useDesktopNotification'

const props = defineProps<{
  scope: 'user' | 'admin'
}>()

const notification = useDesktopNotification(props.scope)

const statusText = computed(() => {
  if (!notification.isSupported) return '不支持'
  if (notification.permission.value === 'granted') return '已开启'
  if (notification.permission.value === 'denied') return '已拒绝'
  return '未开启'
})

const statusType = computed(() => {
  if (notification.permission.value === 'granted') return 'success'
  if (notification.permission.value === 'denied') return 'danger'
  return 'info'
})

async function toggleNotification() {
  if (!notification.isSupported) return

  if (notification.permission.value === 'default') {
    await notification.requestPermission()
  } else if (notification.permission.value === 'denied') {
    // 用户已拒绝，需要在浏览器设置中手动开启
    alert('通知权限已被拒绝，请在浏览器设置中手动开启')
  }
}
</script>

<template>
  <div class="notification-settings">
    <el-tooltip
      content="接收新消息的桌面通知"
      placement="bottom"
    >
      <el-button
        :icon="notification.permission.value === 'granted' ? BellFilled : Bell"
        :type="notification.permission.value === 'granted' ? 'primary' : 'default'"
        :disabled="!notification.isSupported || notification.permission.value === 'denied'"
        circle
        @click="toggleNotification"
      >
        <template #default>
          <el-badge
            v-if="notification.permission.value !== 'granted' && notification.isSupported"
            is-dot
            :type="statusType"
          />
        </template>
      </el-button>
    </el-tooltip>
    <span class="status-text">{{ statusText }}</span>
  </div>
</template>

<style scoped>
.notification-settings {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.status-text {
  color: #8a94a6;
  font-size: 12px;
}
</style>
