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

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

function safeReadString(key: string): string | null {
  try {
    return localStorage.getItem(key)
  } catch {
    return null
  }
}

function safeWrite(key: string, value: string) {
  try {
    localStorage.setItem(key, value)
  } catch {
    /* QuotaExceeded / disabled */
  }
}

export const useUIStore = defineStore('ui', () => {
  const storedTheme = safeReadString('themeMode') as ThemeMode | null
  const themeMode = ref<ThemeMode>(storedTheme || 'system')

  const mediaQuery =
    typeof window !== 'undefined' && typeof window.matchMedia === 'function'
      ? window.matchMedia('(prefers-color-scheme: dark)')
      : null
  const systemDark = ref(mediaQuery ? mediaQuery.matches : false)
  let mediaListener: ((e: MediaQueryListEvent) => void) | null = null
  if (mediaQuery) {
    mediaListener = (e: MediaQueryListEvent) => (systemDark.value = e.matches)
    mediaQuery.addEventListener('change', mediaListener)
  }

  const effectiveDark = computed(() =>
    themeMode.value === 'system' ? systemDark.value : themeMode.value === 'dark',
  )

  watch(
    effectiveDark,
    (v) => {
      if (typeof document !== 'undefined') {
        document.documentElement.classList.toggle('dark', v)
      }
    },
    { immediate: true },
  )

  function cleanupMediaQuery() {
    if (mediaQuery && mediaListener) {
      mediaQuery.removeEventListener('change', mediaListener)
      mediaListener = null
    }
  }

  function setThemeMode(mode: ThemeMode) {
    themeMode.value = mode
    safeWrite('themeMode', mode)
  }

  const sidebarCollapsed = ref(safeReadString('sidebarCollapsed') === 'true')
  watch(sidebarCollapsed, (v) => safeWrite('sidebarCollapsed', String(v)))

  return { themeMode, effectiveDark, setThemeMode, sidebarCollapsed, cleanupMediaQuery }
})
