(function () {
  var themeStorageKey = "klyn-theme";
  var legacyThemeStorageKey = "klyndoc-theme";

  function applyTheme(theme) {
    var root = document.documentElement;
    if (theme === "dark") {
      document.body.classList.add("theme-dark");
      root.classList.add("theme-dark");
    } else {
      document.body.classList.remove("theme-dark");
      root.classList.remove("theme-dark");
    }
  }

  function readTheme() {
    try {
      var saved = localStorage.getItem(themeStorageKey);
      if (saved === "dark" || saved === "light") return saved;
      var legacySaved = localStorage.getItem(legacyThemeStorageKey);
      if (legacySaved === "dark" || legacySaved === "light") return legacySaved;
    } catch (e) {
    }
    return "light";
  }

  function init() {
    applyTheme(readTheme());
  }

  window.addEventListener("storage", function (event) {
    if (event.key !== themeStorageKey && event.key !== legacyThemeStorageKey) return;
    applyTheme(readTheme());
  });

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();
