import { createContext, useContext, useState, useEffect, type ReactNode } from 'react'

export type ThemeId = 'dark' | 'light'

/** MoonShadow Minimal Design tokens (runtime helpers) */
export const RADIUS = {
  xs: '4px',
  sm: '6px',
  md: '8px',
  lg: '12px',
  xl: '16px',
} as const

export const FONT = {
  ui: "var(--font-ui)",
  mono: "var(--font-mono)",
} as const

interface ThemeContextType {
  theme: ThemeId
  setTheme: (theme: ThemeId) => void
  toggleTheme: () => void
  radius: typeof RADIUS
  font: typeof FONT
}

const ThemeContext = createContext<ThemeContextType | null>(null)

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<ThemeId>(() => {
    if (typeof window === 'undefined') return 'dark'
    const saved = localStorage.getItem('theme') as ThemeId | null
    return saved === 'light' || saved === 'dark' ? saved : 'dark'
  })

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('theme', theme)
    const color = theme === 'light' ? '#ffffff' : '#0d0d0d'
    let meta = document.querySelector('meta[name="theme-color"]:not([media])') as HTMLMetaElement | null
    if (!meta) {
      meta = document.createElement('meta')
      meta.name = 'theme-color'
      document.head.appendChild(meta)
    }
    meta.content = color
  }, [theme])

  const toggleTheme = () => setTheme((t) => (t === 'light' ? 'dark' : 'light'))

  return (
    <ThemeContext.Provider value={{ theme, setTheme, toggleTheme, radius: RADIUS, font: FONT }}>
      {children}
    </ThemeContext.Provider>
  )
}

export function useTheme() {
  const ctx = useContext(ThemeContext)
  if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
  return ctx
}
