import { createContext, useContext, useEffect, useState, useCallback } from 'react'
import { api } from '../api/client.js'

const SiteContext = createContext(null)

// Public site settings + mode (always reachable, even during maintenance).
export function SiteProvider({ children }) {
  const [settings, setSettings] = useState({})
  const [loading, setLoading] = useState(true)

  const refresh = useCallback(async () => {
    try {
      const data = await api.publicSettings()
      setSettings(data || {})
    } catch {
      setSettings({})
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    refresh()
  }, [refresh])

  const value = {
    settings,
    loading,
    refresh,
    mode: settings.site_mode || 'live',
    siteTitle: settings.site_title || 'UOMysticmoon',
    contactEmail: settings.contact_email || 'UOMysticmoon@gmail.com',
  }

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

export function useSite() {
  const ctx = useContext(SiteContext)
  if (!ctx) throw new Error('useSite must be used within SiteProvider')
  return ctx
}
