/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const STORAGE_KEY = "matterTheme";
class ThemeServiceImpl {
  constructor() {
    this._preference = "system";
    this._listeners = /* @__PURE__ */ new Set();
    this._mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
    this._mediaQuery.addEventListener("change", () => this._applyTheme());
    this._loadPreference();
    this._applyTheme();
  }
  get preference() {
    return this._preference;
  }
  get effectiveTheme() {
    if (this._preference === "system") {
      return this._mediaQuery.matches ? "dark" : "light";
    }
    return this._preference;
  }
  setPreference(pref) {
    this._preference = pref;
    localStorage.setItem(STORAGE_KEY, pref);
    this._applyTheme();
  }
  cycleTheme() {
    const cycle = ["light", "dark", "system"];
    const currentIndex = cycle.indexOf(this._preference);
    const nextIndex = (currentIndex + 1) % cycle.length;
    this.setPreference(cycle[nextIndex]);
    return this._preference;
  }
  subscribe(callback) {
    this._listeners.add(callback);
    return () => this._listeners.delete(callback);
  }
  _loadPreference() {
    const urlParams = new URLSearchParams(window.location.search);
    const themeParam = urlParams.get("theme");
    if (themeParam && ["light", "dark", "system"].includes(themeParam)) {
      this._preference = themeParam;
      localStorage.setItem(STORAGE_KEY, themeParam);
      urlParams.delete("theme");
      const newUrl = urlParams.toString() ? `${window.location.pathname}?${urlParams.toString()}${window.location.hash}` : `${window.location.pathname}${window.location.hash}`;
      history.replaceState({}, "", newUrl);
      return;
    }
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored && ["light", "dark", "system"].includes(stored)) {
      this._preference = stored;
    }
  }
  _applyTheme() {
    const effective = this.effectiveTheme;
    document.documentElement.classList.toggle("dark-theme", effective === "dark");
    const metaThemeColor = document.querySelector('meta[name="theme-color"]');
    if (metaThemeColor) {
      metaThemeColor.setAttribute("content", effective === "dark" ? "#1e1e1e" : "#03a9f4");
    }
    this._listeners.forEach((cb) => cb(effective));
  }
}
const ThemeService = new ThemeServiceImpl();
export {
  ThemeService
};
//# sourceMappingURL=theme-service.js.map
