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

const pixelPerfect = ref(true);
const darkMode = ref(false);
const negativeSpacingEnabled = ref(false);
const backgroundColor = ref('transparent');
const manualCellSizeEnabled = ref(false);
const manualCellWidth = ref(64);
const manualCellHeight = ref(64);
const checkerboardEnabled = 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;
  }

  function toggleNegativeSpacing() {
    negativeSpacingEnabled.value = !negativeSpacingEnabled.value;
  }

  function setBackgroundColor(color: string) {
    backgroundColor.value = color;
  }

  function toggleManualCellSize() {
    manualCellSizeEnabled.value = !manualCellSizeEnabled.value;
  }

  function setManualCellWidth(width: number) {
    manualCellWidth.value = Math.max(1, Math.floor(width));
  }

  function setManualCellHeight(height: number) {
    manualCellHeight.value = Math.max(1, Math.floor(height));
  }

  function setManualCellSize(width: number, height: number) {
    setManualCellWidth(width);
    setManualCellHeight(height);
  }

  function toggleCheckerboard() {
    checkerboardEnabled.value = !checkerboardEnabled.value;
  }

  return {
    pixelPerfect,
    darkMode,
    negativeSpacingEnabled,
    backgroundColor,
    manualCellSizeEnabled,
    manualCellWidth,
    manualCellHeight,
    checkerboardEnabled,
    togglePixelPerfect,
    setPixelPerfect,
    toggleDarkMode,
    setDarkMode,
    toggleNegativeSpacing,
    setBackgroundColor,
    toggleManualCellSize,
    setManualCellWidth,
    setManualCellHeight,
    setManualCellSize,
    toggleCheckerboard,
  };
});
