/*
 * Theme init + toggle.
 *
 * Loaded in <head> WITHOUT defer so the first block runs before paint and sets
 * the theme attribute, avoiding a flash of the wrong theme. The choice lives in
 * localStorage (no cookie, no server round-trip) and applies site-wide.
 *
 * CSP note: this is an external /static file, so it is allowed under
 * script-src 'self'. We only toggle an attribute / class and never inject inline
 * <style>, which keeps style-src 'self' happy.
 */
(function () {
  var STORAGE_KEY = "warpbox-theme";
  var THEMES = ["revamp", "classic", "retro", "gruvbox", "cyberpunk"];

  function stored() {
    try {
      return localStorage.getItem(STORAGE_KEY);
    } catch (e) {
      return null;
    }
  }

  function apply(theme) {
    if (THEMES.indexOf(theme) === -1) {
      theme = "revamp";
    }
    document.documentElement.dataset.theme = theme;
    return theme;
  }

  // Runs immediately (before paint).
  var current = apply(stored() || "revamp");

  document.addEventListener("DOMContentLoaded", function () {
    var select = document.querySelector("[data-theme-select]");
    if (!select) {
      return;
    }

    // Reflect the active theme in the dropdown.
    select.value = current;

    select.addEventListener("change", function () {
      current = apply(select.value);
      try {
        localStorage.setItem(STORAGE_KEY, current);
      } catch (e) {
        /* ignore persistence failures (private mode, etc.) */
      }
    });
  });
})();
