import { Moon, Sun } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import { useEffect, useState } from "react";

function getInitialTheme() {
  if (typeof document === "undefined") return false;
  return document.documentElement.classList.contains("dark");
}

export function ThemeToggle({ className = "" }) {
  const [dark, setDark] = useState(getInitialTheme);
  const reduceMotion = useReducedMotion();

  useEffect(() => {
    document.documentElement.classList.toggle("dark", dark);
    localStorage.setItem("theme", dark ? "dark" : "light");

    const metaTheme = document.querySelector('meta[name="theme-color"]');
    metaTheme?.setAttribute("content", dark ? "#101614" : "#f5f2ea");
  }, [dark]);

  return (
    <motion.button
      type="button"
      className={`relative grid size-10 place-items-center overflow-hidden rounded-md text-muted transition hover:bg-surface hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent dark:hover:bg-surface ${className}`}
      onClick={() => setDark((value) => !value)}
      aria-label={dark ? "Включить светлую тему" : "Включить темную тему"}
      title={dark ? "Светлая тема" : "Темная тема"}
      whileTap={reduceMotion ? undefined : { scale: 0.92 }}
    >
      <motion.span
        className="absolute inset-1 rounded-full bg-accent-soft"
        initial={false}
        animate={{
          scale: dark ? 1 : 0,
          opacity: dark ? 1 : 0,
        }}
        transition={{ duration: reduceMotion ? 0 : 0.2 }}
      />
      <AnimatePresence initial={false} mode="wait">
        <motion.span
          key={dark ? "sun" : "moon"}
          className="relative z-10"
          initial={reduceMotion ? false : { opacity: 0, rotate: -35, scale: 0.65 }}
          animate={{ opacity: 1, rotate: 0, scale: 1 }}
          exit={reduceMotion ? undefined : { opacity: 0, rotate: 35, scale: 0.65 }}
          transition={{ duration: reduceMotion ? 0 : 0.18 }}
        >
          {dark ? <Sun className="size-5 text-accent" /> : <Moon className="size-5" />}
        </motion.span>
      </AnimatePresence>
    </motion.button>
  );
}
