"use client"

import { useEffect, useRef } from "react"

/**
 * Hook to subscribe to info board WebSocket events for a specific club.
 * Pushes new post notifications to connected members in real-time.
 */
export function useInfoBoardSubscription(
  clubId: string | undefined,
  onNewPost?: (data: InfoBoardPostEvent) => void
) {
  const stompClientRef = useRef<any>(null)

  useEffect(() => {
    if (!clubId) return

    const connectWebSocket = async () => {
      try {
        const SockJS = (await import("sockjs-client")).default
        const { Client } = await import("@stomp/stompjs")

        const client = new Client({
          webSocketFactory: () => new SockJS("/ws"),
          reconnectDelay: 5000,
          heartbeatIncoming: 10000,
          heartbeatOutgoing: 10000,
        })

        client.onConnect = () => {
          client.subscribe(`/topic/club.${clubId}.infoboard`, (message) => {
            const data = JSON.parse(message.body)
            if (data.type === "NEW_POST" && onNewPost) {
              onNewPost(data as InfoBoardPostEvent)
            }
          })
        }

        client.activate()
        stompClientRef.current = client
      } catch (error) {
        console.warn("WebSocket connection failed:", error)
      }
    }

    connectWebSocket()

    return () => {
      if (stompClientRef.current) {
        stompClientRef.current.deactivate()
      }
    }
  }, [clubId, onNewPost])
}

export interface InfoBoardPostEvent {
  type: "NEW_POST"
  postId: string
  title: string
  category: string
  timestamp: string
}
