'use client'
import { useEffect, useState } from 'react'
import { Moon, Sun } from 'lucide-react'
import { motion } from 'framer-motion'
export function ThemeToggle() {
const [theme, setTheme] = useState<'light' | 'dark'>('light')
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
// Check for stored preference or system preference
const stored = localStorage.getItem('theme')
if (stored === 'dark' || stored === 'light') {
setTheme(stored)
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
setTheme('dark')
}
}, [])
useEffect(() => {
if (!mounted) return
const root = document.documentElement
if (theme === 'dark') {
root.classList.add('dark')
} else {
root.classList.remove('dark')
}
localStorage.setItem('theme', theme)
}, [theme, mounted])
const toggleTheme = () => {
setTheme(prev => prev === 'light' ? 'dark' : 'light')
}
// Prevent hydration mismatch
if (!mounted) {
return (
)
}
return (
{theme === 'light' ? (
) : (
)}
)
}
export default ThemeToggle