/**
 * 期数据管理 Composable
 */
import { ref, computed } from 'vue'
import { getActivityIssues } from '@/api/appUser'
import { normalizeIssues, pickLatestIssueId } from '@/utils/activity'

/**
 * 期数据管理
 * @param {Ref<string>} activityIdRef - 活动ID的响应式引用
 */
export function useIssues(activityIdRef) {
    const issues = ref([])
    const selectedIssueIndex = ref(0)
    const loading = ref(false)

    const currentIssueId = computed(() => {
        const arr = issues.value || []
        const cur = arr[selectedIssueIndex.value]
        return (cur && cur.id) || ''
    })

    const currentIssue = computed(() => {
        const arr = issues.value || []
        return arr[selectedIssueIndex.value] || null
    })

    const currentIssueTitle = computed(() => {
        const cur = currentIssue.value
        if (!cur) return '-'
        return cur.title || ('第' + (cur.no || '-') + '期')
    })

    const currentIssueStatusText = computed(() => {
        const cur = currentIssue.value
        return (cur && cur.status_text) || ''
    })

    async function fetchIssues() {
        const id = activityIdRef?.value || activityIdRef
        if (!id) return
        loading.value = true
        try {
            const data = await getActivityIssues(id)
            issues.value = normalizeIssues(data)
            const latestId = pickLatestIssueId(issues.value)
            setSelectedById(latestId)
        } catch (e) {
            console.error('fetchIssues error', e)
            issues.value = []
        } finally {
            loading.value = false
        }
    }

    function setSelectedById(id) {
        const arr = issues.value || []
        const idx = Math.max(0, arr.findIndex(x => x && x.id === id))
        selectedIssueIndex.value = idx
    }

    function prevIssue() {
        const arr = issues.value || []
        if (!arr.length) return
        const next = Math.max(0, Number(selectedIssueIndex.value || 0) - 1)
        selectedIssueIndex.value = next
    }

    function nextIssue() {
        const arr = issues.value || []
        if (!arr.length) return
        const next = Math.min(arr.length - 1, Number(selectedIssueIndex.value || 0) + 1)
        selectedIssueIndex.value = next
    }

    return {
        issues,
        selectedIssueIndex,
        loading,
        currentIssueId,
        currentIssue,
        currentIssueTitle,
        currentIssueStatusText,
        fetchIssues,
        setSelectedById,
        prevIssue,
        nextIssue
    }
}
