Spaces:
Running

File size: 11,138 Bytes
727ec8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b5854b
 
 
 
 
727ec8d
 
 
 
 
4b5854b
 
727ec8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5b0f8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
727ec8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506bd65
 
b5b0f8b
 
 
 
 
4b5854b
 
 
 
 
 
727ec8d
b5b0f8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506bd65
b5b0f8b
 
 
 
 
 
506bd65
b5b0f8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506bd65
b5b0f8b
 
 
 
 
506bd65
b5b0f8b
 
 
 
 
 
 
506bd65
b5b0f8b
 
 
 
 
 
 
727ec8d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
'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>
    )
}