import { defineStore } from 'pinia';
import { ref, watch } from 'vue';

const pixelPerfect = ref(true);
const darkMode = ref(false);

// Initialize dark mode from localStorage or system preference
if (typeof window !== 'undefined') {
  // Check localStorage first
  const storedDarkMode = localStorage.getItem('darkMode');
  if (storedDarkMode !== null) {
    darkMode.value = storedDarkMode === 'true';
  } else {
    // If not in localStorage, check system preference
    darkMode.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
  }
}

export const useSettingsStore = defineStore('settings', () => {
  // Watch for changes to update localStorage and apply class
  watch(
    darkMode,
    newValue => {
      // Save to localStorage
      localStorage.setItem('darkMode', newValue.toString());

      // Apply or remove dark class on document
      if (newValue) {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
    },
    { immediate: true }
  );

  // Actions
  function togglePixelPerfect() {
    pixelPerfect.value = !pixelPerfect.value;
  }

  function setPixelPerfect(value: boolean) {
    pixelPerfect.value = value;
  }

  function toggleDarkMode() {
    darkMode.value = !darkMode.value;
  }

  function setDarkMode(value: boolean) {
    darkMode.value = value;
  }

  return {
    pixelPerfect,
    darkMode,
    togglePixelPerfect,
    setPixelPerfect,
    toggleDarkMode,
    setDarkMode,
  };
});
