export type Theme = 'light' | 'dark'

const STORAGE_KEY = 'oikos-theme'

function applyClass(theme: Theme): void {
  const root = document.documentElement
  if (theme === 'dark') {
    root.classList.add('dark')
  } else {
    root.classList.remove('dark')
  }
}

function storedTheme(): Theme {
  if (typeof localStorage === 'undefined') return 'dark'
  const v = localStorage.getItem(STORAGE_KEY)
  if (v === 'light' || v === 'dark') return v
  return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'
}

const initialTheme = storedTheme()
let current: Theme = $state(initialTheme)

applyClass(initialTheme)

export function setTheme(t: Theme): void {
  current = t
  applyClass(t)
  if (typeof localStorage !== 'undefined') {
    localStorage.setItem(STORAGE_KEY, t)
  }
}

export function getTheme(): Theme {
  return current
}

export function toggleTheme(): Theme {
  const next = current === 'dark' ? 'light' : 'dark'
  setTheme(next)
  return next
}

export const THEME_LABELS: Record<Theme, string> = {
  light: 'Light',
  dark: 'Dark'
}
