import { defineStore } from 'pinia'

export interface IAppConfig {
  sidebarCollapsed: boolean
  showDebug: boolean
}

export const useAppStore = defineStore('app', {
  state: () => ({
    sidebarCollapsed: false,
    showDebug: false,
    isLoading: false,
    loadingText: '',
    device: 'desktop' as 'desktop' | 'mobile' | 'tablet',
    isOnline: true,
    screenWidth: 0,
    screenHeight: 0
  }),

  getters: {
    isMobile: (state) => state.device === 'mobile',
    isTablet: (state) => state.device === 'tablet',
    isDesktop: (state) => state.device === 'desktop',
    hasLoading: (state) => state.isLoading
  },

  actions: {
    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed
    },

    setSidebarCollapsed(collapsed: boolean) {
      this.sidebarCollapsed = collapsed
    },

    setShowDebug(show: boolean) {
      this.showDebug = show
    },

    startLoading(text: string = '加载中...') {
      this.isLoading = true
      this.loadingText = text
    },

    endLoading() {
      this.isLoading = false
      this.loadingText = ''
    },

    setDevice(device: 'desktop' | 'mobile' | 'tablet') {
      this.device = device
    },

    setOnlineStatus(isOnline: boolean) {
      this.isOnline = isOnline
    },

    updateScreenSize(width: number, height: number) {
      this.screenWidth = width
      this.screenHeight = height

      if (width < 768) {
        this.device = 'mobile'
      } else if (width < 1024) {
        this.device = 'tablet'
      } else {
        this.device = 'desktop'
      }
    },

    initConfig(config: Partial<IAppConfig>) {
      if (config.sidebarCollapsed !== undefined) this.setSidebarCollapsed(config.sidebarCollapsed)
      if (config.showDebug !== undefined) this.setShowDebug(config.showDebug)
    },

    reset() {
      this.sidebarCollapsed = false
      this.showDebug = false
      this.isLoading = false
      this.loadingText = ''
    }
  },

  persist: {
    storage: piniaPluginPersistedstate.localStorage(),
    pick: ['sidebarCollapsed', 'showDebug']
  }
})
