"use client"

import { useEffect, useCallback, useRef } from "react"

/**
 * Hook to subscribe to forum WebSocket events for a specific club.
 * Listens for new topics and replies in real-time.
 */
export function useForumSubscription(
  clubId: string | undefined,
  topicId?: string,
  onNewTopic?: (data: ForumTopicEvent) => void,
  onNewReply?: (data: ForumReplyEvent) => void
) {
  const stompClientRef = useRef<any>(null)

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

    // Dynamic import of SockJS client
    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 = () => {
          // Subscribe to general forum channel
          client.subscribe(`/topic/club.${clubId}.forum`, (message) => {
            const data = JSON.parse(message.body)
            if (data.type === "NEW_TOPIC" && onNewTopic) {
              onNewTopic(data as ForumTopicEvent)
            }
          })

          // Subscribe to specific topic if provided
          if (topicId) {
            client.subscribe(`/topic/club.${clubId}.forum.${topicId}`, (message) => {
              const data = JSON.parse(message.body)
              if (data.type === "NEW_REPLY" && onNewReply) {
                onNewReply(data as ForumReplyEvent)
              }
            })
          }
        }

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

    connectWebSocket()

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

export interface ForumTopicEvent {
  type: "NEW_TOPIC"
  topicId: string
  title: string
  authorName: string
  timestamp: string
}

export interface ForumReplyEvent {
  type: "NEW_REPLY"
  topicId: string
  replyId: string
  authorName: string
  timestamp: string
}
