"use client"

import { createContext, useContext, useEffect, type ReactNode } from "react"
import { useTheme } from "next-themes"
import { semanticColors, getSemanticColorCSSProperties } from "@/utils/semantic-colors"

type SemanticColorContextType = {
  semanticColors: typeof semanticColors
}

const SemanticColorContext = createContext<SemanticColorContextType | undefined>(undefined)

/**
 * Provider component for semantic color theming
 * Automatically injects semantic color CSS variables based on the current theme
 */
export function SemanticColorProvider({ children }: { children: ReactNode }) {
  const { theme, resolvedTheme } = useTheme()

  // Update CSS variables when theme changes
  useEffect(() => {
    if (typeof window === "undefined") return

    const currentTheme = (resolvedTheme || theme) as "light" | "dark"
    const root = document.documentElement

    // Get semantic color CSS properties for current theme
    const properties = getSemanticColorCSSProperties(currentTheme === "dark" ? "dark" : "light")

    // Apply all semantic color CSS variables
    Object.entries(properties).forEach(([property, value]) => {
      root.style.setProperty(property, value)
    })
  }, [theme, resolvedTheme])

  const contextValue = {
    semanticColors,
  }

  return <SemanticColorContext.Provider value={contextValue}>{children}</SemanticColorContext.Provider>
}

/**
 * Hook to access the semantic color context
 */
export function useSemanticColors() {
  const context = useContext(SemanticColorContext)
  if (context === undefined) {
    throw new Error("useSemanticColors must be used within a SemanticColorProvider")
  }
  return context
}
