"use client"

import React, { createContext, useContext, useState, useEffect } from "react"

interface SettingsContextType {
  settings: Record<string, string>
  storeName: string
  loading: boolean
}

const defaultContext: SettingsContextType = {
  settings: {},
  storeName: "My Store",
  loading: true
}

const SettingsContext = createContext<SettingsContextType>(defaultContext)

export function SettingsProvider({ children }: { children: React.ReactNode }) {
  const [settings, setSettings] = useState<Record<string, string>>({})
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function fetchSettings() {
      try {
        const res = await fetch("/api/settings") // Wait, /api/settings or /api/admin/settings?
        // Let's use /api/admin/settings for now as it returns the flat object, but a public endpoint is better.
        // I will create /api/settings/public/route.ts if needed, but /api/admin/settings is unprotected in this boilerplate so far or maybe it is protected?
        // Let's use /api/admin/settings
        const data = await res.json()
        setSettings(data)
      } catch (err) {
        console.error("Failed to fetch settings", err)
      } finally {
        setLoading(false)
      }
    }
    fetchSettings()
  }, [])

  const storeName = settings["brand_store_name"] || "My Store"

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

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