/**
 * useTheme — dark-light-theme (spec 114).
 *
 * Reads and sets the active theme preference. Must be consumed inside
 * a <ThemeProvider> tree (throws if context is absent).
 *
 * ThemeContextValue.effectiveMode resolves 'system' against the OS
 * prefers-color-scheme media query so consumers always get 'dark'|'light'.
 */
import { createContext, useContext } from 'react'

export type ThemePreference = 'dark' | 'light' | 'system'
export type EffectiveMode = 'dark' | 'light'

export interface ThemeContextValue {
  /** Stored preference (what the user explicitly chose). */
  theme: ThemePreference
  /** Resolved mode after applying 'system' resolution. */
  effectiveMode: EffectiveMode
  /** Set preference, apply class, persist to localStorage. */
  setTheme: (theme: ThemePreference) => void
}

export const ThemeContext = createContext<ThemeContextValue | null>(null)

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