import React, { createContext, useContext } from 'react'
import { useRouterState } from '@tanstack/react-router'

type Currency = 'Latinum' | 'Credits'

interface CurrencyContextType {
  currency: Currency
}

const CurrencyContext = createContext<CurrencyContextType>({
  currency: 'Latinum',
})

export function CurrencyProvider({ children }: { children: React.ReactNode }) {
  const routerState = useRouterState()

  // Safe search param extraction across any active route
  const searchParams = routerState.location.search as Record<string, any>
  const currency: Currency =
    searchParams.currency === 'Credits' ? 'Credits' : 'Latinum'

  return (
    <CurrencyContext.Provider value={{ currency }}>
      {children}
    </CurrencyContext.Provider>
  )
}

export function useCurrency() {
  return useContext(CurrencyContext)
}
