;(function () {
  var key = "tfcode-theme-id"
  var themeId = localStorage.getItem(key) || "oc-2"

  if (themeId === "oc-1") {
    themeId = "oc-2"
    localStorage.setItem(key, themeId)
    localStorage.removeItem("tfcode-theme-css-light")
    localStorage.removeItem("tfcode-theme-css-dark")
  }

  var urlParams = new URLSearchParams(window.location.search)
  var urlScheme = urlParams.get("theme")
  var scheme = urlScheme || localStorage.getItem("tfcode-color-scheme") || "system"
  var isDark = scheme === "dark" || (scheme === "system" && matchMedia("(prefers-color-scheme: dark)").matches)
  var mode = isDark ? "dark" : "light"

  document.documentElement.dataset.theme = themeId
  document.documentElement.dataset.colorScheme = mode
  // Prevent transparent flash before CSS loads by setting explicit background immediately
  // In dark mode, prefer app-provided background color via URL param
  var urlBg = isDark ? urlParams.get("bg") : null
  document.documentElement.style.backgroundColor = urlBg || (isDark ? "#0c0c0c" : "#ffffff")

  if (themeId === "oc-2") return

  var css = localStorage.getItem("tfcode-theme-css-" + mode)
  if (css) {
    var style = document.createElement("style")
    style.id = "oc-theme-preload"
    style.textContent =
      ":root{color-scheme:" +
      mode +
      ";--text-mix-blend-mode:" +
      (isDark ? "plus-lighter" : "multiply") +
      ";" +
      css +
      "}"
    document.head.appendChild(style)
  }
})()
