import { useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import { useEffect } from 'react';

type Theme = 'dark' | 'light' | 'system';

const themeAtom = atomWithStorage<Theme>('theme', 'system', undefined, {
  getOnInit: true,
});

export function useInitTheme() {
  const [theme] = useAtom(themeAtom);
  useEffect(() => {
    document.documentElement.classList.toggle(
      'dark',
      theme === 'dark' ||
        (theme == 'system' &&
          window.matchMedia('(prefers-color-scheme: dark)').matches),
    );
  });
}

export function useTheme() {
  return useAtom(themeAtom);
}
