All files / web/src/arcade-games/card-sorting Provider.tsx

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

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 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client'

import { type ReactNode, useCallback, useMemo, createContext, useContext, useState } from 'react'
import { useArcadeSession } from '@/hooks/useArcadeSession'
import { useUpdateGameConfig } from '@/hooks/useRoomData'
import { useUserId } from '@/hooks/useUserId'
import { buildPlayerMetadata as buildPlayerMetadataUtil } from '@/lib/arcade/player-ownership.client'
import type { GameMove } from '@/lib/arcade/validation'
import { useGameMode } from '@/contexts/GameModeContext'
import { ArcadeSessionStateContext } from '@/contexts/ArcadeSessionStateContext'
import { generateRandomCards, shuffleCards } from './utils/cardGeneration'
import type {
  CardSortingState,
  CardSortingMove,
  SortingCard,
  CardSortingConfig,
  CardPosition,
} from './types'

// Context value interface
interface CardSortingContextValue {
  state: CardSortingState
  // Actions
  startGame: () => void
  placeCard: (cardId: string, position: number) => void
  insertCard: (cardId: string, insertPosition: number) => void
  removeCard: (position: number) => void
  checkSolution: (finalSequence?: SortingCard[]) => void
  goToSetup: () => void
  resumeGame: () => void
  setConfig: (field: 'cardCount' | 'timeLimit' | 'gameMode', value: unknown) => void
  updateCardPositions: (positions: CardPosition[]) => void
  exitSession: () => void
  // Computed
  canCheckSolution: boolean
  placedCount: number
  elapsedTime: number
  hasConfigChanged: boolean
  canResumeGame: boolean
  // UI state
  selectedCardId: string | null
  selectCard: (cardId: string | null) => void
  // Spectator mode
  localPlayerId: string | undefined
  isSpectating: boolean
  // Multiplayer
  players: Map<string, { id: string; name: string; emoji: string }> // All room players
}

// Create context
const CardSortingContext = createContext<CardSortingContextValue | null>(null)

// Initial state matching validator's getInitialState
const createInitialState = (config: Partial<CardSortingConfig>): CardSortingState => ({
  cardCount: config.cardCount ?? 8,
  timeLimit: config.timeLimit ?? null,
  gameMode: config.gameMode ?? 'solo',
  gamePhase: 'setup',
  playerId: '',
  playerMetadata: {
    id: '',
    name: '',
    emoji: '',
    userId: '',
  },
  activePlayers: [],
  allPlayerMetadata: {},
  gameStartTime: null,
  gameEndTime: null,
  selectedCards: [],
  correctOrder: [],
  availableCards: [],
  placedCards: new Array(config.cardCount ?? 8).fill(null),
  cardPositions: [],
  cursorPositions: {},
  selectedCardId: null,
  scoreBreakdown: null,
})

/**
 * Optimistic move application (client-side prediction)
 */
