import React, { createContext, useEffect, useRef, useState } from 'react';

export const WebSocketContext = createContext(null);

export const WebSocketProvider = ({ children }) => {
  const ws = useRef(null);
  const [isConnected, setIsConnected] = useState(false);
  const [lastMessage, setLastMessage] = useState(null);

  useEffect(() => {
    ws.current = new WebSocket('wss://your-websocket-server.com');

    ws.current.onopen = () => {
      console.log('✅ WebSocket connected');
      setIsConnected(true);
    };

    ws.current.onmessage = (e) => {
      console.log('📩 Message received:', e.data);
      setLastMessage(e.data);
    };

    ws.current.onerror = (e) => {
      console.error('❌ WebSocket error:', e.message);
    };

    ws.current.onclose = (e) => {
      console.log('🔌 WebSocket closed:', e.code, e.reason);
      setIsConnected(false);
    };

    return () => {
      ws.current?.close();
    };
  }, []);

  const sendMessage = (msg) => {
    if (ws.current?.readyState === WebSocket.OPEN) {
      ws.current.send(JSON.stringify(msg));
    } else {
      console.warn('⚠️ WebSocket is not open. Message not sent.');
    }
  };

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