import { defineStore } from 'pinia'
import { setTheme, themes } from '@/styles/theme'

// Helper function to apply display mode
export function applyDisplayMode(mode) {
  const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  let darkModeEnabled = false;

  if (mode === 'dark') {
    darkModeEnabled = true;
  } else if (mode === 'system') {
    darkModeEnabled = prefersDark;
  } // else mode === 'light', darkModeEnabled remains false

  if (darkModeEnabled) {
    document.documentElement.classList.add('dark');
  } else {
    document.documentElement.classList.remove('dark');
  }
}

export const useSettingsStore = defineStore('settings', {
  state: () => ({
    // 侧边栏状态
    sidebarCollapsed: false,
    // 显示模式: 'light', 'dark', 'system'
    displayMode: 'system', // Default to system preference
    // 主题配置 (e.g., 'default', 'fresh', 'warm')
    theme: 'default',
    // 动画效果开关
    animationsEnabled: true,
  }),

  persist: {
    key: 'settings',
    // Persist displayMode and theme
    paths: ['sidebarCollapsed', 'displayMode', 'theme', 'animationsEnabled']
  },

  actions: {
    // 切换侧边栏状态
    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed
    },

    // 切换动画状态
    toggleAnimations(enabled) {
      if (typeof enabled === 'boolean') {
        this.animationsEnabled = enabled;
      } else {
        this.animationsEnabled = !this.animationsEnabled;
      }
      // Apply animation class to body
      if (this.animationsEnabled) {
        document.body.classList.remove('no-animations');
      } else {
        document.body.classList.add('no-animations');
      }
    },

    // 更新显示模式
    updateDisplayMode(newMode) {
      if (['light', 'dark', 'system'].includes(newMode)) {
        this.displayMode = newMode;
        applyDisplayMode(newMode); // Apply the change immediately
        // Optional: Re-apply theme colors if they differ significantly in dark mode
        // setTheme(this.theme); // Uncomment if needed
      } else {
        console.warn(`Invalid display mode: ${newMode}`);
      }
    },

    // 更新主题颜色配置
    updateTheme(newTheme) {
      if (themes.hasOwnProperty(newTheme)) { // Check if the theme exists
        this.theme = newTheme;
        setTheme(newTheme); // Apply the theme colors
      } else {
         console.warn(`Invalid theme: ${newTheme}`);
      }
    },

    // 重置所有设置
    resetSettings() {
      this.$reset()
      // Re-apply settings after reset
      setTheme(this.theme);
      applyDisplayMode(this.displayMode);
      this.toggleAnimations(this.animationsEnabled); // Re-apply animation class
    }
  }
})

// --- Helper Function to apply animation class --- 
// Moved applying logic into the toggleAnimations action directly
// export function applyAnimationSetting(enabled) { ... } 