import { useState, useEffect, useRef } from "react"; import { useNavigate } from "react-router-dom"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { AlertTriangle, Clock, CheckCircle2, ExternalLink } from "lucide-react"; import { notificationsApi } from "@/api/notifications"; import { useAuthStore } from "@/hooks/useAuth"; import { formatDate } from "@/lib/format"; import { Modal } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { toast } from "@/lib/toast"; export function CalibrationReminderModal() { const navigate = useNavigate(); const qc = useQueryClient(); const { user, token } = useAuthStore(); const [open, setOpen] = useState(false); const promptedTokensRef = useRef>(new Set()); const sessionKey = token ? `cal_popup_shown:${token.slice(-16)}` : null; const calNotifsQuery = useQuery({ queryKey: ["notifications", "calibration-login-popup", user?.id], queryFn: () => notificationsApi.list({ type: "calibration_due", unread_only: true, limit: 25, }), enabled: Boolean(user && token), }); const items = calNotifsQuery.data?.items ?? []; useEffect(() => { if (!token || !user || items.length === 0) return; const alreadyShownInRef = promptedTokensRef.current.has(token); let alreadyShownInSession = false; try { alreadyShownInSession = Boolean( sessionKey && sessionStorage.getItem(sessionKey) ); } catch { alreadyShownInSession = false; } if (!alreadyShownInRef && !alreadyShownInSession) { promptedTokensRef.current.add(token); try { if (sessionKey) sessionStorage.setItem(sessionKey, "1"); } catch { // ignore storage errors } setOpen(true); } }, [token, user, items.length, sessionKey]); const acknowledgeMutation = useMutation({ mutationFn: () => notificationsApi.markAllRead("calibration_due"), onSuccess: async () => { await qc.invalidateQueries({ queryKey: ["notifications"] }); await qc.invalidateQueries({ queryKey: ["dashboard"] }); toast.success("Calibration reminders acknowledged"); setOpen(false); }, onError: () => { toast.error("Failed to acknowledge calibration reminders"); }, }); if (!open || items.length === 0) return null; return ( !o && setOpen(false)} title={`Calibration Reminders (${items.length} Unread)`} className="max-w-xl" >

The following equipment calibration schedules are due or overdue and require attention:

{items.map((n) => { const isRed = n.severity === "red"; return (
{isRed ? ( ) : ( )}
{n.title} {n.severity}

{n.message}

{n.due_date && (
Due Date: {formatDate(n.due_date)}
)}
); })}
); }