"use client";

import * as React from "react";
import { LayoutGroup, motion } from "motion/react";
import { Monitor, Moon, Sun } from "lucide-react";
import { cn } from "@/lib/utils";
import { applyTheme, type ThemeMode } from "@/lib/theme";

const OPTIONS: { key: ThemeMode; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
  { key: "light", label: "Light", icon: Sun },
  { key: "dark", label: "Dark", icon: Moon },
  { key: "system", label: "Auto", icon: Monitor },
];

/** Three-way theme switch with a gliding pill; the palette change plays as a wipe. */
export function ThemeSegment({ className }: { className?: string }) {
  const [theme, setTheme] = React.useState<ThemeMode>("system");
  React.useEffect(() => {
    setTheme((document.documentElement.dataset.theme as ThemeMode) ?? "system");
  }, []);
  return (
    <LayoutGroup id="theme-segment">
      <div className={cn("grid grid-cols-3 gap-0.5 rounded-xl bg-surface-2 p-1", className)} role="radiogroup" aria-label="Theme">
        {OPTIONS.map((o) => {
          const active = theme === o.key;
          return (
            <button
              key={o.key}
              type="button"
              role="radio"
              aria-checked={active}
              onClick={(e) => {
                setTheme(o.key);
                const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
                applyTheme(o.key, { x: r.left + r.width / 2, y: r.top + r.height / 2 });
              }}
              className={cn("relative flex items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-medium transition-colors", active ? "text-fg" : "text-fg-muted hover:text-fg")}
            >
              {active ? <motion.span layoutId="theme-pill" transition={{ type: "spring", stiffness: 500, damping: 38 }} className="absolute inset-0 rounded-lg bg-surface shadow-xs hairline-top" aria-hidden /> : null}
              <o.icon className="relative size-3.5" />
              <span className="relative">{o.label}</span>
            </button>
          );
        })}
      </div>
    </LayoutGroup>
  );
}
