import { useState, useEffect } from 'react';

function useSerialData() {
  const [readings, setReadings] = useState([]);
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    const serialUrl = process.env.REACT_APP_SERIAL_URL || 'http://localhost:5000';
    const eventSource = new EventSource(`${serialUrl}/events`);

    eventSource.onopen = () => {
      setIsConnected(true);
      setError(null);
      console.log('Connected to serial bridge SSE');
    };

    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        
        if (data.status === 'connected') {
          console.log('SSE:', data.message);
        } else {
          // Add new reading to the beginning
          setReadings(prev => [data, ...prev].slice(0, 100)); // Keep last 100
          console.log('Received:', data);
        }
      } catch (err) {
        console.error('Error parsing SSE data:', err);
      }
    };

    eventSource.onerror = (error) => {
      console.error('SSE connection error:', error);
      setIsConnected(false);
      setError('Failed to connect to serial bridge');
      eventSource.close();
    };

    return () => {
      eventSource.close();
    };
  }, []);

  return { readings, isConnected, error };
}

export default useSerialData;
