All files / web/src/contexts GameModeContext.tsx

89.05% Statements 350/393
91.83% Branches 45/49
43.47% Functions 10/23
89.05% Lines 350/393

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 3941x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 19x 19x 16x 16x 16x 16x 19x 19x 36x 36x 36x 36x 19x 19x 19x 3x 3x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 19x 19x 36x 36x 36x 36x 19x 19x 19x 3x 3x 4x 4x 4x 3x 19x 16x 16x 15x 12x 12x 16x 16x 19x 19x 36x 36x 36x 36x 36x 17x 6x 6x 6x 24x 24x 24x 6x 6x 6x 6x 24x 24x 24x 24x 24x 24x 24x 6x 6x 17x 11x 11x 11x 11x 11x 17x 17x 36x 36x 36x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 36x 36x 2x 2x 2x 1x 1x 1x 1x       1x 1x 1x 1x 1x 2x 36x 36x 2x 2x 2x 1x 1x       1x 1x 1x 1x 2x 36x 36x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x     1x 36x 36x 1x 1x 1x 1x 36x 36x 2x 2x 36x 36x 2x 2x 36x 36x                                                           36x 36x 36x 36x 36x 36x 18x 18x 4x 14x 2x 12x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 1x 1x 37x 37x 37x 37x  
'use client'
 
import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from 'react'
import type { Player as DBPlayer } from '@/db/schema/players'
import { getNextPlayerColor } from '../types/player'
import { generateUniquePlayerName } from '../utils/playerNames'
 
// Types for the hook data that will be passed as props
// This allows GameModeContext to receive data without importing hooks directly
export interface RoomData {
  id?: string
  memberPlayers?: Record<string, Array<{ id: string; name: string; emoji: string; color: string }>>
  gameConfig?: Record<string, unknown> | null
  members?: Array<{
    id: string
    userId: string
    displayName: string
    isOnline: boolean
    isCreator: boolean
  }>
}
 
// Mutation options type for React Query style callbacks
interface MutationOptions {
  onSuccess?: () => void
}
 
export interface GameModeProviderProps {
  children: ReactNode
  // Player data from useUserPlayers
  dbPlayers: DBPlayer[]
  isLoading: boolean
  // Mutations from useUserPlayers (with optional callbacks)
  createPlayer: (
    player: {
      name: string
      emoji: string
      color: string
      isActive: boolean
      isPracticeStudent?: boolean
    },
    options?: MutationOptions
  ) => void
  updatePlayerMutation: (
    args: {
      id: string
      updates: Partial<Pick<DBPlayer, 'name' | 'emoji' | 'color' | 'isActive'>>
    },
    options?: MutationOptions
  ) => void
  deletePlayer: (id: string, options?: MutationOptions) => void
  // Room data from useRoomData
  roomData: RoomData | null
  notifyRoomOfPlayerUpdate: () => void
  // Viewer ID from useUserId
  viewerId: string | null | undefined
}
 
// Client-side Player type (compatible with old type)
export interface Player {
  id: string
  name: string
  emoji: string
  color: string
  createdAt: Date | number
  isActive?: boolean
  isLocal?: boolean
}
 
export type GameMode = 'single' | 'battle' | 'tournament'
 
export interface GameModeContextType {
  gameMode: GameMode // Computed from activePlayerCount
  players: Map<string, Player>
  activePlayers: Set<string>
  activePlayerCount: number
  addPlayer: (player?: Partial<Player>) => void
  updatePlayer: (id: string, updates: Partial<Player>) => void
  removePlayer: (id: string) => void
  setActive: (id: string, active: boolean) => void
  getActivePlayers: () => Player[]
  getPlayer: (id: string) => Player | undefined
  getAllPlayers: () => Player[]
  resetPlayers: () => void
  isLoading: boolean
  /** Room data passed from the provider — always available when inside a GameModeProvider */
  roomData: RoomData | null
}
 
// Default no-op context value for when GameModeProvider hasn't loaded yet
// This allows pages that don't need game mode to work without the provider
const defaultContextValue: GameModeContextType = {
  gameMode: 'single',
  players: new Map(),
  activePlayers: new Set(),
  activePlayerCount: 0,
  addPlayer: () => {},
  updatePlayer: () => {},
  removePlayer: () => {},
  setActive: () => {},
  getActivePlayers: () => [],
  getPlayer: () => undefined,
  getAllPlayers: () => [],
  resetPlayers: () => {},
  isLoading: true,
  roomData: null,
}
 
