'use client'

import { useLayoutEffect } from 'react'
import { hexToOklch, calculateBrightness } from '@/lib/helpers/colorUtils'
import { getCachedMenuColor, getRestaurantSlugFromPath, getThemeCache, applyCachedThemeToDom } from '@/lib/helpers/themeCache'

export function ThemeColorSetter() {
  useLayoutEffect(() => {
    try {
      const slug = getRestaurantSlugFromPath()
      const cachedTheme = slug ? getThemeCache(slug) : null
      if (cachedTheme) {
        applyCachedThemeToDom(cachedTheme)
        return
      }

      const savedColor = getCachedMenuColor(slug)
      if (savedColor) {
        const oklchColor = hexToOklch(savedColor)
        
        if (oklchColor) {
          document.documentElement.style.setProperty('--primary', oklchColor)
          
          const brightness = calculateBrightness(savedColor)
          const foregroundOklch = brightness > 0.5 ? 'oklch(0 0 0)' : 'oklch(1 0 0)'
          document.documentElement.style.setProperty('--primary-foreground', foregroundOklch)
        }
      }
    } catch (e) {
      // Silent fail
    }
  }, [])

  return null
}

