import { create } from "zustand"
import { useEffect } from "react"

export type ThemeMode = "system" | "light" | "dark"

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

function loadTheme(): ThemeMode {
  try {
    const v = localStorage.getItem("theme")
    if (v === "light" || v === "dark" || v === "system") return v
  } catch { /* unavailable */ }
  return "system"
}

function systemIsDark(): boolean {
  return window.matchMedia("(prefers-color-scheme: dark)").matches
}

export function effectiveTheme(mode: ThemeMode): "light" | "dark" {
  if (mode === "system") return systemIsDark() ? "dark" : "light"
  return mode
}

function applyTheme(mode: ThemeMode) {
  const root = document.documentElement
  if (effectiveTheme(mode) === "dark") {
    root.classList.add("dark")
  } else {
    root.classList.remove("dark")
  }
}

export const useThemeStore = create<ThemeState>((set) => ({
  mode: loadTheme(),
  setMode: (mode) => {
    localStorage.setItem("theme", mode)
    applyTheme(mode)
    set({ mode })
  },
}))

export function ThemeProvider() {
  const mode = useThemeStore((s) => s.mode)

  useEffect(() => {
    applyTheme(mode)
  }, [mode])

  useEffect(() => {
    if (mode !== "system") return
    const mql = window.matchMedia("(prefers-color-scheme: dark)")
    function sync() {
      applyTheme("system")
    }
    mql.addEventListener("change", sync)
    return () => mql.removeEventListener("change", sync)
  }, [mode])

  return null
}
