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

export type ThemeMode = 'system' | 'light' | 'dark'

const STORAGE_KEY = 'sw-theme'

export const useThemeStore = defineStore('theme', () => {
  const mode = ref<ThemeMode>((localStorage.getItem(STORAGE_KEY) as ThemeMode) || 'system')

  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  const systemIsDark = ref(mediaQuery.matches)

  const isDark = computed(() => mode.value === 'dark' || (mode.value === 'system' && systemIsDark.value))

  const label = computed(() => {
    if (mode.value === 'system') {
      return `System (${isDark.value ? 'dark' : 'light'})`
    }
    return mode.value === 'dark' ? 'Dark' : 'Light'
  })

  function applyTheme() {
    document.documentElement.classList.toggle('dark', isDark.value)
  }

  function cycle() {
    const order: ThemeMode[] = ['system', 'light', 'dark']
    const idx = order.indexOf(mode.value)
    mode.value = order[(idx + 1) % 3]
  }

  watch(mode, (val) => {
    localStorage.setItem(STORAGE_KEY, val)
    applyTheme()
  })

  mediaQuery.addEventListener('change', () => {
    systemIsDark.value = mediaQuery.matches
    if (mode.value === 'system') applyTheme()
  })

  // Apply immediately
  applyTheme()

  return { mode, isDark, label, cycle, applyTheme }
})
