import { useState, useEffect } from 'react';

/**
 * @returns {boolean} Whether the user prefers a dark theme
 */
export default function useThemePreference() {
  const [dark, setDark] = useState(true);

  // Automatically respond to theme changes
  useEffect(() => {
    setDark(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);

    const onThemeChange = (event: MediaQueryListEvent) => {
      setDark(event.matches);
    };

    let match = window.matchMedia('(prefers-color-scheme: dark)');
    match.addEventListener('change', onThemeChange);

    return () => match.removeEventListener('change', onThemeChange);
  }, []);

  return dark;
}
