import { useEffect, useState } from 'react';

function isCustomEvent(event: Event): event is CustomEvent {
  return 'detail' in event;
}
const useDarkMode = () => {
  const [darkMode, setDarkMode] = useState<boolean>(() => document.body.classList.contains('dark'));

  useEffect(() => {
    const handleThemeChange = (e: CustomEvent<{ darkMode: boolean }>) => {
      if (!isCustomEvent(e)) {
        return;
      }
      setDarkMode(e.detail.darkMode);
    };

    window.addEventListener('themeChange', handleThemeChange);

    return () => {
      window.removeEventListener('themeChange', handleThemeChange);
    };
  }, []);

  return darkMode;
};

export default useDarkMode;
