import { computed, ref } from 'vue'
import type { AppMode, LoginType } from '@/config/menus'
import { isStaffRole } from '@/config/menus'
import { useAuth } from './useAuth'

const MODE_KEY = 'appMode'
const LOGIN_TYPE_KEY = 'loginType'

const appMode = ref<AppMode>((uni.getStorageSync(MODE_KEY) as AppMode) || 'user')
const loginType = ref<LoginType>((uni.getStorageSync(LOGIN_TYPE_KEY) as LoginType) || 'guest')

export function useAppMode() {
  const { getUser, isAuthenticated } = useAuth()

  const isAdminMode = computed(() => appMode.value === 'admin')
  const isUserMode = computed(() => appMode.value === 'user')

  const canEnterAdmin = computed(() => {
    if (!isAuthenticated()) return false
    const user = getUser() as { role?: string }
    return isStaffRole(user?.role)
  })

  const setLoginType = (type: LoginType) => {
    loginType.value = type
    uni.setStorageSync(LOGIN_TYPE_KEY, type)
  }

  const setAppMode = (mode: AppMode) => {
    appMode.value = mode
    uni.setStorageSync(MODE_KEY, mode)
  }

  const enterAdminMode = () => {
    if (!canEnterAdmin.value) {
      uni.showToast({ title: '无后台权限', icon: 'none' })
      return false
    }
    setAppMode('admin')
    // 延迟 import，避免与 useTheme 循环依赖；切换模式后立刻同步页底色
    import('./useTheme').then(({ useTheme }) => useTheme().apply()).catch(() => {})
    uni.reLaunch({ url: '/subPackages/admin/pages/dashboard/index' })
    return true
  }

  const enterUserMode = () => {
    setAppMode('user')
    import('./useTheme').then(({ useTheme }) => useTheme().apply()).catch(() => {})
    uni.reLaunch({ url: '/pages/home/index' })
  }

  /** 启动时校验：admin 模式但无权限则回退 */
  const hydrateAppMode = () => {
    if (appMode.value === 'admin' && !canEnterAdmin.value) {
      setAppMode('user')
      if (!isAuthenticated()) setLoginType('guest')
    }
    if (isAuthenticated() && canEnterAdmin.value) {
      setLoginType('staff')
    }
  }

  return {
    appMode,
    loginType,
    isAdminMode,
    isUserMode,
    canEnterAdmin,
    setLoginType,
    setAppMode,
    enterAdminMode,
    enterUserMode,
    hydrateAppMode,
  }
}
