(function () {
  var root = document.documentElement;
  var storageKey = 'site-theme';
  var media = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;

  function readStoredTheme() {
    try {
      var saved = localStorage.getItem(storageKey);
      return saved === 'light' || saved === 'dark' ? saved : '';
    } catch (error) {
      return '';
    }
  }

  function systemTheme() {
    return media && media.matches ? 'dark' : 'light';
  }

  function normalizedTheme(theme) {
    return theme === 'dark' ? 'dark' : 'light';
  }

  function ensureToggleMarkup(button) {
    if (button.querySelector('[data-theme-label]')) {
      return;
    }
    button.innerHTML = '<span class="theme-toggle-glyph" aria-hidden="true"></span><span data-theme-label></span>';
  }

  function updateToggle(theme) {
    var next = normalizedTheme(theme);
    document.querySelectorAll('[data-theme-toggle]').forEach(function (button) {
      ensureToggleMarkup(button);
      var label = button.querySelector('[data-theme-label]');
      if (label) {
        label.textContent = next === 'dark' ? 'Light mode' : 'Dark mode';
      }
      button.setAttribute('aria-pressed', next === 'dark' ? 'true' : 'false');
      button.setAttribute('aria-label', next === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
      button.setAttribute('title', next === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
    });
  }

  function setTheme(theme, persist) {
    var next = normalizedTheme(theme);
    root.setAttribute('data-theme', next);
    if (persist) {
      try {
        localStorage.setItem(storageKey, next);
      } catch (error) {
        // Ignore storage failures.
      }
    }
    var metaTheme = document.querySelector('meta[name="theme-color"]');
    if (metaTheme) {
      metaTheme.setAttribute('content', next === 'dark' ? '#0b1320' : '#f1eee6');
    }
    updateToggle(next);
  }

  function activeTheme() {
    return root.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
  }

  setTheme(readStoredTheme() || systemTheme(), false);

  document.querySelectorAll('[data-theme-toggle]').forEach(function (button) {
    button.addEventListener('click', function () {
      setTheme(activeTheme() === 'dark' ? 'light' : 'dark', true);
    });
  });

  if (media && media.addEventListener) {
    media.addEventListener('change', function () {
      if (!readStoredTheme()) {
        setTheme(systemTheme(), false);
      }
    });
  }

  var stamp = document.querySelector('[data-build-stamp]');
  if (stamp) {
    stamp.textContent = new Date().toISOString().slice(0, 10);
  }
})();
