'use client'

import { useSession } from 'next-auth/react'
import { useEffect } from 'react'
import { useWS } from '@/app/lib/wsStore'

export default function WebSocketManager() {
  const { data: session } = useSession()
  const connectWS = useWS((s) => s.connect)
  const disconnectWS = useWS((s) => s.disconnect)

  useEffect(() => {
    if (!session?.user?.steamId) return

    connectWS(session.user.steamId)

    const socket = useWS.getState().socket
    if (!socket) return

    socket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)

        // Typbasierter Event-Dispatch
        switch (data.type) {
          case 'invitation':
            window.dispatchEvent(new CustomEvent('ws-invitation'))
            break
          case 'team-update':
            window.dispatchEvent(new CustomEvent('ws-team-update'))
            break
          case 'team-kick':
            window.dispatchEvent(new CustomEvent('ws-team-kick'))
            break
          case 'team-kick-other':
            window.dispatchEvent(new CustomEvent('ws-team-kick-other'))
            break
          case 'team-joined':
            window.dispatchEvent(new CustomEvent('ws-team-joined'))
            break
          case 'team-member-joined':
            window.dispatchEvent(new CustomEvent('ws-team-member-joined'))
            break
          case 'team-invite':
            window.dispatchEvent(new CustomEvent('ws-team-invite'))
            break
          case 'team-invite-reject':
            window.dispatchEvent(new CustomEvent('ws-team-invite-reject'))
            break
          case 'team-left':
            window.dispatchEvent(new CustomEvent('ws-team-left'))
            break
          case 'team-member-left':
            window.dispatchEvent(new CustomEvent('ws-team-member-left'))
            break
          case 'team-leader-changed':
            window.dispatchEvent(new CustomEvent('ws-team-leader-changed'))
            break
          case 'team-join-request':
            window.dispatchEvent(new CustomEvent('ws-team-join-request'))
            break
          case 'team-renamed':
            console.log('[WS] team-renamed', data.teamId)
            window.dispatchEvent(new CustomEvent('ws-team-renamed', {
              detail: { teamId: data.teamId }
            }))
            break
          case 'team-logo-updated':
            window.dispatchEvent(new CustomEvent('ws-team-logo-updated', { detail: { teamId: data.teamId } }))
            break

          // Weitere Events hier hinzufügen ...
        }
      } catch (error) {
        console.error('[WebSocket] Ungültige Nachricht:', event.data)
      }
    }

    return () => disconnectWS()
  }, [session?.user?.steamId])

  return null
}