function applyMoveOptimistically(state: CardSortingState, move: GameMove): CardSortingState {
  const typedMove = move as CardSortingMove

  switch (typedMove.type) {
    case 'START_GAME': {
      const selectedCards = typedMove.data.selectedCards as SortingCard[]
      const correctOrder = [...selectedCards].sort((a, b) => a.number - b.number)

      return {
        ...state,
        gamePhase: 'playing',
        playerId: typedMove.playerId,
        playerMetadata: typedMove.data.playerMetadata,
        activePlayers: [typedMove.playerId],
        allPlayerMetadata: { [typedMove.playerId]: typedMove.data.playerMetadata },
        gameStartTime: Date.now(),
        selectedCards,
        correctOrder,
        // Use cards in the order they were sent (already shuffled by initiating client)
        availableCards: selectedCards,
        placedCards: new Array(state.cardCount).fill(null),
        // Save original config for pause/resume
        originalConfig: {
          cardCount: state.cardCount,
          timeLimit: state.timeLimit,
          gameMode: state.gameMode,
        },
        pausedGamePhase: undefined,
        pausedGameState: undefined,
      }
    }

    case 'PLACE_CARD': {
      const { cardId, position } = typedMove.data
      const card = state.availableCards.find((c) => c.id === cardId)
      if (!card) return state

      // Simple replacement (can leave gaps)
      const newPlaced = [...state.placedCards]
      const replacedCard = newPlaced[position]
      newPlaced[position] = card

      // Remove card from available
      let newAvailable = state.availableCards.filter((c) => c.id !== cardId)

      // If slot was occupied, add replaced card back to available
      if (replacedCard) {
        newAvailable = [...newAvailable, replacedCard]
      }

      return {
        ...state,
        availableCards: newAvailable,
        placedCards: newPlaced,
      }
    }

    case 'INSERT_CARD': {
      const { cardId, insertPosition } = typedMove.data
      const card = state.availableCards.find((c) => c.id === cardId)
      if (!card) {
        return state
      }

      // Insert with shift and compact (no gaps)
      const newPlaced = new Array(state.cardCount).fill(null)

      // Copy existing cards, shifting those at/after insert position
      for (let i = 0; i < state.placedCards.length; i++) {
        if (state.placedCards[i] !== null) {
          if (i < insertPosition) {
            newPlaced[i] = state.placedCards[i]
          } else {
            // Cards at or after insert position shift right by 1
            // Card will be collected during compaction if it falls off the end
            newPlaced[i + 1] = state.placedCards[i]
          }
        }
      }

      // Place new card at insert position
      newPlaced[insertPosition] = card

      // Compact to remove gaps
      const compacted: SortingCard[] = []
      for (const c of newPlaced) {
        if (c !== null) {
          compacted.push(c)
        }
      }

      // Fill final array (no gaps)
      const finalPlaced = new Array(state.cardCount).fill(null)
      for (let i = 0; i < Math.min(compacted.length, state.cardCount); i++) {
        finalPlaced[i] = compacted[i]
      }

      // Remove from available
      let newAvailable = state.availableCards.filter((c) => c.id !== cardId)

      // Any excess cards go back to available
      if (compacted.length > state.cardCount) {
        const excess = compacted.slice(state.cardCount)
        newAvailable = [...newAvailable, ...excess]
      }

      return {
        ...state,
        availableCards: newAvailable,
        placedCards: finalPlaced,
      }
    }

    case 'REMOVE_CARD': {
      const { position } = typedMove.data
      const card = state.placedCards[position]
      if (!card) return state

      const newPlaced = [...state.placedCards]
      newPlaced[position] = null
      const newAvailable = [...state.availableCards, card]

      return {
        ...state,
        availableCards: newAvailable,
        placedCards: newPlaced,
      }
    }

    case 'CHECK_SOLUTION': {
      // Don't apply optimistic update - wait for server to calculate and return score
      return state
    }

    case 'GO_TO_SETUP': {
      const isPausingGame = state.gamePhase === 'playing'

      return {
        ...createInitialState({
          cardCount: state.cardCount,
          timeLimit: state.timeLimit,
          gameMode: state.gameMode,
        }),
        // Save paused state if coming from active game
        originalConfig: state.originalConfig,
        pausedGamePhase: isPausingGame ? 'playing' : undefined,
        pausedGameState: isPausingGame
          ? {
              selectedCards: state.selectedCards,
              availableCards: state.availableCards,
              placedCards: state.placedCards,
              cardPositions: state.cardPositions,
              gameStartTime: state.gameStartTime || Date.now(),
            }
          : undefined,
      }
    }

    case 'SET_CONFIG': {
      const { field, value } = typedMove.data
      const clearPausedGame = !!state.pausedGamePhase

      return {
        ...state,
        [field]: value,
        // Update placedCards array size if cardCount changes
        ...(field === 'cardCount' ? { placedCards: new Array(value as number).fill(null) } : {}),
        // Clear paused game if config changed
        ...(clearPausedGame
          ? {
              pausedGamePhase: undefined,
              pausedGameState: undefined,
              originalConfig: undefined,
            }
          : {}),
      }
    }

    case 'RESUME_GAME': {
      if (!state.pausedGamePhase || !state.pausedGameState) {
        return state
      }

      const correctOrder = [...state.pausedGameState.selectedCards].sort(
        (a, b) => a.number - b.number
      )

      return {
        ...state,
        gamePhase: state.pausedGamePhase,
        selectedCards: state.pausedGameState.selectedCards,
        correctOrder,
        availableCards: state.pausedGameState.availableCards,
        placedCards: state.pausedGameState.placedCards,
        cardPositions: state.pausedGameState.cardPositions,
        gameStartTime: state.pausedGameState.gameStartTime,
        pausedGamePhase: undefined,
        pausedGameState: undefined,
      }
    }

    case 'UPDATE_CARD_POSITIONS': {
      return {
        ...state,
        cardPositions: typedMove.data.positions,
      }
    }

    default:
      return state
  }
}

