<template>
  <div>
    <slot></slot>
    <login-register-modal 
      v-model:visible="showAuthModal" 
      :default-type="modalType"
      @login-success="handleLoginSuccess"
      @register-success="handleRegisterSuccess"
    />
  </div>
</template>

<script>
import { ref, provide, onMounted, onBeforeMount } from 'vue';
import LoginRegisterModal from './LoginRegisterModal.vue';

// 定义提供的上下文键名
export const AUTH_INJECTION_KEY = Symbol('auth-context');

export default {
  name: 'AuthProvider',
  components: {
    LoginRegisterModal
  },
  setup() {
    const showAuthModal = ref(false);
    const modalType = ref('login');
    const loginSuccessCallback = ref(null);
    const registerSuccessCallback = ref(null);

    // 打开登录弹窗
    const openLogin = (callback) => {
      modalType.value = 'login';
      showAuthModal.value = true;
      loginSuccessCallback.value = callback;
    };

    // 打开注册弹窗
    const openRegister = (callback) => {
      modalType.value = 'register';
      showAuthModal.value = true;
      registerSuccessCallback.value = callback;
    };

    // 处理登录成功
    const handleLoginSuccess = () => {
      if (typeof loginSuccessCallback.value === 'function') {
        loginSuccessCallback.value();
        loginSuccessCallback.value = null;
      }
      // 关闭弹窗
      showAuthModal.value = false;
    };

    // 处理注册成功
    const handleRegisterSuccess = () => {
      if (typeof registerSuccessCallback.value === 'function') {
        registerSuccessCallback.value();
        registerSuccessCallback.value = null;
      }
      // 关闭弹窗
      showAuthModal.value = false;
    };

    // 创建上下文对象
    const authContext = {
      openLogin,
      openRegister
    };

    // 提供上下文给子组件
    provide(AUTH_INJECTION_KEY, authContext);

    // 在挂载前就设置全局访问点，确保路由守卫可以尽早访问
    onBeforeMount(() => {
      window.$authContext = authContext;
    });

    // 确保挂载后也设置了全局访问点
    onMounted(() => {
      window.$authContext = authContext;
      
      // 如果有等待的登录触发事件，执行它
      if (window.routerEvents && typeof window.routerEvents.triggerLogin === 'function') {
        window.routerEvents.triggerLogin();
        window.routerEvents.triggerLogin = null;
      }
    });

    return {
      showAuthModal,
      modalType,
      handleLoginSuccess,
      handleRegisterSuccess
    };
  }
};
</script> 