All files / web/src/arcade-games/know-your-world Provider.tsx

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

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 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client'

import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import {
  buildPlayerMetadata,
  useArcadeSession,
  useGameMode,
  useUpdateGameConfig,
  useUserId,
} from '@/lib/arcade/game-sdk'
import { buildPlayerOwnershipFromRoomData } from '@/lib/arcade/player-ownership.client'
import { useGameCompletionCallback } from '@/contexts/GameCompletionContext'
import { useCoPlayInfo } from '@/contexts/CoPlayContext'
import { ArcadeSessionStateContext } from '@/contexts/ArcadeSessionStateContext'
import type { KnowYourWorldState, AssistanceLevel } from './types'
import type { RegionSize } from './maps'
import type { FeedbackType } from './utils/hotColdPhrases'
import { MusicProvider } from './music'

// Controls state for GameInfoPanel (set by MapRenderer, read by GameInfoPanel)
export interface ControlsState {
  // Pointer lock state
  isPointerLocked: boolean
  fakeCursorPosition: { x: number; y: number } | null

  // Hot/cold state
  showHotCold: boolean
  hotColdEnabled: boolean
  hotColdFeedbackType: FeedbackType | null
  onHotColdToggle: () => void

  // Hint state
  hasHint: boolean
  currentHint: string | null

  // Give up animation state
  isGiveUpAnimating: boolean

  // Speech/audio state
  isSpeechSupported: boolean
  hasAccentOption: boolean
  isSpeaking: boolean
  onSpeak: () => void
  onStopSpeaking: () => void

  // Auto settings
  autoSpeak: boolean
  onAutoSpeakToggle: () => void
  withAccent: boolean
  onWithAccentToggle: () => void
  autoHint: boolean
  onAutoHintToggle: () => void
}

// Celebration state for correct region finds
export type CelebrationType = 'lightning' | 'standard' | 'hard-earned'

export interface CelebrationState {
  regionId: string
  regionName: string
  type: CelebrationType
  startTime: number
}

// Puzzle piece animation target (Learning mode only)
// Contains the screen position where the region silhouette should animate to
export interface PuzzlePieceTarget {
  regionId: string
  regionName: string
  celebrationType: CelebrationType
  // Target screen position (top-left of where the region appears on the map)
  x: number
  y: number
  // Target screen dimensions
  width: number
  height: number
  // SVG coordinate bounding box (from getBBox()) for correct viewBox
  svgBBox: {
    x: number
    y: number
    width: number
    height: number
  }
  // Source screen position (from takeover screen) - populated by GameInfoPanel
  sourceRect?: {
    x: number
    y: number
    width: number
    height: number
  }
}

const defaultControlsState: ControlsState = {
  isPointerLocked: false,
  fakeCursorPosition: null,
  showHotCold: false,
  hotColdEnabled: false,
  hotColdFeedbackType: null,
  onHotColdToggle: () => {},
  hasHint: false,
  currentHint: null,
  isGiveUpAnimating: false,
  // Speech/audio defaults
  isSpeechSupported: false,
  hasAccentOption: false,
  isSpeaking: false,
  onSpeak: () => {},
  onStopSpeaking: () => {},
  // Auto settings defaults
  autoSpeak: false,
  onAutoSpeakToggle: () => {},
  withAccent: false,
  onWithAccentToggle: () => {},
  autoHint: false,
  onAutoHintToggle: () => {},
}

interface KnowYourWorldContextValue {
  state: KnowYourWorldState
  lastError: string | null
  clearError: () => void
  exitSession: () => void

  // Game actions
  startGame: () => void
  clickRegion: (regionId: string, regionName: string) => void
  nextRound: () => void
  endGame: () => void
  giveUp: () => void
  requestHint: () => void
  returnToSetup: () => void
  confirmLetter: (letter: string, letterIndex: number) => void

