All files / web/src/lib/arcade/matching-pairs-framework create-validator.ts

51.76% Statements 440/850
30.66% Branches 23/75
47.82% Functions 11/23
51.76% Lines 440/850

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 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 8511x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x     2x 2x 1x 1x 1x 1x   1x 1x 1x 1x 1x 8x 8x 8x 8x     8x       8x       8x 8x     8x 8x       1x 3x 3x 3x 3x 8x 8x 4x 4x 4x 8x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 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 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 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x                                                                                                                                                                                                                 5x 5x                                                                     5x 5x                                             5x 5x                                                                                     5x 5x                                                                       5x 5x                                                                             5x 5x                               5x 5x 5x 5x 5x 5x 5x               5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x                                                               5x 5x     5x 5x                                   5x 5x 4x 4x 4x 4x 4x 4x 4x   4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 1x     1x 1x 5x 5x 5x  
/**
 * Matching Pairs Framework - Validator Factory
 *
 * Creates a generic GameValidator from a MatchingPairsVariant.
 * Ported from arcade-games/matching/Validator.ts with variant hooks.
 */
 
import type { GameResultsReport, PlayerResult } from '../game-sdk/types'
import { finalizeSongContext, pluralize, songDetail, songList, songMoment } from '../song-context'
import type { GameValidator, PracticeBreakOptions, ValidationResult } from '../validation/types'
import type {
  BaseMatchingCard,
  BaseMatchingConfig,
  MatchingPairsMove,
  MatchingPairsState,
  MatchingPairsVariant,
  Player,
} from './types'
 
/**
 * Format duration in milliseconds to a human-readable string
 */
function formatDuration(ms: number): string {
  const totalSeconds = Math.floor(ms / 1000)
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = totalSeconds % 60
  if (minutes > 0) {
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  }
  return `${seconds}s`
}
 
function getGameDisplay(gameName: string): { name: string; icon: string } {
  switch (gameName) {
    case 'music-matching':
      return { name: 'Music Note Match', icon: '🎵' }
    default:
      return { name: 'Matching Pairs Battle', icon: '⚔️' }
  }
}
 
function describeCardForSong(card: BaseMatchingCard): string | null {
  const data = card as unknown as Record<string, unknown>
 
  if (typeof data.friendlyName === 'string' && data.friendlyName.trim()) {
    return data.friendlyName
  }
  if (typeof data.displayName === 'string' && data.displayName.trim()) {
    const clef = typeof data.clef === 'string' ? ` (${data.clef})` : ''
    return `${data.displayName}${clef}`
  }
  if (typeof data.pitchClass === 'string') {
    const octave = typeof data.octave === 'number' ? data.octave : ''
    return `${data.pitchClass}${octave}`
  }
  if (typeof data.number === 'number') {
    if (typeof data.complement === 'number' && typeof data.targetSum === 'number') {
      return `${data.number} + ${data.complement} = ${data.targetSum}`
    }
    return String(data.number)
  }

  return null
}
 
function uniqueSongDetails(values: Array<string | null | undefined>, limit: number): string[] {
  const seen = new Set<string>()
  const result: string[] = []
  for (const value of values) {
    const trimmed = value?.trim()
    if (!trimmed || seen.has(trimmed)) continue
    seen.add(trimmed)
    result.push(trimmed)
    if (result.length >= limit) break
  }
  return result
}
 
function describeCardIdsForSong<TCard extends BaseMatchingCard>(
  state: MatchingPairsState<TCard>,
  cardIds: [string, string] | null
): string | undefined {
  if (!cardIds) return undefined
  const labels = uniqueSongDetails(
    cardIds.map((id) => {
      const card = state.gameCards.find((candidate) => candidate.id === id)
      return card ? describeCardForSong(card) : null
    }),
    2
  )
  return labels.length > 0 ? labels.join(' + ') : undefined
}
 
function buildMatchingPairsSongContext<
  TCard extends BaseMatchingCard,
  TConfig extends BaseMatchingConfig,
