import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

export function useAuth() {
  const router = useRouter()
  const userStore = useUserStore()

  const loginModalVisible = ref(false)
  const registerModalVisible = ref(false)

  // 检查用户是否已登录，如果未登录则显示登录模态框
  const requireAuth = (callback?: () => void) => {
    if (userStore.isLoggedIn) {
      // 已登录，执行回调
      callback?.()
      return true
    } else {
      // 未登录，显示登录模态框
      loginModalVisible.value = true
      return false
    }
  }

  // 显示登录模态框
  const showLoginModal = () => {
    loginModalVisible.value = true
  }

  // 显示注册模态框
  const showRegisterModal = () => {
    registerModalVisible.value = true
  }

  // 认证成功处理
  const handleAuthSuccess = (callback?: () => void) => {
    loginModalVisible.value = false
    registerModalVisible.value = false
    callback?.()
  }

  // 跳转到课程详情页（需要登录检查）
  const goToCourseDetail = (courseId: string | number) => {
    requireAuth(() => {
      router.push(`/course/${courseId}`)
    })
  }

  // 报名课程（需要登录检查）
  const enrollCourse = (courseId: string | number, successCallback?: () => void) => {
    requireAuth(() => {
      // 这里可以添加报名逻辑
      console.log('报名课程:', courseId)

      // 模拟报名成功，跳转到课程学习页面
      if (successCallback) {
        successCallback()
      } else {
        router.push(`/course/study/${courseId}`)
      }
    })
  }

  return {
    loginModalVisible,
    registerModalVisible,
    requireAuth,
    showLoginModal,
    showRegisterModal,
    handleAuthSuccess,
    goToCourseDetail,
    enrollCourse
  }
}
