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

export const coreSocket = io(
    window.location.origin || "http://localhost:3000",
    {
        path: "/lst/api/ws",
        autoConnect: true,
        // transports: ["websocket", "polling"],
        withCredentials: true,
        reconnectionAttempts: 5,
        timeout: 10_000,
    }
);

// --- Core events ---
coreSocket.on("connect", () => {
    console.log("✅ Core connected:", coreSocket.id);
    console.log("🔗 Transport:", coreSocket.io.engine.transport.name);
});

coreSocket.on("disconnect", (reason) => {
    console.warn("🔴 Core disconnected:", reason);
    if (reason === "io server disconnect") coreSocket.connect();
});

coreSocket.on("connect_error", (err) => {
    console.error("❌ Core connect error:", err.message);
});

coreSocket.io.on("reconnect_attempt", (attempt) => {
    console.log("♻️  Core reconnect attempt:", attempt);
});

coreSocket.io.on("reconnect_failed", () => {
    console.error("💀 Core reconnect failed after max attempts");
});

coreSocket.io.engine.on("upgrade", (transport) => {
    console.log("🚀 Core upgraded to:", transport.name);
});

coreSocket.io.engine.on("close", (reason) => {
    console.warn("🧨 Core engine closed:", reason);
});

setInterval(() => {
    //console.log(window.location.origin);
    if (coreSocket.connected) {
        coreSocket.emit("keepalive");
        console.log("🏓 Ping sent to server");
    } else {
        //console.warn("⚠️ Socket not connected, skipping ping");
    }
}, 30 * 1000);

// Optional: listen for server acknowledgment
coreSocket.on("pongCheck", (data) => {
    console.log("🏓 Pong received from server:", data);
});
