All files / web/src/hooks useArcadeSession.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { useCallback, useContext, useEffect, useRef, useState } from 'react'
import type { GameMove } from '@/lib/arcade/validation'
import { useArcadeSocket } from './useArcadeSocket'
import {
  type UseOptimisticGameStateOptions,
  useOptimisticGameState,
} from './useOptimisticGameState'
import type { RetryState } from '@/lib/arcade/error-handling'
import { PreviewModeContext } from '@/contexts/PreviewModeContext'

export interface UseArcadeSessionOptions<TState> extends UseOptimisticGameStateOptions<TState> {
  /**
   * User ID for the session
   */
  userId: string

  /**
   * Room ID for multi-user sync (optional)
   * If provided, game state will sync across all users in the room
   */
  roomId?: string

  /**
   * Auto-join session on mount
   * @default true
   */
  autoJoin?: boolean
}

export interface UseArcadeSessionReturn<TState> {
  /**
   * Current game state (with optimistic updates)
   */
  state: TState

  /**
   * Server-confirmed version
   */
  version: number

  /**
   * Whether socket is connected
   */
  connected: boolean

  /**
   * Whether there are pending moves
   */
  hasPendingMoves: boolean

  /**
   * Whether authoritative server state has been received at least once.
   * False until the first session-state event from the server.
   */
  hasReceivedServerState: boolean

  /**
   * Last error from server (move rejection)
   */
  lastError: string | null

  /**
   * Current retry state (for showing UI indicators)
   */
  retryState: RetryState

  /**
   * Send a game move (applies optimistically and sends to server)
   * Note: playerId must be provided by caller (not omitted)
   */
  sendMove: (move: Omit<GameMove, 'timestamp'>) => void

  /**
   * Exit the arcade session
   */
  exitSession: () => void

  /**
   * Clear the last error
   */
  clearError: () => void

  /**
   * Manually sync with server (useful after reconnect)
   */
  refresh: () => void

  /**
   * Other players' cursor positions (ephemeral, real-time)
   * Map of userId -> { x, y, playerId, hoveredRegionId } in SVG coordinates, or null if cursor left
   * Keyed by userId (session ID) to support multiple devices in coop mode
   */
  otherPlayerCursors: Record<
    string,
    {
      x: number
      y: number
      playerId: string
      hoveredRegionId: string | null
    } | null
  >

  /**
   * Send cursor position update to other players (ephemeral, real-time)
   * @param playerId - The player ID sending the cursor update
   * @param userId - The session/viewer ID that owns this cursor
   * @param cursorPosition - SVG coordinates, or null when cursor leaves the map
   * @param hoveredRegionId - Region being hovered (from local hit-testing), or null
   */
  sendCursorUpdate: (
    playerId: string,
    userId: string,
    cursorPosition: { x: number; y: number } | null,
    hoveredRegionId: string | null
  ) => void
}

/**
 * Combined hook for arcade session management
 *
 * Handles WebSocket connection, optimistic updates, and server sync automatically.
 *
 * @example
 * ```tsx
 * const { state, sendMove, connected } = useArcadeSession({
 *   userId: user.id,
 *   initialState: { ... },
 *   applyMove: (state, move) => { ... }
 * })
 *
 * // Send a move
 * sendMove({ type: 'FLIP_CARD', data: { cardId: '123' } })
 * ```
 */
