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

function changeTheme(e) {
  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 (e) {
    // do nothing.
  }
}

function prefersDarkTheme() {
  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 (e) {
    return false;
  }
}

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

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

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

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

  themeButton.addEventListener('click', changeTheme);

  mqPrefersDarkTheme.addListener(mq => {
    toggleDarkTheme(mq.matches);
  });
}

function init() {
  if (isCSSVariablesSupported()) {
    initThemeSelector();
  }
}

init();