/**
 * Card Sorting Provider - Single Player Pattern Recognition Game
 */
export function CardSortingProvider({ children }: { children: ReactNode }) {
  const { data: viewerId } = useUserId()
  const { activePlayers, players, roomData } = useGameMode()
  const { mutate: updateGameConfig } = useUpdateGameConfig()

  // Local UI state (not synced to server)
  const [selectedCardId, setSelectedCardId] = useState<string | null>(null)

  // Get local player (single player game)
  const localPlayerId = useMemo(() => {
    return Array.from(activePlayers).find((id) => {
      const player = players.get(id)
      return player?.isLocal !== false
    })
  }, [activePlayers, players])

  // Merge saved config from room data
  const mergedInitialState = useMemo(() => {
    const gameConfig = roomData?.gameConfig as Record<string, unknown> | null
    const savedConfig = gameConfig?.['card-sorting'] as Partial<CardSortingConfig> | undefined

    return createInitialState(savedConfig || {})
  }, [roomData?.gameConfig])

  // Arcade session integration
  const { state, sendMove, exitSession, hasReceivedServerState } =
    useArcadeSession<CardSortingState>({
      userId: viewerId || '',
      roomId: roomData?.id,
      initialState: mergedInitialState,
      applyMove: applyMoveOptimistically,
    })

  // Build player metadata for the single local player
  const buildPlayerMetadata = useCallback(() => {
    if (!localPlayerId) {
      return {
        id: '',
        name: '',
        emoji: '',
        userId: '',
      }
    }

    const playerOwnership: Record<string, string> = {}
    if (viewerId) {
      playerOwnership[localPlayerId] = viewerId
    }

    const metadata = buildPlayerMetadataUtil(
      [localPlayerId],
      playerOwnership,
      players,
      viewerId ?? undefined
    )

    return metadata[localPlayerId] || { id: '', name: '', emoji: '', userId: '' }
  }, [localPlayerId, players, viewerId])

  // Computed values
  const canCheckSolution = useMemo(
    () => state.placedCards.every((c) => c !== null),
    [state.placedCards]
  )

  const placedCount = useMemo(
    () => state.placedCards.filter((c) => c !== null).length,
    [state.placedCards]
  )

  const elapsedTime = useMemo(() => {
    if (!state.gameStartTime) return 0
    const now = state.gameEndTime || Date.now()
    return Math.floor((now - state.gameStartTime) / 1000)
  }, [state.gameStartTime, state.gameEndTime])

  const hasConfigChanged = useMemo(() => {
    if (!state.originalConfig) return false
    return (
      state.cardCount !== state.originalConfig.cardCount ||
      state.timeLimit !== state.originalConfig.timeLimit ||
      state.gameMode !== state.originalConfig.gameMode
    )
  }, [state.cardCount, state.timeLimit, state.gameMode, state.originalConfig])

  const canResumeGame = useMemo(() => {
    return !!state.pausedGamePhase && !!state.pausedGameState && !hasConfigChanged
  }, [state.pausedGamePhase, state.pausedGameState, hasConfigChanged])

  // Action creators
  const startGame = useCallback(() => {
    if (!localPlayerId) {
      return
    }

    // Prevent rapid double-sends within 500ms to avoid duplicate game starts
    const now = Date.now()
    const justStarted = state.gameStartTime && now - state.gameStartTime < 500

    if (justStarted) {
      return
    }

    const playerMetadata = buildPlayerMetadata()
    const selectedCards = shuffleCards(generateRandomCards(state.cardCount))

    sendMove({
      type: 'START_GAME',
      playerId: localPlayerId,
      userId: viewerId || '',
      data: {
        playerMetadata,
        selectedCards,
      },
    })
  }, [
    localPlayerId,
    state.cardCount,
    state.gamePhase,
    state.gameStartTime,
    buildPlayerMetadata,
    sendMove,
    viewerId,
  ])

  const placeCard = useCallback(
    (cardId: string, position: number) => {
      if (!localPlayerId) return

      sendMove({
        type: 'PLACE_CARD',
        playerId: localPlayerId,
        userId: viewerId || '',
        data: { cardId, position },
      })

      // Clear selection
      setSelectedCardId(null)
    },
    [localPlayerId, sendMove, viewerId]
  )

  const insertCard = useCallback(
    (cardId: string, insertPosition: number) => {
      if (!localPlayerId) return

      sendMove({
        type: 'INSERT_CARD',
        playerId: localPlayerId,
        userId: viewerId || '',
        data: { cardId, insertPosition },
      })

      // Clear selection
      setSelectedCardId(null)
    },
    [localPlayerId, sendMove, viewerId]
  )

  const removeCard = useCallback(
    (position: number) => {
      if (!localPlayerId) return

      sendMove({
        type: 'REMOVE_CARD',
        playerId: localPlayerId,
        userId: viewerId || '',
        data: { position },
      })
    },
    [localPlayerId, sendMove, viewerId]
  )

  const checkSolution = useCallback(
    (finalSequence?: SortingCard[]) => {
      if (!localPlayerId) return

      // If finalSequence provided, use it. Otherwise check current placedCards
      if (!finalSequence && !canCheckSolution) {
        return
      }

      sendMove({
        type: 'CHECK_SOLUTION',
        playerId: localPlayerId,
        userId: viewerId || '',
        data: {
          finalSequence,
        },
      })
    },
    [localPlayerId, canCheckSolution, sendMove, viewerId]
  )

  const goToSetup = useCallback(() => {
    if (!localPlayerId) return

    sendMove({
      type: 'GO_TO_SETUP',
      playerId: localPlayerId,
      userId: viewerId || '',
      data: {},
    })
  }, [localPlayerId, sendMove, viewerId])

  const resumeGame = useCallback(() => {
    if (!localPlayerId || !canResumeGame) {
      console.warn('[CardSortingProvider] Cannot resume - no paused game or config changed')
      return
    }

    sendMove({
      type: 'RESUME_GAME',
      playerId: localPlayerId,
      userId: viewerId || '',
      data: {},
    })
  }, [localPlayerId, canResumeGame, sendMove, viewerId])

  const setConfig = useCallback(
    (field: 'cardCount' | 'timeLimit' | 'gameMode', value: unknown) => {
      if (!localPlayerId) return

      sendMove({
        type: 'SET_CONFIG',
        playerId: localPlayerId,
        userId: viewerId || '',
        data: { field, value },
      })

      // Persist to database
      if (roomData?.id) {
        const currentGameConfig = (roomData.gameConfig as Record<string, unknown>) || {}
        const currentCardSortingConfig =
          (currentGameConfig['card-sorting'] as Record<string, unknown>) || {}

        const updatedConfig = {
          ...currentGameConfig,
          'card-sorting': {
            ...currentCardSortingConfig,
            [field]: value,
          },
        }

        updateGameConfig({
          roomId: roomData.id,
          gameConfig: updatedConfig,
        })
      }
    },
    [localPlayerId, sendMove, viewerId, roomData, updateGameConfig]
  )

  const updateCardPositions = useCallback(
    (positions: CardPosition[]) => {
      if (!localPlayerId) return

      sendMove({
        type: 'UPDATE_CARD_POSITIONS',
        playerId: localPlayerId,
        userId: viewerId || '',
        data: { positions },
      })
    },
    [localPlayerId, sendMove, viewerId]
  )

  const contextValue: CardSortingContextValue = {
    state,
    // Actions
    startGame,
    placeCard,
    insertCard,
    removeCard,
    checkSolution,
    goToSetup,
    resumeGame,
    setConfig,
    updateCardPositions,
    exitSession,
    // Computed
    canCheckSolution,
    placedCount,
    elapsedTime,
    hasConfigChanged,
    canResumeGame,
    // UI state
    selectedCardId,
    selectCard: setSelectedCardId,
    // Spectator mode
    localPlayerId,
    isSpectating: !localPlayerId,
    // Multiplayer
    players,
  }

  return (
    <ArcadeSessionStateContext.Provider value={{ hasReceivedServerState }}>
      <CardSortingContext.Provider value={contextValue}>{children}</CardSortingContext.Provider>
    </ArcadeSessionStateContext.Provider>
  )
}

/**
 * Hook to access Card Sorting context
 */
export function useCardSorting() {
  const context = useContext(CardSortingContext)
  if (!context) {
    throw new Error('useCardSorting must be used within CardSortingProvider')
  }
  return context
}