import { io, Socket } from "socket.io-client";

const SOCKET_URL = process.env.NEXT_PUBLIC_SOCKET_URL || "http://localhost:3001";

class SocketService {
  private socket: Socket | null = null;

  connect(): Socket {
    if (this.socket?.connected) return this.socket;

    this.socket = io(SOCKET_URL, {
      autoConnect: true,
      reconnection: true,
      transports: ["websocket"],
    });

    this.socket.on("connect", () => {
      console.log("⚡ Socket connected:", this.socket?.id);
    });

    this.socket.on("disconnect", () => {
      console.log("🔌 Socket disconnected");
    });

    return this.socket;
  }

  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
  }

  joinRoom(room: string) {
    if (this.socket) {
      this.socket.emit("join_room", { room });
      console.log(`🚪 Joined room: ${room}`);
    }
  }

  leaveRoom(room: string) {
    if (this.socket) {
      this.socket.emit("leave_room", { room });
      console.log(`🚪 Left room: ${room}`);
    }
  }

  getSocket(): Socket | null {
    return this.socket;
  }
}

export const socketService = new SocketService();
