All files / web/src/app/arcade page.tsx

0% Statements 0/435
0% Branches 0/1
0% Functions 0/1
0% Lines 0/435

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client'

import { useRouter } from 'next/navigation'
import { useState, useEffect } from 'react'
import { useRoomData, useSetRoomGame, useCreateRoom } from '@/hooks/useRoomData'
import { useUserId } from '@/hooks/useUserId'
import { GAMES_CONFIG } from '@/components/GameSelector'
import type { GameType } from '@/components/GameSelector'
import { PageWithNav } from '@/components/PageWithNav'
import { css } from '../../../styled-system/css'
import { getGame, hasGame } from '@/lib/arcade/game-registry'
import { useAllGames } from '@/hooks/useAllGames'

/**
 * /arcade - Renders the game for the user's current room
 * Since users can only be in one room at a time, this is a simple singular route
 *
 * Shows game selection when no game is set, then shows the game itself once selected.
 * URL never changes - it's always /arcade regardless of selection, setup, or gameplay.
 *
 * Auto-creates a solo room if the user doesn't have one, ensuring they always have
 * a context in which to play games.
 *
 * Note: ModerationNotifications is handled by PageWithNav inside each game component,
 * so we don't need to render it here.
 *
 * Test: Verifying compose-updater automatic deployment cycle
 */
