import { useEffect, useState } from 'react';
import { useAppStore, type ResolvedTheme } from '@/stores/app';

function getSystemTheme(): ResolvedTheme {
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

/** 返回当前真正应用的 light/dark */
export function useResolvedTheme(): ResolvedTheme {
  const preference = useAppStore(s => s.themePreference);
  const [systemTheme, setSystemTheme] = useState<ResolvedTheme>(() =>
    typeof window === 'undefined' ? 'light' : getSystemTheme(),
  );

  useEffect(() => {
    const mql = window.matchMedia('(prefers-color-scheme: dark)');
    const onChange = (e: MediaQueryListEvent) => {
      setSystemTheme(e.matches ? 'dark' : 'light');
    };
    mql.addEventListener('change', onChange);
    return () => mql.removeEventListener('change', onChange);
  }, []);

  if (preference === 'system') return systemTheme;
  return preference;
}