>(
  state: MatchingPairsState<TCard, TConfig> & TConfig,
  options: {
    gameName: string
    headline: string
    gameModeLabel: string
    difficultyLabel: string
    matchedDetails: string[]
    unmatchedDetails: string[]
    bestStreak: number
    isSinglePlayer: boolean
  }
): NonNullable<GameResultsReport['songContext']> {
  const {
    gameName,
    headline,
    gameModeLabel,
    difficultyLabel,
    matchedDetails,
    unmatchedDetails,
    bestStreak,
    isSinglePlayer,
  } = options
  const remainingPairs = Math.max(0, state.totalPairs - state.matchedPairs)
  const mismatchChecks = Math.max(0, state.moves - state.matchedPairs)
  const finalMatch = describeCardIdsForSong(state, state.lastMatchedPair)
  const openingMatch = matchedDetails[0]
  const cleanRun = state.matchedPairs === state.totalPairs && mismatchChecks === 0
 
  return finalizeSongContext({
    summary: `${state.matchedPairs}/${state.totalPairs} pairs found in ${state.moves} ${pluralize(
      state.moves,
      'move'
    )}`,
    details: [
      songDetail('Mode', gameModeLabel),
      songDetail('Difficulty', difficultyLabel),
      finalMatch ? songDetail('Final match', finalMatch) : undefined,
      songList('Matched pairs', matchedDetails, 8),
      songList('Still hidden', unmatchedDetails, 5),
    ],
    dramaticMoments: [
      openingMatch
        ? songMoment('Opening beat', `first visible matched pair was ${openingMatch}`)
        : undefined,
      finalMatch ? songMoment('Clutch moment', `final match was ${finalMatch}`) : undefined,
      cleanRun ? songMoment('Perfect run', 'cleared the board with no mismatch checks') : undefined,
      remainingPairs === 1 && unmatchedDetails[0]
        ? songMoment('Near miss', `one pair left hidden: ${unmatchedDetails[0]}`)
        : undefined,
      mismatchChecks > 0 && state.matchedPairs > 0
        ? songMoment(
            'Comeback',
            `found ${state.matchedPairs} ${pluralize(
              state.matchedPairs,
              'pair'
            )} after ${mismatchChecks} mismatch ${pluralize(mismatchChecks, 'check')}`
          )
        : undefined,
      bestStreak >= 3 ? songMoment('Strategy', `built a ${bestStreak}-match streak`) : undefined,
      unmatchedDetails[0] && remainingPairs > 0
        ? songMoment('Tough item', `${unmatchedDetails[0]} stayed hidden`)
        : undefined,
    ],
    strategyNotes: [
      gameName === 'music-matching'
        ? 'Matched musical notes by name and staff position'
        : 'Matched abacus, numeral, or complement cards by value',
      isSinglePlayer ? 'Solo scan of the board' : 'Competitive turn-taking match',
    ],
    outcome:
      state.matchedPairs === state.totalPairs ? `cleared all ${state.totalPairs} pairs` : headline,
  })
}
 
/**
 * Default canFlipCard check — used when variant doesn't override
 */
function defaultCanFlipCard<TCard extends BaseMatchingCard>(
  card: TCard,
  flippedCards: TCard[],
  isProcessingMove: boolean
): boolean {
  if (isProcessingMove) return false
  if (card.matched) return false
  if (flippedCards.some((c) => c.id === card.id)) return false
  if (flippedCards.length >= 2) return false
  return true
}
 
/**
 * Default results report generator — provides standard matching-pairs report.
 * Variants override only if they need custom stats/achievements.
 */
function defaultGetResultsReport<
  TCard extends BaseMatchingCard,
  TConfig extends BaseMatchingConfig,