export function useArcadeSession<TState>(
  options: UseArcadeSessionOptions<TState>
): UseArcadeSessionReturn<TState> {
  const { userId, roomId, autoJoin = true, ...optimisticOptions } = options

  // Check if we're in preview mode
  const previewMode = useContext(PreviewModeContext)

  // If in preview mode, return mock session immediately
  if (previewMode?.isPreview && previewMode?.mockState) {
    const mockRetryState: RetryState = {
      isRetrying: false,
      retryCount: 0,
      move: null,
      timestamp: null,
    }

    return {
      state: previewMode.mockState as TState,
      version: 1,
      connected: true,
      hasPendingMoves: false,
      hasReceivedServerState: true,
      lastError: null,
      retryState: mockRetryState,
      sendMove: () => {
        // Mock: do nothing in preview
      },
      exitSession: () => {
        // Mock: do nothing in preview
      },
      clearError: () => {
        // Mock: do nothing in preview
      },
      refresh: () => {
        // Mock: do nothing in preview
      },
      otherPlayerCursors: {},
      sendCursorUpdate: () => {
        // Mock: do nothing in preview
      },
    }
  }

  // Optimistic state management
  const optimistic = useOptimisticGameState<TState>(optimisticOptions)

  // Track retry state (exposed to UI for indicators)
  const [retryState, setRetryState] = useState<RetryState>({
    isRetrying: false,
    retryCount: 0,
    move: null,
    timestamp: null,
  })

  // Track other players' cursor positions (ephemeral, real-time)
  // Keyed by userId (session ID) to support multiple devices in coop mode
  const [otherPlayerCursors, setOtherPlayerCursors] = useState<
    Record<
      string,
      {
        x: number
        y: number
        playerId: string
        hoveredRegionId: string | null
      } | null
    >
  >({})

  // WebSocket connection
  const {
    socket,
    connected,
    joinSession,
    sendMove: socketSendMove,
    exitSession: socketExitSession,
    sendCursorUpdate: socketSendCursorUpdate,
  } = useArcadeSocket({
    onSessionState: (data) => {
      optimistic.syncWithServer(data.gameState as TState, data.version)
    },

    onMoveAccepted: (data) => {
      // Check if this was a retried move
      const isRetry = retryState.move?.timestamp === data.move.timestamp
      if (isRetry && retryState.isRetrying) {
        // Clear retry state
        setRetryState({
          isRetrying: false,
          retryCount: 0,
          move: null,
          timestamp: null,
        })
      }
      optimistic.handleMoveAccepted(data.gameState as TState, data.version, data.move)
    },

    onMoveRejected: (data) => {
      const isRetry = retryState.move?.timestamp === data.move.timestamp

      // For version conflicts, automatically retry the move
      if (data.versionConflict) {
        const retryCount = isRetry && retryState.isRetrying ? retryState.retryCount + 1 : 1

        if (retryCount > 5) {
          console.error(`[AutoRetry] FAILED after 5 retries move=${data.move.type}`)
          // Clear retry state and show error
          setRetryState({
            isRetrying: false,
            retryCount: 0,
            move: null,
            timestamp: null,
          })
          optimistic.handleMoveRejected(data.error, data.move)
          return
        }

        // Update retry state
        setRetryState({
          isRetrying: true,
          retryCount,
          move: data.move,
          timestamp: data.move.timestamp,
        })

        // Wait a tiny bit for server state to propagate, then retry
        setTimeout(() => {
          socketSendMove(userId, data.move, roomId)
        }, 10 * retryCount)

        // Don't show error to user - we're handling it automatically
        return
      }

      // Non-version-conflict errors: show to user
      optimistic.handleMoveRejected(data.error, data.move)
    },

    onSessionEnded: () => {
      optimistic.reset()
    },

    onNoActiveSession: () => {
      // Silent - normal state
    },

    onError: () => {},

    onCursorUpdate: (data) => {
      // Key by userId (session ID) to support multiple devices in coop mode
      // Each device has a unique userId, even if they're playing as the same player
      setOtherPlayerCursors((prev) => {
        const newState = {
          ...prev,
          [data.userId]: data.cursorPosition
            ? {
                ...data.cursorPosition,
                playerId: data.playerId,
                hoveredRegionId: data.hoveredRegionId,
              }
            : null,
        }
        return newState
      })
    },
  })

  // Auto-join session when connected
  useEffect(() => {
    if (connected && autoJoin && userId) {
      joinSession(userId, roomId)
    }
  }, [connected, autoJoin, userId, roomId, joinSession])

  // Send move with optimistic update
  const sendMove = useCallback(
    (move: Omit<GameMove, 'timestamp'>) => {
      // IMPORTANT: playerId must always be explicitly provided by caller
      // playerId is the database player ID (avatar), never the userId/viewerId
      if (!('playerId' in move) || !move.playerId) {
        throw new Error('playerId is required in all moves and must be a valid player ID')
      }

      const fullMove: GameMove = {
        ...move,
        timestamp: Date.now(),
      } as GameMove

      // Apply optimistically
      optimistic.applyOptimisticMove(fullMove)

      // Send to server with roomId for room-based games
      socketSendMove(userId, fullMove, roomId)
    },
    [userId, roomId, optimistic.applyOptimisticMove, socketSendMove]
  )

  const exitSession = useCallback(() => {
    socketExitSession(userId)
    optimistic.reset()
  }, [userId, socketExitSession, optimistic.reset])

  const refresh = useCallback(() => {
    if (connected && userId) {
      joinSession(userId, roomId)
    }
  }, [connected, userId, roomId, joinSession])

  // Send cursor position update to other players (ephemeral, real-time)
  const sendCursorUpdate = useCallback(
    (
      playerId: string,
      sessionUserId: string,
      cursorPosition: { x: number; y: number } | null,
      hoveredRegionId: string | null
    ) => {
      if (!roomId) return // Only works in room-based games
      socketSendCursorUpdate(roomId, playerId, sessionUserId, cursorPosition, hoveredRegionId)
    },
    [roomId, socketSendCursorUpdate]
  )

  return {
    state: optimistic.state,
    version: optimistic.version,
    connected,
    hasPendingMoves: optimistic.hasPendingMoves,
    hasReceivedServerState: optimistic.hasReceivedServerState,
    lastError: optimistic.lastError,
    retryState,
    sendMove,
    exitSession,
    clearError: optimistic.clearError,
    refresh,
    otherPlayerCursors,
    sendCursorUpdate,
  }
}