Spaces:
Running

microfunnel-api / frontend /components /NotificationBell.tsx
axeronis
fix: Increase Sidebar Header z-index to fix dropdown stacking
4b5854b
Raw History Blame Contribute Delete
11.1 kB
'use client'
import { useState, useEffect } from 'react'
import { Bell } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import { useRouter } from 'next/navigation'
import { cn } from '@/lib/utils'
interface Notification {
id: string
type: string
title: string
message: string
is_read: boolean
created_at: string
lead_id: string
}
interface NotificationBellProps {
align?: 'right' | 'left' | 'right-side'
}
export default function NotificationBell({ align = 'right' }: NotificationBellProps) {
const router = useRouter()
const [unreadCount, setUnreadCount] = useState(0)
const [notifications, setNotifications] = useState<Notification[]>([])
const [isOpen, setIsOpen] = useState(false)
const [loading, setLoading] = useState(false)
const containerRef = useState<HTMLDivElement | null>(null)
// Fetch unread count
useEffect(() => {
fetchUnreadCount()
const interval = setInterval(fetchUnreadCount, 30000) // Every 30s
return () => clearInterval(interval)
}, [])
const fetchUnreadCount = async () => {
try {
const token = localStorage.getItem('auth_token')
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/notifications/unread-count`, {
headers: { 'Authorization': `Bearer ${token}` }
})
const data = await response.json()
setUnreadCount(data.unread_count)
} catch (error) {
console.error('Failed to fetch unread count:', error)
}
}
const fetchNotifications = async () => {
try {
setLoading(true)
const token = localStorage.getItem('auth_token')
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/notifications`, {
headers: { 'Authorization': `Bearer ${token}` }
})
const data = await response.json()
setNotifications(data)
} catch (error) {
console.error('Failed to fetch notifications:', error)
} finally {
setLoading(false)
}
}
const handleClick = async () => {
if (!isOpen) {
await fetchNotifications()
}
setIsOpen(!isOpen)
}
const handleNotificationClick = async (notification: Notification) => {
// Mark as read
const token = localStorage.getItem('auth_token')
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/notifications/${notification.id}/mark-read`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${token}` }
})
// Navigate to chat
router.push(`/chats?lead=${notification.lead_id}`)
setIsOpen(false)
fetchUnreadCount()
}
const getIcon = (type: string) => {
switch (type) {
case 'order': return '🛍️';
case 'booking': return '📅';
case 'lead_heat': return '🔥';
case 'message': return '💬';
default: return '🔔';
}
}
const formatTime = (dateStr: string) => {
const date = new Date(dateStr)
const now = new Date()
const diffMs = now.getTime() - date.getTime()
const diffMins = Math.round(diffMs / 60000)
const diffHrs = Math.round(diffMs / 3600000)
if (diffMins < 1) return 'Только что'
if (diffMins < 60) return `${diffMins} мин. назад`
if (diffHrs < 24) return `${diffHrs} ч. назад`
return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' })
}
const markAllRead = async () => {
const token = localStorage.getItem('auth_token')
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/notifications/mark-all-read`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${token}` }
})
fetchUnreadCount()
fetchNotifications()
}
return (
<div className="relative">
{/* Bell Icon */}
<button
onClick={handleClick}
className="relative p-2 hover:bg-slate-100 rounded-lg transition-colors"
>
<Bell className="w-6 h-6 text-slate-600" />
{unreadCount > 0 && (
<motion.span
initial={{ scale: 0 }}
animate={{ scale: 1 }}
className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center font-bold"
>
{unreadCount > 9 ? '9+' : unreadCount}
</motion.span>
)}
</button>
{/* Dropdown */}
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, scale: 0.95, y: 10 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 10 }}
transition={{ duration: 0.2 }}
className={cn(
"absolute mt-3 w-80 sm:w-96 bg-white rounded-2xl shadow-xl border border-slate-100 overflow-hidden z-[100]",
align === 'right' ? "right-0 origin-top-right" :
align === 'left' ? "left-0 origin-top-left" :
"left-full top-0 ml-4 origin-top-left" // right-side
)}
>
{/* Header */}
<div className="px-4 py-3 border-b border-slate-100 flex items-center justify-between bg-white/50 backdrop-blur-sm">
<h3 className="font-semibold text-slate-900">Уведомления</h3>
{unreadCount > 0 && (
<button
onClick={markAllRead}
className="text-xs text-indigo-600 hover:text-indigo-700 font-medium px-2 py-1 rounded hover:bg-indigo-50 transition-colors"
>
Прочитать все
</button>
)}
</div>
{/* Notifications List */}
<div className="max-h-[28rem] overflow-y-auto custom-scrollbar">
{loading && notifications.length === 0 ? (
<div className="p-8 text-center text-slate-400">
<div className="animate-spin w-6 h-6 border-2 border-indigo-500 border-t-transparent rounded-full mx-auto mb-2" />
Загрузка...
</div>
) : notifications.length === 0 ? (
<div className="py-12 px-8 text-center text-slate-400">
<Bell className="w-12 h-12 mx-auto mb-3 opacity-20" />
<p className="text-sm">Нет новых уведомлений</p>
</div>
) : (
<div className="divide-y divide-slate-50">
{notifications.map((notification) => (
<button
key={notification.id}
onClick={() => handleNotificationClick(notification)}
className={cn(
"w-full p-4 text-left hover:bg-slate-50 transition-all duration-200 group relative",
!notification.is_read ? "bg-indigo-50/50" : "bg-white"
)}
>
{!notification.is_read && (
<div className="absolute left-0 top-0 bottom-0 w-1 bg-indigo-500" />
)}
<div className="flex gap-3">
{/* Icon */}
<div className={cn(
"w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 text-lg shadow-sm group-hover:scale-110 transition-transform",
notification.type === 'booking' ? "bg-purple-100" :
notification.type === 'order' ? "bg-emerald-100" :
notification.type === 'message' ? "bg-blue-100" :
"bg-orange-100"
)}>
{getIcon(notification.type)}
</div>
{/* Content */}
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex justify-between items-start mb-0.5">
<h4 className={cn(
"text-sm font-medium truncate pr-2",
!notification.is_read ? "text-slate-900" : "text-slate-700"
)}>
{notification.title}
</h4>
<span className="text-[10px] text-slate-400 whitespace-nowrap flex-shrink-0 mt-1">
{formatTime(notification.created_at)}
</span>
</div>
<p className="text-xs text-slate-500 line-clamp-2 leading-relaxed">
{notification.message}
</p>
</div>
</div>
</button>
))}
</div>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
)
}