import { useState, useEffect } from 'react'
import { Sun, Moon } from 'lucide-react'
import clsx from 'clsx'

export default function ThemeToggle() {
  const [isDark, setIsDark] = useState(true)

  useEffect(() => {
    // 从 localStorage 读取主题
    const saved = localStorage.getItem('theme')
    if (saved) {
      setIsDark(saved === 'dark')
      document.documentElement.classList.toggle('light', saved === 'light')
    } else {
      // 检测系统偏好
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      setIsDark(prefersDark)
      if (!prefersDark) {
        document.documentElement.classList.add('light')
      }
    }
  }, [])

  const toggleTheme = () => {
    const newIsDark = !isDark
    setIsDark(newIsDark)
    document.documentElement.classList.toggle('light', !newIsDark)
    localStorage.setItem('theme', newIsDark ? 'dark' : 'light')
  }

  return (
    <button
      onClick={toggleTheme}
      className="p-2 rounded-lg transition-all duration-200 hover:bg-white/10 text-secondary hover:text-primary"
      title={isDark ? '切换到浅色模式' : '切换到深色模式'}
    >
      {isDark ? (
        <Sun className="w-4 h-4" />
      ) : (
        <Moon className="w-4 h-4" />
      )}
    </button>
  )
}