import { useEffect } from "react"; import { Socket } from "socket.io-client"; export interface EmailPayload { messageId: number; userId: string; from: { name?: string; address: string; }; to: Array<{ name?: string; address: string; }>; subject: string; preview?: string; hasAttachments: boolean; timestamp: string; mailboxId: string; mailboxName: string; isRead: boolean; isFlagged: boolean; size: number; } export interface EmailStatusPayload { messageId: number; userId: string; mailboxId: string; timestamp: string; } export interface UnreadCountPayload { userId: string; totalUnread: number; mailboxCounts: Record; timestamp: string; count: number; } interface EmailEventHandlers { onNewEmail?: (email: EmailPayload) => void; onEmailRead?: (data: EmailStatusPayload) => void; onEmailDeleted?: (data: EmailStatusPayload) => void; onEmailSent?: (data: EmailStatusPayload) => void; onUnreadCountUpdated?: (data: UnreadCountPayload) => void; onMailboxUpdated?: (data: EmailStatusPayload) => void; } export const useEmailEvents = ( socket: Socket | null, handlers: EmailEventHandlers ) => { useEffect(() => { if (!socket) return; // Register event handlers if (handlers.onNewEmail) { socket.on("new_email", handlers.onNewEmail); } if (handlers.onEmailRead) { socket.on("email_read", handlers.onEmailRead); } if (handlers.onEmailRead) { socket.on("email_unread", handlers.onEmailRead); } if (handlers.onEmailDeleted) { socket.on("email_deleted", handlers.onEmailDeleted); } if (handlers.onEmailSent) { socket.on("email_sent", handlers.onEmailSent); } if (handlers.onUnreadCountUpdated) { socket.on("unread_count_updated", handlers.onUnreadCountUpdated); } if (handlers.onMailboxUpdated) { socket.on("mailbox_updated", handlers.onMailboxUpdated); } // Cleanup on unmount return () => { socket.off("new_email"); socket.off("email_read"); socket.off("email_deleted"); socket.off("email_sent"); socket.off("unread_count_updated"); socket.off("mailbox_updated"); }; }, [socket, handlers]); };