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

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' : ''}`"
    >
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>
        <path d="M13.73 21a2 2 0 0 1-3.46 0"/>
      </svg>
      <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, #ef4444);
  color: #fff;
  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>
