'use client'

import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from 'react'

export type DisplayCurrency = 'native' | 'usd'

const DISPLAY_CURRENCY_STORAGE_KEY = 'explorer_display_currency'

const DisplayCurrencyContext = createContext<{
  currency: DisplayCurrency
  setCurrency: (currency: DisplayCurrency) => void
} | null>(null)

export function DisplayCurrencyProvider({ children }: { children: ReactNode }) {
  const [currency, setCurrencyState] = useState<DisplayCurrency>('native')

  useEffect(() => {
    if (typeof window === 'undefined') return
    const stored = window.localStorage.getItem(DISPLAY_CURRENCY_STORAGE_KEY)
    if (stored === 'native' || stored === 'usd') {
      setCurrencyState(stored)
    }
  }, [])

  const setCurrency = (nextCurrency: DisplayCurrency) => {
    setCurrencyState(nextCurrency)
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(DISPLAY_CURRENCY_STORAGE_KEY, nextCurrency)
    }
  }

  const value = useMemo(
    () => ({
      currency,
      setCurrency,
    }),
    [currency],
  )

  return <DisplayCurrencyContext.Provider value={value}>{children}</DisplayCurrencyContext.Provider>
}

export function useDisplayCurrency() {
  const context = useContext(DisplayCurrencyContext)
  if (!context) {
    throw new Error('useDisplayCurrency must be used within a DisplayCurrencyProvider')
  }
  return context
}
