"use client";

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

/** Sun/moon button: the icon spins out, the other spins in, and the page wipes to the new palette from the button. */
export function ThemeToggle({ className, dark: onDark }: { className?: string; dark?: boolean }) {
  const [isDark, setIsDark] = React.useState(false);
  React.useEffect(() => {
    const el = document.documentElement;
    const sync = () => setIsDark(el.classList.contains("dark"));
    sync();
    const mo = new MutationObserver(sync);
    mo.observe(el, { attributes: true, attributeFilter: ["class"] });
    return () => mo.disconnect();
  }, []);
  return (
    <button
      type="button"
      onClick={(e) => {
        const r = e.currentTarget.getBoundingClientRect();
        applyTheme(isDark ? "light" : "dark", { x: r.left + r.width / 2, y: r.top + r.height / 2 });
      }}
      className={cn("relative flex size-9 items-center justify-center overflow-hidden rounded-full border transition-all duration-300 active:scale-90", onDark ? "border-white/20 bg-white/10 text-white hover:bg-white/20" : "border-border bg-surface text-fg-muted hover:border-primary/40 hover:text-fg", className)}
      aria-label={isDark ? "Switch to light mode" : "Switch to dark mode"}
    >
      <AnimatePresence mode="wait" initial={false}>
        <motion.span key={isDark ? "moon" : "sun"} initial={{ rotate: -90, scale: 0.4, opacity: 0 }} animate={{ rotate: 0, scale: 1, opacity: 1 }} exit={{ rotate: 90, scale: 0.4, opacity: 0 }} transition={{ type: "spring", stiffness: 400, damping: 24 }} className="flex">
          {isDark ? <Moon className="size-4" /> : <Sun className="size-4" />}
        </motion.span>
      </AnimatePresence>
    </button>
  );
}