>(
  state: MatchingPairsState<TCard, TConfig> & TConfig,
  config: TConfig,
  gameName: string
): GameResultsReport {
  const startedAt = state.gameStartTime ?? Date.now()
  const endedAt = state.gameEndTime ?? Date.now()
  const durationMs = endedAt - startedAt
 
  const playerResults: PlayerResult[] = state.activePlayers
    .map((playerId) => {
      const meta = state.playerMetadata[playerId]
      const playerScore = state.scores[playerId] ?? 0
      const isSinglePlayer = state.activePlayers.length === 1
      const movesForAccuracy = isSinglePlayer ? state.moves : playerScore * 2
      const accuracy = movesForAccuracy > 0 ? Math.round((playerScore / movesForAccuracy) * 100) : 0
 
      return {
        playerId,
        playerName: meta?.name ?? 'Player',
        playerEmoji: meta?.emoji ?? '👤',
        userId: meta?.userId ?? playerId,
        score: playerScore,
        rank: 0,
        isWinner: false,
        correctCount: playerScore,
        totalAttempts: isSinglePlayer ? state.moves : undefined,
        accuracy: isSinglePlayer ? accuracy : undefined,
        bestStreak: state.consecutiveMatches[playerId] ?? 0,
      }
    })
    .sort((a, b) => b.score - a.score)
    .map((p, idx) => ({ ...p, rank: idx + 1, isWinner: idx === 0 }))
 
  const winner = playerResults[0]
  const isSinglePlayer = playerResults.length === 1
 
  const overallAccuracy =
    isSinglePlayer && state.moves > 0
      ? Math.round((state.matchedPairs / state.moves) * 100)
      : (winner?.accuracy ?? 0)
 
  let headline = 'Game Complete!'
  let resultTheme: GameResultsReport['resultTheme'] = 'neutral'
  let celebrationType: GameResultsReport['celebrationType'] = 'none'
 
  if (isSinglePlayer) {
    if (overallAccuracy >= 100) {
      headline = 'Perfect Memory!'
      resultTheme = 'success'
      celebrationType = 'confetti'
    } else if (overallAccuracy >= 80) {
      headline = 'Great Job!'
      resultTheme = 'good'
      celebrationType = 'stars'
    } else if (overallAccuracy >= 50) {
      headline = 'Nice Work!'
      resultTheme = 'neutral'
    } else {
      headline = 'Keep Practicing!'
      resultTheme = 'needs-practice'
    }
  } else {
    headline = `${winner?.playerName ?? 'Player'} Wins!`
    resultTheme = 'success'
    celebrationType = 'confetti'
  }
 
  const customStats: GameResultsReport['customStats'] = [
    {
      label: 'Pairs Found',
      value: `${state.matchedPairs}/${state.totalPairs}`,
      icon: '🎯',
      highlight: state.matchedPairs === state.totalPairs,
    },
    { label: 'Total Moves', value: state.moves, icon: '👆' },
    { label: 'Time', value: formatDuration(durationMs), icon: '⏱️' },
  ]
 
  if (isSinglePlayer) {
    customStats.push({
      label: 'Accuracy',
      value: `${overallAccuracy}%`,
      icon: '📊',
      highlight: overallAccuracy >= 80,
    })
  }
 
  const bestStreak = Math.max(...Object.values(state.consecutiveMatches), 0)
  if (bestStreak >= 3) {
    customStats.push({
      label: 'Best Streak',
      value: bestStreak,
      icon: '🔥',
      highlight: true,
    })
  }
 
  const display = getGameDisplay(gameName)
  const matchedDetails = uniqueSongDetails(
    state.gameCards.filter((card) => card.matched).map(describeCardForSong),
    8
  )
  const unmatchedDetails = uniqueSongDetails(
    state.gameCards.filter((card) => !card.matched).map(describeCardForSong),
    5
  )
  const gameModeLabel = isSinglePlayer ? 'single-player' : 'competitive'
 
  let difficultyLabel: string
  if (config.difficulty <= 6) {
    difficultyLabel = 'easy'
  } else if (config.difficulty <= 8) {
    difficultyLabel = 'medium'
  } else if (config.difficulty <= 12) {
    difficultyLabel = 'hard'
  } else {
    difficultyLabel = 'expert'
  }
 
  return {
    gameName,
    gameDisplayName: display.name,
    gameIcon: display.icon,
    durationMs,
    completedNormally: state.matchedPairs === state.totalPairs,
    startedAt,
    endedAt,
    gameMode: isSinglePlayer ? 'single-player' : 'competitive',
    playerCount: playerResults.length,
    playerResults,
    winnerId: isSinglePlayer ? null : (winner?.playerId ?? null),
    itemsCompleted: state.matchedPairs,
    itemsTotal: state.totalPairs,
    completionPercent: Math.round((state.matchedPairs / state.totalPairs) * 100),
    leaderboardEntry: {
      normalizedScore: isSinglePlayer ? overallAccuracy : (winner?.score ?? 0) * 10,
      category: 'memory',
      difficulty: difficultyLabel,
    },
    customStats,
    headline,
    subheadline: isSinglePlayer
      ? `${state.matchedPairs} pairs in ${formatDuration(durationMs)}`
      : `Final Score: ${winner?.score ?? 0} pairs`,
    resultTheme,
    celebrationType,
    songContext: buildMatchingPairsSongContext(state, {
      gameName,
      headline,
      gameModeLabel,
      difficultyLabel,
      matchedDetails,
      unmatchedDetails,
      bestStreak,
      isSinglePlayer,
    }),
  }
}
 
