const isCSSVariablesSupported = () => {
  return window.CSS && window.CSS.supports('color', 'var(--fake-color');
};

const changeTheme = event => {
  const currentPref = sessionStorage.getItem('t-dark');
  const isDark = currentPref && currentPref === 'true' ? true : false;

  if (isDark) {
    document.documentElement.classList.remove('dark-theme');
  } else {
    document.documentElement.classList.add('dark-theme');
  }

  try {
    sessionStorage.setItem('t-dark', !isDark);
  } catch (error) {
    // do nothing.
  }
};

const getThemePreference = () => {
  try {
    const currentPref = sessionStorage.getItem('t-dark');

    if (currentPref && currentPref === 'true') {
      return true;
    } else if (
      !currentPref &&
      window.matchMedia('(prefers-color-scheme: dark)').matches
    ) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    return false;
  }
};

const toggleDarkTheme = isDark => {
  if (isDark) {
    document.documentElement.classList.add('dark-theme');
  } else {
    document.documentElement.classList.remove('dark-theme');
  }

  try {
    sessionStorage.setItem('t-dark', isDark);
  } catch (error) {
    // do nothing.
  }
};

const initThemeSelector = () => {
  const themeButton = document.getElementsByClassName('theme-switcher')[0];
  const prefersDarkTheme = window.matchMedia('(prefers-color-scheme: dark)');

  if (getThemePreference()) {
    toggleDarkTheme(true);
  }

  themeButton.addEventListener('click', changeTheme);

  prefersDarkTheme.addListener(mediaQuery => {
    toggleDarkTheme(mediaQuery.matches);
  });
};

const init = () => {
  if (isCSSVariablesSupported()) {
    initThemeSelector();
  }
};

init();
