<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(--fs-border-color);
  border-radius: var(--fs-radius-sm);
  padding: 0.25rem 0.45rem;
  cursor: pointer;
  color: var(--fs-text-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.btn-bell:hover,
.btn-bell.active {
  background: var(--fs-surface-raised);
  color: var(--fs-text-primary);
  border-color: var(--fs-accent);
}

.bell-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: var(--fs-error);
  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>