  // Setup actions
  setMap: (map: 'world' | 'usa') => void
  setMode: (mode: 'cooperative' | 'race' | 'turn-based') => void
  setRegionSizes: (sizes: RegionSize[]) => void
  setAssistanceLevel: (level: AssistanceLevel) => void
  setContinent: (continent: import('./continents').ContinentId | 'all') => void

  // Cursor position sharing (for multiplayer)
  // 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
  >
  sendCursorUpdate: (
    playerId: string,
    userId: string,
    cursorPosition: { x: number; y: number } | null,
    hoveredRegionId: string | null
  ) => void

  // Member players mapping (userId -> players) for cursor emoji display
  memberPlayers: Record<string, Array<{ id: string; name: string; emoji: string; color: string }>>

  // Controls state shared between MapRenderer and GameInfoPanel
  controlsState: ControlsState
  setControlsState: React.Dispatch<React.SetStateAction<ControlsState>>

  // Learning mode takeover state (set by GameInfoPanel, read by MapRenderer)
  // When true, a scrim covers the map and user can't interact
  isInTakeover: boolean
  setIsInTakeover: React.Dispatch<React.SetStateAction<boolean>>

  // Celebration state for correct region finds
  celebration: CelebrationState | null
  setCelebration: React.Dispatch<React.SetStateAction<CelebrationState | null>>
  promptStartTime: React.MutableRefObject<number>

  // Puzzle piece animation state (Learning mode only)
  // When set, GameInfoPanel animates the region silhouette to the target position
  puzzlePieceTarget: PuzzlePieceTarget | null
  setPuzzlePieceTarget: React.Dispatch<React.SetStateAction<PuzzlePieceTarget | null>>

  // Shared container ref for pointer lock button detection
  sharedContainerRef: React.RefObject<HTMLDivElement>
}

const KnowYourWorldContext = createContext<KnowYourWorldContextValue | null>(null)

export function useKnowYourWorld() {
  const context = useContext(KnowYourWorldContext)
  if (!context) {
    throw new Error('useKnowYourWorld must be used within KnowYourWorldProvider')
  }
  return context
}

