import { createFileRoute, useNavigate } from "@tanstack/react-router"; import { useState } from "react"; import type { Lobby } from "@lila/shared"; const API_URL = (import.meta.env["VITE_API_URL"] as string) || ""; type LobbySuccessResponse = { success: true; data: Lobby }; type LobbyErrorResponse = { success: false; error: string }; type LobbyApiResponse = LobbySuccessResponse | LobbyErrorResponse; export const Route = createFileRoute("/multiplayer/")({ component: MultiplayerPage, }); function MultiplayerPage() { const navigate = useNavigate(); const [joinCode, setJoinCode] = useState(""); const [isCreating, setIsCreating] = useState(false); const [isJoining, setIsJoining] = useState(false); const [error, setError] = useState(null); const handleCreate = async (): Promise => { setIsCreating(true); setError(null); try { const response = await fetch(`${API_URL}/api/v1/lobbies`, { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", }); const data = (await response.json()) as LobbyApiResponse; if (!data.success) { setError(data.error); return; } void navigate({ to: "/multiplayer/lobby/$code", params: { code: data.data.code }, }); } catch { setError("Could not connect to server. Please try again."); } finally { setIsCreating(false); } }; const handleJoin = async (): Promise => { const code = joinCode.trim().toUpperCase(); if (!code) { setError("Please enter a lobby code."); return; } setIsJoining(true); setError(null); try { const response = await fetch(`${API_URL}/api/v1/lobbies/${code}/join`, { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", }); const data = (await response.json()) as LobbyApiResponse; if (!data.success) { setError(data.error); return; } void navigate({ to: "/multiplayer/lobby/$code", params: { code: data.data.code }, }); } catch { setError("Could not connect to server. Please try again."); } finally { setIsJoining(false); } }; return (

Multiplayer

{error &&

{error}

} {/* Create lobby */}

Create a lobby

Start a new game and invite friends with a code.

{/* Join lobby */}

Join a lobby

Enter the code shared by your host.

setJoinCode(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { void handleJoin().catch((err) => { console.error("Join lobby error:", err); }); } }} maxLength={10} disabled={isCreating || isJoining} />
); }