<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useNotificationsStore } from '@/stores/notifications'
import NotificationsPanel from './NotificationsPanel.vue'
import { Bell } from 'lucide-vue-next'

const store = useNotificationsStore()
const open = ref(false)
const wrapRef = ref<HTMLElement | null>(null)

let pollInterval: ReturnType<typeof setInterval> | null = null

function toggle() {
  open.value = !open.value
  if (open.value) store.fetchAll()
}

function close() {
  open.value = false
}

function onDocClick(e: MouseEvent) {
  if (open.value && wrapRef.value && !wrapRef.value.contains(e.target as Node)) {
    close()
  }
}

onMounted(() => {
  store.fetchCount()
  pollInterval = setInterval(() => store.fetchCount(), 60_000)
  document.addEventListener('click', onDocClick, true)
})

onUnmounted(() => {
  if (pollInterval) clearInterval(pollInterval)
  document.removeEventListener('click', onDocClick, true)
})
</script>

<template>
  <div class="bell-wrap" ref="wrapRef">
    <button
      class="btn-bell"
      :class="{ active: open }"
      @click="toggle"
      aria-label="Notifications"
      :title="`${store.count} unread notification${store.count !== 1 ? 's' : ''}`"
    >
      <Bell :size="16" aria-hidden="true" />
      <span v-if="store.count > 0" class="bell-badge" aria-live="polite">{{ store.count > 99 ? '99+' : store.count }}</span>
    </button>
    <NotificationsPanel v-if="open" @close="close" />
  </div>
</template>

<style scoped>
.bell-wrap {
  position: relative;
}

.btn-bell {
  background: none;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  padding: 0.25rem 0.45rem;
  cursor: pointer;
  color: var(--color-text-muted);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.btn-bell:hover,
.btn-bell.active {
  background: var(--color-bg-card);
  color: var(--color-text);
  border-color: var(--color-primary);
}

.bell-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: var(--color-danger);
  color: var(--fs-text-on-action);
  font-size: 0.6rem;
  font-weight: 700;
  min-width: 16px;
  height: 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 3px;
  line-height: 1;
  pointer-events: none;
}
</style>