/**
 * Create a GameValidator for a matching-pairs variant.
 */
export function createMatchingPairsValidator<
  TCard extends BaseMatchingCard,
  TConfig extends BaseMatchingConfig,
>(
  variant: MatchingPairsVariant<TCard, TConfig>
): GameValidator<MatchingPairsState<TCard, TConfig> & TConfig, MatchingPairsMove<TCard>> {
  type State = MatchingPairsState<TCard, TConfig> & TConfig
  type Move = MatchingPairsMove<TCard>
 
  const canFlip = variant.canFlipCard ?? defaultCanFlipCard
 
  function validateFlipCard(
    state: State,
    cardId: string,
    playerId: string,
    context?: { userId?: string; playerOwnership?: Record<string, string> }
  ): ValidationResult {
    if (state.gamePhase !== 'playing') {
      return {
        valid: false,
        error: 'Cannot flip cards outside of playing phase',
      }
    }

    if (state.activePlayers.length > 1 && state.currentPlayer !== playerId) {
      return { valid: false, error: 'Not your turn' }
    }

    if (context?.userId && context?.playerOwnership) {
      const playerOwner = context.playerOwnership[playerId]
      if (playerOwner && playerOwner !== context.userId) {
        return { valid: false, error: 'You can only move your own players' }
      }
    }

    const card = state.gameCards.find((c) => c.id === cardId)
    if (!card) {
      return { valid: false, error: 'Card not found' }
    }

    if (!canFlip(card, state.flippedCards, state.isProcessingMove)) {
      return { valid: false, error: 'Cannot flip this card' }
    }

    const newFlippedCards = [...state.flippedCards, card]
    let newState: State = {
      ...state,
      flippedCards: newFlippedCards,
      isProcessingMove: newFlippedCards.length === 2,
      showMismatchFeedback: false,
    }

    if (newFlippedCards.length === 2) {
      const [card1, card2] = newFlippedCards
      const matchResult = variant.validateMatch(card1, card2)

      if (matchResult.isValid) {
        newState = {
          ...newState,
          gameCards: newState.gameCards.map((c) =>
            c.id === card1.id || c.id === card2.id
              ? { ...c, matched: true, matchedBy: state.currentPlayer }
              : c
          ) as TCard[],
          matchedPairs: state.matchedPairs + 1,
          scores: {
            ...state.scores,
            [state.currentPlayer]: (state.scores[state.currentPlayer] || 0) + 1,
          },
          consecutiveMatches: {
            ...state.consecutiveMatches,
            [state.currentPlayer]: (state.consecutiveMatches[state.currentPlayer] || 0) + 1,
          },
          moves: state.moves + 1,
          flippedCards: [],
          isProcessingMove: false,
          lastMatchedPair: [card1.id, card2.id],
        }

        if (newState.matchedPairs === newState.totalPairs) {
          newState = {
            ...newState,
            gamePhase: 'results',
            gameEndTime: Date.now(),
          }
        }
      } else {
        const shouldSwitchPlayer = state.activePlayers.length > 1
        const nextPlayerIndex = shouldSwitchPlayer
          ? (state.activePlayers.indexOf(state.currentPlayer) + 1) % state.activePlayers.length
          : 0
        const nextPlayer = shouldSwitchPlayer
          ? state.activePlayers[nextPlayerIndex]
          : state.currentPlayer

        newState = {
          ...newState,
          currentPlayer: nextPlayer,
          consecutiveMatches: {
            ...state.consecutiveMatches,
            [state.currentPlayer]: 0,
          },
          moves: state.moves + 1,
          flippedCards: newFlippedCards,
          isProcessingMove: true,
          showMismatchFeedback: true,
          playerHovers: {
            ...state.playerHovers,
            [state.currentPlayer]: null,
          },
        }
      }
    }

    return { valid: true, newState }
  }
 
  function validateStartGame(
    state: State,
    activePlayers: Player[],
    cards?: TCard[],
    playerMetadata?: { [playerId: string]: any }
  ): ValidationResult {
    if (!activePlayers || activePlayers.length === 0) {
      return { valid: false, error: 'Must have at least one player' }
    }

    const configFromState = extractConfig(state)
    const gameCards = cards || variant.generateCards(configFromState)

    const newState: State = {
      ...state,
      gameCards,
      cards: gameCards,
      activePlayers,
      playerMetadata: playerMetadata || {},
      gamePhase: 'playing',
      gameStartTime: Date.now(),
      currentPlayer: activePlayers[0],
      flippedCards: [],
      matchedPairs: 0,
      moves: 0,
      scores: activePlayers.reduce((acc, p) => ({ ...acc, [p]: 0 }), {}),
      consecutiveMatches: activePlayers.reduce((acc, p) => ({ ...acc, [p]: 0 }), {}),
      originalConfig: variant.getOriginalConfig(configFromState),
      pausedGamePhase: undefined,
      pausedGameState: undefined,
      playerHovers: {},
    }

    return { valid: true, newState }
  }
 
  function validateClearMismatch(state: State): ValidationResult {
    if (!state.showMismatchFeedback || state.flippedCards.length === 0) {
      return { valid: true, newState: state }
    }

    const clearedHovers = { ...state.playerHovers }
    for (const playerId of state.activePlayers) {
      if (playerId !== state.currentPlayer) {
        clearedHovers[playerId] = null
      }
    }

    return {
      valid: true,
      newState: {
        ...state,
        flippedCards: [],
        showMismatchFeedback: false,
        isProcessingMove: false,
        playerHovers: clearedHovers,
      },
    }
  }
 
  function validateGoToSetup(state: State): ValidationResult {
    const isPausingGame = state.gamePhase === 'playing' || state.gamePhase === 'results'

    return {
      valid: true,
      newState: {
        ...state,
        gamePhase: 'setup',
        pausedGamePhase: isPausingGame ? state.gamePhase : undefined,
        pausedGameState: isPausingGame
          ? {
              gameCards: state.gameCards,
              currentPlayer: state.currentPlayer,
              matchedPairs: state.matchedPairs,
              moves: state.moves,
              scores: state.scores,
              activePlayers: state.activePlayers,
              playerMetadata: state.playerMetadata,
              consecutiveMatches: state.consecutiveMatches,
              gameStartTime: state.gameStartTime,
            }
          : undefined,
        gameCards: [] as unknown as TCard[],
        cards: [] as unknown as TCard[],
        flippedCards: [] as unknown as TCard[],
        currentPlayer: '',
        matchedPairs: 0,
        moves: 0,
        scores: {},
        activePlayers: [],
        playerMetadata: {},
        consecutiveMatches: {},
        gameStartTime: null,
        gameEndTime: null,
        currentMoveStartTime: null,
        celebrationAnimations: [],
        isProcessingMove: false,
        showMismatchFeedback: false,
        lastMatchedPair: null,
        playerHovers: {},
      },
    }
  }
 
  function validateSetConfig(state: State, field: string, value: any): ValidationResult {
    if (state.gamePhase !== 'setup') {
      return {
        valid: false,
        error: 'Cannot change configuration outside of setup phase',
      }
    }

    const error = variant.validateConfigField(field, value)
    if (error) {
      return { valid: false, error }
    }

    const clearPausedGame = !!state.pausedGamePhase

    // Build new config to compute totalPairs
    const configUpdate: Record<string, any> = { [field]: value }
    const newConfigState = { ...state, ...configUpdate } as TConfig
    const newTotalPairs = variant.getTotalPairs(newConfigState)

    return {
      valid: true,
      newState: {
        ...state,
        [field]: value,
        totalPairs: newTotalPairs,
        ...(clearPausedGame
          ? {
              pausedGamePhase: undefined,
              pausedGameState: undefined,
              originalConfig: undefined,
            }
          : {}),
      },
    }
  }
 
  function validateResumeGame(state: State): ValidationResult {
    if (state.gamePhase !== 'setup') {
      return { valid: false, error: 'Can only resume from setup phase' }
    }

    if (!state.pausedGamePhase || !state.pausedGameState) {
      return { valid: false, error: 'No paused game to resume' }
    }

    if (state.originalConfig) {
      const configFromState = extractConfig(state)
      if (variant.hasConfigChangedFrom(configFromState, state.originalConfig)) {
        return {
          valid: false,
          error: 'Cannot resume - configuration has changed',
        }
      }
    }

    return {
      valid: true,
      newState: {
        ...state,
        gamePhase: state.pausedGamePhase,
        gameCards: state.pausedGameState.gameCards,
        cards: state.pausedGameState.gameCards,
        currentPlayer: state.pausedGameState.currentPlayer,
        matchedPairs: state.pausedGameState.matchedPairs,
        moves: state.pausedGameState.moves,
        scores: state.pausedGameState.scores,
        activePlayers: state.pausedGameState.activePlayers,
        playerMetadata: state.pausedGameState.playerMetadata,
        consecutiveMatches: state.pausedGameState.consecutiveMatches,
        gameStartTime: state.pausedGameState.gameStartTime,
        pausedGamePhase: undefined,
        pausedGameState: undefined,
      },
    }
  }
 
  function validateHoverCard(
    state: State,
    cardId: string | null,
    playerId: string
  ): ValidationResult {
    return {
      valid: true,
      newState: {
        ...state,
        playerHovers: {
          ...state.playerHovers,
          [playerId]: cardId,
        },
      },
    }
  }
 
  /**
   * Extract TConfig from the full state.
   * The state is State = MatchingPairsState & TConfig,
   * so variant config fields are top-level.
   */
  function extractConfig(state: State): TConfig {
    // We reconstruct from defaultConfig keys
    const config = {} as any
    for (const key of Object.keys(variant.defaultConfig)) {
      config[key] = (state as any)[key]
    }
    return config as TConfig
  }
 
  function buildInitialState(config: TConfig): State {
    const totalPairs = variant.getTotalPairs(config)
    const baseState: MatchingPairsState<TCard, TConfig> = {
      cards: [] as unknown as TCard[],
      gameCards: [] as unknown as TCard[],
      flippedCards: [] as unknown as TCard[],
      difficulty: config.difficulty,
      turnTimer: config.turnTimer,
      gamePhase: 'setup',
      currentPlayer: '',
      matchedPairs: 0,
      totalPairs,
      moves: 0,
      scores: {},
      activePlayers: [],
      playerMetadata: {},
      consecutiveMatches: {},
      gameStartTime: null,
      gameEndTime: null,
      currentMoveStartTime: null,
      celebrationAnimations: [],
      isProcessingMove: false,
      showMismatchFeedback: false,
      lastMatchedPair: null,
      originalConfig: undefined,
      pausedGamePhase: undefined,
      pausedGameState: undefined,
      playerHovers: {},
    }
 
    // Merge variant config fields into state
    return { ...baseState, ...config } as State
  }
 
  const validator: GameValidator<State, Move> = {
    stateSchema: variant.stateSchema,
 
    validateMove(
      state: State,
      move: Move,
      context?: { userId?: string; playerOwnership?: Record<string, string> }
    ): ValidationResult {
      switch (move.type) {
        case 'FLIP_CARD':
          return validateFlipCard(state, move.data.cardId, move.playerId, context)
        case 'START_GAME':
          return validateStartGame(
            state,
            move.data.activePlayers,
            move.data.cards,
            move.data.playerMetadata
          )
        case 'CLEAR_MISMATCH':
          return validateClearMismatch(state)
        case 'GO_TO_SETUP':
          return validateGoToSetup(state)
        case 'SET_CONFIG':
          return validateSetConfig(state, move.data.field, move.data.value)
        case 'RESUME_GAME':
          return validateResumeGame(state)
        case 'HOVER_CARD':
          return validateHoverCard(state, move.data.cardId, move.playerId)
        default:
          return {
            valid: false,
            error: `Unknown move type: ${(move as any).type}`,
          }
      }
    },
 
    isGameComplete(state: State): boolean {
      return state.gamePhase === 'results' || state.matchedPairs === state.totalPairs
    },
 
    getInitialState(config: unknown): State {
      const typedConfig = config as TConfig

      if (typedConfig.skipSetupPhase) {
        const gameCards = variant.generateCards(typedConfig)
        const state = buildInitialState(typedConfig)
        return {
          ...state,
          gameCards,
          cards: gameCards,
          gamePhase: 'playing',
          gameStartTime: Date.now(),
          originalConfig: variant.getOriginalConfig(typedConfig),
        }
      }

      return buildInitialState(typedConfig)
    },
 
    getInitialStateForPracticeBreak(config: unknown, options: PracticeBreakOptions): State {
      const defaults = variant.practiceBreakDefaults ?? variant.defaultConfig
      let fullConfig: TConfig = {
        ...defaults,
        ...(config as Partial<TConfig>),
      }
 
      if (variant.adjustConfigForBreak) {
        fullConfig = variant.adjustConfigForBreak(fullConfig, options.maxDurationMinutes)
      } else if (options.maxDurationMinutes <= 3 && fullConfig.difficulty > 6) {
        fullConfig = { ...fullConfig, difficulty: 6 as any }
      }
 
      const gameCards = variant.generateCards(fullConfig)
      const playerId = options.playerId
      const playerMetadata: Record<string, any> = {
        [playerId]: {
          id: playerId,
          name: options.playerName || 'Player',
          emoji: '🎮',
          userId: playerId,
        },
      }
 
      // Build player arrays starting with the primary player
      const activePlayers: string[] = [playerId]
      const scores: Record<string, number> = { [playerId]: 0 }
      const consecutiveMatches: Record<string, number> = { [playerId]: 0 }
 
      // Include additional players (observers joining at game start)
      if (options.additionalPlayers) {
        for (const ap of options.additionalPlayers) {
          activePlayers.push(ap.playerId)
          scores[ap.playerId] = 0
          consecutiveMatches[ap.playerId] = 0
          playerMetadata[ap.playerId] = {
            id: ap.playerId,
            name: ap.playerName,
            emoji: ap.emoji,
            userId: ap.userId,
            color: ap.color,
          }
        }
      }
 
      const state = buildInitialState(fullConfig)
      return {
        ...state,
        cards: gameCards,
        gameCards,
        gamePhase: 'playing',
        currentPlayer: playerId,
        scores,
        activePlayers,
        playerMetadata,
        consecutiveMatches,
        gameStartTime: Date.now(),
        originalConfig: variant.getOriginalConfig(fullConfig),
      }
    },
  }
 
  // Attach getResultsReport as a non-interface method
  ;(validator as any).getResultsReport = (state: State, config: TConfig): GameResultsReport => {
    if (variant.getResultsReport) {
      return variant.getResultsReport(state, config)
    }
    return defaultGetResultsReport(state, config, variant.gameName)
  }
 
  return validator
}