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,
    // 语音设置
    voiceInputSettings: {
      sendDirectly: true, // 语音转文字后直接发送
      // 自动文字语音播报
      autoTTS: false,
    },
  }),

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'settings',
        storage: localStorage,
      },
    ],
  },

  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;
        // Apply with transition if available
        if (document.startViewTransition) {
          document.startViewTransition(() => {
            applyDisplayMode(newMode);
          });
        } else {
          applyDisplayMode(newMode); // Fallback
        }
        // 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;
        // Apply with transition if available
        if (document.startViewTransition) {
          document.startViewTransition(() => {
            setTheme(newTheme);
          });
        } else {
          setTheme(newTheme); // Fallback
        }
      } else {
         console.warn(`Invalid theme: ${newTheme}`);
      }
    },

    // 重置所有设置
    resetSettings() {
      this.$reset()
      // Re-apply settings after reset, potentially with transition
      if (document.startViewTransition) {
        document.startViewTransition(() => {
          setTheme(this.theme);
          applyDisplayMode(this.displayMode);
          this.toggleAnimations(this.animationsEnabled); // Include animation class update
        });
      } else {
        setTheme(this.theme);
        applyDisplayMode(this.displayMode);
        this.toggleAnimations(this.animationsEnabled); // Fallback
      }
    },

    // 更新语音输入设置
    updateVoiceInputSettings(settings) {
      this.voiceInputSettings = {
        ...this.voiceInputSettings,
        ...settings
      }
    },
  }
})

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

// --- Watch for system theme changes --- 
// Ensure this runs after Pinia is initialized if useSettingsStore is called immediately
// Placing it here runs it once when the module is imported.
if (window.matchMedia) {
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

  const handleSystemThemeChange = () => {
    // Need to get the store instance inside the handler
    // Ensure Pinia is active before calling this
    try {
      const settingsStore = useSettingsStore(); 
      if (settingsStore.displayMode === 'system') {
        console.log('System theme changed, re-applying display mode.');
        applyDisplayMode('system');
      }
    } catch (error) {
      console.error("Pinia store not available yet for system theme change handler", error);
    }
  };

  // Add the listener
  mediaQuery.addEventListener('change', handleSystemThemeChange);

  // Optional: Cleanup listener if the store or app unmounts, 
  // though usually not strictly necessary for a global listener like this.
  // Example (would need proper context, e.g., within app setup):
  // onUnmounted(() => { 
  //   mediaQuery.removeEventListener('change', handleSystemThemeChange);
  // });
} 