import { create } from "zustand";

type Theme = "sage" | "blue";

interface ThemeState {
  theme: Theme;
  setTheme: (theme: Theme) => void;
  toggleTheme: () => void;
}

export const useThemeStore = create<ThemeState>((set) => ({
  theme: (typeof window !== "undefined"
    ? (localStorage.getItem("plm_theme") as Theme)
    : "sage") || "sage",

  setTheme: (theme) => {
    if (typeof window !== "undefined") {
      localStorage.setItem("plm_theme", theme);
      document.documentElement.setAttribute("data-theme", theme);
    }
    set({ theme });
  },

  toggleTheme: () =>
    set((s) => {
      const next = s.theme === "sage" ? "blue" : "sage";
      if (typeof window !== "undefined") {
        localStorage.setItem("plm_theme", next);
        document.documentElement.setAttribute("data-theme", next);
      }
      return { theme: next };
    }),
}));
