import { useCallback, useEffect, useState } from "react"; import { saveSession } from "../cookie"; import { ThemeTypes } from "../types/theme"; import { Moon, Sun } from "lucide-react"; export const SunMoonToggle = ({ theme: initialTheme, }: { theme: ThemeTypes; }) => { const [theme, setTheme] = useState(initialTheme); useEffect(() => { // Apply theme class to document body to match root.tsx const body = document.body; if (theme === "dark") { body.classList.add("dark"); } else { body.classList.remove("dark"); } }, [theme]); const changeTheme = useCallback(async () => { const newTheme = theme === "light" ? "dark" : "light"; setTheme(newTheme); // Update document body class immediately to match root.tsx const body = document.body; if (newTheme === "dark") { body.classList.add("dark"); } else { body.classList.remove("dark"); } await saveSession("theme", newTheme); // Refresh the page to ensure all components update with new theme window.location.reload(); }, [theme]); return (
{ if (e.key === "Enter") { changeTheme(); } }} className="relative w-14 h-7 bg-gradient-to-r from-blue-400 to-blue-500 dark:from-indigo-600 dark:to-purple-600 rounded-full cursor-pointer transition-all duration-300 ease-in-out shadow-lg hover:shadow-xl" > {/* Track background with gradient */}
{/* Sliding circle */}
{/* Icon inside the circle */}
{theme === "light" ? ( ) : ( )}
{/* Stars for dark mode */} {theme === "dark" && (
)} {/* Clouds for light mode */} {theme === "light" && (
)}
); };