export function KnowYourWorldProvider({ children }: { children: React.ReactNode }) {
  const { data: viewerId } = useUserId()
  const { activePlayers: activePlayerIds, players, roomData } = useGameMode()
  const { mutate: updateGameConfig } = useUpdateGameConfig()

  const activePlayers = Array.from(activePlayerIds)

  // Controls state shared between MapRenderer and GameInfoPanel
  const [controlsState, setControlsState] = useState<ControlsState>(defaultControlsState)

  // Learning mode takeover state (set by GameInfoPanel, read by MapRenderer)
  const [isInTakeover, setIsInTakeover] = useState(false)

  // Celebration state for correct region finds
  const [celebration, setCelebration] = useState<CelebrationState | null>(null)
  const promptStartTime = useRef<number>(Date.now())

  // Puzzle piece animation state (Learning mode only)
  const [puzzlePieceTarget, setPuzzlePieceTarget] = useState<PuzzlePieceTarget | null>(null)

  // Shared container ref for pointer lock button detection
  const sharedContainerRef = useRef<HTMLDivElement>(null)

  // Merge saved config from room
  const initialState = useMemo(() => {
    const gameConfig = (roomData?.gameConfig as any)?.['know-your-world']

    // Validate selectedContinent
    const rawContinent = gameConfig?.selectedContinent
    const validContinents = [
      'all',
      'africa',
      'asia',
      'europe',
      'north-america',
      'south-america',
      'oceania',
      'antarctica',
    ]
    const selectedContinent: import('./continents').ContinentId | 'all' =
      typeof rawContinent === 'string' && validContinents.includes(rawContinent)
        ? (rawContinent as any)
        : 'all'

    // Validate includeSizes - should be an array of valid size strings
    const validSizes: RegionSize[] = ['huge', 'large', 'medium', 'small', 'tiny']
    const rawSizes = gameConfig?.includeSizes
    const includeSizes: RegionSize[] = Array.isArray(rawSizes)
      ? rawSizes.filter((s: string) => validSizes.includes(s as RegionSize))
      : ['huge', 'large', 'medium'] // Default to most regions

    // Validate assistanceLevel
    const validAssistanceLevels = ['learning', 'guided', 'helpful', 'standard', 'none']
    const rawAssistance = gameConfig?.assistanceLevel
    const assistanceLevel: AssistanceLevel =
      typeof rawAssistance === 'string' && validAssistanceLevels.includes(rawAssistance)
        ? (rawAssistance as AssistanceLevel)
        : 'helpful'

    return {
      gamePhase: 'setup' as const,
      selectedMap: (gameConfig?.selectedMap as 'world' | 'usa') || 'world',
      gameMode: (gameConfig?.gameMode as 'cooperative' | 'race' | 'turn-based') || 'cooperative',
      includeSizes,
      assistanceLevel,
      selectedContinent,
      currentPrompt: null,
      regionsToFind: [],
      regionsFound: [],
      regionsGivenUp: [],
      currentPlayer: '',
      scores: {},
      attempts: {},
      guessHistory: [],
      startTime: 0,
      activePlayers: [],
      activeUserIds: [],
      playerMetadata: {},
      giveUpReveal: null,
      giveUpVotes: [],
      hintsUsed: 0,
      hintActive: null,
      nameConfirmationProgress: 0,
    }
  }, [roomData])

  const {
    state: rawState,
    sendMove,
    exitSession,
    lastError,
    clearError,
    otherPlayerCursors,
    sendCursorUpdate: sessionSendCursorUpdate,
    hasReceivedServerState,
  } = useArcadeSession<KnowYourWorldState>({
    userId: viewerId || '',
    roomId: roomData?.id,
    initialState,
    applyMove: (state) => state, // Server handles all state updates
  })

  // Detect and log incomplete state from server (backward compatibility with old sessions)
  // This helps us track when the database contains sessions created before certain fields were added
  const state = useMemo<KnowYourWorldState>(() => {
    // Check for missing required array fields
    const missingFields: string[] = []
    if (rawState.regionsFound === undefined) missingFields.push('regionsFound')
    if (rawState.regionsToFind === undefined) missingFields.push('regionsToFind')
    if (rawState.regionsGivenUp === undefined) missingFields.push('regionsGivenUp')
    if (rawState.guessHistory === undefined) missingFields.push('guessHistory')
    if (rawState.activePlayers === undefined) missingFields.push('activePlayers')
    if (rawState.activeUserIds === undefined) missingFields.push('activeUserIds')
    if (rawState.giveUpVotes === undefined) missingFields.push('giveUpVotes')

    // Log when we detect incomplete state (indicates old session data in DB)
    if (missingFields.length > 0) {
      console.warn(
        '[KnowYourWorld] INCOMPLETE_STATE_DETECTED: Session is missing required fields.',
        {
          missingFields,
          gamePhase: rawState.gamePhase,
          hasRawState: Object.keys(rawState).length > 0,
          rawStateKeys: Object.keys(rawState),
        }
      )
    }

    // Merge with defaults for backward compatibility
    return {
      ...initialState,
      ...rawState,
      // Ensure arrays are never undefined (backward compatibility with old sessions)
      regionsFound: rawState.regionsFound ?? [],
      regionsToFind: rawState.regionsToFind ?? [],
      regionsGivenUp: rawState.regionsGivenUp ?? [],
      guessHistory: rawState.guessHistory ?? [],
      activePlayers: rawState.activePlayers ?? [],
      activeUserIds: rawState.activeUserIds ?? [],
      giveUpVotes: rawState.giveUpVotes ?? [],
    }
  }, [rawState, initialState])

  // Update promptStartTime when currentPrompt changes (for celebration timing)
  useEffect(() => {
    if (state.currentPrompt) {
      promptStartTime.current = Date.now()
    }
  }, [state.currentPrompt])

  // Co-play auto-join: if an observer is in co-play mode and not yet in the game,
  // send a JOIN_GAME move to add them as a participant (drop-in mode)
  const coPlayInfo = useCoPlayInfo()
  const hasAutoJoinedRef = useRef(false)
  useEffect(() => {
    if (
      !coPlayInfo ||
      !hasReceivedServerState ||
      hasAutoJoinedRef.current ||
      !state.activePlayers
    ) {
      return
    }

    // Check if observer is already in the game
    if (state.activePlayers.includes(coPlayInfo.playerId)) {
      hasAutoJoinedRef.current = true
      return
    }

    // Only auto-join during playing phase
    if (state.gamePhase !== 'playing') return

    console.log('[KnowYourWorld] Co-play auto-join: sending JOIN_GAME for', coPlayInfo.playerName)
    hasAutoJoinedRef.current = true
    sendMove({
      type: 'JOIN_GAME',
      playerId: coPlayInfo.playerId,
      userId: coPlayInfo.playerId,
      data: {
        playerName: coPlayInfo.playerName,
        emoji: coPlayInfo.emoji,
        color: coPlayInfo.color,
      },
    })
  }, [coPlayInfo, hasReceivedServerState, state.activePlayers, state.gamePhase, sendMove])

  // Notify parent when game reaches results phase (for practice game break detection)
  const onGameComplete = useGameCompletionCallback()
  const previousPhaseRef = useRef<string | null>(null)
  useEffect(() => {
    if (state.gamePhase === 'results' && previousPhaseRef.current !== 'results' && onGameComplete) {
      onGameComplete(state as unknown as Record<string, unknown>)
    }
    previousPhaseRef.current = state.gamePhase
  }, [state.gamePhase, onGameComplete, state])

  // Pass through cursor updates with the provided player ID and userId
  const sendCursorUpdate = useCallback(
    (
      playerId: string,
      sessionUserId: string,
      cursorPosition: { x: number; y: number } | null,
      hoveredRegionId: string | null
    ) => {
      if (playerId && sessionUserId) {
        sessionSendCursorUpdate(playerId, sessionUserId, cursorPosition, hoveredRegionId)
      }
    },
    [sessionSendCursorUpdate]
  )

  // Action: Start Game
  const startGame = useCallback(() => {
    // Build ownership map from roomData to correctly map players to their owners
    const ownershipMap = buildPlayerOwnershipFromRoomData(roomData)
    const playerMetadata = buildPlayerMetadata(
      activePlayers,
      ownershipMap,
      players,
      viewerId || undefined
    )

    sendMove({
      type: 'START_GAME',
      playerId: activePlayers[0] || 'player-1',
      userId: viewerId || '',
      data: {
        activePlayers,
        playerMetadata,
        selectedMap: state.selectedMap,
        gameMode: state.gameMode,
        includeSizes: state.includeSizes,
        assistanceLevel: state.assistanceLevel,
      },
    })
  }, [
    activePlayers,
    players,
    viewerId,
    roomData,
    sendMove,
    state.selectedMap,
    state.gameMode,
    state.includeSizes,
    state.assistanceLevel,
  ])

  // Action: Click Region
  const clickRegion = useCallback(
    (regionId: string, regionName: string) => {
      if (!state.currentPlayer) {
        return
      }

      // Use the current player from game state (PLAYER ID, not USER ID)
      // In turn-based mode, this is the player whose turn it is
      // In other modes, all moves use the current player ID
      sendMove({
        type: 'CLICK_REGION',
        playerId: state.currentPlayer, // CRITICAL: Use PLAYER ID from state, not USER ID
        userId: viewerId || '',
        data: { regionId, regionName },
      })
    },
    [
      viewerId,
      sendMove,
      state.currentPlayer,
      state.currentPrompt,
      state.regionsToFind,
      state.gamePhase,
    ]
  )

  // Action: Next Round
  const nextRound = useCallback(() => {
    sendMove({
      type: 'NEXT_ROUND',
      playerId: state.currentPlayer || activePlayers[0] || '',
      userId: viewerId || '',
      data: {},
    })
  }, [activePlayers, viewerId, sendMove, state.currentPlayer])

  // Action: End Game
  const endGame = useCallback(() => {
    sendMove({
      type: 'END_GAME',
      playerId: state.currentPlayer || activePlayers[0] || '',
      userId: viewerId || '',
      data: {},
    })
  }, [viewerId, sendMove, state.currentPlayer, activePlayers])

  // Action: Give Up (skip current region, reveal it, move to next)
  const giveUp = useCallback(() => {
    sendMove({
      type: 'GIVE_UP',
      playerId: state.currentPlayer || activePlayers[0] || '',
      userId: viewerId || '',
      data: {},
    })
  }, [viewerId, sendMove, state.currentPlayer, activePlayers])

  // Action: Request Hint (highlight current region briefly)
  const requestHint = useCallback(() => {
    sendMove({
      type: 'REQUEST_HINT',
      playerId: state.currentPlayer || activePlayers[0] || '',
      userId: viewerId || '',
      data: {},
    })
  }, [viewerId, sendMove, state.currentPlayer, activePlayers])

  // Action: Confirm Letter (for learning mode name confirmation)
  const confirmLetter = useCallback(
    (letter: string, letterIndex: number) => {
      sendMove({
        type: 'CONFIRM_LETTER',
        playerId: state.currentPlayer || activePlayers[0] || '',
        userId: viewerId || '',
        data: { letter, letterIndex },
      })
    },
    [viewerId, sendMove, state.currentPlayer, activePlayers]
  )

  // Setup Action: Set Map
  const setMap = useCallback(
    (selectedMap: 'world' | 'usa') => {
      sendMove({
        type: 'SET_MAP',
        playerId: activePlayers[0] || '', // Use first active player
        userId: viewerId || '',
        data: { selectedMap },
      })

      // Persist to database
      if (roomData?.id) {
        const currentGameConfig = (roomData.gameConfig as Record<string, any>) || {}
        const currentConfig = (currentGameConfig['know-your-world'] as Record<string, any>) || {}

        updateGameConfig({
          roomId: roomData.id,
          gameConfig: {
            ...currentGameConfig,
            'know-your-world': {
              ...currentConfig,
              selectedMap,
            },
          },
        })
      }
    },
    [viewerId, sendMove, roomData, updateGameConfig, activePlayers]
  )

  // Setup Action: Set Mode
  const setMode = useCallback(
    (gameMode: 'cooperative' | 'race' | 'turn-based') => {
      sendMove({
        type: 'SET_MODE',
        playerId: activePlayers[0] || '', // Use first active player
        userId: viewerId || '',
        data: { gameMode },
      })

      // Persist to database
      if (roomData?.id) {
        const currentGameConfig = (roomData.gameConfig as Record<string, any>) || {}
        const currentConfig = (currentGameConfig['know-your-world'] as Record<string, any>) || {}

        updateGameConfig({
          roomId: roomData.id,
          gameConfig: {
            ...currentGameConfig,
            'know-your-world': {
              ...currentConfig,
              gameMode,
            },
          },
        })
      }
    },
    [viewerId, sendMove, roomData, updateGameConfig, activePlayers]
  )

  // Setup Action: Set Region Sizes (which sizes to include)
  const setRegionSizes = useCallback(
    (includeSizes: RegionSize[]) => {
      sendMove({
        type: 'SET_REGION_SIZES',
        playerId: activePlayers[0] || '',
        userId: viewerId || '',
        data: { includeSizes },
      })

      // Persist to database
      if (roomData?.id) {
        const currentGameConfig = (roomData.gameConfig as Record<string, any>) || {}
        const currentConfig = (currentGameConfig['know-your-world'] as Record<string, any>) || {}

        updateGameConfig({
          roomId: roomData.id,
          gameConfig: {
            ...currentGameConfig,
            'know-your-world': {
              ...currentConfig,
              includeSizes,
            },
          },
        })
      }
    },
    [viewerId, sendMove, roomData, updateGameConfig, activePlayers]
  )

  // Setup Action: Set Assistance Level
  const setAssistanceLevel = useCallback(
    (assistanceLevel: AssistanceLevel) => {
      sendMove({
        type: 'SET_ASSISTANCE_LEVEL',
        playerId: activePlayers[0] || '',
        userId: viewerId || '',
        data: { assistanceLevel },
      })

      // Persist to database
      if (roomData?.id) {
        const currentGameConfig = (roomData.gameConfig as Record<string, any>) || {}
        const currentConfig = (currentGameConfig['know-your-world'] as Record<string, any>) || {}

        updateGameConfig({
          roomId: roomData.id,
          gameConfig: {
            ...currentGameConfig,
            'know-your-world': {
              ...currentConfig,
              assistanceLevel,
            },
          },
        })
      }
    },
    [viewerId, sendMove, roomData, updateGameConfig, activePlayers]
  )

  // Setup Action: Set Continent
  const setContinent = useCallback(
    (selectedContinent: import('./continents').ContinentId | 'all') => {
      sendMove({
        type: 'SET_CONTINENT',
        playerId: activePlayers[0] || '', // Use first active player
        userId: viewerId || '',
        data: { selectedContinent },
      })

      // Persist to database
      if (roomData?.id) {
        const currentGameConfig = (roomData.gameConfig as Record<string, any>) || {}
        const currentConfig = (currentGameConfig['know-your-world'] as Record<string, any>) || {}

        updateGameConfig({
          roomId: roomData.id,
          gameConfig: {
            ...currentGameConfig,
            'know-your-world': {
              ...currentConfig,
              selectedContinent,
            },
          },
        })
      }
    },
    [viewerId, sendMove, roomData, updateGameConfig, activePlayers]
  )

  // Action: Return to Setup
  const returnToSetup = useCallback(() => {
    sendMove({
      type: 'RETURN_TO_SETUP',
      playerId: state.currentPlayer || activePlayers[0] || '',
      userId: viewerId || '',
      data: {},
    })
  }, [viewerId, sendMove, state.currentPlayer, activePlayers])

  // Memoize memberPlayers from roomData for cursor emoji display
  const memberPlayers = useMemo(() => {
    return (roomData?.memberPlayers ?? {}) as Record<
      string,
      Array<{ id: string; name: string; emoji: string; color: string }>
    >
  }, [roomData?.memberPlayers])

  // Music is active when game is in playing phase
  const isMusicActive = state.gamePhase === 'playing'

  // Pass celebration state to music provider (type + startTime for deduplication)
  const musicCelebration = celebration
    ? { type: celebration.type, startTime: celebration.startTime }
    : null

  return (
    <ArcadeSessionStateContext.Provider value={{ hasReceivedServerState }}>
      <KnowYourWorldContext.Provider
        value={{
          state,
          lastError,
          clearError,
          exitSession,
          startGame,
          clickRegion,
          nextRound,
          endGame,
          giveUp,
          requestHint,
          confirmLetter,
          returnToSetup,
          setMap,
          setMode,
          setRegionSizes,
          setAssistanceLevel,
          setContinent,
          otherPlayerCursors,
          sendCursorUpdate,
          memberPlayers,
          controlsState,
          setControlsState,
          isInTakeover,
          setIsInTakeover,
          celebration,
          setCelebration,
          promptStartTime,
          puzzlePieceTarget,
          setPuzzlePieceTarget,
          sharedContainerRef,
        }}
      >
        <MusicProvider
          isGameActive={isMusicActive}
          currentRegionId={state.currentPrompt}
          mapType={state.selectedMap}
          hotColdFeedback={controlsState.hotColdFeedbackType}
          celebration={musicCelebration}
        >
          {children}
        </MusicProvider>
      </KnowYourWorldContext.Provider>
    </ArcadeSessionStateContext.Provider>
  )
}