import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
import { useEffect } from "react";
import { authClient } from "../lib/auth-client.js";
import { WsProvider } from "../lib/ws-provider.js";
import { useWsConnect } from "../lib/ws-hooks.js";

const wsBaseUrl =
  (import.meta.env["VITE_WS_URL"] as string) ||
  (import.meta.env["VITE_API_URL"] as string) ||
  "";

export const Route = createFileRoute("/multiplayer")({
  component: MultiplayerLayout,
  beforeLoad: async () => {
    const { data: session } = await authClient.getSession();
    if (!session) {
      throw redirect({
        to: "/",
        search: { modal: "auth", redirect: "/multiplayer" },
      });
    }
    return { session };
  },
});

function WsConnector() {
  const connect = useWsConnect();

  useEffect(() => {
    void connect(wsBaseUrl).catch((err) => {
      console.error("WebSocket connection failed:", err);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return null;
}

function MultiplayerLayout() {
  return (
    <WsProvider>
      <WsConnector />
      <Outlet />
    </WsProvider>
  );
}
