<template>
  <div class="author-application-provider">
    <AuthorApplicationModal 
      v-model:visible="modalVisible" 
      @application-success="handleApplicationSuccess"
    />
    <slot></slot>
  </div>
</template>

<script>
import { ref, provide } from 'vue';
import AuthorApplicationModal from './AuthorApplicationModal.vue';

// 创建一个上下文注入的唯一键值
export const AUTHOR_APPLICATION_INJECTION_KEY = Symbol('author-application');

export default {
  name: 'AuthorApplicationProvider',
  components: {
    AuthorApplicationModal
  },
  setup() {
    const modalVisible = ref(false);
    const successCallback = ref(null);

    // 打开作家申请弹窗方法
    const openApplicationModal = (callback = null) => {
      modalVisible.value = true;
      successCallback.value = callback;
    };

    // 处理申请成功
    const handleApplicationSuccess = (applicationData) => {
      // 确保此时localStorage和store中都有正确的作家状态
      localStorage.setItem('isAuthor', 'true');
      
      // 获取store并更新作家状态
      if (window.$pinia?.state?.value?.main) {
        const store = window.$pinia._s.get('main');
        if (store && typeof store.setAsAuthor === 'function') {
          store.setAsAuthor();
        }
      }
      
      // 如果有设置回调则执行
      if (successCallback.value && typeof successCallback.value === 'function') {
        successCallback.value(applicationData);
      }
      
      // 关闭弹窗
      modalVisible.value = false;
      successCallback.value = null;
      
      // 打印调试信息
      if (window.$debug?.logUserState) {
        window.$debug.logUserState();
      }
    };

    // 提供作家申请上下文
    const context = {
      openApplicationModal
    };
    
    provide(AUTHOR_APPLICATION_INJECTION_KEY, context);

    // 设置全局变量以便路由守卫使用
    window.$authorApplicationContext = context;

    return {
      modalVisible,
      handleApplicationSuccess
    };
  }
};
</script>

<style scoped>
.author-application-provider {
  display: contents;
}
</style> 