import React, { useEffect, useState } from "react";
export const WebSocketStatus = ({ socket }) => {
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    console.log('socket changed', socket)
    if (!socket) return;

    const handleOpen = () => { console.log('socket open'); setIsConnected(true) };
    const handleClose = () => { console.log('socket close'); setIsConnected(false) };
    const handleError = () => { console.log('socket error'); setIsConnected(false) };

    socket.addEventListener("open", handleOpen);
    socket.addEventListener("close", handleClose);
    socket.addEventListener("error", handleError);

    // 🧹 Cleanup to remove listeners when component unmounts or socket changes
    return () => {
      socket.removeEventListener("open", handleOpen);
      socket.removeEventListener("close", handleClose);
      socket.removeEventListener("error", handleError);
    };

  }, [socket])
  return (
    <div className="d-flex align-items-center gap-2">
      <span
        className={`badge ${isConnected ? "text-bg-success" : "text-bg-danger"}`}
      >
        {isConnected ? "Connected" : "Disconnected"}
      </span>
    </div>
  );
};