import { Moon, Sun } from "lucide-react"

import { Button } from "~/components/ui/button"

const STORAGE_KEY = "crema-theme"

function applyTheme(next: "light" | "dark") {
  document.documentElement.classList.toggle("dark", next === "dark")
  localStorage.setItem(STORAGE_KEY, next)
}

export function ThemeToggle() {
  const toggle = () => {
    const isDark = document.documentElement.classList.contains("dark")
    applyTheme(isDark ? "light" : "dark")
  }

  return (
    <Button
      data-action="theme-toggle"
      variant="ghost"
      size="icon-sm"
      aria-label="Toggle theme"
      onClick={toggle}
    >
      <Sun className="hidden dark:block" />
      <Moon className="block dark:hidden" />
    </Button>
  )
}
