<template>
  <el-dropdown trigger="click" @command="handleThemeChange">
    <el-button type="text" :icon="isDark ? 'MoonNight' : 'Sunny'" circle>
    </el-button>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="light">
          <el-icon><Sunny /></el-icon>
          <span>浅色模式</span>
        </el-dropdown-item>
        <el-dropdown-item command="dark">
          <el-icon><MoonNight /></el-icon>
          <span>深色模式</span>
        </el-dropdown-item>
        <el-dropdown-item command="auto">
          <el-icon><Monitor /></el-icon>
          <span>跟随系统</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { computed } from 'vue'
import { Sunny, MoonNight, Monitor } from '@element-plus/icons-vue'
import { useThemeStore } from '../store/theme'

const themeStore = useThemeStore()

// 当前主题状态
const isDark = computed(() => themeStore.isDark)

// 切换主题
const handleThemeChange = (theme) => {
  if (theme === 'auto') {
    // 跟随系统主题
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    themeStore.isDark = prefersDark
  } else {
    // 手动设置主题
    themeStore.isDark = theme === 'dark'
  }
  
  // 更新localStorage和document属性
  localStorage.setItem('theme', themeStore.isDark ? 'dark' : 'light')
  document.documentElement.setAttribute('data-theme', themeStore.isDark ? 'dark' : 'light')
}
</script>

<style scoped>
.el-dropdown {
  display: inline-block;
}
</style>
