// MusicRoom - UI theme and layout experiments

(function() {
  const M = window.MusicRoom;

  const THEMES = new Set([
    "default",
    "phosphor",
    "vaporwave",
    "sunrise",
    "paper",
    "contrast",
    "aquarium",
    "amber",
    "compact",
    "cinema",
    "hotdog",
    "spreadsheet",
    "myspace",
    "sideways"
  ]);

  function decodeCookieValue(value) {
    if (!value) return null;
    try {
      return decodeURIComponent(value);
    } catch {
      M.clearCookieValue(M.THEME_STORAGE_KEY);
      return null;
    }
  }

  function normalizeTheme(theme) {
    return THEMES.has(theme) ? theme : "default";
  }

  M.getSavedTheme = function() {
    const cookieTheme = normalizeTheme(decodeCookieValue(M.getCookieValue(M.THEME_STORAGE_KEY)));
    if (cookieTheme !== "default") return cookieTheme;

    try {
      const storedTheme = normalizeTheme(localStorage.getItem(M.THEME_STORAGE_KEY));
      if (storedTheme !== "default") {
        M.rememberTheme(storedTheme);
        return storedTheme;
      }
    } catch {}

    return "default";
  };

  M.rememberTheme = function(theme) {
    const normalized = normalizeTheme(theme);
    if (normalized === "default") {
      M.clearThemePreference();
      return;
    }

    M.setCookieValue(M.THEME_STORAGE_KEY, normalized);
    try {
      localStorage.setItem(M.THEME_STORAGE_KEY, normalized);
    } catch {}
  };

  M.clearThemePreference = function() {
    M.clearCookieValue(M.THEME_STORAGE_KEY);
    try {
      localStorage.removeItem(M.THEME_STORAGE_KEY);
    } catch {}
  };

  M.applyTheme = function(theme, remember = true) {
    const normalized = normalizeTheme(theme);
    document.documentElement.dataset.uiTheme = normalized;
    document.body.dataset.uiTheme = normalized;

    const selector = document.getElementById("theme-select");
    if (selector) selector.value = normalized;

    if (remember) M.rememberTheme(normalized);
  };

  document.addEventListener("DOMContentLoaded", () => {
    const selector = document.getElementById("theme-select");
    M.applyTheme(M.getSavedTheme(), false);

    if (selector) {
      selector.onchange = () => M.applyTheme(selector.value);
    }
  });
})();
