import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import {
  DEFAULT_WARD_SORT_DIRECTION,
  DEFAULT_WARD_SORT_FIELD,
  defaultSortDirection,
} from '@/composables/wardSort'

export const useSettingsStore = defineStore('settings', () => {
  const darkMode = ref(localStorage.getItem('darkMode') === 'true')
  const pollInterval = ref(10_000)
  const wardSortField = ref(localStorage.getItem('wardSortField') ?? DEFAULT_WARD_SORT_FIELD)
  const wardSortDirection = ref(localStorage.getItem('wardSortDirection') ?? DEFAULT_WARD_SORT_DIRECTION)
  const alertSoundMuted = ref(localStorage.getItem('alertSoundMuted') === 'true')

  watch(darkMode, (val) => {
    localStorage.setItem('darkMode', val)
    document.documentElement.classList.toggle('dark', val)
  }, { immediate: true })

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

  function toggleAlertSoundMute() {
    alertSoundMuted.value = !alertSoundMuted.value
    localStorage.setItem('alertSoundMuted', String(alertSoundMuted.value))
  }

  function setWardSort(field) {
    if (wardSortField.value === field) {
      wardSortDirection.value = wardSortDirection.value === 'desc' ? 'asc' : 'desc'
    } else {
      wardSortField.value = field
      wardSortDirection.value = defaultSortDirection(field)
    }
    localStorage.setItem('wardSortField', wardSortField.value)
    localStorage.setItem('wardSortDirection', wardSortDirection.value)
  }

  return {
    darkMode,
    pollInterval,
    wardSortField,
    wardSortDirection,
    alertSoundMuted,
    toggleDarkMode,
    toggleAlertSoundMute,
    setWardSort,
  }
})
