"use client"

import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from "react"
import { loadAISettings, saveAISettings } from "@/lib/ai/settings"
import { DEFAULT_AI_SETTINGS, type AISettings } from "@/lib/ai/types"

type Ctx = {
  settings: AISettings
  setSettings: (next: AISettings) => void
  loaded: boolean
}

const AISettingsContext = createContext<Ctx | null>(null)

export function AISettingsProvider({ children }: { children: ReactNode }) {
  const [settings, setSettingsState] = useState<AISettings>(DEFAULT_AI_SETTINGS)
  const [loaded, setLoaded] = useState(false)

  useEffect(() => {
    setSettingsState(loadAISettings())
    setLoaded(true)
  }, [])

  const setSettings = useCallback((next: AISettings) => {
    setSettingsState(next)
    saveAISettings(next)
  }, [])

  return (
    <AISettingsContext.Provider value={{ settings, setSettings, loaded }}>{children}</AISettingsContext.Provider>
  )
}

export function useAISettings() {
  const ctx = useContext(AISettingsContext)
  if (!ctx) throw new Error("useAISettings must be used within AISettingsProvider")
  return ctx
}
