"use client"; import { useEffect, useRef, useState } from 'react'; import { io, Socket } from 'socket.io-client'; export const useSocket = () => { const [isConnected, setIsConnected] = useState(false); const socketRef = useRef(null); useEffect(() => { // Initialize socket connection only on client if (typeof window === 'undefined') return; // Create a socket connection const socket = io({ path: '/api/socket', addTrailingSlash: false, }); // Set up event handlers socket.on('connect', () => { console.log('Socket connected:', socket.id); setIsConnected(true); }); socket.on('disconnect', () => { console.log('Socket disconnected'); setIsConnected(false); }); socket.on('connect_error', (err) => { console.error('Socket connection error:', err); setIsConnected(false); }); // Store socket reference socketRef.current = socket; // Clean up on unmount return () => { socket.disconnect(); }; }, []); // Join a location share room const joinLocationShare = (shareToken: string) => { if (socketRef.current && shareToken) { socketRef.current.emit('share:join', shareToken); } }; // Leave a location share room const leaveLocationShare = (shareToken: string) => { if (socketRef.current && shareToken) { socketRef.current.emit('share:leave', shareToken); } }; // Send a location update const sendLocationUpdate = (data: { latitude: number; longitude: number; accuracy?: number; shareToken?: string; }) => { if (socketRef.current) { socketRef.current.emit('location:update', { ...data, timestamp: new Date().toISOString(), }); } }; // Subscribe to location updates for a specific share const subscribeToLocationUpdates = ( shareToken: string, callback: (data: any) => void ) => { if (!socketRef.current) return () => {}; // Join the location share room joinLocationShare(shareToken); // Listen for location updates socketRef.current.on('location:updated', callback); // Return cleanup function return () => { if (socketRef.current) { socketRef.current.off('location:updated', callback); leaveLocationShare(shareToken); } }; }; return { socket: socketRef.current, isConnected, joinLocationShare, leaveLocationShare, sendLocationUpdate, subscribeToLocationUpdates, }; };