export default function RoomPage() {
  const router = useRouter()
  const { roomData, isLoading } = useRoomData()
  const { data: viewerId } = useUserId()
  const { mutate: setRoomGame } = useSetRoomGame()
  const { mutate: createRoom, isPending: isCreatingRoom } = useCreateRoom()
  const [permissionError, setPermissionError] = useState<string | null>(null)
  const allGames = useAllGames()

  // Auto-create room when user has no room
  // This happens when:
  // 1. First time visiting /arcade
  // 2. After leaving a room
  useEffect(() => {
    if (!isLoading && !roomData && viewerId && !isCreatingRoom) {
      console.log('[RoomPage] No room found, auto-creating room for user:', viewerId)

      createRoom(
        {
          name: 'My Room',
          gameName: null, // No game selected yet
          gameConfig: undefined, // No game config since no game selected
          accessMode: 'open' as const, // Open by default - user can change settings later
        },
        {
          onSuccess: (result) => {
            console.log('[RoomPage] Successfully created room:', result.room.id)
          },
          onError: (error) => {
            console.error('[RoomPage] Failed to auto-create room:', error)
          },
        }
      )
    }
  }, [isLoading, roomData, viewerId, isCreatingRoom, createRoom])

  // Show loading state (includes both initial load and room creation)
  if (isLoading || isCreatingRoom) {
    return (
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100vh',
          fontSize: '18px',
          color: 'token(colors.text.secondary)',
        }}
      >
        {isCreatingRoom ? 'Creating solo room...' : 'Loading room...'}
      </div>
    )
  }

  // If still no room after loading and creation attempt, show fallback
  // This should rarely happen (only if auto-creation fails)
  if (!roomData) {
    return (
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100vh',
          fontSize: '18px',
          color: 'token(colors.text.secondary)',
          gap: '1rem',
        }}
      >
        <div>Unable to create room</div>
        <div style={{ fontSize: '14px', color: '#999' }}>Please try refreshing the page</div>
      </div>
    )
  }

  // Show game selection if no game is set
  if (!roomData.gameName) {
    // Determine if current user is the host
    const currentMember = roomData.members.find((m) => m.userId === viewerId)
    const isHost = currentMember?.isCreator === true
    const hostMember = roomData.members.find((m) => m.isCreator)

    const handleGameSelect = (gameType: GameType) => {
      console.log('[RoomPage] handleGameSelect called with gameType:', gameType)

      // Check if user is host before allowing selection
      if (!isHost) {
        setPermissionError(
          `Only the room host can select a game. Ask ${hostMember?.displayName || 'the host'} to choose.`
        )
        // Clear error after 5 seconds
        setTimeout(() => setPermissionError(null), 5000)
        return
      }

      // Clear any previous errors
      setPermissionError(null)

      // All games are now in the registry
      if (hasGame(gameType)) {
        const gameDef = getGame(gameType)
        if (!gameDef?.manifest.available) {
          console.log('[RoomPage] Registry game not available, blocking selection')
          return
        }

        console.log('[RoomPage] Selecting registry game:', gameType)
        setRoomGame(
          {
            roomId: roomData.id,
            gameName: gameType,
          },
          {
            onError: (error: any) => {
              console.error('[RoomPage] Failed to set game:', error)
              setPermissionError(
                error.message || 'Failed to select game. Only the host can change games.'
              )
              setTimeout(() => setPermissionError(null), 5000)
            },
          }
        )
        return
      }

      console.log('[RoomPage] Unknown game type:', gameType)
    }

    return (
      <PageWithNav
        navTitle="Choose Game"
        navEmoji="🎮"
        emphasizePlayerSelection={true}
        onExitSession={() => router.push('/arcade')}
      >
        <div
          className={css({
            minHeight: '100vh',
            background: 'linear-gradient(135deg, #0f0f23 0%, #1a1a3a 50%, #2d1b69 100%)',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '4',
          })}
        >
          <h1
            className={css({
              fontSize: { base: '2xl', md: '3xl' },
              fontWeight: 'bold',
              color: 'text.inverse',
              mb: '4',
              textAlign: 'center',
            })}
          >
            Choose a Game
          </h1>

          {/* Host info and permission messaging */}
          <div
            className={css({
              maxWidth: '800px',
              width: '100%',
              mb: '6',
            })}
          >
            {isHost ? (
              <div
                className={css({
                  background: 'rgba(34, 197, 94, 0.1)',
                  border: '1px solid rgba(34, 197, 94, 0.3)',
                  borderRadius: '8px',
                  padding: '12px 16px',
                  color: '#86efac',
                  fontSize: 'sm',
                  textAlign: 'center',
                })}
              >
                👑 You're the room host. Select a game to start playing.
              </div>
            ) : (
              <div
                className={css({
                  background: 'rgba(234, 179, 8, 0.1)',
                  border: '1px solid rgba(234, 179, 8, 0.3)',
                  borderRadius: '8px',
                  padding: '12px 16px',
                  color: '#fde047',
                  fontSize: 'sm',
                  textAlign: 'center',
                })}
              >
                ⏳ Waiting for {hostMember?.displayName || 'the host'} to select a game...
              </div>
            )}

            {/* Permission error message */}
            {permissionError && (
              <div
                className={css({
                  background: 'rgba(239, 68, 68, 0.1)',
                  border: '1px solid rgba(239, 68, 68, 0.3)',
                  borderRadius: '8px',
                  padding: '12px 16px',
                  color: '#fca5a5',
                  fontSize: 'sm',
                  textAlign: 'center',
                  mt: '3',
                })}
              >
                ⚠️ {permissionError}
              </div>
            )}
          </div>

          <div
            className={css({
              display: 'grid',
              gridTemplateColumns: { base: '1fr', md: 'repeat(2, 1fr)' },
              gap: '4',
              maxWidth: '800px',
              width: '100%',
            })}
          >
            {/* Legacy games */}
            {Object.entries(GAMES_CONFIG).map(([gameType, config]: [string, any]) => {
              const isAvailable = !('available' in config) || config.available !== false
              const isDisabled = !isHost || !isAvailable
              return (
                <button
                  key={gameType}
                  onClick={() => handleGameSelect(gameType as GameType)}
                  disabled={isDisabled}
                  className={css({
                    background: config.gradient,
                    border: '2px solid',
                    borderColor: config.borderColor || 'blue.200',
                    borderRadius: '2xl',
                    padding: '6',
                    cursor: isDisabled ? 'not-allowed' : 'pointer',
                    opacity: isDisabled ? 0.4 : 1,
                    transition: 'all 0.3s ease',
                    _hover: isDisabled
                      ? {}
                      : {
                          transform: 'translateY(-4px) scale(1.02)',
                          boxShadow: '0 20px 40px rgba(59, 130, 246, 0.2)',
                        },
                  })}
                >
                  <div
                    className={css({
                      fontSize: '4xl',
                      mb: '2',
                    })}
                  >
                    {config.icon}
                  </div>
                  <h3
                    className={css({
                      fontSize: 'xl',
                      fontWeight: 'bold',
                      color: 'text.primary',
                      mb: '2',
                    })}
                  >
                    {config.name}
                  </h3>
                  <p
                    className={css({
                      fontSize: 'sm',
                      color: 'text.secondary',
                    })}
                  >
                    {config.description}
                  </p>
                </button>
              )
            })}

            {/* Registry games */}
            {allGames.map((gameDef) => {
              const isAvailable = gameDef.manifest.available
              const isDisabled = !isHost || !isAvailable
              return (
                <button
                  key={gameDef.manifest.name}
                  onClick={() => handleGameSelect(gameDef.manifest.name)}
                  disabled={isDisabled}
                  style={{
                    background: gameDef.manifest.gradient,
                    borderColor: gameDef.manifest.borderColor,
                  }}
                  className={css({
                    border: '2px solid',
                    borderRadius: '2xl',
                    padding: '6',
                    cursor: isDisabled ? 'not-allowed' : 'pointer',
                    opacity: isDisabled ? 0.4 : 1,
                    transition: 'all 0.3s ease',
                    _hover: isDisabled
                      ? {}
                      : {
                          transform: 'translateY(-4px) scale(1.02)',
                          boxShadow: '0 20px 40px rgba(59, 130, 246, 0.2)',
                        },
                  })}
                >
                  <div
                    className={css({
                      fontSize: '4xl',
                      mb: '2',
                    })}
                  >
                    {gameDef.manifest.icon}
                  </div>
                  <h3
                    className={css({
                      fontSize: 'xl',
                      fontWeight: 'bold',
                      color: 'text.primary',
                      mb: '2',
                    })}
                  >
                    {gameDef.manifest.displayName}
                  </h3>
                  <p
                    className={css({
                      fontSize: 'sm',
                      color: 'text.secondary',
                    })}
                  >
                    {gameDef.manifest.description}
                  </p>
                </button>
              )
            })}
          </div>
        </div>
      </PageWithNav>
    )
  }

  // Check if this is a registry game first
  if (hasGame(roomData.gameName)) {
    const gameDef = getGame(roomData.gameName)
    if (!gameDef) {
      return (
        <PageWithNav
          navTitle="Game Not Found"
          navEmoji="⚠️"
          emphasizePlayerSelection={true}
          onExitSession={() => router.push('/arcade')}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              height: '100vh',
              fontSize: '18px',
              color: 'token(colors.text.secondary)',
            }}
          >
            Game "{roomData.gameName}" not found in registry
          </div>
        </PageWithNav>
      )
    }

    // Render registry game dynamically
    const { Provider, GameComponent } = gameDef
    return (
      <Provider>
        <GameComponent />
      </Provider>
    )
  }

  // Render legacy games based on room's gameName
  switch (roomData.gameName) {
    // TODO: Add other legacy games (complement-race, etc.) once migrated
    default:
      return (
        <PageWithNav
          navTitle="Game Not Available"
          navEmoji="⚠️"
          emphasizePlayerSelection={true}
          onExitSession={() => router.push('/arcade')}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              height: '100vh',
              fontSize: '18px',
              color: 'token(colors.text.secondary)',
            }}
          >
            Game "{roomData.gameName}" not yet supported
          </div>
        </PageWithNav>
      )
  }
}