"use client";

import { ReactNode, useEffect } from "react";
import { useStore } from "zustand";

import { useSocketStore } from "@/services/socket";

interface SocketProviderProps {
  userId: string | null;
  children: ReactNode;
}

export default function SocketProvider({
  userId,
  children,
}: SocketProviderProps) {
  const connect = useStore(useSocketStore, state => state.connect);
  const disconnect = useStore(useSocketStore, state => state.disconnect);

  useEffect(() => {
    if (!userId) {
      disconnect();
      return;
    }

    connect(userId);
    return () => disconnect();
  }, [connect, disconnect, userId]);

  return <>{children}</>;
}
