import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; import { BellIcon, CircleNotchIcon } from '@phosphor-icons/react'; import { useToast } from '../context/ToastContext'; import { NotificationFeed, NotificationItem, getNotifications, markAllNotificationsRead, markNotificationRead, } from '../services/notifications'; import { useIsMobile } from '../hooks/useMediaQuery'; const formatWhen = (value: string) => new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }).format(new Date(value)); export const NotificationsPage: React.FC = () => { const { showToast } = useToast(); const isMobile = useIsMobile(); const [feed, setFeed] = useState(null); const [loading, setLoading] = useState(true); const load = async () => { setLoading(true); try { setFeed(await getNotifications()); } catch { setFeed({ items: [], unread: 0 }); showToast('Não foi possível carregar suas notificações.', 'error'); } finally { setLoading(false); } }; useEffect(() => { void load(); }, []); const markAll = async () => { try { await markAllNotificationsRead(); setFeed((current) => current ? { ...current, unread: 0, items: current.items.map((item) => ({ ...item, readAt: item.readAt || new Date().toISOString() })) } : current, ); window.dispatchEvent(new Event('compor:notifications-updated')); } catch { showToast('Não foi possível marcar as notificações como lidas.', 'error'); } }; const open = (item: NotificationItem) => { if (item.readAt) return; void markNotificationRead(item.id) .then(() => { setFeed((current) => current ? { ...current, unread: Math.max(0, current.unread - 1), items: current.items.map((entry) => (entry.id === item.id ? { ...entry, readAt: new Date().toISOString() } : entry)), } : current, ); window.dispatchEvent(new Event('compor:notifications-updated')); }) .catch(() => undefined); }; const list = loading ? (
) : feed?.items.length ? (
{feed.items.map((item) => ( open(item)}> {item.title} {item.body &&

{item.body}

}
{formatWhen(item.createdAt)} ))}
) : (

Nenhuma notificação

Quando alguém responder seus comentários ou fizer uma pergunta nos seus cursos, você verá aqui.

); if (isMobile) return (

Notificações

{Boolean(feed?.unread) && ( )}
{list}
); return (

Notificações

{feed?.unread ? `${feed.unread} não ${feed.unread === 1 ? 'lida' : 'lidas'}` : 'Tudo em dia.'}

{Boolean(feed?.unread) && ( )}
{list}
); };