import { defineStore } from 'pinia'
import { getUserLaunchCampaignStatus, markUserGuide, markUserClickedRewardButton } from '@/api'
import dayjs from 'dayjs'
import { RewardButtonEnum } from '@/constants'
import { useYaBiStore } from './yabi'

const STORAGE_KEYS = {
  CG_WATCHED: 'activity_cg_watched',
  CLAIMED_PAGES: 'activity_claimed_pages',
  CLICK_COUNT: 'activity_click_count',
  SURVEY_SUBMITTED: 'activity_survey_submitted',
} as const

export const useActivityStore = defineStore('activity', () => {
  // ========== CG 引导 ==========
  const isLaunchCampaignTime = ref(false)
  // 2026.3.16 00:00:00 - 2026.3.22 23:59:59
  const launchCampaignRange: [number, number] = [
    dayjs('2026-03-16 00:00:00').unix(),
    dayjs('2026-03-22 23:59:59').unix(),
  ]
  // cg动画引导是否显示
  const showCgGuide = ref(false)
  // 普通的动画引导
  const showCommonGuide = ref(false)

  const markUserGuideWatched = async (key: 'isView' | 'isViewGuide') => {
    await markUserGuide(key)
  }

  const triggerCgGuide = async () => {
    const { data } = await getUserLaunchCampaignStatus()
    // 用户是否观看过CG
    if (!data.isView) {
      showCgGuide.value = true
    }
    if (!data.isViewGuide) {
      showCommonGuide.value = true
    }
    // 是否在活动期间
    if (data.currentTime >= launchCampaignRange[0] && data.currentTime <= launchCampaignRange[1]) {
      isLaunchCampaignTime.value = true
    }
  }

  // ========== 碎片奖励动画 ==========
  const showRewardAnimation = ref(false)
  const rewardText = ref({ fragment: 1, yabi: 2 })

  const triggerPageReward = async (pageKey: RewardButtonEnum) => {
    const { data } = await markUserClickedRewardButton(pageKey)
    const yabiStore = useYaBiStore()
    yabiStore.fetchYaBiData()
    if (data) {
      setTimeout(() => {
        showRewardAnimation.value = true
        setTimeout(() => {
          showRewardAnimation.value = false
        }, 2500)
      }, 500)
    }
  }

  // ========== 满意度问卷 ==========
  const clickCount = ref(0)
  const surveySubmitted = ref(false)
  const showSurvey = ref(false)
  const surveyThreshold = ref(999999)

  const incrementClickCount = () => {
    if (surveySubmitted.value) return
    clickCount.value++
    localStorage.setItem(STORAGE_KEYS.CLICK_COUNT, String(clickCount.value))
    if (clickCount.value >= surveyThreshold.value && !surveySubmitted.value) {
      showSurvey.value = true
    }
  }

  const markSurveySubmitted = () => {
    surveySubmitted.value = true
    localStorage.setItem(STORAGE_KEYS.SURVEY_SUBMITTED, '1')
    showSurvey.value = false
  }

  return {
    isLaunchCampaignTime,
    // CG
    // hasWatchedCg,
    showCgGuide,
    showCommonGuide,
    markUserGuideWatched,
    triggerCgGuide,
    // 碎片奖励
    showRewardAnimation,
    rewardText,
    triggerPageReward,
    // 问卷
    clickCount,
    surveySubmitted,
    showSurvey,
    surveyThreshold,
    incrementClickCount,
    markSurveySubmitted,
  }
})
