function themeToggle() {
  let oldValue = localStorage.getItem('theme');
  if (!oldValue) {
    oldValue = 'light';
    if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
      oldValue = 'dark';
    }
  }

  let newValue;
  if (oldValue == 'light') {
    newValue = 'dark';
  } else if (oldValue == 'dark') {
    newValue = 'light';
  }
  localStorage.setItem('theme', newValue);
  themeRefresh();
}

function themeClear() {
  localStorage.setItem('theme', '');
  themeRefresh();
}

function themeRefresh() {
  const theme = localStorage.getItem('theme')
  const el = document.getElementsByTagName('html')[0];
  if (theme == 'light') {
    el.setAttribute('theme', 'light');
  } else if (theme == 'dark') {
    el.setAttribute('theme', 'dark');
  } else {
    el.setAttribute('theme', '');
  }
}

function main() {
  const buttonToggle = document.getElementsByClassName('theme-toggle');
  for (const el of buttonToggle) {
    el.onclick = themeToggle;
  }
  const buttonClear = document.getElementsByTagName('theme-clear');
  for (const el of buttonClear) {
    el.onclick = themeClear;
  }
  themeRefresh();
}

addEventListener('DOMContentLoaded', main);
