import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { postForm } from '@/utils/request'
import { useI18nStore } from '@/stores/i18n'

interface WebInfoContent {
  id: number
  title: string
  content: string
  createTime: string
  imgUrl: string
  isTop: string
}

interface HelpInfo {
  cate: string
  titleEN: string
  titleCN: string
  content: WebInfoContent[]
}

import { toBackendLang } from '@/utils/backendLang'

export interface HelpDetail {
  id: number
  title: string
  content: string
  createTime: string
}

export const useHelpCenterStore = defineStore('helpCenter', () => {
  const groups = ref<HelpInfo[]>([])
  const expandedIndices = ref<Set<number>>(new Set())
  const loading = ref(false)
  const error = ref('')

  const detail = ref<HelpDetail | null>(null)
  const detailLoading = ref(false)
  const detailError = ref('')

  function getLang(): string {
    const i18n = useI18nStore()
    return toBackendLang(i18n.current)
  }

  async function fetchGroups() {
    loading.value = true
    error.value = ''
    expandedIndices.value = new Set()
    try {
      const res = await postForm<HelpInfo[]>('uc/ancillary/more/help', { lang: getLang() })
      groups.value = Array.isArray(res) ? res : []
    } catch (e) {
      error.value = e instanceof Error ? e.message : '获取帮助信息失败'
      groups.value = []
    } finally {
      loading.value = false
    }
  }

  async function fetchDetail(helpId: string) {
    detailLoading.value = true
    detailError.value = ''
    detail.value = null
    try {
      let res: WebInfoContent
      if (helpId === '63') {
        res = await postForm<WebInfoContent>('uc/ancillary/more/help/desclaimer')
      } else if (helpId === '64') {
        res = await postForm<WebInfoContent>('uc/ancillary/more/help/privacy')
      } else if (helpId === '68') {
        res = await postForm<WebInfoContent>('uc/ancillary/more/help/follow')
      } else {
        res = await postForm<WebInfoContent>('uc/ancillary/more/help/detail', { id: helpId, lang: getLang() })
      }

      if (res) {
        detail.value = {
          id: res.id ?? helpId,
          title: res.title ?? '',
          content: res.content ?? '',
          createTime: res.createTime ?? '',
        }
      }
    } catch (e) {
      detailError.value = e instanceof Error ? e.message : '获取帮助详情失败'
    } finally {
      detailLoading.value = false
    }
  }

  function toggleExpand(index: number) {
    const next = new Set(expandedIndices.value)
    if (next.has(index)) {
      next.delete(index)
    } else {
      next.add(index)
    }
    expandedIndices.value = next
  }

  const groupCount = computed(() => groups.value.length)

  return {
    groups,
    expandedIndices,
    loading,
    error,
    detail,
    detailLoading,
    detailError,
    groupCount,
    fetchGroups,
    fetchDetail,
    toggleExpand,
  }
})
