'use client'

import { createContext, useContext, useState, useEffect } from 'react'

type Mode = 'dark' | 'light'

const ThemeModeContext = createContext<{ mode: Mode; toggle: () => void }>({
  mode: 'dark',
  toggle: () => {},
})

export function ThemeModeProvider({ children }: { children: React.ReactNode }) {
  const [mode, setMode] = useState<Mode>('dark')

  useEffect(() => {
    const saved = localStorage.getItem('gps-theme-mode') as Mode | null
    if (saved === 'light' || saved === 'dark') setMode(saved)
  }, [])

  const toggle = () => setMode(m => {
    const next = m === 'dark' ? 'light' : 'dark'
    localStorage.setItem('gps-theme-mode', next)
    return next
  })

  return (
    <ThemeModeContext.Provider value={{ mode, toggle }}>
      {children}
    </ThemeModeContext.Provider>
  )
}

export const useThemeMode = () => useContext(ThemeModeContext)
