<script>
  if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches))
  {
    document.documentElement.classList.add('dark');
  }
  else
  {
    document.documentElement.classList.remove('dark');
  }
  function toggleTheme() {
    const btn_icon_dark = document.getElementById('theme-toggle-dark');
    const btn_icon_light = document.getElementById('theme-toggle-light');
    if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches))
    {
      localStorage.theme = 'light';
      btn_icon_dark.classList.remove("hidden");
      btn_icon_light.classList.add("hidden");
    }
    else
    {
      localStorage.theme = 'dark';
      btn_icon_dark.classList.add("hidden");
      btn_icon_light.classList.remove("hidden");
    }
    document.documentElement.classList.toggle('dark');
    if ( typeof charts !== 'undefined' )
    {

      if ( Array.isArray(charts) )
      {
        //charts exist in this page, change theme
        charts.forEach(chart => {
          chart.updateOptions({theme: { mode: localStorage.theme}});
        });

      }
    }
  }
  document.addEventListener('DOMContentLoaded', function ()
  {
    const toggleButton = document.getElementById('theme-toggle');
    const btn_icon_dark = document.getElementById('theme-toggle-dark');
    const btn_icon_light = document.getElementById('theme-toggle-light');

    if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches))
    {
      btn_icon_dark.classList.add("hidden");
      btn_icon_light.classList.remove("hidden");
    }
    else
    {
      btn_icon_dark.classList.remove("hidden");
      btn_icon_light.classList.add("hidden");
    }
    toggleButton.addEventListener('click', toggleTheme);
  });
</script> 