All files / web/src/contexts UserProfileContext.tsx

100% Statements 76/76
87.5% Branches 7/8
100% Functions 5/5
100% Lines 76/76

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 771x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 6x 6x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 10x 10x 4x 4x 6x 6x  
'use client'
 
import { createContext, type ReactNode, useContext } from 'react'
import type { UserStats } from '@/db/schema/user-stats'
import { useUpdateUserStats, useUserStats } from '@/hooks/useUserStats'
 
// Client-side stats type (compatible with old UserStatsProfile)
export interface UserStatsProfile {
  gamesPlayed: number
  totalWins: number
  favoriteGameType: 'abacus-numeral' | 'complement-pairs' | null
  bestTime: number | null
  highestAccuracy: number
}
 
export interface UserProfileContextType {
  profile: UserStatsProfile
  updateGameStats: (stats: Partial<UserStatsProfile>) => void
  resetProfile: () => void
  isLoading: boolean
}
 
const defaultProfile: UserStatsProfile = {
  gamesPlayed: 0,
  totalWins: 0,
  favoriteGameType: null,
  bestTime: null,
  highestAccuracy: 0,
}
 
const UserProfileContext = createContext<UserProfileContextType | null>(null)
 
// Convert DB stats to client profile type
function toClientProfile(dbStats: UserStats | undefined): UserStatsProfile {
  if (!dbStats) return defaultProfile
 
  return {
    gamesPlayed: dbStats.gamesPlayed,
    totalWins: dbStats.totalWins,
    favoriteGameType: dbStats.favoriteGameType,
    bestTime: dbStats.bestTime,
    highestAccuracy: dbStats.highestAccuracy,
  }
}
 
export function UserProfileProvider({ children }: { children: ReactNode }) {
  const { data: dbStats, isLoading } = useUserStats()
  const { mutate: updateStats } = useUpdateUserStats()
 
  const profile = toClientProfile(dbStats)
 
  const updateGameStats = (stats: Partial<UserStatsProfile>) => {
    updateStats(stats)
  }
 
  const resetProfile = () => {
    updateStats(defaultProfile)
  }
 
  const contextValue: UserProfileContextType = {
    profile,
    updateGameStats,
    resetProfile,
    isLoading,
  }
 
  return <UserProfileContext.Provider value={contextValue}>{children}</UserProfileContext.Provider>
}
 
export function useUserProfile(): UserProfileContextType {
  const context = useContext(UserProfileContext)
  if (!context) {
    throw new Error('useUserProfile must be used within a UserProfileProvider')
  }
  return context
}