import {defineStore} from 'pinia';

export const useDarkMode = defineStore('darkMode', {
  state: () => ({
    isDarkMode: localStorage.theme === "dark" ||
      (!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches)
  }),
  actions: {
    // Explicitly choose light mode
    setLightMode() {
      localStorage.theme = "light";
      this.isDarkMode = false;
      this.applyDarkMode();
    },

    // Explicitly choose dark mode
    setDarkMode() {
      localStorage.theme = "dark";
      this.isDarkMode = true;
      this.applyDarkMode();
    },

    // Respect OS preference (remove explicit theme choice)
    setSystemMode() {
      localStorage.removeItem("theme");
      this.isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
      this.applyDarkMode();
    },

    // Toggle between light and dark (keeping system as fallback)
    toggleDarkMode() {
      if (this.isDarkMode) {
        this.setLightMode();
      } else {
        this.setDarkMode();
      }
    },

    applyDarkMode() {
      document.documentElement.classList.toggle('dark', this.isDarkMode);
    },

    initDarkMode() {
      // On page load or when changing themes, best to add inline in `head` to avoid FOUC
      document.documentElement.classList.toggle(
        "dark",
        localStorage.theme === "dark" ||
        (!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches)
      );

      // Update state to match what was applied
      this.isDarkMode = localStorage.theme === "dark" ||
        (!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches);
    }
  }
});
