/**
 * useTheme — 主题切换 Hook
 *
 * 管理主题切换逻辑：监听系统 prefers-color-scheme，同步 data-theme 属性。
 * 支持 dark / light / auto 三种模式。
 */

import { useEffect } from 'react';
import { useUIStore, type ThemeMode } from '@renderer/stores/ui-store';

/**
 * 应用主题到 DOM
 */
function applyTheme(resolved: 'dark' | 'light'): void {
  document.documentElement.setAttribute('data-theme', resolved);
}

/**
 * 解析系统主题
 */
function getSystemTheme(): 'dark' | 'light' {
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

/**
 * 主题切换 Hook
 *
 * 在 App 根组件调用一次即可。
 */
export function useTheme(): void {
  const theme = useUIStore((s) => s.theme);
  const setResolvedTheme = useUIStore((s) => s.setResolvedTheme);

  // 初始化：从 localStorage 恢复主题偏好
  useEffect(() => {
    const saved = localStorage.getItem('metona-theme') as ThemeMode | null;
    if (saved && ['dark', 'light', 'auto'].includes(saved)) {
      useUIStore.getState().setTheme(saved);
    }
  }, []);

  // 监听系统主题变化
  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

    const handleChange = (): void => {
      if (theme === 'auto') {
        const resolved = getSystemTheme();
        applyTheme(resolved);
        setResolvedTheme(resolved);
      }
    };

    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, [theme, setResolvedTheme]);

  // 主题变化时应用
  useEffect(() => {
    const resolved = theme === 'auto' ? getSystemTheme() : theme;
    applyTheme(resolved);
    setResolvedTheme(resolved);
    localStorage.setItem('metona-theme', theme);
  }, [theme, setResolvedTheme]);
}

/**
 * 切换主题（dark ↔ light）
 */
export function toggleTheme(): void {
  const { resolvedTheme, setTheme } = useUIStore.getState();
  setTheme(resolvedTheme === 'dark' ? 'light' : 'dark');
}
