'use client'

import Link from 'next/link'
import { useQuery } from '@tanstack/react-query'
import { Bell } from 'lucide-react'
import { api, type NotificationItem } from '@/lib/api'
import { useAuth } from '@/contexts/AuthContext'
import { hasPermission } from '@/lib/permissions'

export function NotificationBell() {
  const { user } = useAuth()
  const enabled = hasPermission(user, 'notifications.view')

  const { data } = useQuery({
    queryKey: ['notifications', 'bell'],
    queryFn: () =>
      api.get<{ data: NotificationItem[]; meta: { unread_count: number } }>('/notifications'),
    enabled,
    refetchInterval: 60_000,
  })

  const unread = data?.data.meta?.unread_count ?? 0

  if (!enabled) return null

  return (
    <Link
      href="/notifications"
      className="premium-chip relative rounded-xl p-2 text-[var(--premium-icon-strong)] transition-transform hover:scale-105"
      aria-label="Notifications"
    >
      <Bell size={18} />
      {unread > 0 ? (
        <span className="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-red-600 px-1 text-[10px] font-bold text-white">
          {unread > 99 ? '99+' : unread}
        </span>
      ) : null}
    </Link>
  )
}
