import { defineStore } from 'pinia';

// 存储键名
const TOUR_STORAGE_KEY = 'guide_tour_completed';

export const useGuideTourStore = defineStore('guideTour', () => {
  // 是否是首次访问
  const isFirstVisit = ref(!localStorage.getItem(TOUR_STORAGE_KEY));

  // 当前引导阶段
  const currentPhase = ref<'idle' | 'header' | 'userCenter' | 'chat'>('idle');

  // 是否需要在用户中心弹窗打开后开始引导
  const shouldStartUserCenterTour = ref(false);

  // 是否需要在聊天页面开始引导
  const shouldStartChatTour = ref(false);

  // 用户中心导航切换回调
  const userCenterNavChangeCallback = ref<((nav: string) => void) | null>(null);

  // 用户中心弹窗关闭回调
  const userCenterCloseCallback = ref<(() => void) | null>(null);

  // 标记引导已完成
  function markTourCompleted() {
    localStorage.setItem(TOUR_STORAGE_KEY, Date.now().toString());
    isFirstVisit.value = false;
  }

  // 重置引导状态
  function resetTourStatus() {
    localStorage.removeItem(TOUR_STORAGE_KEY);
    isFirstVisit.value = true;
  }

  // 设置当前引导阶段
  function setCurrentPhase(phase: 'idle' | 'header' | 'userCenter' | 'chat') {
    currentPhase.value = phase;
  }

  // 触发用户中心引导
  function triggerUserCenterTour() {
    shouldStartUserCenterTour.value = true;
  }

  // 清除用户中心引导触发标记
  function clearUserCenterTourTrigger() {
    shouldStartUserCenterTour.value = false;
  }

  // 触发聊天页面引导
  function triggerChatTour() {
    shouldStartChatTour.value = true;
  }

  // 清除聊天页面引导触发标记
  function clearChatTourTrigger() {
    shouldStartChatTour.value = false;
  }

  // 设置用户中心导航切换回调
  function setUserCenterNavChangeCallback(callback: (nav: string) => void) {
    userCenterNavChangeCallback.value = callback;
  }

  // 设置用户中心弹窗关闭回调
  function setUserCenterCloseCallback(callback: () => void) {
    userCenterCloseCallback.value = callback;
  }

  // 切换用户中心导航
  function changeUserCenterNav(nav: string) {
    if (userCenterNavChangeCallback.value) {
      userCenterNavChangeCallback.value(nav);
    }
  }

  // 关闭用户中心弹窗
  function closeUserCenterDialog() {
    if (userCenterCloseCallback.value) {
      userCenterCloseCallback.value();
    }
  }

  return {
    isFirstVisit,
    currentPhase,
    shouldStartUserCenterTour,
    shouldStartChatTour,
    userCenterNavChangeCallback,
    userCenterCloseCallback,
    markTourCompleted,
    resetTourStatus,
    setCurrentPhase,
    triggerUserCenterTour,
    clearUserCenterTourTrigger,
    triggerChatTour,
    clearChatTourTrigger,
    setUserCenterNavChangeCallback,
    setUserCenterCloseCallback,
    changeUserCenterNav,
    closeUserCenterDialog,
  };
});
