import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export type ThemeMode = 'light' | 'dark' | 'system'
export type AccentKey = 'green' | 'blue' | 'purple' | 'amber' | 'teal'

export const ACCENT_PRESETS: { key: AccentKey; label: string; hex: string }[] = [
  { key: 'green',  label: 'Schaeffler Green', hex: '#00893d' },
  { key: 'blue',   label: 'Blue',             hex: '#2563eb' },
  { key: 'purple', label: 'Purple',           hex: '#7c3aed' },
  { key: 'amber',  label: 'Amber',            hex: '#d97706' },
  { key: 'teal',   label: 'Teal',             hex: '#0d9488' },
]

interface ThemeState {
  mode: ThemeMode
  accent: AccentKey
  setMode: (mode: ThemeMode) => void
  setAccent: (accent: AccentKey) => void
}

/** Returns 'light' | 'dark' based on mode + system preference */
export function resolveTheme(mode: ThemeMode): 'light' | 'dark' {
  if (mode === 'system') {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }
  return mode
}

/** Applies theme to <html> element */
export function applyTheme(mode: ThemeMode, accent: AccentKey) {
  const resolved = resolveTheme(mode)
  const html = document.documentElement
  if (resolved === 'dark') {
    html.classList.add('dark')
  } else {
    html.classList.remove('dark')
  }
  html.setAttribute('data-accent', accent)
}

export const useThemeStore = create<ThemeState>()(
  persist(
    (set, get) => ({
      mode: 'light',
      accent: 'green',
      setMode: (mode) => {
        set({ mode })
        applyTheme(mode, get().accent)
      },
      setAccent: (accent) => {
        set({ accent })
        applyTheme(get().mode, accent)
      },
    }),
    { name: 'schaeffler-theme' },
  ),
)
