import { defineStore } from 'pinia'
import { ref } from 'vue'

const DARK_KEY = 'nocollit:dark-mode'
const SIDEBAR_KEY = 'nocollit:sidebar-collapsed'

export const useUiStore = defineStore('ui', () => {
  // 从 localStorage 恢复暗色模式设置
  const saved = typeof localStorage !== 'undefined' ? localStorage.getItem(DARK_KEY) : null
  const isDark = ref(saved === 'true')

  const sidebarCollapsed = ref(typeof localStorage !== 'undefined' ? localStorage.getItem(SIDEBAR_KEY) === 'true' : false)
  const isMobile = ref(false)

  function applyDark(v: boolean) {
    isDark.value = v
    if (typeof document !== 'undefined') {
      if (v) {
        document.documentElement.classList.add('dark')
      } else {
        document.documentElement.classList.remove('dark')
      }
    }
    if (typeof localStorage !== 'undefined') {
      localStorage.setItem(DARK_KEY, String(v))
    }
  }

  function toggleDark() { applyDark(!isDark.value) }

  // 初始化时应用
  applyDark(isDark.value)
  function toggleSidebar() { sidebarCollapsed.value = !sidebarCollapsed.value; if (typeof localStorage !== 'undefined') localStorage.setItem(SIDEBAR_KEY, String(sidebarCollapsed.value)) }

  // 监听窗口尺寸
  let _resizeHandler: (() => void) | null = null
  if (typeof window !== 'undefined') {
    isMobile.value = window.innerWidth < 768
    _resizeHandler = () => {
      const now = window.innerWidth < 768
      if (now && !isMobile.value) {
        // 进入移动端：自动展开侧边栏，避免下次回到桌面时仍为收起状态
        sidebarCollapsed.value = false
      }
      isMobile.value = now
    }
    window.addEventListener('resize', _resizeHandler)
  }

  function dispose() {
    if (_resizeHandler) {
      window.removeEventListener('resize', _resizeHandler)
      _resizeHandler = null
    }
  }

  return { isDark, sidebarCollapsed, isMobile, toggleDark, toggleSidebar, dispose }
})
