This commit is contained in:
magdo
2025-11-17 19:39:00 +01:00
10 changed files with 2007 additions and 72 deletions
+180 -19
View File
@@ -9,6 +9,7 @@ import { startGame } from "../../api/gameApi.js"
const Lobby = () => {
const [visible, setVisible] = useState(false)
const [isStarting, setIsStarting] = useState(false)
const sectionRef = useRef(null)
const { goHome, goGame } = HandleNavigate()
const location = useLocation()
@@ -25,19 +26,29 @@ const Lobby = () => {
players,
isGamemaster,
gameStarted,
pendingPlayers,
approvalStatus,
approvePlayer,
rejectPlayer,
} = useGameWebSocket(gameToken)
const gameCode = gameCodeFromState || gameState?.gameCode || 'Loading...'
// Filter out gamemaster from player list - gamemaster is NOT a player
const currentPlayers = (players || []).filter(p => {
// If we have userId info, filter by that
if (p.userId) {
return p.userId !== gameState?.createdBy
// Players list - gamemaster is separate, don't filter
// Backend should handle this correctly
const currentPlayers = players || []
// Debug logging
useEffect(() => {
if (import.meta.env.DEV) {
console.log('🎮 Lobby state update:')
console.log(' - isGamemaster:', isGamemaster)
console.log(' - gameState:', gameState)
console.log(' - players:', players)
console.log(' - currentPlayers:', currentPlayers)
console.log(' - pendingPlayers:', pendingPlayers)
}
// Otherwise filter by name (less reliable but works for now)
return true
})
}, [isGamemaster, gameState, players, currentPlayers, pendingPlayers])
useEffect(() => {
const observer = new IntersectionObserver(
@@ -56,7 +67,18 @@ const Lobby = () => {
console.log('🎮 Game started, navigating to /game')
goGame()
}
}, [gameStarted, goGame])
}, [gameStarted, navigate])
// Handle approval status changes
useEffect(() => {
if (approvalStatus === 'denied') {
alert('A gamemaster elutasította a csatlakozási kérelmedet.')
localStorage.removeItem('gameToken')
navigate("/home")
} else if (approvalStatus === 'approved') {
console.log('✅ Join approved, you can now see the lobby')
}
}, [approvalStatus, navigate])
const handleExit = () => {
if (window.confirm("Biztosan ki szeretnél lépni a lobbyból?")) {
@@ -66,7 +88,15 @@ const Lobby = () => {
}
const handleStartGame = async () => {
// Prevent double-click
if (isStarting) {
console.log('⚠️ Game start already in progress, ignoring duplicate request')
return
}
try {
setIsStarting(true)
// Get gameId from gameState
const gameId = gameState?.gameId
if (!gameId) {
@@ -78,12 +108,29 @@ const Lobby = () => {
const response = await startGame(gameId)
console.log('Game start response:', response)
// Backend will broadcast game:started event to all players
// Navigate to game page
goGame()
// Store boardData and updated game state for GameScreen
if (response.boardData) {
localStorage.setItem('boardData', JSON.stringify(response.boardData))
console.log('✅ boardData stored in localStorage')
}
// Navigate immediately after successful start (don't wait for WebSocket)
console.log('🎮 Navigating to /game...')
navigate('/game')
} catch (error) {
console.error('Failed to start game:', error)
alert(`Nem sikerült elindítani a játékot: ${error.response?.data?.error || error.message}`)
// Check if game already started
if (error.response?.status === 409) {
console.log('Game already started, navigating to /game...')
// Navigate anyway - game is already running
navigate('/game')
} else {
alert(`Nem sikerült elindítani a játékot: ${error.response?.data?.error || error.message}`)
}
} finally {
setIsStarting(false)
}
}
@@ -92,6 +139,21 @@ const Lobby = () => {
alert('Játék kód vágólapra másolva: ' + gameCode)
}
const handleApprovePlayer = (playerName) => {
if (approvePlayer(playerName)) {
console.log(`✅ Player ${playerName} approved`)
}
}
const handleRejectPlayer = (playerName) => {
const reason = prompt(`Miért utasítod el ${playerName}-t?`, 'Nincs hely a játékban')
if (reason !== null) { // User didn't cancel
if (rejectPlayer(playerName, reason)) {
console.log(`❌ Player ${playerName} rejected`)
}
}
}
const getInitials = (name) => {
return name
.split(" ")
@@ -111,7 +173,47 @@ const Lobby = () => {
<Navbar />
</div>
<main className="flex-grow text-white px-6 pt-16 mt-0 mb-20 flex items-center justify-center">
{/* Waiting for Approval Screen (Non-gamemaster, PRIVATE games) */}
{!isGamemaster && approvalStatus === 'pending' && (
<div className="flex-1 flex items-center justify-center px-4 py-24">
<div className="bg-zinc-900/95 backdrop-blur-sm rounded-3xl p-8 max-w-md w-full border border-yellow-500/50 shadow-2xl">
<div className="text-center">
<div className="mb-6">
<div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-yellow-900/30 border-4 border-yellow-500/50 animate-pulse">
<span className="text-4xl"></span>
</div>
</div>
<h2 className="text-3xl font-bold text-yellow-300 mb-4">
Várakozás jóváhagyásra
</h2>
<p className="text-zinc-300 text-lg mb-6">
A gamemaster még nem hagyta jóvá a csatlakozásodat.
</p>
<p className="text-zinc-400 text-sm mb-8">
Kérjük, várj türelemmel, amíg a gamemaster elfogadja a kérelmedet.
</p>
<div className="flex flex-col gap-3">
<div className="bg-zinc-800 rounded-lg p-4 border border-zinc-700">
<p className="text-zinc-400 text-xs mb-1">Játék kód:</p>
<p className="text-2xl font-mono font-bold text-green-300 tracking-widest">
{gameCode}
</p>
</div>
<button
onClick={handleExit}
className="bg-red-600 hover:bg-red-500 text-white px-6 py-3 rounded-lg font-semibold transition-all duration-200 hover:scale-105"
>
Mégse
</button>
</div>
</div>
</div>
</div>
)}
{/* Normal Lobby View (Gamemaster or approved players) */}
{(isGamemaster || approvalStatus !== 'pending') && (
<div className="flex-1 flex items-center justify-center px-4 py-24">
<section
ref={sectionRef}
className={`w-full max-w-3xl rounded-2xl p-8 md:p-10 transition-all duration-1000 ease-out backdrop-blur-md shadow-2xl ${
@@ -160,6 +262,58 @@ const Lobby = () => {
Játékosok ({currentPlayers.length}):
</p>
{/* Pending Players Section (Gamemaster only, PRIVATE games) */}
{isGamemaster && pendingPlayers && pendingPlayers.length > 0 && (
<div className="bg-yellow-900/20 border-2 border-yellow-500/50 rounded-xl shadow-lg p-6 mb-6">
<h3 className="text-xl font-bold text-yellow-300 mb-4 flex items-center gap-2">
<span></span>
Jóváhagyásra váró játékosok ({pendingPlayers.length})
</h3>
<ul className="flex flex-col gap-3">
{pendingPlayers.map((player, index) => (
<li
key={index}
className="bg-zinc-700 py-3 px-4 rounded-xl flex items-center gap-4"
>
<div
className="w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold bg-yellow-900/30 text-yellow-300 border border-yellow-500/50"
>
{getInitials(player.playerName)}
</div>
<div className="flex-1">
<span className="text-white text-lg font-semibold">
{player.playerName}
</span>
{player.isAuthenticated && (
<span className="ml-2 text-xs bg-green-600/30 text-green-300 px-2 py-0.5 rounded-full border border-green-500/50">
Bejelentkezve
</span>
)}
</div>
<div className="flex gap-2">
<button
onClick={() => handleApprovePlayer(player.playerName)}
className="bg-green-600 hover:bg-green-500 text-white px-4 py-2 rounded-lg font-semibold transition-all duration-200 hover:scale-105 flex items-center gap-1"
title="Jóváhagyás"
>
<span></span>
<span className="hidden sm:inline">Jóváhagy</span>
</button>
<button
onClick={() => handleRejectPlayer(player.playerName)}
className="bg-red-600 hover:bg-red-500 text-white px-4 py-2 rounded-lg font-semibold transition-all duration-200 hover:scale-105 flex items-center gap-1"
title="Elutasítás"
>
<span></span>
<span className="hidden sm:inline">Elutasít</span>
</button>
</div>
</li>
))}
</ul>
</div>
)}
<div className="bg-zinc-800/90 rounded-xl shadow-lg p-6 mb-8">
<ul className="flex flex-col gap-4">
{currentPlayers.length === 0 ? (
@@ -215,15 +369,21 @@ const Lobby = () => {
/* Gamemaster view - can start game */
<button
onClick={handleStartGame}
disabled={currentPlayers.length < 2}
disabled={currentPlayers.length < 2 || isStarting}
className={`px-8 py-3 rounded-xl font-semibold shadow-lg transition-transform transform hover:scale-105 ${
currentPlayers.length >= 2
currentPlayers.length >= 2 && !isStarting
? 'bg-gradient-to-r from-green-700 to-green-500 hover:from-green-600 hover:to-green-400 text-white hover:shadow-green-400/30'
: 'bg-gray-600 text-gray-400 cursor-not-allowed'
}`}
title={currentPlayers.length < 2 ? 'Minimum 2 játékos szükséges' : 'Játék indítása'}
title={
isStarting
? 'Játék indítása folyamatban...'
: currentPlayers.length < 2
? 'Minimum 2 játékos szükséges'
: 'Játék indítása'
}
>
Játék Indítása
{isStarting ? '⏳ Indítás...' : 'Játék Indítása'}
</button>
) : (
/* Player view - cannot start game, just wait */
@@ -240,7 +400,8 @@ const Lobby = () => {
</button>
</div>
</section>
</main>
</div>
)}
</div>
)
}