import { useEffect, useRef, useState, useCallback } from 'react';

export default function useWebSocket(onMessage) {
  const wsRef = useRef(null);
  const [connected, setConnected] = useState(false);
  const reconnectTimeout = useRef(null);

  const connect = useCallback(() => {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/ws`;

    try {
      const ws = new WebSocket(wsUrl);
      wsRef.current = ws;

      ws.onopen = () => {
        setConnected(true);
        console.log('WebSocket connecté');
      };

      ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          if (onMessage) onMessage(data);
        } catch (e) {
          console.error('Erreur parsing WS message:', e);
        }
      };

      ws.onclose = () => {
        setConnected(false);
        console.log('WebSocket déconnecté, reconnexion dans 5s...');
        reconnectTimeout.current = setTimeout(connect, 5000);
      };

      ws.onerror = (err) => {
        console.error('Erreur WebSocket:', err);
        ws.close();
      };
    } catch (err) {
      console.error('Erreur connexion WebSocket:', err);
      reconnectTimeout.current = setTimeout(connect, 5000);
    }
  }, [onMessage]);

  useEffect(() => {
    connect();
    return () => {
      if (wsRef.current) wsRef.current.close();
      if (reconnectTimeout.current) clearTimeout(reconnectTimeout.current);
    };
  }, [connect]);

  return { connected };
}