const GameModeContext = createContext<GameModeContextType>(defaultContextValue)
 
// Default players to create if none exist
// Names are generated randomly on first initialization
const DEFAULT_PLAYER_CONFIGS = [
  { emoji: '😀', color: '#3b82f6' },
  { emoji: '😎', color: '#8b5cf6' },
  { emoji: '🤠', color: '#10b981' },
  { emoji: '🚀', color: '#f59e0b' },
]
 
// Convert DB player to client Player type
function toClientPlayer(dbPlayer: DBPlayer): Player {
  return {
    id: dbPlayer.id,
    name: dbPlayer.name,
    emoji: dbPlayer.emoji,
    color: dbPlayer.color,
    createdAt: dbPlayer.createdAt,
    isActive: dbPlayer.isActive,
  }
}
 
export function GameModeProvider({
  children,
  dbPlayers,
  isLoading,
  createPlayer,
  updatePlayerMutation,
  deletePlayer,
  roomData,
  notifyRoomOfPlayerUpdate,
  viewerId,
}: GameModeProviderProps) {
  const [isInitialized, setIsInitialized] = useState(false)
 
  // Convert DB players to Map (local players)
  const localPlayers = useMemo(() => {
    const map = new Map<string, Player>()
    dbPlayers.forEach((dbPlayer) => {
      map.set(dbPlayer.id, {
        ...toClientPlayer(dbPlayer),
        isLocal: true,
      })
    })
    return map
  }, [dbPlayers])
 
  // When in a room, merge all players from all room members
  const players = useMemo(() => {
    const map = new Map<string, Player>(localPlayers)
 
    if (roomData?.memberPlayers) {
      // Add players from other room members (marked as remote)
      Object.entries(roomData.memberPlayers).forEach(([userId, memberPlayers]) => {
        // Skip the current user's players (already in localPlayers)
        if (userId === viewerId) return
 
        memberPlayers.forEach((roomPlayer) => {
          map.set(roomPlayer.id, {
            id: roomPlayer.id,
            name: roomPlayer.name,
            emoji: roomPlayer.emoji,
            color: roomPlayer.color,
            createdAt: Date.now(),
            isActive: true, // Players in memberPlayers are active
            isLocal: false, // Remote player
          })
        })
      })
    }
 
    return map
  }, [localPlayers, roomData, viewerId])
 
  // Track active players (local + room members when in a room)
  const activePlayers = useMemo(() => {
    const set = new Set<string>()
 
    if (roomData?.memberPlayers) {
      // In room mode: all players from all members are active
      Object.values(roomData.memberPlayers).forEach((memberPlayers) => {
        memberPlayers.forEach((player) => {
          set.add(player.id)
        })
      })
    } else {
      // Solo mode: only local active players
      dbPlayers.forEach((player) => {
        if (player.isActive) {
          set.add(player.id)
        }
      })
    }
 
    return set
  }, [dbPlayers, roomData])
 
  // Initialize with default players if none exist
  useEffect(() => {
    if (!isLoading && !isInitialized) {
      if (dbPlayers.length === 0) {
        // Generate unique names for default players, themed by their emoji
        const existingNames: string[] = []
        const generatedNames = DEFAULT_PLAYER_CONFIGS.map((config) => {
          const name = generateUniquePlayerName(existingNames, config.emoji)
          existingNames.push(name)
          return name
        })
 
        // Create default players with generated names (arcade players, not practice students)
        DEFAULT_PLAYER_CONFIGS.forEach((config, index) => {
          createPlayer({
            name: generatedNames[index],
            emoji: config.emoji,
            color: config.color,
            isActive: index === 0, // First player active by default
            isPracticeStudent: false,
          })
        })
        console.log('✅ Created default players via API with auto-generated names:', generatedNames)
      } else {
        console.log('✅ Loaded players from API', {
          playerCount: dbPlayers.length,
          activeCount: dbPlayers.filter((p) => p.isActive).length,
        })
      }
      setIsInitialized(true)
    }
  }, [dbPlayers, isLoading, isInitialized, createPlayer])
 
  const addPlayer = (playerData?: Partial<Player>) => {
    const playerList = Array.from(players.values())
    const existingNames = playerList.map((p) => p.name)
    const emoji = playerData?.emoji ?? '🎮'
 
    const newPlayer = {
      name: playerData?.name ?? generateUniquePlayerName(existingNames, emoji),
      emoji,
      color: playerData?.color ?? getNextPlayerColor(playerList),
      isActive: playerData?.isActive ?? false,
      isPracticeStudent: false, // Arcade players are not practice students
    }
 
    createPlayer(newPlayer, {
      onSuccess: () => {
        // Notify room members if in a room
        notifyRoomOfPlayerUpdate()
      },
    })
  }
 
  const updatePlayer = (id: string, updates: Partial<Player>) => {
    const player = players.get(id)
    // Only allow updating local players
    if (player?.isLocal) {
      updatePlayerMutation(
        { id, updates },
        {
          onSuccess: () => {
            // Notify room members if in a room
            notifyRoomOfPlayerUpdate()
          },
        }
      )
    } else {
      console.warn('[GameModeContext] Cannot update remote player:', id)
    }
  }
 
  const removePlayer = (id: string) => {
    const player = players.get(id)
    // Only allow removing local players
    if (player?.isLocal) {
      deletePlayer(id, {
        onSuccess: () => {
          // Notify room members if in a room
          notifyRoomOfPlayerUpdate()
        },
      })
    } else {
      console.warn('[GameModeContext] Cannot remove remote player:', id)
    }
  }
 
  const setActive = (id: string, active: boolean) => {
    const player = players.get(id)
    // Only allow changing active status of local players
    if (player?.isLocal) {
      updatePlayerMutation(
        { id, updates: { isActive: active } },
        {
          onSuccess: () => {
            // Notify room members if in a room
            notifyRoomOfPlayerUpdate()
          },
        }
      )
    } else {
      console.warn('[GameModeContext] Cannot change active status of remote player:', id)
    }
  }
 
  const getActivePlayers = (): Player[] => {
    return Array.from(activePlayers)
      .map((id) => players.get(id))
      .filter((p): p is Player => p !== undefined)
  }
 
  const getPlayer = (id: string): Player | undefined => {
    return players.get(id)
  }
 
  const getAllPlayers = (): Player[] => {
    return Array.from(players.values())
  }
 
  const resetPlayers = () => {
    // Delete all existing players
    dbPlayers.forEach((player) => {
      deletePlayer(player.id)
    })

    // Generate unique names for default players, themed by their emoji
    const existingNames: string[] = []
    const generatedNames = DEFAULT_PLAYER_CONFIGS.map((config) => {
      const name = generateUniquePlayerName(existingNames, config.emoji)
      existingNames.push(name)
      return name
    })

    // Create default players with generated names (arcade players, not practice students)
    DEFAULT_PLAYER_CONFIGS.forEach((config, index) => {
      createPlayer({
        name: generatedNames[index],
        emoji: config.emoji,
        color: config.color,
        isActive: index === 0,
        isPracticeStudent: false,
      })
    })

    // Notify room members after reset (slight delay to ensure mutations complete)
    setTimeout(() => {
      notifyRoomOfPlayerUpdate()
    }, 100)
  }
 
  const activePlayerCount = activePlayers.size
 
  // Compute game mode from active player count
  const gameMode: GameMode =
    activePlayerCount === 1
      ? 'single'
      : activePlayerCount === 2
        ? 'battle'
        : activePlayerCount >= 3
          ? 'tournament'
          : 'single'
 
  const contextValue: GameModeContextType = {
    gameMode,
    players,
    activePlayers,
    activePlayerCount,
    addPlayer,
    updatePlayer,
    removePlayer,
    setActive,
    getActivePlayers,
    getPlayer,
    getAllPlayers,
    resetPlayers,
    isLoading,
    roomData,
  }
 
  return <GameModeContext.Provider value={contextValue}>{children}</GameModeContext.Provider>
}
 
export function useGameMode(): GameModeContextType {
  // Context now has a default value, so it will return that when no provider exists
  // This allows pages that don't need game mode to work without errors
  return useContext(GameModeContext)
}