/**
 * Theme Composable for Light/Dark Mode Management
 * Uses Nuxt UI's useColorMode under the hood
 */

export const useTheme = () => {
  const colorMode = useColorMode()

  // Reactive state for the current theme
  const isDark = computed(() => colorMode.value === 'dark')
  const isLight = computed(() => colorMode.value === 'light')
  const currentTheme = computed(() => colorMode.value)

  // Toggle between light and dark
  const toggleTheme = () => {
    colorMode.preference = colorMode.value === 'dark' ? 'light' : 'dark'
    updateHtmlAttributes(colorMode.preference)
    // Mark this as an explicit user choice so the per-route auto-default
    // (mobile=dark, desktop=light) in the nuxt.config head script stops
    // recomputing it on each load and honours the choice everywhere.
    if (import.meta.client) localStorage.setItem('logship_theme_set', '1')
  }

  // Set a specific theme
  const setTheme = (theme: 'light' | 'dark' | 'system') => {
    colorMode.preference = theme
    updateHtmlAttributes(theme === 'system' ? colorMode.value : theme)
  }

  // Update HTML attributes for compatibility with various CSS selectors
  const updateHtmlAttributes = (mode: string) => {
    if (import.meta.client) {
      const html = document.documentElement
      html.setAttribute('data-mode', mode)
      html.classList.remove('light', 'dark')
      html.classList.add(mode)

      // Store preference
      localStorage.setItem('logship_theme', mode)
    }
  }

  // Initialize theme on mount
  const initTheme = () => {
    if (import.meta.client) {
      // Check for stored preference
      const stored = localStorage.getItem('logship_theme')
      if (stored && (stored === 'light' || stored === 'dark')) {
        setTheme(stored)
      } else {
        // Apply current colorMode value
        updateHtmlAttributes(colorMode.value)
      }
    }
  }

  // Theme-aware color getter
  const getThemeColor = (lightColor: string, darkColor: string) => {
    return isDark.value ? darkColor : lightColor
  }

  // CSS variable getter
  const getCSSVar = (varName: string) => {
    if (import.meta.client) {
      return getComputedStyle(document.documentElement).getPropertyValue(varName).trim()
    }
    return ''
  }

  return {
    // State
    isDark,
    isLight,
    currentTheme,
    colorMode,

    // Methods
    toggleTheme,
    setTheme,
    initTheme,
    getThemeColor,
    getCSSVar
  }
}

// Simple state for theme preference persistence
export const useThemePreference = () => useState<'light' | 'dark' | 'system'>('themePreference', () => 'light')
