/**
 * 活动数据管理 Composable
 */
import { ref, computed } from 'vue'
import { getActivityDetail } from '@/api/appUser'
import { cleanUrl } from '@/utils/format'
import { statusToText } from '@/utils/activity'

/**
 * 活动数据管理
 * @param {Ref<string>} activityIdRef - 活动ID的响应式引用
 */
export function useActivity(activityIdRef) {
    const detail = ref({})
    const loading = ref(false)

    const coverUrl = computed(() => {
        const d = detail.value || {}
        return cleanUrl(d.image || d.banner || d.cover || '')
    })

    const statusText = computed(() => statusToText(detail.value?.status))

    const pricePerDraw = computed(() => {
        const cents = Number(detail.value?.price_draw || 0)
        return cents / 100
    })

    const activityName = computed(() => {
        const d = detail.value || {}
        return d.name || d.title || ''
    })

    const scheduledTime = computed(() => detail.value?.scheduled_time || detail.value?.scheduledTime || '')

    async function fetchDetail() {
        const id = activityIdRef?.value || activityIdRef
        if (!id) return
        loading.value = true
        try {
            const data = await getActivityDetail(id)
            detail.value = data || {}
        } catch (e) {
            console.error('fetchDetail error', e)
            detail.value = {}
        } finally {
            loading.value = false
        }
    }

    function setNavigationTitle(fallback = '活动') {
        const title = activityName.value || fallback
        try {
            uni.setNavigationBarTitle({ title })
        } catch (_) { }
    }

    return {
        detail,
        loading,
        coverUrl,
        statusText,
        pricePerDraw,
        activityName,
        scheduledTime,
        fetchDetail,
        setNavigationTitle
    }
}
