(function () {
  function currentSystemTheme() {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'tokyo' : 'light';
  }

  var btn = document.getElementById('theme-toggle');
  if (btn) {
    btn.addEventListener('click', function () {
      var current = document.documentElement.getAttribute('data-theme') || 'light';
      var next = current === 'light' ? 'tokyo' : 'light';
      document.documentElement.setAttribute('data-theme', next);
      localStorage.setItem('poc-theme', next);
      window.dispatchEvent(new Event('theme-change'));
    });
  }

  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function () {
    if (!localStorage.getItem('poc-theme')) {
      document.documentElement.setAttribute('data-theme', currentSystemTheme());
      window.dispatchEvent(new Event('theme-change'));
    }
  });
})();
