/**
 * Shared Socket.IO client singleton.
 *
 * Import `socket` anywhere in the frontend to use the shared connection.
 * The socket connects lazily — the first import triggers the connection.
 */
import { io, Socket } from "socket.io-client";

// When served through nginx (any port other than Vite's own 3000), nginx already
// proxies /socket.io/ with WS upgrade support — connect same-origin so TLS and
// CORS are handled consistently with the rest of the app.
// When hitting Vite's dev server directly on :3000, connect straight to the
// backend instead, since Vite's own WS proxy fails on upgrade (unhandled
// AggregateError from engine.io's Promise.any() probe).
const SOCKET_URL =
  import.meta.env.VITE_API_BASE_URL_BACKEND ||
  (window.location.port === "3000"
    ? `${window.location.protocol}//${window.location.hostname}:5000`
    : window.location.origin);

export const socket: Socket = io(SOCKET_URL, {
  withCredentials: true,
  autoConnect: true,
  reconnectionAttempts: 5,
  reconnectionDelay: 2000,
});

socket.on("connect", () => {
  console.log("[socket] connected:", socket.id);
});

socket.on("disconnect", () => {
  console.log("[socket] disconnected");
});

socket.on("connect_error", (err) => {
  console.warn("[socket] connection error:", err.message);
});
