'use client';

import React, { createContext, useContext } from 'react';
import { useWebSocket } from '@/hooks/useWebSocket';

// Define the shape of the context
interface WebSocketContextType {
  isConnected: boolean;
  isConnecting: boolean;
  sendMessage: (message: any) => void;
  joinRoom: (roomId: string) => void;
  leaveRoom: (roomId: string) => void;
  connectionId: string | null;
  lastMessage: any | null;
}

// Create the context with a default value
const WebSocketContext = createContext<WebSocketContextType | undefined>(undefined);

// Custom hook to use the WebSocket context
export const useWebSocketContext = () => {
  const context = useContext(WebSocketContext);
  if (context === undefined) {
    throw new Error('useWebSocketContext must be used within a WebSocketProvider');
  }
  return context;
};

// Provider component
export const WebSocketProvider = ({ children }: { children: React.ReactNode }) => {
  const webSocket = useWebSocket({
    autoConnect: true, // Auto-connect when the provider is mounted
  });

  return (
    <WebSocketContext.Provider value={webSocket}>
      {children}
    </WebSocketContext.Provider>
  );
};
