"use client"

import { useEffect, useState } from "react"
import { Moon, Sun, Monitor } from "lucide-react"
import { useTheme } from "next-themes"

import { cn } from "@/lib/utils"

const options = [
  { value: "light", label: "Light mode", icon: Sun },
  { value: "vibrant", label: "Vibrant theme", icon: Monitor },
  { value: "dark", label: "Dark mode", icon: Moon },
] as const

/**
 * Renders an empty slot until mounted: `theme` is unknown on the server (and on the
 * client's first paint, before next-themes reads localStorage), so rendering the active
 * segment before that would either be wrong or cause a hydration mismatch.
 */
export function ThemeToggle({ className }: { className?: string }) {
  const { theme, setTheme } = useTheme()
  const [mounted, setMounted] = useState(false)
  useEffect(() => setMounted(true), [])

  if (!mounted) {
    return <div className={cn("h-10 w-27 shrink-0", className)} aria-hidden="true" />
  }

  return (
    <div
      role="radiogroup"
      aria-label="Theme"
      className={cn("flex shrink-0 items-center gap-0.5 rounded-full bg-muted p-1", className)}
    >
      {options.map(({ value, label, icon: Icon }) => {
        const isActive = theme === value
        const isVibrant = value === "vibrant"
        return (
          <button
            key={value}
            type="button"
            role="radio"
            aria-checked={isActive}
            aria-label={label}
            title={label}
            onClick={() => setTheme(value)}
            className={cn(
              "flex size-8 shrink-0 items-center justify-center rounded-full transition-colors",
              isActive
                ? isVibrant
                  ? "bg-linear-to-br from-indigo-500 to-violet-600 text-white shadow-sm"
                  : "bg-card text-primary shadow-sm ring-1 ring-foreground/10"
                : "text-muted-foreground hover:text-foreground"
            )}
          >
            <Icon className="size-4" />
          </button>
        )
      })}
    </div>
  )
}
