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

const SettingsContext = createContext({})

export function SettingsProvider({ children }) {
  const [settings, setSettings] = useState({
    kennel_name: 'BREEDR',
    kennel_tagline: '',
  })
  const [loading, setLoading] = useState(true)
  // Surfaced by consumers inside the ToastProvider (this provider sits above it)
  const [loadError, setLoadError] = useState(false)

  useEffect(() => {
    axios.get('/api/settings')
      .then(res => {
        setSettings(prev => ({ ...prev, ...res.data }))
      })
      .catch((err) => {
        console.error('Failed to load settings:', err)
        setLoadError(true)
      })
      .finally(() => setLoading(false))
  }, [])

  const saveSettings = async (updates) => {
    await axios.put('/api/settings', updates)
    setSettings(prev => ({ ...prev, ...updates }))
  }

  return (
    <SettingsContext.Provider value={{ settings, saveSettings, loading, loadError }}>
      {children}
    </SettingsContext.Provider>
  )
}

export function useSettings() {
  return useContext(SettingsContext)
}
