import { createContext, useContext, ReactNode } from 'react'
import { useWebSocket, WebSocketMessage } from '../hooks/useWebSocket'

interface WebSocketContextType {
  isConnected: boolean
  lastMessage: WebSocketMessage | null
  messageHistory: WebSocketMessage[]
  sendMessage: (message: any) => void
  subscribe: (messageType: string, handler: (message: WebSocketMessage) => void) => () => void
}

const WebSocketContext = createContext<WebSocketContextType | undefined>(undefined)

export function WebSocketProvider({ children }: { children: ReactNode }) {
  const wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:8000/ws/'
  const { isConnected, lastMessage, messageHistory, sendMessage, subscribe } = useWebSocket(wsUrl)

  return (
    <WebSocketContext.Provider value={{ isConnected, lastMessage, messageHistory, sendMessage, subscribe }}>
      {children}
    </WebSocketContext.Provider>
  )
}

export function useWebSocketContext() {
  const context = useContext(WebSocketContext)
  if (!context) {
    throw new Error('useWebSocketContext must be used within WebSocketProvider')
  }
  return context
}
