import React, { createContext, useContext, useState, useEffect } from 'react'
import * as SecureStore from 'expo-secure-store'

type FontScale = 1.0 | 1.2 | 1.5
interface FontCtx { fontScale: FontScale; setFontScale: (s: FontScale) => void }

export const FontContext = createContext<FontCtx>({ fontScale: 1.0, setFontScale: () => {} })

export function FontProvider({ children }: { children: React.ReactNode }) {
  const [fontScale, setScale] = useState<FontScale>(1.0)
  useEffect(() => {
    SecureStore.getItemAsync('grd_font_scale').then(v => {
      const n = parseFloat(v ?? '1.0')
      if (n === 1.2 || n === 1.5) setScale(n as FontScale)
    })
  }, [])
  const setFontScale = (s: FontScale) => {
    setScale(s)
    SecureStore.setItemAsync('grd_font_scale', String(s))
  }
  return <FontContext.Provider value={{ fontScale, setFontScale }}>{children}</FontContext.Provider>
}

export const useFontScale = () => useContext(FontContext)
