import { useCookie, useNuxtApp, useRuntimeConfig } from '#imports'
import { useAuthStore } from '~/stores/auth'

/**
 * Client for the standalone customer-behavior tracking service (/tracker).
 * Independent from the main backend API — reuses the same `imei` cookie
 * as an anonymous visitor id, plus user_id when logged in.
 *
 * All calls are best-effort: tracking must never block or break the
 * actual ad-browsing experience, so failures are swallowed silently.
 */
export const useTracker = () => {
    const { $api } = useNuxtApp()
    const config = useRuntimeConfig()
    const BASE = config.public?.trackerBaseUrl || 'https://tracker.artjoo.com/api'

    const getImei = (): string => {
        const imei = useCookie('imei', { maxAge: 60 * 60 * 24 * 365 })
        return (imei.value as unknown as string) || ''
    }

    const getUserId = (): number | null => {
        try {
            const auth = useAuthStore()
            return auth.user?.id ?? null
        } catch {
            return null
        }
    }

    const post = (path: string, data: Record<string, unknown>) => {
        return $api.post(path, data, { baseURL: BASE }).catch(() => {})
    }

    const startVisit = async (advertiseId: number, categoryId: number | null = null, businessId: number | null = null): Promise<number | null> => {
        try {
            const { data } = await $api.post('/track/view/start', {
                imei: getImei(),
                user_id: getUserId(),
                advertise_id: advertiseId,
                category_id: categoryId,
                business_id: businessId,
            }, { baseURL: BASE })
            return data?.visit_id ?? null
        } catch {
            return null
        }
    }

    const sendProgress = (
        visitId: number | null,
        payload: { duration_seconds: number; photos_viewed: number; total_photos: number; scrolled_bottom: boolean },
        useBeacon = false
    ) => {
        if (!visitId) return
        const body = { visit_id: visitId, ...payload }

        if (useBeacon && typeof navigator !== 'undefined' && navigator.sendBeacon) {
            const blob = new Blob([JSON.stringify(body)], { type: 'application/json' })
            navigator.sendBeacon(`${BASE}/track/view/progress`, blob)
            return
        }

        post('/track/view/progress', body)
    }

    const trackContactView = (visitId: number | null) => {
        if (!visitId) return
        post('/track/contact-view', { visit_id: visitId })
    }

    const trackBookmark = (visitId: number | null, bookmarked: boolean) => {
        if (!visitId) return
        post('/track/bookmark', { visit_id: visitId, bookmarked })
    }

    const trackShare = (visitId: number | null) => {
        if (!visitId) return
        post('/track/share', { visit_id: visitId })
    }

    const trackChatMessage = (advertiseId: number, message: string) => {
        if (!advertiseId || !message) return
        post('/track/chat-message', {
            imei: getImei(),
            user_id: getUserId(),
            advertise_id: advertiseId,
            message,
        })
    }

    return {
        startVisit,
        sendProgress,
        trackContactView,
        trackBookmark,
        trackShare,
        trackChatMessage,
    }
}
