'use client' import { useState, useEffect, useRef, useCallback } from 'react' import { Toggle, toast, Spinner } from '@ciphera-net/ui' import { useAuth } from '@/lib/auth/context' import { getNotificationSettings, updateNotificationSettings, type NotificationSettingsResponse } from '@/lib/api/notification-settings' export default function WorkspaceNotificationsTab({ onDirtyChange, onRegisterSave }: { onDirtyChange?: (dirty: boolean) => void; onRegisterSave?: (fn: () => Promise) => void }) { const { user } = useAuth() const [data, setData] = useState(null) const [settings, setSettings] = useState>({}) const [loading, setLoading] = useState(true) const initialRef = useRef('') const hasInitialized = useRef(false) useEffect(() => { if (!user?.org_id) return getNotificationSettings() .then(resp => { setData(resp) setSettings(resp.settings || {}) if (!hasInitialized.current) { initialRef.current = JSON.stringify(resp.settings || {}) hasInitialized.current = true } }) .catch(() => {}) .finally(() => setLoading(false)) }, [user?.org_id]) // Track dirty state useEffect(() => { if (!initialRef.current) return onDirtyChange?.(JSON.stringify(settings) !== initialRef.current) }, [settings, onDirtyChange]) const handleToggle = (key: string) => { setSettings(prev => ({ ...prev, [key]: !prev[key] })) } const handleSave = useCallback(async () => { try { await updateNotificationSettings(settings) initialRef.current = JSON.stringify(settings) onDirtyChange?.(false) toast.success('Notification preferences updated') } catch { toast.error('Failed to update notification preferences') } }, [settings, onDirtyChange]) useEffect(() => { onRegisterSave?.(handleSave) }, [handleSave, onRegisterSave]) if (loading) return
return (

Notifications

Choose what notifications you receive.

{(data?.categories || []).map(cat => (

{cat.label}

{cat.description}

handleToggle(cat.id)} />
))} {(!data?.categories || data.categories.length === 0) && (

No notification preferences available.

)}
) }