import { ref } from "vue";

export type ThemePreference = "system" | "light" | "dark";

const STORAGE_KEY = "builder-theme";

// Shared reactive state (module-level singleton)
const theme = ref<ThemePreference>(
  (localStorage.getItem(STORAGE_KEY) as ThemePreference) ?? "system",
);

function applyTheme(preference: ThemePreference): void {
  const isDark =
    preference === "dark" ||
    (preference === "system" &&
      window.matchMedia("(prefers-color-scheme: dark)").matches);
  document.documentElement.classList.toggle("dark", isDark);
  localStorage.setItem(STORAGE_KEY, preference);
  theme.value = preference;
}

// Listen for OS-level changes (only affects 'system' mode)
window
  .matchMedia("(prefers-color-scheme: dark)")
  .addEventListener("change", () => {
    if (theme.value === "system") {
      applyTheme("system");
    }
  });

export function useTheme() {
  return {
    theme,
    setTheme: applyTheme,
  };
}
