import { useState, useEffect, useCallback } from "react"; function getStorageKey(seasonId: string) { return `draftNotifications-${seasonId}`; } export function useDraftNotifications(seasonId: string) { const [isSupported, setIsSupported] = useState(false); const [permissionState, setPermissionState] = useState< NotificationPermission | "unsupported" >("unsupported"); const [enabled, setEnabledState] = useState(false); // Check browser support and restore persisted preference useEffect(() => { if (typeof window === "undefined" || !("Notification" in window)) { return; } setIsSupported(true); setPermissionState(Notification.permission); // Restore preference from localStorage only if permission is granted if (Notification.permission === "granted") { const stored = localStorage.getItem(getStorageKey(seasonId)); if (stored === "true") { setEnabledState(true); } } }, [seasonId]); const setEnabled = useCallback( async (value: boolean) => { if (!isSupported) return; if (value) { // Request permission if not yet granted if (Notification.permission === "default") { const result = await Notification.requestPermission(); setPermissionState(result); if (result !== "granted") { return; } } else if (Notification.permission === "denied") { return; } setEnabledState(true); localStorage.setItem(getStorageKey(seasonId), "true"); } else { setEnabledState(false); localStorage.setItem(getStorageKey(seasonId), "false"); } }, [isSupported, seasonId] ); const sendNotification = useCallback( (title: string, body: string) => { if ( !enabled || !isSupported || Notification.permission !== "granted" || !document.hidden ) { return; } new Notification(title, { body, tag: `draft-${seasonId}`, }); }, [enabled, isSupported, seasonId] ); return { isSupported, permissionState, enabled, setEnabled, sendNotification, }; }