"use client";

import { useEffect } from "react";
import { useStore } from "zustand/react";

import { useSocketStore } from "@/services/socket";
import type { ServerToClientEvents } from "@/services/socket/events";

export function useSocketEvent<E extends keyof ServerToClientEvents>(
  event: E,
  handler: ServerToClientEvents[E]
) {
  const socket = useStore(useSocketStore, state => state.socket);

  useEffect(() => {
    if (!socket || !handler) return;

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    socket.on(event, handler as any);
    return () => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      socket.off(event, handler as any);
    };
  }, [socket, event, handler]);
}
