import { socketService } from '@/lib/socket';
import { useAuthStore } from '@/stores/authStore';
import { useSocketStore } from '@/stores/socketStore';
import { useEffect } from 'react';

export const useSocket = () => {
  const { token, isAuthenticated } = useAuthStore();
  const { socket, isConnected, setSocket } = useSocketStore();

  useEffect(() => {
    if (isAuthenticated && token && !socket) {
      const socketInstance = socketService.connect(token);
      setSocket(socketInstance);
    } else if (!isAuthenticated && socket) {
      socketService.disconnect();
    }
  }, [isAuthenticated, token, socket, setSocket]);

  return {
    socket,
    isConnected,
    emit: socket?.emit.bind(socket),
    on: socket?.on.bind(socket),
    off: socket?.off.bind(socket),
  };
};
